feat(devices): add inverter profiles

An inverter profile describes the technical data of an inverter model: its
nominal AC power, the DC→AC and AC→DC efficiency curves over the load
fraction (AC power relative to the nominal power), the AC charge power
limit of the model, whether that limit also limits PV charging, and an
optional power derating over the ambient temperature. Curves are read
linearly and clamped at their ends, so every lookup yields a value. The
packaged profile generic-hybrid has typical hybrid inverter efficiencies,
no nominal power (the inverter device has to provide it) and full power up
to 45 degC.

Inverter settings name their profile (inverter_profile, default
generic-hybrid) and hold the differences of the unit in profile_adjustment:
nominal_power_w (replaces the profile value, required for a generic
profile), max_power_w and max_ac_charge_power_w (installation limits that
can only lower; an AC charge limit of 0 disables AC charging). The
effective parameters are resolved at the ambient temperature of the
inverter, given by the new measurement key <device_id>-temperature-degc
(45 degC without a fresh value); the power derating lowers the maximum
power and the AC charge limit.

Optimization parameters are always valid: the GENETIC and GENETIC0
parameter preparation resolve the inverter with
resolve_current_operating_parameters_or_defaults, which never raises. An
unusable profile gives the generic-hybrid profile, a missing nominal power
the fallback of 10000 W, an inverter derated to zero power the parameters
at 45 degC, and no usable profile at all the profile adjustment with
constant efficiency; each is logged as error. The GENETIC inverter takes
the AC→DC efficiency curve of the profile, solved exactly on each linear
piece of the curve (about 2 % longer runs); GENETIC0 keeps constant
efficiencies and no longer replaces the configured inverters with the demo
inverter; a battery, electric vehicle or inverter that cannot be prepared
is left out of the GENETIC0 run, never replaced by a demo device.

Configurations migrate: max_power_w becomes
profile_adjustment.nominal_power_w, max_ac_charge_power_w moves into the
adjustment, an ac_to_dc_efficiency of 0 keeps AC charging disabled, and
the efficiency fields are dropped with an error log, as for batteries, so
the profile efficiencies apply. Home Assistant config paths follow.

Additional changes
- Move the curve algorithms of the battery profile into profilecurve, so
  battery and inverter profiles share them; the battery profile keeps its
  document format and classes.
- Move ProfileBaseModel, the strict base of profile documents, into
  profilestore.
- Serve inverter profiles through the profile REST API. Refuse to delete a
  profile that a configured device uses and that has no packaged profile
  to revert to (409).
- Share the measurement access of the device settings in
  devicemeasurement.
- Rename check_battery_profiles to check_device_profiles; the device
  profile check at configuration setup covers inverters, too.
- Document inverter profiles, their configuration, defaults and sharing;
  regenerate the configuration and OpenAPI documentation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Bobby Noelte
