Utilities and I/O

The utilities layer supports the main targeting workflow with import/export helpers, physical-property utilities, optimisation routines, and plotting support. Several of these modules are also useful independently of the full OpenPinch workflow.

Data Conversion and Validation

These modules translate spreadsheet- or table-oriented data sources into the schema-compatible structures consumed by the service layer.

Utility helpers used across OpenPinch analyses.

This module aggregates reusable conversion utilities, workbook import/export helpers, numerical shortcuts, and the timing decorator used to measure performance critical routines.

Excel workbook ingestion helpers for OpenPinch problem/result data.

OpenPinch.utils.wkbook_to_json.get_problem_from_excel(excel_file, output_json=None)[source]

Read workbook stream/utility sheets and return OpenPinch problem JSON.

OpenPinch.utils.wkbook_to_json.get_results_from_excel(excel_file, output_json, project_name)[source]

Read workbook summary results and return structured target JSON.

CSV ingestion helpers that mirror the workbook-to-JSON conversion flow.

OpenPinch.utils.csv_to_json.get_problem_from_csv(streams_csv, utilities_csv, output_json=None, *, row_units=1, row_data=2, encoding='utf-8-sig')[source]

Read stream and utility CSV files into one OpenPinch input mapping.

Parameters:
  • streams_csv (str | IO)

  • utilities_csv (str | IO)

  • output_json (str | None)

  • row_units (int)

  • row_data (int)

  • encoding (str)

OpenPinch.utils.csv_to_json.get_results_from_csv(summary_csv, output_json, project_name, *, row_units=2, row_data=4, encoding='utf-8-sig')[source]

Read one summary CSV file into structured target JSON.

Parameters:
  • summary_csv (str | IO)

  • output_json (str | None)

  • project_name (str)

  • row_units (int)

  • row_data (int)

  • encoding (str)

Input normalisation helpers shared by Excel/CSV/JSON ingestion paths.

OpenPinch.utils.input_validation.validate_stream_data(sd)[source]

Normalise stream records and fill missing names/zones with sensible defaults.

Parameters:

sd (DataFrame)

OpenPinch.utils.input_validation.validate_utility_data(ud)[source]

Drop utility rows without a name.

Parameters:

ud (DataFrame)

Export and Reporting

Use the export helpers when you want the solved TargetOutput and Zone hierarchy written back to an Excel workbook for review or archiving.

Excel export utilities for OpenPinch targeting outputs.

OpenPinch.utils.export.export_target_summary_to_excel_with_units(target_response, master_zone, out_dir='.')[source]

Export solved targets and problem tables to an Excel workbook.

Parameters:
  • target_response (TargetOutput) – Structured response returned by the high-level targeting service.

  • master_zone (Zone) – Solved zone hierarchy used to export shifted and real problem tables for the master zone and all subzones. May be None when only the summary sheet is required.

  • out_dir (str) – Destination directory for the workbook.

Returns:

Absolute or relative path to the workbook that was written.

Return type:

str

Notes

The workbook currently includes a summary sheet plus one or more problem- table sheets. Value-with-unit objects are flattened into adjacent (value) and (unit) columns for easy review in Excel.

Math, Optimisation, and Targeting Helpers

These modules provide reusable numerical support for targeting and post- processing tasks.

Recursive dispatch helpers for zone-scale targeting and result extraction.

OpenPinch.utils.multiscale_targeting.get_targets_for_zone_and_sub_zones(zone, direct_service_func=None, indirect_service_func=None, args=None)[source]

Dispatch a prepared zone tree to the appropriate targeting routine.

Parameters:
OpenPinch.utils.multiscale_targeting.extract_results(zone, state_id=None)[source]

Serialise solved targets, generated utilities, and graph payloads.

Parameters:
  • zone (Zone)

  • state_id (str | None)

Return type:

dict

Shared numerical helpers.

OpenPinch.utils.miscellaneous.clean_composite_curve(y_array, x_array)[source]

Remove redundant points in composite curves.

Parameters:
Return type:

