carbatpy.optimizations.helpers_optimization =========================================== .. py:module:: carbatpy.optimizations.helpers_optimization Classes ------- .. autoapisummary:: carbatpy.optimizations.helpers_optimization.BoundaryEntry carbatpy.optimizations.helpers_optimization.EvalResult carbatpy.optimizations.helpers_optimization.CombinedTermination carbatpy.optimizations.helpers_optimization.OptiProblem Functions --------- .. autoapisummary:: carbatpy.optimizations.helpers_optimization.default_n_processes carbatpy.optimizations.helpers_optimization.extract_boundary_with_path carbatpy.optimizations.helpers_optimization.traverse_dict carbatpy.optimizations.helpers_optimization.create_config carbatpy.optimizations.helpers_optimization.warning_score carbatpy.optimizations.helpers_optimization.apply_dt_min_start carbatpy.optimizations.helpers_optimization.calc_costs carbatpy.optimizations.helpers_optimization.opti_func Module Contents --------------- .. py:function:: default_n_processes() -> int 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. :rtype: int .. py:class:: BoundaryEntry Represents a single optimization variable with its location and bounds. :param path: Keys describing the variable's location in the nested configuration dictionary, e.g. ``['hp', 'evaporator', 'dt_min']``. :param lower: Lower bound of the variable. :param 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 .. py:attribute:: path :type: list[str] .. py:attribute:: lower :type: float | int .. py:attribute:: upper :type: float | int .. py:function:: extract_boundary_with_path(bounds: dict[str, Any]) -> tuple[list[list[str]], tuple[float, Ellipsis], tuple[float, Ellipsis]] Extract variable paths and their lower/upper boundaries from a nested dictionary. :param bounds: Nested dictionary with variable boundaries, e.g. ``{'param': [lower, upper]}``. :type bounds: dict[str, Any] :returns: - List of variable paths (each path is a list of keys). - Tuple of lower bounds. - Tuple of upper bounds. :rtype: tuple[list[list[str]], tuple[float, ...], tuple[float, ...]] .. py:function:: traverse_dict(d: dict[str, Any], current_path: list[str] | None = None, entries: list[BoundaryEntry] | None = None) -> list[BoundaryEntry] Recursively traverse a nested dictionary to extract variable boundaries. :param d: Dictionary to traverse. :type d: dict[str, Any] :param current_path: Current key path. Defaults to ``None``. :type current_path: list[str] | None :param entries: Collected entries. Defaults to ``None``. :type entries: list[BoundaryEntry] | None :returns: List of :class:`BoundaryEntry` objects with path, lower, and upper bounds. :rtype: list[BoundaryEntry] .. py:function:: create_config(values: Iterable[float] | None, paths: list[list[str]]) -> dict[str, Any] Build a nested configuration dictionary from flattened optimizer variables and paths. Fractions are handled specially: the last fraction is calculated as ``1 - sum(others)``. :param values: Variable values from the optimizer. :type values: Iterable[float] | None :param paths: Corresponding paths in the configuration dictionary. :type paths: list[list[str]] :raises ValueError: If ``values`` is ``None``. :returns: Nested dictionary usable by carbatpy. :rtype: dict[str, Any] .. py:function:: warning_score(res: dict[str, Any], system_key: None | str = None) -> float Compute a total warning score from carbatpy simulation results. :param res: Simulation results from carbatpy. :type res: dict[str, Any] :param system_key: Specific system (``'hp'`` or ``'orc'``) to compute warnings for. Defaults to ``None`` for all systems. :type system_key: str | None :returns: Absolute sum of warnings (``0.0`` if none). :rtype: float .. py:function:: apply_dt_min_start(conf_act: dict[str, Any], opti_fun: str, paths: list[list[str]]) -> dict[str, Any] Set starting delta-T (``dT_min``) values in the config based on heat exchanger values. :param conf_act: Current configuration dictionary. :type conf_act: dict[str, Any] :param opti_fun: Cycle type. Must be one of ``'hp'``, ``'orc'``, or ``'cb'``. :type opti_fun: str :param paths: Paths to check whether ``dt_min`` is being optimized. :type paths: list[list[str]] :returns: Updated configuration with starting ``dT_min`` values. :rtype: dict[str, Any] .. py:function:: calc_costs(results: dict[str, Any], system: str, verbose: bool = False) -> tuple[float, dict[str, Any], dict[str, Any]] 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. :param results: Simulation results containing cost data. :type results: dict[str, Any] :param system: System type. Must be one of ``'hp'``, ``'orc'``, or ``'cb'``. :type system: str :param verbose: Print details about ORC cost components. Defaults to ``False``. :type verbose: bool :raises ValueError: If ``system`` is not ``'hp'``, ``'orc'``, or ``'cb'``. :returns: - Total system cost. - HP cost dictionary. - ORC cost dictionary. :rtype: tuple[float, dict[str, Any], dict[str, Any]] .. py:class:: EvalResult Container for the results of a carbatpy optimization evaluation. :param performance: Performance metric of the system (e.g., COP or thermal efficiency). :param costs: Total system cost calculated for the optimization case. :param p_low: Minimum pressure value in the system, used for constraints. :param warn: Warning score representing thermodynamic or design violations. .. py:attribute:: performance :type: float .. py:attribute:: costs :type: float .. py:attribute:: p_low :type: float .. py:attribute:: warn :type: float .. py:function:: 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 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. :param x: Decision variable values generated by the optimizer. :type x: Iterable[float] :param dir_config: General carbatpy configuration. :type dir_config: Any :param paths: Paths indicating where each value in ``x`` should be placed in the configuration dictionary. :type paths: list[list[str]] :param opti_fun: Cycle to optimize. Must be one of ``'hp'``, ``'orc'``, or ``'cb'``. :type opti_fun: str :param same_fluid: Whether to reuse the HP working fluid in the ORC. Only used in ``'cb'`` mode. Defaults to ``True``. :type same_fluid: bool :param heat_losses: Thermal losses in storage components. Only used in ``'cb'`` mode. Defaults to ``0.0``. :type heat_losses: float :param COP: COP of the HP. Required if ``opti_fun='orc'``. :type COP: float | None :param q_dot: Heat flow of the HP. Required if ``opti_fun='orc'``. :type q_dot: float | None :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). :rtype: EvalResult .. note:: In the presence of warnings, costs are penalized with ``1e12`` to discourage infeasible solutions during optimization. .. py:class:: CombinedTermination(max_gen: int, ftol: float, period: int, n_skip: int = 5) Bases: :py:obj:`pymoo.core.termination.Termination` Termination criteria combining multiple conditions for Pymoo optimizations. Combines: - Maximum number of generations (:class:`MaximumGenerationTermination`) - Multi-objective function tolerance with robust checking (:class:`RobustTermination`) :param max_gen_termination: Termination based on maximum number of generations. :type max_gen_termination: MaximumGenerationTermination :param ftol_termination: Termination based on objective function tolerance over a rolling period. :type ftol_termination: RobustTermination :param criteria: List of active termination criteria. :type criteria: list[Termination] Initialize the combined termination. :param max_gen: Maximum number of generations. :type max_gen: int :param ftol: Tolerance for objective function changes. :type ftol: float :param period: Number of generations to check tolerance over. :type period: int :param n_skip: Number of initial generations to skip for robust checking. Defaults to ``5``. :type n_skip: int .. py:attribute:: max_gen_termination .. py:attribute:: ftol_termination .. py:attribute:: criteria .. py:class:: OptiProblem(**kwargs) Bases: :py:obj:`pymoo.core.problem.ElementwiseProblem` Pymoo :class:`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. :param dir_config: General configuration passed to carbatpy. :param paths_var: Paths to decision variables in the config. :type paths_var: list[list[str]] :param opti_fun: Optimized cycle (``'hp'``, ``'orc'``, or ``'cb'``). :type opti_fun: str :param same_fluid: Whether fluids are reused across cycles. :type same_fluid: bool :param heat_losses: Heat loss fraction in ``'cb'`` mode. :type heat_losses: float :param COP: COP used for ``'orc'`` optimizations. :type COP: float | None :param q_dot: Heat flow used for ``'orc'`` optimizations. :type q_dot: float | None :param n_var: Number of Variables :type n_var: int :param n_obj: Number of Objectives :type n_obj: int :param n_ieq_constr: Number of Inequality Constraints :type n_ieq_constr: int :param n_eq_constr: Number of Equality Constraints :type n_eq_constr: int :param xl: Lower bounds for the variables. if integer all lower bounds are equal. :type xl: np.array, float, int :param xu: Upper bounds for the variable. if integer all upper bounds are equal. :type xu: np.array, float, int :param vtype: The variable type. So far, just used as a type hint. :type vtype: type .. py:attribute:: dir_config :type: Any .. py:attribute:: paths_var :type: list[list[str]] .. py:attribute:: opti_fun :type: str .. py:attribute:: same_fluid :type: bool .. py:attribute:: heat_losses :type: float | int .. py:attribute:: COP .. py:attribute:: q_dot