Source code for tmhp.compressor_calibration

"""Fit the compressor scale factors to a heat pump's catalogue (#189).

A model's compressor is the default maps of :mod:`tmhp.compressor_efficiency`
under a :class:`~tmhp.compressor_efficiency.CompressorMapScale` (#274). This
module finds the scale that makes a model follow a product's published
operating points, and reports which factors the catalogue actually locates::

    from tmhp import AirSourceHeatPumpBoiler, calibrate_compressor

    def make_model(scale):
        return AirSourceHeatPumpBoiler(ref="R32", hp_capacity=9000.0, V_cmp_ref=42e-6, compressor_scale=scale)

    cal = calibrate_compressor(make_model, table_df, columns={"T0": "air_C", "T_w_out": "water_C", "Q": "Q_W", "cop": "COP"})
    model = make_model(cal.scale)           # or AirSourceHeatPumpBoiler(..., compressor_scale=cal.scale)

Catalogue tables (``table``)
    ``"duty"``
        Each row is a published duty ``Q`` [W] at an outdoor air ``T0`` [°C]
        and a leaving water ``T_w_out`` [°C], with its ``cop``. The model is
        solved at that duty with the EN 14511 water boundary (the water enters
        the standard's rise below ``T_w_out``, at the flow that carries ``Q``
        at that rise; :func:`tmhp.standard_conditions.en14511_condenser_water`),
        as the validation harness and the EnergyPlus plugin do. A row the
        model delivers more than 1 % short of ``Q``, or meets only as an on/off
        cycling mean, is infeasible for that candidate.
    ``"max_capacity"``
        Each row is the unit's maximum capacity ``Q`` at ``T0`` / ``T_w_out``,
        with its ``cop``. The model is asked for 1.5 ``Q`` at the same water
        boundary and must stop at its ceiling (``capacity_clamped == "max"``);
        the delivered heat is compared with ``Q`` as well as the COP. A row at
        which the model meets the whole request has no ceiling below it and is
        infeasible for that candidate.

    Optional columns: ``T_dis`` [°C], the published discharge temperature,
    and ``rps`` [rev/s], the published compressor speed at the row.

Residuals (one row may give several)
    ``ln(COP_model / COP_catalogue)``; with ``T_dis``,
    ``(T_dis,model - T_dis,catalogue) / discharge_scale_K``; with ``rps``,
    ``ln(N_model / N_catalogue)``; for a ``"max_capacity"`` table,
    ``ln(Q_model / Q_catalogue)``. A row a candidate cannot solve gives
    :data:`FAIL_RESIDUAL` in each of its residuals and is counted; rows the
    default model itself cannot solve are left out of the fit before it starts
    and listed in :attr:`CompressorCalibration.excluded` with their reason.

Factors and what identifies them
    ``k_ov`` is always free. ``k_v`` is free only when the table gives the
    speed (``rps``) or is a ``"max_capacity"`` table: at a fixed duty the
    volumetric efficiency changes the speed, not the COP. ``k_f`` is free only
    when the adapter says the table separates it from ``k_ov``: for a boiler
    table that is a ``T_dis`` column (the heat-loss share moves the discharge
    temperature; a heating COP sees ``eta_ov`` and ``f_loss`` together). A
    factor that is never free stays at its identity and is reported
    ``"unidentified"``.

Stages (:data:`DEFAULT_STAGES`, nested; each refits all its free factors)
    ``L0`` ``k_ov`` (and ``k_v``) → ``L1`` + ``k_f`` → ``M1`` + ``delta_N``
    → ``M2`` + ``w_N`` → ``M3`` + ``delta_r``, ``w_r``. A stage starts from the
    last adopted one and is judged against it. A rejected stage that adds only
    level factors does not end the sequence: ``k_ov`` alone may fail where
    ``k_ov`` with ``k_f`` passes (a discharge temperature pulls ``k_ov`` to a
    bound until ``k_f`` is free), and a rejected ``L1`` that adds ``k_f`` alone
    fixes ``k_f`` at 1. The first rejected shape stage ends the sequence; the
    later stages are fitted for the record and not adopted.

Adoption rule (:class:`AdoptionRule`, provisional until #272)
    A stage is adopted when, against the last adopted stage, (1) its k-fold
    cross-validated RMSE of the residuals drops by at least ``min_cv_gain``
    (relative), (2) each new factor's interval at ``ci_level`` excludes the
    factor's identity, (3) no two free factors correlate beyond ``max_corr``,
    and (4) no new factor rests on its search bound. Intervals and
    correlations come from the linearised covariance at the optimum,
    ``s² (JᵀJ)⁻¹`` with ``s² = Σr²/(m − p)`` and the Student-t quantile on
    ``m − p`` degrees of freedom, computed in the internal coordinates
    (logarithm of a factor, scaled shift) and mapped back. Read the interval
    as a measure of how flat the error valley is, not as a probability: the
    residuals of a catalogue are mostly the model's systematic gap, not
    random scatter.

Diagnostics (never reject a row or a candidate)
    Per row at the chosen scale: the discharge below the isentropic one
    (``f_loss > 1 - eta_ov``) with the shell loss ``Q_cmp_loss``, the maps read
    outside their data (``efficiency_extrapolated``, ``eta_ov`` at the
    transformed coordinates), and per factor whether it rests on a bound.

Limitation (#275): ``k_ov`` and ``k_f`` move independently, so the shell heat
loss is not tied to the overall efficiency; a calibration can reach a machine
whose discharge lies below the isentropic one.
"""