Tuple[ndarray | list]

OpenPinch.utils.miscellaneous.clean_composite_curve_ends(y_vals, x_vals)[source]

Remove redundant points in composite curves.

Parameters:
Return type:

Tuple[ndarray, ndarray]

OpenPinch.utils.miscellaneous.delta_vals(x, descending_vals=True)[source]

Compute difference between successive entries in a column.

Parameters:
Return type:

ndarray

OpenPinch.utils.miscellaneous.delta_with_zero_at_start(x)[source]

Compute successive differences and prepend a zero entry.

Parameters:

x (ndarray)

Return type:

ndarray

OpenPinch.utils.miscellaneous.g_ineq_penalty(g, *, eta=0.01, rho=10, form='square')[source]

Return a penalty value for an inequality-constraint residual.

Parameters:
Return type:

float64

OpenPinch.utils.miscellaneous.get_value(val, val2=None, zone_name=None, state_id=None)[source]

Extract a numeric value from supported scalars and payload wrappers.

Parameters:
Return type:

float

OpenPinch.utils.miscellaneous.graph_simple_cc_plot(Tc, Hc, Th, Hh)[source]

Render a quick Plotly plot of hot/cold composite curves for debugging.

OpenPinch.utils.miscellaneous.interp_with_plateaus(h_vals, t_vals, targets, side, tol=1e-06)[source]

Interpolate temperatures while respecting vertical curve segments.

Parameters:
Return type:

ndarray

OpenPinch.utils.miscellaneous.linear_interpolation(xi, x1, x2, y1, y2)[source]

Estimate y at xi using two known points and linear interpolation.

Parameters:
Return type:

float

OpenPinch.utils.miscellaneous.make_monotonic(h_vals, side, tol=1e-06)[source]

Adjust repeated values to become strictly increasing for interpolation.

Parameters:
Return type:

ndarray

OpenPinch.utils.miscellaneous.resolve_stream_attr(stream, attr_name, state_id=None, *, default_allowed=True)[source]

Resolve one stream attribute to a scalar for the selected state.

Parameters:
  • stream (Any)

  • attr_name (str)

  • state_id (str | None)

  • default_allowed (bool)

Return type:

float | None

OpenPinch.utils.miscellaneous.resolve_stream_attr_array(streams, attr_name, state_id=None, *, default_allowed=True)[source]

Resolve one attribute across a stream iterable into a float array.

Parameters:
Return type:

ndarray

Black-box optimisation entrypoint with lightweight backend dispatch.

OpenPinch.utils.blackbox_minimisers.multiminima(func, x0_ls=None, func_kwargs=None, bounds=None, opt_kwargs=None, optimiser_handle=BB_Minimiser.DA)[source]

Run a selected multi-start optimizer by handle.

Parameters:
Return type:

list

Generate piecewise-linear approximations for non-linear thermodynamic streams.

OpenPinch.utils.stream_linearisation.get_piecewise_linearisation_for_streams(streams, t_h_data, dt_diff_max=0.1)[source]

Generate piecewise-linear T-H profiles for non-linear streams.

Parameters:
Return type:

array

OpenPinch.utils.stream_linearisation.get_piecewise_data_points(curve, is_hot_stream, dt_diff_max=0.1)[source]

Perform piecewise linearisation with the Ramer-Douglas-Peucker algorithm.

Parameters:
  • curve (list) – Numpy array of plot points for th curve

  • dt_diff_max (float) – Maximum allowed temperature differential tolerance

  • is_hot_stream (bool)

Returns:

Numpy array of new curve points

Return type:

array

Heat-exchanger performance correlations used by area targeting routines.

OpenPinch.utils.heat_exchanger.CalcAreaUE(Arrangement, U, C_p, T_p1, T_p2, T_u1, T_u2, Passes)[source]

Estimate the exchanger area * U product from duty and temperatures.

OpenPinch.utils.heat_exchanger.Coth(R)[source]

Convenience wrapper for the hyperbolic cotangent function.