2026-11-11 22:08:18 +01:00
co-authored by Claude Opus 5.5
parent e255f987bf
commit faf37abfe7
45 changed files with 3235 additions and 784 deletions
@@ -2,7 +2,7 @@
Measurement access is asynchronous (``DataSequence.key_to_value``), so it is
kept out of the battery settings model and out of the parameter resolution.
``get_measured_value`` is the only place that talks to the measurement
``get_measured_value`` (from ``devicemeasurement``) talks to the measurement
subsystem; ``measure_operating_point`` turns the measured values of one battery
into a ``BatteryOperatingPoint``.
"""
@@ -10,46 +10,25 @@ into a ``BatteryOperatingPoint``.
import math
from typing import TYPE_CHECKING, Optional
from loguru import logger
from akkudoktoreos.devices.settings.batteryresolution import (
BATTERY_DEFAULT_SOC_FACTOR,
BATTERY_DEFAULT_TEMPERATURE_DEGC,
BatteryOperatingPoint,
)
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime, to_duration
from akkudoktoreos.devices.settings.devicemeasurement import (
DEVICE_MEASUREMENT_MAX_AGE,
)
from akkudoktoreos.devices.settings.devicemeasurement import (
get_measured_value as get_measured_value,
)
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
if TYPE_CHECKING:
from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettings
# Maximum age of a measurement that is still taken as "current".
BATTERY_MEASUREMENT_MAX_AGE: str = "1 hour"
async def get_measured_value(key: str, target_datetime: DateTime) -> Optional[float]:
"""Return the measured value for a measurement key nearest to a datetime.
Args:
key: Measurement key.
target_datetime: Datetime the value is looked up for.
Returns:
The value nearest to target_datetime within BATTERY_MEASUREMENT_MAX_AGE,
or None if there is no such value or the measurement cannot be queried.
"""
try:
from akkudoktoreos.core.coreabc import get_measurement
value = await get_measurement().key_to_value(
key=key,
target_datetime=target_datetime,
time_window=to_duration(BATTERY_MEASUREMENT_MAX_AGE),
)
return None if value is None else float(value)
except Exception as exc: # a missing measurement falls back to the defaults
logger.warning(f"Battery measurement '{key}' not available: {exc}")
return None
BATTERY_MEASUREMENT_MAX_AGE: str = DEVICE_MEASUREMENT_MAX_AGE
def _soc_factor_or_default(value: Optional[float]) -> float:
@@ -690,6 +690,12 @@ class BatteriesCommonSettings(DevicesBaseSettings):
operating_point = await self.measure_operating_point(target_datetime)
return self.resolve_operating_parameters_or_defaults(operating_point, report)
def uses_profile(self, kind: str, name: str) -> bool:
"""Return whether this battery uses the profile of the given kind and name."""
from akkudoktoreos.devices.profile.batteryprofile import BatteryProfileSettings
return kind == BatteryProfileSettings.profile_kind and name == self.battery_profile
def check_profile(self) -> tuple[list[str], list[str]]:
"""Check that the battery can be resolved from its profile and adjustment.
@@ -0,0 +1,42 @@
"""Reading device measurements for the device settings.
Measurement access is asynchronous (``DataSequence.key_to_value``), so it is
kept out of the device settings models and out of the parameter resolution.
``get_measured_value`` is the only place where device settings talk to the
measurement subsystem; the device specific modules (e.g. ``batterymeasurement``,
``invertermeasurement``) turn the measured values into operating points.
"""
from typing import Optional
from loguru import logger
from akkudoktoreos.utils.datetimeutil import DateTime, to_duration
# Maximum age of a measurement that is still taken as "current".
DEVICE_MEASUREMENT_MAX_AGE: str = "1 hour"
async def get_measured_value(key: str, target_datetime: DateTime) -> Optional[float]:
"""Return the measured value for a measurement key nearest to a datetime.
Args:
key: Measurement key.
target_datetime: Datetime the value is looked up for.
Returns:
The value nearest to target_datetime within DEVICE_MEASUREMENT_MAX_AGE,
or None if there is no such value or the measurement cannot be queried.
"""
try:
from akkudoktoreos.core.coreabc import get_measurement
value = await get_measurement().key_to_value(
key=key,
target_datetime=target_datetime,
time_window=to_duration(DEVICE_MEASUREMENT_MAX_AGE),
)
return None if value is None else float(value)
except Exception as exc: # a missing measurement falls back to the defaults
logger.warning(f"Device measurement '{key}' not available: {exc}")
return None
@@ -0,0 +1,49 @@
"""Reading the inverter operating point from measurements.
``measure_operating_point`` turns the measured ambient temperature of one
inverter into an ``InverterOperatingPoint``. ``get_measured_value`` (from
``devicemeasurement``) talks to the measurement subsystem.
"""
import math
from typing import TYPE_CHECKING, Optional
from akkudoktoreos.devices.settings.devicemeasurement import (
get_measured_value as get_measured_value,
)
from akkudoktoreos.devices.settings.inverterresolution import (
INVERTER_DEFAULT_TEMPERATURE_DEGC,
InverterOperatingPoint,
)
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
if TYPE_CHECKING:
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
def _temperature_or_default(value: Optional[float]) -> float:
"""Return a measured ambient temperature [degC], or the default."""
if value is None or not math.isfinite(value):
return INVERTER_DEFAULT_TEMPERATURE_DEGC
return value
async def measure_operating_point(
settings: "InverterCommonSettings", target_datetime: Optional[DateTime] = None
) -> InverterOperatingPoint:
"""Read the current operating point of an inverter from its measurements.
A missing, stale, non-finite or unavailable temperature measurement falls back
to ``INVERTER_DEFAULT_TEMPERATURE_DEGC`` (45 degC). This function never raises
for missing measurements.
Args:
settings: Inverter device settings, providing the measurement key.
target_datetime: Datetime the measurement is looked up for, now if None.
Returns:
The measured operating point.
"""
target = to_datetime(target_datetime) if target_datetime is not None else to_datetime()
temperature = await get_measured_value(settings.measurement_key_temperature_degc, target)
return InverterOperatingPoint(temperature_degC=_temperature_or_default(temperature))
@@ -0,0 +1,284 @@
"""Resolution of the effective inverter parameters.
Every effective inverter parameter (nominal and maximum power, AC charge power
limit, efficiencies) comes from exactly two sources:
- the compiled inverter profile (``InverterProfile``): efficiency curves over the
load fraction, the AC charge power limit of the model, the power derating over
the ambient temperature and, unless it is a generic profile, the nominal power,
- the inverter device settings (``InverterCommonSettings``): the
``profile_adjustment`` of this unit (nominal power, installation limits).
The profile is evaluated at an operating point (``InverterOperatingPoint``), the
ambient temperature of the inverter. Without a temperature measurement it is
``INVERTER_DEFAULT_TEMPERATURE_DEGC`` (45 degC). If the parameters cannot be
resolved, an ``InverterResolutionError`` names the inverter and the reason.
The parameter preparation of the optimizations never fails: it falls back to
defaults (``INVERTER_FALLBACK_*``) and reports them, see
``InverterCommonSettings.resolve_operating_parameters_or_defaults``.
The functions here are pure: they neither load profiles nor read measurements.
"""
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from akkudoktoreos.devices.profile.inverterprofile import InverterProfile
from akkudoktoreos.devices.profile.profilecurve import PrecomputedCurve
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
# Ambient temperature of the inverter assumed when no measurement is available.
INVERTER_DEFAULT_TEMPERATURE_DEGC: float = 45.0
# Values for the optimization if the configuration does not allow to resolve
# them: the example power and the default efficiency of the former settings.
INVERTER_FALLBACK_NOMINAL_POWER_W: float = 10000.0
INVERTER_FALLBACK_EFFICIENCY: float = 1.0
class InverterResolutionError(ValueError):
"""The effective parameters of an inverter cannot be resolved.
The message names the inverter and the reason.
"""
@dataclass(frozen=True)
class InverterOperatingPoint:
"""Conditions the inverter profile is evaluated at.
Attributes:
temperature_degC: Ambient temperature of the inverter [degC].
"""
temperature_degC: float = INVERTER_DEFAULT_TEMPERATURE_DEGC
@dataclass(frozen=True)
class InverterOperatingParameters:
"""Consistent snapshot of the effective inverter parameters.
All values belong to the same operating point.
Attributes:
temperature_degC: Ambient temperature the profile was evaluated at.
nominal_power_w: Effective nominal AC power [W]: profile adjustment, else
profile.
power_fraction: Derating of the nominal power at the temperature
[0.0 ... 1.0].
max_power_w: Effective maximum AC power [W]: the derated nominal power,
capped by the installation limit of the profile adjustment.
max_ac_charge_power_w: Effective AC charge power limit [W]: the smallest
of the maximum power, the derated limit of the model and the
installation limit. 0 disables AC charging.
ac_charge_limits_total_charge: Whether the AC charge power limit also
limits PV charging of the battery.
dc_to_ac_efficiency_curve: DC→AC efficiency over the load fraction of
``max_power_w`` as ``(load_fraction, efficiency)`` points within
[0, 1].
ac_to_dc_efficiency_curve: AC→DC efficiency over the load fraction of
``max_power_w`` as ``(load_fraction, efficiency)`` points within
[0, 1].
dc_to_ac_efficiency: DC→AC efficiency at the reference load fraction of
the settings.
ac_to_dc_efficiency: AC→DC efficiency at the AC charge power limit (at
the maximum power if AC charging is disabled).
"""
temperature_degC: float
nominal_power_w: float
power_fraction: float
max_power_w: float
max_ac_charge_power_w: float
ac_charge_limits_total_charge: bool
dc_to_ac_efficiency_curve: tuple[tuple[float, float], ...]
ac_to_dc_efficiency_curve: tuple[tuple[float, float], ...]
dc_to_ac_efficiency: float
ac_to_dc_efficiency: float
def _resolution_error(settings: "InverterCommonSettings", reason: str) -> InverterResolutionError:
"""Return an error naming the inverter."""
return InverterResolutionError(f"Inverter '{settings.device_id}': {reason}")
def _curve_over_max_power(
curve: "PrecomputedCurve", scale: float
) -> tuple[tuple[float, float], ...]:
"""Return a profile efficiency curve over the load fraction of the maximum power.
The profile curve is over the load fraction of the nominal power; ``scale``
is nominal power / maximum power (>= 1). Loads above the maximum power cannot
occur, so the curve ends at load fraction 1.0 with the value there. It always
has at least two points within [0, 1].
Args:
curve: Profile curve over the load fraction of the nominal power.
scale: Nominal power divided by maximum power.
Returns:
The ``(load_fraction, efficiency)`` points.
"""
points = [(x * scale, y) for x, y in zip(curve.x, curve.y) if x * scale < 1.0]
end_value = curve.lookup(1.0 / scale)
points.append((1.0, end_value if end_value is not None else curve.y[-1]))
if len(points) < 2:
points.insert(0, (0.0, curve.y[0]))
return tuple(points)
def resolve_nominal_power_w(
settings: "InverterCommonSettings", profile: "InverterProfile"
) -> float:
"""Resolve the nominal AC power [W]: profile adjustment, else profile.
Raises:
InverterResolutionError: If neither the profile adjustment nor the
profile provides a nominal power (a generic profile without
adjustment).
"""
adjusted_w = settings.profile_adjustment.nominal_power_w
if adjusted_w is not None:
return adjusted_w
if profile.nominal_power_w is not None:
return profile.nominal_power_w
raise _resolution_error(
settings,
f"inverter profile '{settings.inverter_profile}' is generic and provides no "
"nominal power; set 'profile_adjustment.nominal_power_w'.",
)
def resolve_inverter_parameters(
settings: "InverterCommonSettings",
profile: "InverterProfile",
operating_point: InverterOperatingPoint,
) -> InverterOperatingParameters:
"""Resolve the effective inverter parameters at an operating point.
Args:
settings: Inverter device settings.
profile: Compiled inverter profile.
operating_point: Conditions to evaluate the profile at.
Returns:
The effective parameters.
Raises:
InverterResolutionError: If the nominal power cannot be resolved or the
inverter is derated to zero power at the operating point.
"""
adjustment = settings.profile_adjustment
nominal_power_w = resolve_nominal_power_w(settings, profile)
power_fraction = profile.power_fraction_at(operating_point.temperature_degC)
max_power_w = nominal_power_w * power_fraction
if adjustment.max_power_w is not None:
max_power_w = min(max_power_w, adjustment.max_power_w)
if max_power_w <= 0.0:
raise _resolution_error(
settings,
f"inverter profile '{settings.inverter_profile}' allows no power at "
f"{operating_point.temperature_degC} degC.",
)
max_ac_charge_power_w = max_power_w
if profile.max_ac_charge_power_w is not None:
max_ac_charge_power_w = min(
max_ac_charge_power_w, profile.max_ac_charge_power_w * power_fraction
)
if adjustment.max_ac_charge_power_w is not None:
max_ac_charge_power_w = min(max_ac_charge_power_w, adjustment.max_ac_charge_power_w)
# The profile curves are over the load fraction of the nominal power, the
# optimizers read them over the load fraction of the maximum power.
scale = nominal_power_w / max_power_w
dc_to_ac_curve = _curve_over_max_power(profile.dc_to_ac_efficiency, scale)
ac_to_dc_curve = _curve_over_max_power(profile.ac_to_dc_efficiency, scale)
reference_power_w = settings.dc_to_ac_efficiency_reference_load_fraction * max_power_w
ac_charge_power_w = max_ac_charge_power_w if max_ac_charge_power_w > 0.0 else max_power_w
return InverterOperatingParameters(
temperature_degC=operating_point.temperature_degC,
nominal_power_w=nominal_power_w,
power_fraction=power_fraction,
max_power_w=max_power_w,
max_ac_charge_power_w=max_ac_charge_power_w,
ac_charge_limits_total_charge=profile.ac_charge_limits_total_charge,
dc_to_ac_efficiency_curve=dc_to_ac_curve,
ac_to_dc_efficiency_curve=ac_to_dc_curve,
dc_to_ac_efficiency=profile.dc_to_ac_efficiency_at(reference_power_w / nominal_power_w),
ac_to_dc_efficiency=profile.ac_to_dc_efficiency_at(ac_charge_power_w / nominal_power_w),
)
def resolve_inverter_parameters_without_profile(
settings: "InverterCommonSettings", operating_point: InverterOperatingPoint
) -> tuple[InverterOperatingParameters, list[str]]:
"""Resolve the parameters from the profile adjustment and the fallback values.
Used if no inverter profile can be used. Never raises.
Args:
settings: Inverter device settings.
operating_point: Operating point the parameters are for.
Returns:
``(parameters, defaults)``: the parameters and descriptions of the
fallback values used, for the error log.
"""
adjustment = settings.profile_adjustment
defaults: list[str] = []
nominal_power_w = adjustment.nominal_power_w
if nominal_power_w is None:
nominal_power_w = INVERTER_FALLBACK_NOMINAL_POWER_W
defaults.append(f"nominal power {nominal_power_w:g} W")
max_power_w = nominal_power_w
if adjustment.max_power_w is not None:
max_power_w = min(max_power_w, adjustment.max_power_w)
max_ac_charge_power_w = max_power_w
if adjustment.max_ac_charge_power_w is not None:
max_ac_charge_power_w = min(max_ac_charge_power_w, adjustment.max_ac_charge_power_w)
efficiency = INVERTER_FALLBACK_EFFICIENCY
defaults.append(f"constant efficiency {efficiency:g}")
flat = ((0.0, efficiency), (1.0, efficiency))
parameters = InverterOperatingParameters(
temperature_degC=operating_point.temperature_degC,
nominal_power_w=nominal_power_w,
power_fraction=1.0,
max_power_w=max_power_w,
max_ac_charge_power_w=max_ac_charge_power_w,
ac_charge_limits_total_charge=False,
dc_to_ac_efficiency_curve=flat,
ac_to_dc_efficiency_curve=flat,
dc_to_ac_efficiency=efficiency,
ac_to_dc_efficiency=efficiency,
)
return parameters, defaults
def check_inverter_adjustment(
settings: "InverterCommonSettings", parameters: InverterOperatingParameters
) -> list[str]:
"""Return warnings for installation limits of the adjustment that have no effect.
Args:
settings: Inverter device settings.
parameters: Resolved parameters; only the nominal power is used.
Returns:
One warning per installation limit above the nominal power.
"""
warnings: list[str] = []
adjustment = settings.profile_adjustment
for name, limit_w in (
("max_power_w", adjustment.max_power_w),
("max_ac_charge_power_w", adjustment.max_ac_charge_power_w),
):
if limit_w is not None and limit_w > parameters.nominal_power_w:
warnings.append(
f"Inverter '{settings.device_id}': 'profile_adjustment.{name}' {limit_w} W is "
f"above the nominal power {parameters.nominal_power_w} W and has no effect."
)
return warnings
@@ -1,20 +1,105 @@
"""Inverter device settings."""
"""Inverter device settings.
The technical inverter data (nominal power, efficiency curves, AC charge power
limit of the model, power derating) comes from an inverter profile (see
``InverterProfileSettings``). The user selects the profile by name via
``inverter_profile`` (default ``generic-hybrid``) and describes how the
installed unit differs from it in ``profile_adjustment``.
``InverterCommonSettings`` holds the configuration fields, their validation and
the measurement keys. The other concerns live in their own modules:
- ``profilestore``: loading (and caching) the compiled inverter profile.
- ``invertermeasurement``: reading the ambient temperature from the
measurements.
- ``inverterresolution``: resolving the effective parameters from profile,
profile adjustment and operating point (pure functions).
The computed ``effective_*`` fields are evaluated at the reference operating
point (``InverterOperatingPoint()``: 45 degC ambient temperature). They never
raise; they are None if the inverter cannot be resolved.
"""
from typing import TYPE_CHECKING, Optional
from pydantic import Field, computed_field, field_validator, model_validator
from loguru import logger
from pydantic import Field, computed_field, model_validator
from akkudoktoreos.config.configabc import ConfigScope
from akkudoktoreos.devices.devicesabc import validate_efficiency_curve
from akkudoktoreos.config.configabc import ConfigScope, SettingsBaseModel
from akkudoktoreos.devices.settings import invertermeasurement
from akkudoktoreos.devices.settings.devicebasesettings import (
DevicesBaseSettings,
)
from akkudoktoreos.devices.settings.inverterresolution import (
INVERTER_FALLBACK_NOMINAL_POWER_W,
InverterOperatingParameters,
InverterOperatingPoint,
InverterResolutionError,
check_inverter_adjustment,
resolve_inverter_parameters,
resolve_inverter_parameters_without_profile,
resolve_nominal_power_w,
)
from akkudoktoreos.utils.datetimeutil import DateTime
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic0.genetic0inverter import (
Genetic0InverterParameters,
)
from akkudoktoreos.devices.genetic.inverter import InverterParameters
from akkudoktoreos.devices.profile.inverterprofile import InverterProfile
# Name of the inverter profile used when the user selects none.
INVERTER_DEFAULT_PROFILE: str = "generic-hybrid"
class InverterProfileAdjustment(SettingsBaseModel):
"""How an inverter unit differs from its inverter profile.
None keeps the profile value.
"""
nominal_power_w: Optional[float] = Field(
default=None,
gt=0,
allow_inf_nan=False,
json_schema_extra={
"description": (
"Nominal AC power of the installed inverter [W]. Replaces the nominal "
"power of the inverter profile. Required if the profile is generic and "
"provides no nominal power. The effective value is available as "
"'effective_nominal_power_w'."
),
"examples": [None, 10000],
},
)
max_power_w: Optional[float] = Field(
default=None,
gt=0,
allow_inf_nan=False,
json_schema_extra={
"description": (
"Maximum AC power of the installation [W], e.g. a configured output "
"limit. Can only lower the (derated) nominal power. The effective value "
"is available as 'effective_max_power_w'."
),
"examples": [None, 8000],
},
)
max_ac_charge_power_w: Optional[float] = Field(
default=None,
ge=0,
allow_inf_nan=False,
json_schema_extra={
"description": (
"AC charge power limit of the installation [W]. Can only lower the limit "
"of the inverter profile. 0 disables AC charging. The effective value is "
"available as 'effective_max_ac_charge_power_w'."
),
"examples": [None, 0, 5000],
},
)
class InverterCommonSettings(DevicesBaseSettings):
@@ -29,99 +114,46 @@ class InverterCommonSettings(DevicesBaseSettings):
# Shared fields (GENETIC + GENETIC0)
# ------------------------------------------------------------------
max_power_w: Optional[float] = Field(
default=None,
gt=0,
inverter_profile: str = Field(
default=INVERTER_DEFAULT_PROFILE,
min_length=1,
json_schema_extra={
"description": "Maximum AC output power [W].",
"examples": [10000],
"description": (
"Name of the inverter profile (without '.json') providing the nominal "
"power, efficiency curves, AC charge power limit and power derating. "
"Differences of this unit go into 'profile_adjustment'."
),
"examples": [INVERTER_DEFAULT_PROFILE],
"x-scope": [str(ConfigScope.GENETIC), str(ConfigScope.GENETIC0)],
},
)
ac_to_dc_efficiency: float = Field(
default=1.0,
ge=0,
le=1,
profile_adjustment: InverterProfileAdjustment = Field(
default_factory=InverterProfileAdjustment,
json_schema_extra={
"description": (
"Efficiency of AC→DC conversion for grid-to-battery charging (0–1). "
"Set to 0 to disable AC charging. Default 1.0."
"How this inverter unit differs from its inverter profile: nominal power "
"and installation limits."
),
"examples": [0.95, 1.0, 0.0],
"examples": [{"nominal_power_w": 10000}],
"x-scope": [str(ConfigScope.GENETIC), str(ConfigScope.GENETIC0)],
},
)
dc_to_ac_efficiency: float = Field(
default=1.0,
gt=0,
le=1,
json_schema_extra={
"description": (
"Efficiency of DC→AC conversion for battery discharging (0–1). Default 1.0."
),
"examples": [0.95, 1.0],
"x-scope": [str(ConfigScope.GENETIC), str(ConfigScope.GENETIC0)],
},
)
dc_to_ac_efficiency_curve: Optional[list[tuple[float, float]]] = Field(
default=None,
json_schema_extra={
"description": (
"Load-dependent efficiency of DC→AC conversion for battery discharging as "
"a list of [load_fraction, efficiency] points. The load fraction is the AC "
"power relative to max_power_w (0–1); points must be strictly increasing in "
"load fraction, efficiencies in (0, 1]. Values are interpolated linearly and "
"clamped to the first/last point. When set, the curve replaces "
"dc_to_ac_efficiency. null keeps the constant dc_to_ac_efficiency. "
"Default null."
),
"examples": [None, [[0.02, 0.8], [0.07, 0.93], [0.3, 0.96], [1.0, 0.95]]],
"x-scope": [str(ConfigScope.GENETIC)],
},
)
dc_to_ac_efficiency_reference_load_fraction: float = Field(
default=0.06,
ge=0,
le=1,
json_schema_extra={
"description": (
"Load fraction of max_power_w (0–1) at which dc_to_ac_efficiency_curve is "
"evaluated to value stored battery energy without a specific conversion "
"(remaining energy at the end of the horizon, AC charge break-even). Should "
"represent the typical load served by the battery, e.g. the night-time base "
"load. Only used with dc_to_ac_efficiency_curve. Default 0.06."
"Load fraction of the effective maximum power (0–1) at which the DC→AC "
"efficiency curve is evaluated to value stored battery energy without a "
"specific conversion (remaining energy at the end of the horizon, AC "
"charge break-even). Should represent the typical load served by the "
"battery, e.g. the night-time base load. Default 0.06."
),
"examples": [0.06, 0.1],
"x-scope": [str(ConfigScope.GENETIC)],
},
)
max_ac_charge_power_w: Optional[float] = Field(
default=None,
ge=0,
json_schema_extra={
"description": (
"Maximum AC charging power [W]. "
"null means no additional limit. 0 disables AC charging."
),
"examples": [None, 0, 5000],
"x-scope": [str(ConfigScope.GENETIC), str(ConfigScope.GENETIC0)],
},
)
ac_charge_limits_total_charge: bool = Field(
default=False,
json_schema_extra={
"description": (
"True if the AC charge setpoint caps the battery's total charge power, "
"PV included. Some hybrid inverters (e.g. Deye in time-of-use grid "
"charging) limit the whole charge current to the grid charge current; "
"PV surplus above it is exported, not stored. False keeps the default "
"model: PV surplus charges first and the grid adds "
"ac_charge x max_charge_power_w on top."
),
"examples": [False, True],
"x-scope": [str(ConfigScope.GENETIC)],
},
)
battery_id: Optional[str] = Field(
default=None,
json_schema_extra={
@@ -384,13 +416,6 @@ class InverterCommonSettings(DevicesBaseSettings):
# Validators
# ------------------------------------------------------------------
@field_validator("dc_to_ac_efficiency_curve")
@classmethod
def _validate_dc_to_ac_efficiency_curve(
cls, value: Optional[list[tuple[float, float]]]
) -> Optional[list[tuple[float, float]]]:
return validate_efficiency_curve(value)
@model_validator(mode="after")
def _validate_soc_factors(self) -> "InverterCommonSettings":
if self.battery_min_soc_factor >= self.battery_max_soc_factor:
@@ -399,59 +424,339 @@ class InverterCommonSettings(DevicesBaseSettings):
)
return self
# ------------------------------------------------------------------
# Inverter profile loading (see profilestore)
# ------------------------------------------------------------------
def get_inverter_profile(self) -> "InverterProfile":
"""Return the compiled inverter profile for ``inverter_profile``.
Raises:
FileNotFoundError: If the configured inverter profile does not exist.
ValueError: If the profile document fails validation.
"""
from akkudoktoreos.devices.profile.inverterprofile import (
InverterProfileSettings,
)
from akkudoktoreos.devices.profile.profilestore import get_profile_store
return get_profile_store().get(InverterProfileSettings, self.inverter_profile)
def _load_inverter_profile(self) -> "InverterProfile":
"""Return the compiled inverter profile, or raise an error naming the inverter.
Raises:
InverterResolutionError: If the profile does not exist, cannot be
read or fails validation.
"""
try:
return self.get_inverter_profile()
except InverterResolutionError:
raise
except (OSError, ValueError) as exc:
raise InverterResolutionError(
f"Inverter '{self.device_id}': inverter profile '{self.inverter_profile}' "
f"is not usable: {exc}"
) from exc
# ------------------------------------------------------------------
# Measurement access (see invertermeasurement)
# ------------------------------------------------------------------
async def measure_operating_point(
self, target_datetime: Optional[DateTime] = None
) -> InverterOperatingPoint:
"""Read the ambient temperature from the measurements, 45 degC if unavailable."""
return await invertermeasurement.measure_operating_point(self, target_datetime)
# ------------------------------------------------------------------
# Parameter resolution (see inverterresolution)
# ------------------------------------------------------------------
def resolve_operating_parameters(
self, operating_point: Optional[InverterOperatingPoint] = None
) -> InverterOperatingParameters:
"""Resolve the effective parameters at an operating point.
Args:
operating_point: Conditions to evaluate the profile at, the reference
operating point (45 degC) if None.
Raises:
InverterResolutionError: If the profile is not usable or the
parameters cannot be resolved.
"""
return resolve_inverter_parameters(
self, self._load_inverter_profile(), operating_point or InverterOperatingPoint()
)
async def resolve_current_operating_parameters(
self, target_datetime: Optional[DateTime] = None
) -> InverterOperatingParameters:
"""Resolve the effective parameters at the measured ambient temperature.
Raises:
InverterResolutionError: See ``resolve_operating_parameters``.
"""
operating_point = await self.measure_operating_point(target_datetime)
return self.resolve_operating_parameters(operating_point)
def resolve_operating_parameters_or_defaults(
self, operating_point: Optional[InverterOperatingPoint] = None, report: bool = True
) -> InverterOperatingParameters:
"""Resolve for the optimizations; never raises.
Optimization parameters must always be valid, so a configuration that
cannot be resolved gives defaults and an error log:
- an unusable inverter profile is replaced by the packaged
``generic-hybrid`` profile with this unit's profile adjustment,
- a missing nominal power, or no usable profile at all, gives the
fallback values (``INVERTER_FALLBACK_*``),
- an inverter derated to zero power at the operating point is resolved
at the reference temperature instead.
Args:
operating_point: Operating point to evaluate the profile at, the
reference operating point if None.
report: Whether to log an error naming the inverter, the problem
and the defaults used.
Returns:
The parameters.
"""
if operating_point is None:
operating_point = InverterOperatingPoint()
problems: list[str] = []
defaults: list[str] = []
profile: Optional["InverterProfile"] = None
try:
profile = self._load_inverter_profile()
except InverterResolutionError as exc:
problems.append(str(exc))
if self.inverter_profile != INVERTER_DEFAULT_PROFILE:
try:
from akkudoktoreos.devices.profile.inverterprofile import (
InverterProfileSettings,
)
from akkudoktoreos.devices.profile.profilestore import (
get_profile_store,
)
profile = get_profile_store().get(
InverterProfileSettings, INVERTER_DEFAULT_PROFILE
)
defaults.append(f"inverter profile '{INVERTER_DEFAULT_PROFILE}'")
except (OSError, ValueError) as default_exc:
problems.append(str(default_exc))
parameters: Optional[InverterOperatingParameters] = None
if profile is not None:
settings: InverterCommonSettings = self
try:
resolve_nominal_power_w(settings, profile)
except InverterResolutionError as exc:
problems.append(str(exc))
defaults.append(f"nominal power {INVERTER_FALLBACK_NOMINAL_POWER_W:g} W")
settings = self.model_copy(
update={
"profile_adjustment": self.profile_adjustment.model_copy(
update={"nominal_power_w": INVERTER_FALLBACK_NOMINAL_POWER_W}
)
}
)
try:
parameters = resolve_inverter_parameters(settings, profile, operating_point)
except InverterResolutionError as exc:
# Derated to zero power at the operating point.
problems.append(str(exc))
reference = InverterOperatingPoint()
defaults.append(f"the parameters at {reference.temperature_degC:g} degC")
try:
parameters = resolve_inverter_parameters(settings, profile, reference)
except InverterResolutionError as reference_exc:
problems.append(str(reference_exc))
if parameters is None:
parameters, fallback_defaults = resolve_inverter_parameters_without_profile(
self, operating_point
)
defaults.extend(fallback_defaults)
if problems and report:
logger.error(
"{} Using defaults for the optimization: {}.",
" ".join(problems),
", ".join(defaults),
)
return parameters
async def resolve_current_operating_parameters_or_defaults(
self, target_datetime: Optional[DateTime] = None, report: bool = True
) -> InverterOperatingParameters:
"""Resolve like ``resolve_operating_parameters_or_defaults`` at the measured temperature.
Args:
target_datetime: Datetime the measurement is looked up for, now if None.
report: Whether to log the configuration error and the defaults used.
Returns:
The parameters.
"""
operating_point = await self.measure_operating_point(target_datetime)
parameters = self.resolve_operating_parameters_or_defaults(operating_point, report)
logger.debug(
f"Inverter '{self.device_id}' at {parameters.temperature_degC} degC: "
f"maximum power {parameters.max_power_w} W."
)
return parameters
def uses_profile(self, kind: str, name: str) -> bool:
"""Return whether this inverter uses the profile of the given kind and name."""
from akkudoktoreos.devices.profile.inverterprofile import (
InverterProfileSettings,
)
return kind == InverterProfileSettings.profile_kind and name == self.inverter_profile
def check_profile(self) -> tuple[list[str], list[str]]:
"""Check that the inverter can be resolved from its profile.
Returns:
``(errors, warnings)``: an error if the inverter cannot be resolved,
warnings for installation limits without effect.
"""
try:
parameters = self.resolve_operating_parameters()
except InverterResolutionError as exc:
return [str(exc)], []
return [], check_inverter_adjustment(self, parameters)
def _effective_parameters(self) -> Optional[InverterOperatingParameters]:
"""Resolve at the reference operating point, None if that is not possible."""
try:
return self.resolve_operating_parameters()
except ValueError as exc:
logger.debug(f"Inverter '{self.device_id}' not resolvable: {exc}")
return None
# ------------------------------------------------------------------
# Computed fields, evaluated on every access at the reference operating point
# ------------------------------------------------------------------
@computed_field # type: ignore[prop-decorator]
@property
def effective_nominal_power_w(self) -> Optional[float]:
"""Effective nominal AC power [W]: profile adjustment, else profile."""
p = self._effective_parameters()
return p.nominal_power_w if p is not None else None
@computed_field # type: ignore[prop-decorator]
@property
def effective_max_power_w(self) -> Optional[float]:
"""Maximum AC power [W] at the reference temperature, derated and capped."""
p = self._effective_parameters()
return p.max_power_w if p is not None else None
@computed_field # type: ignore[prop-decorator]
@property
def effective_max_ac_charge_power_w(self) -> Optional[float]:
"""AC charge power limit [W] at the reference temperature; 0 disables AC charging."""
p = self._effective_parameters()
return p.max_ac_charge_power_w if p is not None else None
@computed_field # type: ignore[prop-decorator]
@property
def effective_dc_to_ac_efficiency(self) -> Optional[float]:
"""DC→AC efficiency at the reference load fraction."""
p = self._effective_parameters()
return p.dc_to_ac_efficiency if p is not None else None
@computed_field # type: ignore[prop-decorator]
@property
def effective_ac_to_dc_efficiency(self) -> Optional[float]:
"""AC→DC efficiency at the AC charge power limit."""
p = self._effective_parameters()
return p.ac_to_dc_efficiency if p is not None else None
# ------------------------------------------------------------------
# GENETIC domain conversion
# ------------------------------------------------------------------
def to_genetic_param(self) -> "InverterParameters":
"""Return InverterParameters for the GENETIC optimizer."""
def to_genetic_param(
self, operating_parameters: Optional[InverterOperatingParameters] = None
) -> "InverterParameters":
"""Return InverterParameters for the GENETIC optimizer.
Args:
operating_parameters: Resolved snapshot to convert, e.g. from
``resolve_current_operating_parameters``. None resolves at the
reference operating point.
Raises:
InverterResolutionError: If the snapshot is resolved here and the
inverter cannot be resolved.
"""
from akkudoktoreos.devices.genetic.inverter import InverterParameters
if self.max_power_w is None:
raise ValueError("Inverter max_power_w is required for optimization")
p = operating_parameters or self.resolve_operating_parameters()
return InverterParameters(
device_id=self.device_id,
max_power_wh=self.max_power_w,
max_power_wh=p.max_power_w,
battery_id=self.battery_id,
ac_to_dc_efficiency=self.ac_to_dc_efficiency,
dc_to_ac_efficiency=self.dc_to_ac_efficiency,
dc_to_ac_efficiency_curve=self.dc_to_ac_efficiency_curve,
ac_to_dc_efficiency=p.ac_to_dc_efficiency,
dc_to_ac_efficiency=p.dc_to_ac_efficiency,
dc_to_ac_efficiency_curve=list(p.dc_to_ac_efficiency_curve),
ac_to_dc_efficiency_curve=list(p.ac_to_dc_efficiency_curve),
dc_to_ac_efficiency_reference_load_fraction=(
self.dc_to_ac_efficiency_reference_load_fraction
),
max_ac_charge_power_w=self.max_ac_charge_power_w,
ac_charge_limits_total_charge=self.ac_charge_limits_total_charge,
max_ac_charge_power_w=p.max_ac_charge_power_w,
ac_charge_limits_total_charge=p.ac_charge_limits_total_charge,
)
# ------------------------------------------------------------------
# GENETIC0 domain conversion
# ------------------------------------------------------------------
def to_genetic0_param(self) -> "Genetic0InverterParameters":
"""Return Genetic0InverterParameters for the GENETIC0 optimizer."""
def to_genetic0_param(
self, operating_parameters: Optional[InverterOperatingParameters] = None
) -> "Genetic0InverterParameters":
"""Return Genetic0InverterParameters for the GENETIC0 optimizer.
GENETIC0 uses constant efficiencies: the DC→AC efficiency at the
reference load fraction and the AC→DC efficiency at the AC charge limit.
Raises:
InverterResolutionError: See ``to_genetic_param``.
"""
from akkudoktoreos.devices.genetic0.genetic0inverter import (
Genetic0InverterParameters,
)
if self.max_power_w is None:
raise ValueError("Inverter max_power_w is required for optimization")
p = operating_parameters or self.resolve_operating_parameters()
return Genetic0InverterParameters(
device_id=self.device_id,
max_power_wh=self.max_power_w,
max_power_wh=p.max_power_w,
battery_id=self.battery_id,
ac_to_dc_efficiency=self.ac_to_dc_efficiency,
dc_to_ac_efficiency=self.dc_to_ac_efficiency,
max_ac_charge_power_w=self.max_ac_charge_power_w,
ac_to_dc_efficiency=p.ac_to_dc_efficiency,
dc_to_ac_efficiency=p.dc_to_ac_efficiency,
max_ac_charge_power_w=p.max_ac_charge_power_w,
)
@computed_field # type: ignore[prop-decorator]
@property
def measurement_key_temperature_degc(self) -> str:
"""Measurement key for the ambient temperature of the inverter [degC]."""
return f"{self.device_id}-temperature-degc"
@computed_field # type: ignore[prop-decorator]
@property
def measurement_keys(self) -> list[str]:
"""Measurement keys for this inverter.
Returns the ``battery_initial_soc_factor_key`` if non-empty, so
the EMS measurement store knows to watch for this key.
The ambient temperature, and the ``battery_initial_soc_factor_key`` if
non-empty, so the EMS measurement store knows to watch for them.
"""
keys = [self.measurement_key_temperature_degc]
if self.battery_initial_soc_factor_key:
return [self.battery_initial_soc_factor_key]
return []
keys.append(self.battery_initial_soc_factor_key)
return keys