carbatpy.optimizations.helpers_optimization

Classes

BoundaryEntry

Represents a single optimization variable with its location and bounds.

EvalResult

Container for the results of a carbatpy optimization evaluation.

CombinedTermination

Termination criteria combining multiple conditions for Pymoo optimizations.

OptiProblem

Pymoo ElementwiseProblem wrapper for carbatpy optimizations.

Functions

default_n_processes(→ int)

Determine the default number of processes to use for parallelization.

extract_boundary_with_path(→ tuple[list[list[str]], ...)

Extract variable paths and their lower/upper boundaries from a nested dictionary.

traverse_dict(→ list[BoundaryEntry])

Recursively traverse a nested dictionary to extract variable boundaries.

create_config(→ dict[str, Any])

Build a nested configuration dictionary from flattened optimizer variables and paths.

warning_score(→ float)

Compute a total warning score from carbatpy simulation results.

apply_dt_min_start(→ dict[str, Any])

Set starting delta-T (dT_min) values in the config based on heat exchanger values.

calc_costs(→ tuple[float, dict[str, Any], dict[str, Any]])

Calculate total system costs and cost distribution for HP, ORC, or CB.

opti_func(→ EvalResult)

Run a carbatpy simulation and return evaluation metrics for optimization.

Module Contents

carbatpy.optimizations.helpers_optimization.default_n_processes() int[source]

Determine the default number of processes to use for parallelization.

By default, this is the number of physical CPU cores minus 2, with a minimum of 1. If the number of physical cores cannot be determined, it falls back to the total logical cores, or 1 as a last resort.

Returns:

Recommended number of worker processes.

Return type:

int

class carbatpy.optimizations.helpers_optimization.BoundaryEntry[source]

Represents a single optimization variable with its location and bounds.

Parameters:
  • path – Keys describing the variable’s location in the nested configuration dictionary, e.g. ['hp', 'evaporator', 'dt_min'].

  • lower – Lower bound of the variable.

  • upper – Upper bound of the variable.

Example:

>>> entry = BoundaryEntry(path=['hp', 'evaporator', 'dt_min'], lower=1.0, upper=10.0)
>>> entry.path
['hp', 'evaporator', 'dt_min']
>>> entry.lower
1.0
path: list[str][source]
lower: float | int[source]
upper: float | int[source]
carbatpy.optimizations.helpers_optimization.extract_boundary_with_path(bounds: dict[str, Any]) tuple[list[list[str]], tuple[float, Ellipsis], tuple[float, Ellipsis]][source]

Extract variable paths and their lower/upper boundaries from a nested dictionary.

Parameters:

bounds (dict[str, Any]) – Nested dictionary with variable boundaries, e.g. {'param': [lower, upper]}.

Returns:

  • List of variable paths (each path is a list of keys).

  • Tuple of lower bounds.

  • Tuple of upper bounds.

Return type:

tuple[list[list[str]], tuple[float, …], tuple[float, …]]

carbatpy.optimizations.helpers_optimization.traverse_dict(d: dict[str, Any], current_path: list[str] | None = None, entries: list[BoundaryEntry] | None = None) list[BoundaryEntry][source]

Recursively traverse a nested dictionary to extract variable boundaries.

Parameters:
  • d (dict[str, Any]) – Dictionary to traverse.

  • current_path (list[str] | None) – Current key path. Defaults to None.

  • entries (list[BoundaryEntry] | None) – Collected entries. Defaults to None.

Returns:

List of BoundaryEntry objects with path, lower, and upper bounds.

Return type:

list[BoundaryEntry]

carbatpy.optimizations.helpers_optimization.create_config(values: Iterable[float] | None, paths: list[list[str]]) dict[str, Any][source]

Build a nested configuration dictionary from flattened optimizer variables and paths.

Fractions are handled specially: the last fraction is calculated as 1 - sum(others).

Parameters:
  • values (Iterable[float] | None) – Variable values from the optimizer.

  • paths (list[list[str]]) – Corresponding paths in the configuration dictionary.

Raises:

ValueError – If values is None.

Returns:

Nested dictionary usable by carbatpy.

Return type:

dict[str, Any]

carbatpy.optimizations.helpers_optimization.warning_score(res: dict[str, Any], system_key: None | str = None) float[source]

Compute a total warning score from carbatpy simulation results.

Parameters:
  • res (dict[str, Any]) – Simulation results from carbatpy.

  • system_key (str | None) – Specific system ('hp' or 'orc') to compute warnings for. Defaults to None for all systems.

Returns:

Absolute sum of warnings (0.0 if none).

Return type:

float

carbatpy.optimizations.helpers_optimization.apply_dt_min_start(conf_act: dict[str, Any], opti_fun: str, paths: list[list[str]]) dict[str, Any][source]

Set starting delta-T (dT_min) values in the config based on heat exchanger values.

Parameters:
  • conf_act (dict[str, Any]) – Current configuration dictionary.

  • opti_fun (str) – Cycle type. Must be one of 'hp', 'orc', or 'cb'.

  • paths (list[list[str]]) – Paths to check whether dt_min is being optimized.

Returns:

Updated configuration with starting dT_min values.

Return type:

dict[str, Any]

carbatpy.optimizations.helpers_optimization.calc_costs(results: dict[str, Any], system: str, verbose: bool = False) tuple[float, dict[str, Any], dict[str, Any]][source]

Calculate total system costs and cost distribution for HP, ORC, or CB.

For 'cb', distinguishes between HP and ORC components to avoid double counting shared components.

Parameters:
  • results (dict[str, Any]) – Simulation results containing cost data.

  • system (str) – System type. Must be one of 'hp', 'orc', or 'cb'.

  • verbose (bool) – Print details about ORC cost components. Defaults to False.

Raises:

ValueError – If system is not 'hp', 'orc', or 'cb'.

Returns:

  • Total system cost.

  • HP cost dictionary.

  • ORC cost dictionary.

Return type:

tuple[float, dict[str, Any], dict[str, Any]]

class carbatpy.optimizations.helpers_optimization.EvalResult[source]

Container for the results of a carbatpy optimization evaluation.

Parameters:
  • performance – Performance metric of the system (e.g., COP or thermal efficiency).

  • costs – Total system cost calculated for the optimization case.

  • p_low – Minimum pressure value in the system, used for constraints.

  • warn – Warning score representing thermodynamic or design violations.

performance: float[source]
costs: float[source]
p_low: float[source]
warn: float[source]
carbatpy.optimizations.helpers_optimization.opti_func(x: Iterable[float], dir_config: Any, paths: list[list[str]], opti_fun: str, same_fluid: bool = True, heat_losses: float = 0.0, COP: float | None = None, q_dot: float | None = None) EvalResult[source]

Run a carbatpy simulation and return evaluation metrics for optimization.

Constructs a complete configuration from optimizer variables x and the corresponding paths, simulates the chosen cycle, and assesses any thermodynamic warnings. Infeasible or violating results are returned with heavily penalized values to guide the optimizer away from invalid solutions.

Parameters:
  • x (Iterable[float]) – Decision variable values generated by the optimizer.

  • dir_config (Any) – General carbatpy configuration.

  • paths (list[list[str]]) – Paths indicating where each value in x should be placed in the configuration dictionary.

  • opti_fun (str) – Cycle to optimize. Must be one of 'hp', 'orc', or 'cb'.

  • same_fluid (bool) – Whether to reuse the HP working fluid in the ORC. Only used in 'cb' mode. Defaults to True.

  • heat_losses (float) – Thermal losses in storage components. Only used in 'cb' mode. Defaults to 0.0.

  • COP (float | None) – COP of the HP. Required if opti_fun='orc'.

  • q_dot (float | None) – Heat flow of the HP. Required if opti_fun='orc'.

Raises:

ValueError – If an unknown opti_fun is specified or required parameters are missing.

Returns:

Evaluation result containing:
  • performance: Cycle performance (e.g., COP or thermal efficiency).

  • costs: Total system costs.

  • p_low: Low-side pressure, used for constraints.

  • warn: Warning score (0.0 = no violations; high values indicate infeasible solutions).

Return type:

EvalResult

Note

In the presence of warnings, costs are penalized with 1e12 to discourage infeasible solutions during optimization.

class carbatpy.optimizations.helpers_optimization.CombinedTermination(max_gen: int, ftol: float, period: int, n_skip: int = 5)[source]

Bases: pymoo.core.termination.Termination

Termination criteria combining multiple conditions for Pymoo optimizations.

Combines:

  • Maximum number of generations (MaximumGenerationTermination)

  • Multi-objective function tolerance with robust checking (RobustTermination)

Parameters:
  • max_gen_termination (MaximumGenerationTermination) – Termination based on maximum number of generations.

  • ftol_termination (RobustTermination) – Termination based on objective function tolerance over a rolling period.

  • criteria (list[Termination]) – List of active termination criteria.

Initialize the combined termination.

Parameters:
  • max_gen (int) – Maximum number of generations.

  • ftol (float) – Tolerance for objective function changes.

  • period (int) – Number of generations to check tolerance over.

  • n_skip (int) – Number of initial generations to skip for robust checking. Defaults to 5.

max_gen_termination[source]
ftol_termination[source]
criteria[source]
class carbatpy.optimizations.helpers_optimization.OptiProblem(**kwargs)[source]

Bases: pymoo.core.problem.ElementwiseProblem

Pymoo ElementwiseProblem wrapper for carbatpy optimizations.

Handles different optimization modes ('hp', 'orc', 'cb') and sets up variables, bounds, constraints, and the evaluation function to interface with Pymoo.

Parameters:
  • dir_config – General configuration passed to carbatpy.

  • paths_var (list[list[str]]) – Paths to decision variables in the config.

  • opti_fun (str) – Optimized cycle ('hp', 'orc', or 'cb').

  • same_fluid (bool) – Whether fluids are reused across cycles.

  • heat_losses (float) – Heat loss fraction in 'cb' mode.

  • COP (float | None) – COP used for 'orc' optimizations.

  • q_dot (float | None) – Heat flow used for 'orc' optimizations.

  • n_var (int) – Number of Variables

  • n_obj (int) – Number of Objectives

  • n_ieq_constr (int) – Number of Inequality Constraints

  • n_eq_constr (int) – Number of Equality Constraints

  • xl (np.array, float, int) – Lower bounds for the variables. if integer all lower bounds are equal.

  • xu (np.array, float, int) – Upper bounds for the variable. if integer all upper bounds are equal.

  • vtype (type) – The variable type. So far, just used as a type hint.

dir_config: Any[source]
paths_var: list[list[str]][source]
opti_fun: str[source]
same_fluid: bool[source]
heat_losses: float | int[source]
COP[source]
q_dot[source]