OpenPinch.utils.heat_exchanger.CrossflowUnmixedEff1(Ntu, c)[source]

Series approximation for cross-flow effectiveness with unmixed streams.

OpenPinch.utils.heat_exchanger.CrossflowUnmixedEff2(Ntu, c, Rows, Cmin_fluid)[source]

Lookup-derived correlations for cross-flow exchangers with finite rows.

OpenPinch.utils.heat_exchanger.HX_Eff(Arrangement, Ntu, c, Passes=None, Rows=None, Cmin_Phase=None)[source]

Return heat exchanger effectiveness for the specified arrangement/NTU/c ratio.

OpenPinch.utils.heat_exchanger.HX_NTU(Arrangement, eff, c, Passes=None)[source]

Compute NTU for a target effectiveness and exchanger arrangement.

OpenPinch.utils.heat_exchanger.HX_NTU_Numerical(Arrangement, eff, c)[source]

Solve for NTU numerically when closed-form expressions are unavailable.

OpenPinch.utils.heat_exchanger.MultiPassEff(eff, c, Passes)[source]

Convert single-pass effectiveness into equivalent multi-pass effectiveness.

OpenPinch.utils.heat_exchanger.MultiPassNTU(Eff_p, c, Passes)[source]

Convert multi-pass effectiveness back to an equivalent single-pass value.

OpenPinch.utils.heat_exchanger.compute_LMTD_from_dts(delta_T1, delta_T2)[source]

Return the LMTD for a counterflow heat exchanger from end-point deltas.

Parameters:
Return type:

ndarray

OpenPinch.utils.heat_exchanger.compute_LMTD_from_ts(T_hot_in, T_hot_out, T_cold_in, T_cold_out)[source]

Return the LMTD for a counterflow heat exchanger from temperatures.

Parameters:
Return type:

float

OpenPinch.utils.heat_exchanger.eNTU_slope_Numerical(Arrangement, Ntu, c, Passes)[source]

Compute a finite-difference effectiveness slope with respect to NTU.

Utility helpers for costing heat exchangers.

OpenPinch.utils.costing.compute_capital_recovery_factor(interest_rate, years)[source]

Calculate the capital recovery factor, also called annualisation.

Parameters:
Return type:

float

OpenPinch.utils.costing.compute_capital_cost(area, num_units, fixed_cost_factor, variable_cost_factor, n_exp_factor)[source]

Determine the capital cost of a heat exchanger.

Parameters:
Return type:

float

OpenPinch.utils.costing.compute_annual_capital_cost(capital_cost, discount_rate, service_life)[source]

Determine the annualised capital cost of heat exchanger.

Parameters:
Return type:

float

Convenience wrappers around CoolProp for common water property queries.

OpenPinch.utils.water_properties.Tsat_p(P)[source]

Saturation temperature (degC) at pressure P (bar).

OpenPinch.utils.water_properties.fromSIunit_T(Ins)[source]

Convert Kelvin to degC.

OpenPinch.utils.water_properties.fromSIunit_h(Ins)[source]

Convert J/kg to kJ/kg.

OpenPinch.utils.water_properties.fromSIunit_p(Ins)[source]

Convert Pa to bar.

OpenPinch.utils.water_properties.fromSIunit_s(Ins)[source]

Identity conversion for entropy; maintained for API symmetry.

OpenPinch.utils.water_properties.hL_p(P)[source]

Liquid enthalpy (kJ/kg) at pressure P (bar).

OpenPinch.utils.water_properties.hV_p(P)[source]

Vapour enthalpy (kJ/kg) at pressure P (bar).

OpenPinch.utils.water_properties.h_pT(P, T)[source]

Specific enthalpy (kJ/kg) at (P, T) where P is bar and T is degC.

OpenPinch.utils.water_properties.h_ps(P, s)[source]

Specific enthalpy (kJ/kg) at pressure P (bar) and entropy s (kJ/kg/K).

OpenPinch.utils.water_properties.psat_T(T)[source]

Saturation pressure (bar) at temperature T (degC).