from __future__ import annotations

import math
import warnings
from collections.abc import Callable, Mapping, Sequence
from dataclasses import asdict, dataclass, field, replace
from typing import Any, Protocol

import numpy as np
import pandas as pd

from .compressor_efficiency import COEFFICIENT_VERSION, CompressorMapScale, InvalidCompressorEfficiency
from .operating_limits import OperatingLimitWarning
from .standard_conditions import en14511_condenser_water

__all__ = [
    "DEFAULT_BOUNDS",
    "DEFAULT_STAGES",
    "FAIL_RESIDUAL",
    "FACTORS",
    "AdoptionRule",
    "BoilerCatalogue",
    "CalibrationVersionError",
    "CatalogueAdapter",
    "CataloguePoint",
    "CompressorCalibration",
    "FactorEstimate",
    "PointOutcome",
    "StageRecord",
    "calibrate_compressor",
]

#: The seven factors, in the order of :class:`CompressorMapScale`.
FACTORS = ("k_v", "k_ov", "k_f", "delta_N", "w_N", "delta_r", "w_r")

#: Residual of each quantity of a row the candidate cannot solve (about a factor e^0.5 = 1.65 off).
FAIL_RESIDUAL = 0.5

#: Search bounds in factor units. ``k_f`` <= 4 keeps the default ``f_loss`` (<= 0.244) below one;
#: ``delta_r`` <= 1 keeps ``PR - delta_r`` positive down to a pressure ratio of 1.
DEFAULT_BOUNDS: dict[str, tuple[float, float]] = {
    "k_v": (0.7, 1.3),
    "k_ov": (0.3, 3.0),
    "k_f": (0.2, 4.0),
    "delta_N": (-35.0, 35.0),
    "w_N": (0.4, 2.5),
    "delta_r": (-2.0, 1.0),
    "w_r": (0.4, 2.5),
}

#: Internal coordinates: every factor O(1) and its identity at z = 0.
_LOG_FACTORS = frozenset({"k_v", "k_ov", "k_f", "w_N", "w_r"})
_SHIFT_UNIT = {"delta_N": 10.0, "delta_r": 0.5}
_IDENTITY = CompressorMapScale().as_dict()

#: ``(label, factors)``: the nested stages; a factor the table cannot identify is dropped from each.
DEFAULT_STAGES: tuple[tuple[str, tuple[str, ...]], ...] = (
    ("L0", ("k_v", "k_ov")),
    ("L1", ("k_v", "k_ov", "k_f")),
    ("M1", ("k_v", "k_ov", "k_f", "delta_N")),
    ("M2", ("k_v", "k_ov", "k_f", "delta_N", "w_N")),
    ("M3", ("k_v", "k_ov", "k_f", "delta_N", "w_N", "delta_r", "w_r")),
)

#: Factors whose rejected stage fixes them at identity without ending the sequence.
_OPTIONAL = frozenset({"k_f"})
#: The level factors: a rejected stage that adds only these does not end the sequence.
_LEVEL = frozenset({"k_v", "k_ov", "k_f"})

#: Extra starts for a shift factor the first time it is free (internal units of the shift).
_SHIFT_STARTS = {"delta_N": (-12.0, 12.0), "delta_r": (-0.4, 0.4)}

_REQUIRED_COLUMNS = ("T0", "T_w_out", "Q", "cop")
_OPTIONAL_COLUMNS = ("T_dis", "rps")
_TABLES = ("duty", "max_capacity")
#: The request of a ``"max_capacity"`` row, as a multiple of its published capacity.
MAX_REQUEST_FACTOR = 1.5
#: Shortfall of the published duty beyond which a ``"duty"`` row is infeasible.
CAPACITY_SHORT_TOL = 0.01
_SCHEMA = 1