OpenPinch.utils.water_properties.s_ph(P, H)[source]

Specific entropy (kJ/kg/K) at pressure P (bar) and enthalpy H (kJ/kg).

OpenPinch.utils.water_properties.toSIunit_T(Ins)[source]

Convert degC to Kelvin.

OpenPinch.utils.water_properties.toSIunit_h(Ins)[source]

Convert kJ/kg to J/kg.

OpenPinch.utils.water_properties.toSIunit_p(Ins)[source]

Convert bar to Pa.

OpenPinch.utils.water_properties.toSIunit_s(Ins)[source]

Identity conversion for entropy; maintained for API symmetry.

Internal Optimiser Backends

The modules below back OpenPinch.utils.blackbox_minimisers.multiminima(). They are primarily useful when you need to inspect or extend the optimiser implementations themselves.

Black-box optimiser backend implementations.

Shared helpers for black-box optimisation backends.

Dual-annealing multi-start backend.

CMA-ES multi-start backend.

Bayesian-optimisation multi-start backend.

RBF-surrogate multi-start backend.

Plotting and Instrumentation

These helpers cover quick standalone plotting, execution-time measurement, and the richer Streamlit dashboard components used by streamlit_app.py.

Install openpinch[notebook] for the standalone Plotly plotting helpers and Excel-oriented utility modules. Install openpinch[dashboard] for the Streamlit dashboard path.

Plotly helper routines for quick temperature-enthalpy visual checks.

OpenPinch.utils.plots.plot_t_h_curve(points, title='Temperature vs. Enthalpy')[source]

Plot Temperature vs. Enthalpy. :param points: tuple with columns ‘Temperature (K)’ and ‘Enthalpy (kJ/mol)’. :param title: Title of the graph. :returns: None

Parameters:

title (str)

Return type:

None

OpenPinch.utils.plots.plot_t_h_curve_with_piecewise_and_bounds(points, piecewise_points, epsilon, title='Temperature vs. Enthalpy')[source]

Plot the TH curve, its piecewise linearization, and a shaded ±epsilon band. :param points: Original TH curve points. :param piecewise_points: Simplified piecewise linear curve points. :param epsilon: Epsilon value for shading. :param title: Title of the graph.

Parameters:
  • points (array)

  • piecewise_points (array)

  • epsilon (float)

  • title (str)

Return type:

None

Decorators and lifecycle hooks for execution-time instrumentation.

OpenPinch.utils.decorators.timing_decorator(func=None, *, activate_overide=False)[source]

Decorator to measure execution time and track per-function totals. Supports both @timing_decorator and @timing_decorator(activate_overide=True)

Streamlit helpers for visualising OpenPinch outputs.

The functions in this module provide a lightweight dashboard scaffold that renders the Composite Curve style graphs emitted by OpenPinch.services alongside the corresponding problem tables. The dashboard is intentionally minimal so user projects can layer additional controls as needed.

class OpenPinch.streamlit_webviewer.web_graphing.StreamlitGraphSet(name, graphs)[source]

Bases: object

Convenience wrapper storing graphs grouped by target name.

Parameters:
classmethod from_payload(payload)[source]

Build a graph-set wrapper from the JSON-style graph payload.

Parameters:

payload (Mapping[str, object])

Return type:

StreamlitGraphSet

OpenPinch.streamlit_webviewer.web_graphing.collect_targets(zone)[source]

Flattens all energy targets beneath zone keyed by their display name.

Parameters:

zone (Zone)

Return type:

Dict[str, BaseTargetModel]

OpenPinch.streamlit_webviewer.web_graphing.problem_table_to_dataframe(table, *, round_decimals=2)[source]

Convert a ProblemTable into a pandas.DataFrame.

Parameters:
Return type:

DataFrame

OpenPinch.streamlit_webviewer.web_graphing.render_streamlit_dashboard(zone, *, graph_payload=None, page_title=None, value_rounding=2)[source]

Render a basic Streamlit dashboard for zone.

Parameters:
Return type:

None