[docs] class CalibrationVersionError(ValueError): """A saved calibration was fitted on other default maps than the library's."""
def _to_z(name: str, value: float) -> float: return math.log(value) if name in _LOG_FACTORS else value / _SHIFT_UNIT[name] def _from_z(name: str, z: float) -> float: return math.exp(z) if name in _LOG_FACTORS else z * _SHIFT_UNIT[name] def _limit_from_z(name: str, z: float, upper: bool) -> float: """An interval limit in factor units; an undefined or unrepresentable limit is unbounded. A weakly constrained factor can give a standard error so large that ``exp`` of the limit overflows, or a NaN from an ill-conditioned covariance. Either is an interval that does not bound the factor, so it is returned as unbounded and the factor is not identified (it contains the identity value). """ if math.isfinite(z): try: return _from_z(name, z) except OverflowError: pass if upper: return math.inf return 0.0 if name in _LOG_FACTORS else -math.inf # ---------------------------------------------------------------- catalogue
[docs] @dataclass(frozen=True) class CataloguePoint: """One catalogue row: outdoor air ``T0`` [°C], leaving water ``T_w_out`` [°C], duty ``Q`` [W], ``cop``. ``T_dis`` [°C] and ``rps`` [rev/s] are NaN when the table does not give them. """ T0: float T_w_out: float Q: float cop: float T_dis: float = math.nan rps: float = math.nan
[docs] @dataclass(frozen=True) class PointOutcome: """What a model gives at one catalogue row; ``feasible`` False carries the ``reason``.""" feasible: bool reason: str = "none" cop: float = math.nan Q: float = math.nan T_dis: float = math.nan rps: float = math.nan pr: float = math.nan T_evap: float = math.nan eta_v: float = math.nan eta_ov: float = math.nan f_loss: float = math.nan Q_cmp_loss: float = math.nan extrapolated: bool = False @property def below_isentropic(self) -> bool: """Discharge enthalpy below the isentropic one: ``f_loss > 1 - eta_ov`` (#275).""" return bool(self.feasible and self.f_loss > 1.0 - self.eta_ov)
[docs] class CatalogueAdapter(Protocol): """How a family of models is solved at a catalogue row (#189: boilers; #193: air-to-air).""" @property def name(self) -> str: """A label recorded with the calibration.""" ...
[docs] def solve(self, model: Any, point: CataloguePoint, table: str) -> PointOutcome: """The model at ``point`` for a table of kind ``table``; never raises for an infeasible point.""" ...
[docs] def f_loss_identifiable(self, points: Sequence[CataloguePoint]) -> bool: """Whether the rows separate ``k_f`` from ``k_ov``.""" ...
def _number(result: Mapping[str, Any], key: str) -> float: try: value = float(result[key]) except (KeyError, TypeError, ValueError): return math.nan return value if math.isfinite(value) else math.nan
[docs] @dataclass(frozen=True) class BoilerCatalogue: """:class:`tmhp.AirSourceHeatPumpBoiler` at an EN 14511 catalogue row (``analyze_steady``). The boundary is the validation harness's and the EnergyPlus plugin's: the water enters the standard's rise below the leaving temperature, at the flow that carries the published duty at that rise. """ name: str = "AirSourceHeatPumpBoiler (EN 14511)"
[docs] def solve(self, model: Any, point: CataloguePoint, table: str) -> PointOutcome: if not (math.isfinite(point.Q) and point.Q > 0): return PointOutcome(False, "invalid_duty") T_entering, m_dot_w = en14511_condenser_water(point.T_w_out, point.Q) request = point.Q * (MAX_REQUEST_FACTOR if table == "max_capacity" else 1.0) try: result = model.analyze_steady( T_tank_w=T_entering, T0=point.T0, Q_ref_tank=request, m_dot_w=m_dot_w, return_dict=True ) except (InvalidCompressorEfficiency, ValueError, ArithmeticError) as exc: return PointOutcome(False, f"error: {type(exc).__name__}") failure = result.get("failure_reason", "none") if failure != "none": return PointOutcome(False, str(failure)) delivered = abs(_number(result, "Q_ref_tank [W]")) cop = _number(result, "cop_sys [-]") if not (math.isfinite(cop) and cop > 0 and math.isfinite(delivered)): return PointOutcome(False, "no_cop") if table == "max_capacity": if result.get("capacity_clamped") != "max": return PointOutcome(False, "no_ceiling_below_request") else: if delivered < point.Q * (1.0 - CAPACITY_SHORT_TOL): return PointOutcome(False, "capacity_short") if result.get("capacity_clamped") == "min": return PointOutcome(False, "cycling_mean") return PointOutcome( True, cop=cop, Q=delivered, T_dis=_number(result, "T_ref_cmp_out [°C]"), rps=_number(result, "cmp_rpm [rpm]") / 60.0, pr=_number(result, "pr_cmp [-]"), T_evap=_number(result, "T_ref_evap_sat [°C]"), eta_v=_number(result, "eta_v [-]"), eta_ov=_number(result, "eta_ov [-]"), f_loss=_number(result, "f_loss [-]"), Q_cmp_loss=_number(result, "Q_cmp_loss [W]"), extrapolated=bool(result.get("efficiency_extrapolated", False)), )
[docs] def f_loss_identifiable(self, points: Sequence[CataloguePoint]) -> bool: return any(math.isfinite(p.T_dis) for p in points)
def _read_points(points: pd.DataFrame, columns: Mapping[str, str] | None) -> list[CataloguePoint]: mapping = {name: name for name in (*_REQUIRED_COLUMNS, *_OPTIONAL_COLUMNS)} if columns: unknown = set(columns) - set(mapping) if unknown: raise ValueError(f"unknown catalogue quantities {sorted(unknown)}; known: {sorted(mapping)}") mapping.update(columns) missing = [q for q in _REQUIRED_COLUMNS if mapping[q] not in points.columns] if missing: raise ValueError(f"the catalogue has no column for {missing} (columns= maps a quantity to a column)") out: list[CataloguePoint] = [] for _, row in points.iterrows(): values = {q: float(row[mapping[q]]) for q in _REQUIRED_COLUMNS} for q in _OPTIONAL_COLUMNS: values[q] = float(row[mapping[q]]) if mapping[q] in points.columns else math.nan if not (math.isfinite(values["cop"]) and values["cop"] > 0): raise ValueError(f"catalogue row {len(out)}: cop must be positive, got {values['cop']!r}") out.append(CataloguePoint(**values)) if not out: raise ValueError("the catalogue has no rows") return out # ---------------------------------------------------------------- evaluation class _Evaluator: """Solves the catalogue rows for a scale; one new model per distinct scale, outcomes cached.""" def __init__( self, make_model: Callable[[CompressorMapScale], Any], adapter: CatalogueAdapter, points: Sequence[CataloguePoint], table: str, discharge_scale_K: float, ) -> None: self.make_model = make_model self.adapter = adapter self.points = list(points) self.table = table self.discharge_scale_K = discharge_scale_K self.use_T_dis = any(math.isfinite(p.T_dis) for p in self.points) self.use_rps = any(math.isfinite(p.rps) for p in self.points) self._models: dict[CompressorMapScale, Any] = {} self._outcomes: dict[tuple[CompressorMapScale, int], PointOutcome] = {} self.cycle_evaluations = 0 @property def candidates(self) -> int: return len(self._models) def outcome(self, scale: CompressorMapScale, i: int) -> PointOutcome: key = (scale, i) hit = self._outcomes.get(key) if hit is not None: return hit model = self._models.get(scale) if model is None: try: model = self.make_model(scale) except (InvalidCompressorEfficiency, ValueError, ArithmeticError) as exc: model = exc # the scaled machine has no rated point: every row infeasible self._models[scale] = model if isinstance(model, Exception): out = PointOutcome(False, f"no_model: {type(model).__name__}") else: self.cycle_evaluations += 1 out = self.adapter.solve(model, self.points[i], self.table) self._outcomes[key] = out return out def row_residuals(self, scale: CompressorMapScale, i: int) -> np.ndarray: p, o = self.points[i], self.outcome(scale, i) parts: list[float] = [] parts.append(math.log(o.cop / p.cop) if o.feasible else FAIL_RESIDUAL) if self.table == "max_capacity": parts.append(math.log(o.Q / p.Q) if o.feasible else FAIL_RESIDUAL) if self.use_T_dis and math.isfinite(p.T_dis): ok = o.feasible and math.isfinite(o.T_dis) parts.append((o.T_dis - p.T_dis) / self.discharge_scale_K if ok else FAIL_RESIDUAL) if self.use_rps and math.isfinite(p.rps): ok = o.feasible and math.isfinite(o.rps) and o.rps > 0 parts.append(math.log(o.rps / p.rps) if ok else FAIL_RESIDUAL) return np.array(parts) def residuals(self, scale: CompressorMapScale, rows: Sequence[int] | np.ndarray) -> np.ndarray: return np.concatenate([self.row_residuals(scale, i) for i in rows]) if len(rows) else np.zeros(0) # ---------------------------------------------------------------- fitting
[docs] @dataclass(frozen=True) class AdoptionRule: """When a stage is adopted (see the module docstring); provisional until #272.""" min_cv_gain: float = 0.10 ci_level: float = 0.95 max_corr: float = 0.95 #: A new factor within this share of its search range (internal units) from a bound rests on it. bound_tol: float = 0.01 n_folds: int = 5 seed: int = 0 #: Residual RMSE at or below which a stage is not improved upon (the catalogue is already met). rmse_floor: float = 1e-4
@dataclass class _Fit: names: tuple[str, ...] scale: CompressorMapScale rmse: float residuals: np.ndarray jac: np.ndarray def _scale_with(base: CompressorMapScale, names: Sequence[str], z: np.ndarray) -> CompressorMapScale: return replace(base, **{n: _from_z(n, float(v)) for n, v in zip(names, z, strict=True)}) def _fit( ev: _Evaluator, names: tuple[str, ...], start: CompressorMapScale, rows: Sequence[int] | np.ndarray, bounds: Mapping[str, tuple[float, float]], extra_starts: Sequence[CompressorMapScale] = (), ) -> _Fit: """Bounded trust-region least squares from ``start`` and any ``extra_starts``; the lowest RMSE wins.""" from scipy.optimize import least_squares lo = np.array([_to_z(n, bounds[n][0]) for n in names]) hi = np.array([_to_z(n, bounds[n][1]) for n in names]) best: _Fit | None = None for s in (start, *extra_starts): z0 = np.clip([_to_z(n, getattr(s, n)) for n in names], lo + 1e-9, hi - 1e-9) def fun(z: np.ndarray, s: CompressorMapScale = s) -> np.ndarray: return ev.residuals(_scale_with(s, names, z), rows) sol = least_squares(fun, z0, bounds=(lo, hi), method="trf", diff_step=0.02, max_nfev=60, xtol=1e-4, ftol=1e-5) scale = _scale_with(s, names, sol.x) r = fun(sol.x) cand = _Fit(names, scale, float(np.sqrt(np.mean(r**2))), r, np.asarray(sol.jac)) if best is None or cand.rmse < best.rmse: best = cand assert best is not None return best def _folds(n: int, k: int, seed: int) -> list[np.ndarray]: k = max(2, min(k, n)) order = np.random.default_rng(seed).permutation(n) return [np.sort(order[i::k]) for i in range(k)] def _cross_validate( ev: _Evaluator, names: tuple[str, ...], full: CompressorMapScale, rows: np.ndarray, rule: AdoptionRule, bounds: Mapping[str, tuple[float, float]], ) -> tuple[float, float]: """K-fold CV of a stage, each fold warm-started from the all-rows optimum: (RMSE of residuals, COP MAPE).""" held: list[np.ndarray] = [] ape: list[float] = [] for test in _folds(len(rows), rule.n_folds, rule.seed): train = np.delete(rows, test) fitted = _fit(ev, names, full, train, bounds).scale held.append(ev.residuals(fitted, rows[test])) for i in rows[test]: o = ev.outcome(fitted, int(i)) ape.append(abs(o.cop / ev.points[i].cop - 1.0) if o.feasible else math.nan) r = np.concatenate(held) return float(np.sqrt(np.mean(r**2))), float(np.nanmean(ape)) if np.isfinite(ape).any() else math.nan def _identification( fit: _Fit, new: Sequence[str], rule: AdoptionRule, bounds: Mapping[str, tuple[float, float]] ) -> dict[str, Any]: """Intervals, largest correlation and bound contacts from the Jacobian at the optimum.""" from scipy.stats import t as student_t J = fit.jac m, p = J.shape dof = max(m - p, 1) s2 = float(fit.residuals @ fit.residuals) / dof out: dict[str, Any] = {"ci": {}, "max_corr": math.nan, "at_bound": [], "ok": False, "reason": ""} try: cov = np.linalg.inv(J.T @ J) * s2 except np.linalg.LinAlgError: out["reason"] = "singular JᵀJ" return out sd = np.sqrt(np.clip(np.diag(cov), 0.0, None)) if not np.all(np.isfinite(sd)): out["reason"] = "non-finite standard error" if p > 1 and np.all(sd > 0): corr = cov / np.outer(sd, sd) out["max_corr"] = float(np.max(np.abs(corr - np.eye(p)))) else: out["max_corr"] = 0.0 if p == 1 else 1.0 q = float(student_t.ppf(0.5 + rule.ci_level / 2.0, dof)) ok = out["max_corr"] <= rule.max_corr for j, n in enumerate(fit.names): z = _to_z(n, getattr(fit.scale, n)) lo, hi = _limit_from_z(n, z - q * sd[j], upper=False), _limit_from_z(n, z + q * sd[j], upper=True) out["ci"][n] = (lo, hi) if n in new: ok &= not (lo <= _IDENTITY[n] <= hi) zlo, zhi = _to_z(n, bounds[n][0]), _to_z(n, bounds[n][1]) if min(z - zlo, zhi - z) <= rule.bound_tol * (zhi - zlo): out["at_bound"].append(n) ok &= not out["at_bound"] out["ok"] = bool(ok) return out # ---------------------------------------------------------------- results
[docs] @dataclass(frozen=True) class FactorEstimate: """One factor: the ``value`` the calibrated model uses and how it was reached. ``status``: ``"adopted"`` (free in the adopted stage), ``"not_adopted"`` (fitted in a stage that was not adopted; the model keeps its identity) or ``"unidentified"`` (the table cannot locate it; never fitted). ``estimate`` and ``ci`` are from the last stage that fitted it, or None. """ value: float status: str estimate: float | None = None ci: tuple[float, float] | None = None stage: str | None = None at_bound: bool = False
[docs] @dataclass(frozen=True) class StageRecord: """One fitted stage: free factors, fitted scale, scores and the adoption decision.""" label: str free: tuple[str, ...] scale: dict[str, float] rmse_fit: float mape_fit: float rmse_cv: float | None mape_cv: float | None cv_gain: float | None max_corr: float | None ci: dict[str, tuple[float, float]] at_bound: tuple[str, ...] infeasible_rows: int adopted: bool reason: str
def _mape(ev: _Evaluator, scale: CompressorMapScale, rows: Sequence[int] | np.ndarray) -> float: ape = [abs(ev.outcome(scale, i).cop / ev.points[i].cop - 1.0) for i in rows if ev.outcome(scale, i).feasible] return float(np.mean(ape)) if ape else math.nan
[docs] @dataclass class CompressorCalibration: """The result of :func:`calibrate_compressor`. :attr:`scale` is what a model takes (``compressor_scale=cal.scale``). :attr:`points` has one row per catalogue row: the catalogue values, the default model's (``*_default``) and the calibrated model's (``*_cal``) predictions, whether each solved, and the diagnostics (``below_isentropic``, ``Q_cmp_loss``, ``extrapolated``) at the calibrated scale. ``excluded`` lists the rows left out before the fit (the default model cannot solve them) with the reason. """ scale: CompressorMapScale factors: dict[str, FactorEstimate] stages: list[StageRecord] points: pd.DataFrame excluded: list[dict[str, Any]] table: str adapter: str rule: AdoptionRule coefficient_version: str = COEFFICIENT_VERSION trace: dict[str, int] = field(default_factory=dict) @property def adopted_stage(self) -> str: """Label of the last adopted stage (``"default"`` when none was).""" adopted = [s.label for s in self.stages if s.adopted] return adopted[-1] if adopted else "default"
[docs] def stage_scores(self): """The stages as :class:`tmhp.compressor_plots.StageScore` (the default maps first).""" from .compressor_plots import StageScore return [ StageScore(s.label, s.rmse_fit, s.mape_fit, s.rmse_cv, s.mape_cv, s.adopted) for s in self.stages if math.isfinite(s.rmse_fit) ]
[docs] def plot_stages(self, *, title: str | None = None): """:func:`tmhp.compressor_plots.plot_calibration_stages` of this calibration.""" from .compressor_plots import plot_calibration_stages return plot_calibration_stages(self.stage_scores(), title=title)
[docs] def plot_parity(self, *, title: str | None = None): """:func:`tmhp.compressor_plots.plot_cop_parity`: default maps against the calibrated scale.""" from .compressor_plots import plot_cop_parity df = self.points[self.points["fitted"]] return plot_cop_parity(df["cop"], df["cop_default"], df["cop_cal"], title=title)
[docs] def plot_map(self, quantity: str = "eta_ov", **kwargs): """:func:`tmhp.compressor_plots.plot_compressor_map`: the default maps before, :attr:`scale` after.""" from .compressor_plots import plot_compressor_map return plot_compressor_map(None, self.scale, quantity=quantity, **kwargs)
[docs] def to_dict(self) -> dict[str, Any]: """A JSON-safe record (NaN as None); :meth:`from_dict` reads it back.""" def clean(o: Any) -> Any: if isinstance(o, dict): return {str(k): clean(v) for k, v in o.items()} if isinstance(o, (list, tuple)): return [clean(v) for v in o] if isinstance(o, (bool, np.bool_)): return bool(o) if isinstance(o, (int, np.integer)): return int(o) if isinstance(o, (float, np.floating)): return float(o) if math.isfinite(float(o)) else None return o record: dict[str, Any] = clean( { "schema": _SCHEMA, "coefficient_version": self.coefficient_version, "table": self.table, "adapter": self.adapter, "rule": asdict(self.rule), "scale": self.scale.as_dict(), "factors": {k: asdict(v) for k, v in self.factors.items()}, "stages": [asdict(s) for s in self.stages], "points": self.points.to_dict(orient="list"), "excluded": self.excluded, "trace": self.trace, } ) return record
[docs] @classmethod def from_dict(cls, data: Mapping[str, Any]) -> CompressorCalibration: """Read :meth:`to_dict` back; :class:`CalibrationVersionError` if the default maps have changed since. The factors scale one set of default maps: on other maps the same numbers describe another machine, so a record of other maps is refused rather than applied. """ version = data.get("coefficient_version") if version != COEFFICIENT_VERSION: raise CalibrationVersionError( f"calibration fitted on the default maps {version!r}; the library's are {COEFFICIENT_VERSION!r}. " "Fit the catalogue again." ) if data.get("schema") != _SCHEMA: raise ValueError(f"unknown calibration record schema {data.get('schema')!r}") def num(v: Any) -> float: return math.nan if v is None else float(v) def opt(v: Any) -> float | None: return None if v is None else float(v) factors = {} for k, v in data["factors"].items(): ci = v.get("ci") factors[k] = FactorEstimate( value=float(v["value"]), status=v["status"], estimate=opt(v.get("estimate")), ci=None if ci is None else (num(ci[0]), num(ci[1])), stage=v.get("stage"), at_bound=bool(v.get("at_bound", False)), ) stages = [ StageRecord( label=s["label"], free=tuple(s["free"]), scale={k: float(v) for k, v in s["scale"].items()}, rmse_fit=num(s["rmse_fit"]), mape_fit=num(s["mape_fit"]), rmse_cv=opt(s["rmse_cv"]), mape_cv=opt(s["mape_cv"]), cv_gain=opt(s["cv_gain"]), max_corr=opt(s["max_corr"]), ci={k: (num(c[0]), num(c[1])) for k, c in s["ci"].items()}, at_bound=tuple(s["at_bound"]), infeasible_rows=int(s["infeasible_rows"]), adopted=bool(s["adopted"]), reason=s["reason"], ) for s in data["stages"] ] points = pd.DataFrame({k: [np.nan if v is None else v for v in col] for k, col in data["points"].items()}) return cls( scale=CompressorMapScale(**data["scale"]), factors=factors, stages=stages, points=points, excluded=list(data["excluded"]), table=data["table"], adapter=data["adapter"], rule=AdoptionRule(**data["rule"]), coefficient_version=version, trace=dict(data.get("trace", {})), )
# ---------------------------------------------------------------- driver
[docs] def calibrate_compressor( make_model: Callable[[CompressorMapScale], Any], points: pd.DataFrame, *, columns: Mapping[str, str] | None = None, table: str = "duty", adapter: CatalogueAdapter | None = None, stages: Sequence[tuple[str, Sequence[str]]] = DEFAULT_STAGES, rule: AdoptionRule | None = None, bounds: Mapping[str, tuple[float, float]] | None = None, discharge_scale_K: float = 50.0, ) -> CompressorCalibration: """Fit the scale factors of the default compressor maps to a catalogue (see the module docstring). Parameters ---------- make_model ``make_model(scale)`` builds a NEW model with ``compressor_scale=scale`` (called once per candidate scale; a model is never changed in place). points The catalogue, one row per operating point. columns Maps the quantities ``T0``, ``T_w_out``, ``Q``, ``cop`` (required) and ``T_dis``, ``rps`` (optional) to column names of ``points``; a quantity not mapped is read from the column of its own name. table ``"duty"`` or ``"max_capacity"``. adapter How a row is solved; :class:`BoilerCatalogue` by default. stages ``(label, factors)`` pairs, nested; :data:`DEFAULT_STAGES`. rule :class:`AdoptionRule`; the provisional default until #272. bounds Search bounds per factor, over :data:`DEFAULT_BOUNDS`. discharge_scale_K A discharge-temperature error of this many kelvin weighs like a COP off by a factor e (50 K: 1 K weighs like 2 % of COP). """ if table not in _TABLES: raise ValueError(f"table must be one of {_TABLES}, got {table!r}") if not (math.isfinite(discharge_scale_K) and discharge_scale_K > 0): raise ValueError(f"discharge_scale_K must be positive, got {discharge_scale_K!r}") rule = rule or AdoptionRule() solver: CatalogueAdapter = adapter if adapter is not None else BoilerCatalogue() all_bounds = dict(DEFAULT_BOUNDS) if bounds: unknown = set(bounds) - set(FACTORS) if unknown: raise ValueError(f"unknown factors in bounds: {sorted(unknown)}") all_bounds.update(bounds) for name, (lo, hi) in all_bounds.items(): if not lo < _IDENTITY[name] < hi: raise ValueError(f"the bounds of {name} must enclose its identity {_IDENTITY[name]}, got {(lo, hi)}") stage_list = [(label, tuple(names)) for label, names in stages] for label, names in stage_list: unknown = set(names) - set(FACTORS) if unknown: raise ValueError(f"stage {label}: unknown factors {sorted(unknown)}") rows = _read_points(points, columns) with warnings.catch_warnings(): # the search visits many machines at their limits; each candidate's rows record their own state warnings.simplefilter("ignore", OperatingLimitWarning) return _calibrate(make_model, rows, table, solver, stage_list, rule, all_bounds, discharge_scale_K)
def _calibrate( make_model: Callable[[CompressorMapScale], Any], rows: list[CataloguePoint], table: str, adapter: CatalogueAdapter, stage_list: list[tuple[str, tuple[str, ...]]], rule: AdoptionRule, all_bounds: dict[str, tuple[float, float]], discharge_scale_K: float, ) -> CompressorCalibration: ev = _Evaluator(make_model, adapter, rows, table, discharge_scale_K) identity = CompressorMapScale() identifiable = {"k_ov", "delta_N", "w_N", "delta_r", "w_r"} if table == "max_capacity" or ev.use_rps: identifiable.add("k_v") if adapter.f_loss_identifiable(rows): identifiable.add("k_f") base = [ev.outcome(identity, i) for i in range(len(rows))] fitted_rows = np.array([i for i, o in enumerate(base) if o.feasible], dtype=int) excluded = [{"row": i, "reason": o.reason} for i, o in enumerate(base) if not o.feasible] records: list[StageRecord] = [] r0 = ev.residuals(identity, fitted_rows) rmse0 = float(np.sqrt(np.mean(r0**2))) if r0.size else math.nan mape0 = _mape(ev, identity, fitted_rows) records.append( StageRecord( "default", (), identity.as_dict(), rmse0, mape0, rmse0, mape0, None, None, {}, (), 0, True, "default maps" ) ) last_cv: float = rmse0 last_scale: CompressorMapScale = identity last_names: tuple[str, ...] = () stopped = False dropped: set[str] = set() seen: set[tuple[str, ...]] = set() fitted_by: dict[str, tuple[str, float, tuple[float, float] | None, bool]] = {} if len(fitted_rows) >= 2: for label, wanted in stage_list: names = tuple(n for n in wanted if n in identifiable and n not in dropped) if not names or names in seen: continue seen.add(names) new = tuple(n for n in names if n not in last_names) starts = [replace(last_scale, **{n: v}) for n in new if n in _SHIFT_STARTS for v in _SHIFT_STARTS[n]] fit = _fit(ev, names, last_scale, fitted_rows, all_bounds, starts) ident = _identification(fit, new, rule, all_bounds) if stopped: cv, cv_mape = None, None else: cv, cv_mape = _cross_validate(ev, names, fit.scale, fitted_rows, rule, all_bounds) gain = (last_cv - cv) / last_cv if (cv is not None and last_cv > 0) else None met = last_cv <= rule.rmse_floor adopted = (not stopped) and not met and gain is not None and gain >= rule.min_cv_gain and ident["ok"] if stopped: reason = "after a rejected stage (fitted for the record)" elif met: reason = f"the last adopted stage already meets the catalogue (CV RMSE {last_cv:.1e} <= {rule.rmse_floor:.0e})" elif gain is None or gain < rule.min_cv_gain: reason = f"CV gain {gain if gain is not None else math.nan:+.1%} < {rule.min_cv_gain:.0%}" elif not ident["ok"]: reason = ( f"not identified: {ident['reason'] or ''} at bound {ident['at_bound']}, " f"max |rho| {ident['max_corr']:.2f}, intervals {ident['ci']}" ) else: reason = "adopted" infeasible = sum(not ev.outcome(fit.scale, int(i)).feasible for i in fitted_rows) records.append( StageRecord( label, names, fit.scale.as_dict(), fit.rmse, _mape(ev, fit.scale, fitted_rows), cv, cv_mape, gain, ident["max_corr"], {k: (float(a), float(b)) for k, (a, b) in ident["ci"].items()}, tuple(ident["at_bound"]), infeasible, adopted, reason, ) ) for n in names: # adopted factors report their adopted stage; the others the stage that first tried them if adopted or n not in fitted_by: ci = ident["ci"].get(n) fitted_by[n] = ( label, float(getattr(fit.scale, n)), None if ci is None else (float(ci[0]), float(ci[1])), n in ident["at_bound"], ) if adopted: assert cv is not None last_cv, last_scale, last_names = cv, fit.scale, names elif not stopped and set(new) and set(new) <= _OPTIONAL: dropped |= set(new) records[-1] = replace(records[-1], reason=records[-1].reason + f"; {', '.join(new)} fixed at identity") elif not stopped and set(new) <= _LEVEL: # a level stage that fails is refitted with more level factors in the next stage records[-1] = replace(records[-1], reason=records[-1].reason + "; the next stage refits the levels") else: stopped = True factors: dict[str, FactorEstimate] = {} for n in FACTORS: value = getattr(last_scale, n) if n not in identifiable: factors[n] = FactorEstimate(value, "unidentified") continue status = "adopted" if n in last_names else "not_adopted" rec = fitted_by.get(n) if rec is None: factors[n] = FactorEstimate(value, status) else: factors[n] = FactorEstimate(value, status, rec[1], rec[2], rec[0], rec[3]) frame = [] for i, p in enumerate(rows): d, c = base[i], ev.outcome(last_scale, i) frame.append( { "row": i, "T0": p.T0, "T_w_out": p.T_w_out, "Q": p.Q, "cop": p.cop, "T_dis": p.T_dis, "rps": p.rps, "fitted": bool(d.feasible), "feasible_default": d.feasible, "reason_default": d.reason, "cop_default": d.cop, "Q_default": d.Q, "T_dis_default": d.T_dis, "rps_default": d.rps, "feasible_cal": c.feasible, "reason_cal": c.reason, "cop_cal": c.cop, "Q_cal": c.Q, "T_dis_cal": c.T_dis, "rps_cal": c.rps, "pr_cal": c.pr, "T_evap_cal": c.T_evap, "eta_v_cal": c.eta_v, "eta_ov_cal": c.eta_ov, "f_loss_cal": c.f_loss, "Q_cmp_loss_cal": c.Q_cmp_loss, "below_isentropic": c.below_isentropic, "extrapolated": c.extrapolated, } ) return CompressorCalibration( scale=last_scale, factors=factors, stages=records, points=pd.DataFrame(frame), excluded=excluded, table=table, adapter=adapter.name, rule=rule, trace={"candidates": ev.candidates, "cycle_evaluations": ev.cycle_evaluations}, )