feat: integrate device and runtime configuration foundation on main (#1328)

* feat: adapt configuration for multi optimization algorithms

Decouple configuration from optimization algorithm parameters. Add to_[algorithm]_param() methods
to the configuration that derive optimization algorithm specific parameters from the configuration.
Add x-scope tags to the configuration options that describe for which specific algorithms the
configuration option is for.

The whole device settings are restructured. There are now general settings for the device classes
with the afore mentioned to_[algorithm]_param() methods. The general device settings got their own
directory `devices/settings`. By this the parameter class also does not have to be a pydantic model
which can be used for future optimization/ simulations speed up.

Also the parameter class for a device is now part of the device module. This better decouples and
also is the natural place for parameters of a device.

Besides this feature there are also fixes and improvements:

* feat: extend home appliance time window settings and simulation

  Home appliance can now be configured for multiple runs with per-cycle allowed time windows. The
  number of remaining cycles to plan is determined at runtime by reading the
  ``cycles_completed_measurement_key`` from the measurement store.

* feat: specialiced CycleTimeWindowSequence for time window sequences

  Sequence of time windows associated to cycles.

  This model specializes ``ValueTimeWindowSequence`` so that the ``value``
  field of each ``ValueTimeWindow`` encodes the **cycle index** (0-based
  integer) the window belongs to.

  Typical use: an appliance that must run ``n`` times per day, each run
  constrained to a distinct time window.  Assign ``value=0`` to windows
  for the first cycle, ``value=1`` for the second, and so on.  Multiple
  windows may share the same cycle index (their allowed regions are unioned).
  Windows with ``value=None`` are silently ignored by all cycle-aware methods.

* fix: Make test_configmigrate also regard the _ANY_SENTENIEL in key values

* chore: Make devices configurations a map instead of a list

  This makes config paths stable regardless of declaration order and lets each device settings
  class build its own config path from ``self.device_id`` without needing an external index.
  Tests are adapted likewise.

  Devices configurations are automatically migrated from lists to maps.

* chore: rename levelized_cost_of_storage_kwh to levelized_cost_of_storage_amt kwh

  This better fits in the naming scheme and also makes clear the costs are money.

Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>

* fix: runtime config update ignored by config file

Runtime settings were handed back to pydantic-settings as init settings,
which rank below the config file and the environment. Any key already
present in EOS.config.json or in the environment silently discarded the
update, so a bulk PUT /v1/config returned 200 without applying anything,
while the granular PUT /v1/config/{path} endpoint kept working.

Add a dedicated runtime settings source ranked directly below the command
line arguments and record granular updates there as well, so both
endpoints share one store that survives re-evaluation of the settings
sources. Environment variables keep precedence over the config file for
all keys that were not set at runtime.

Also repairs revert_settings() and update(), which passed their data
through the same init settings.

Closes #1303

* fix: env vars ignored on first config build

ConfigEOS.__init__ passed self as first positional argument to _setup,
which forwards it to pydantic_settings.BaseSettings.__init__. Its first
positional parameter is _case_sensitive, so the environment source
matched the upper case variable names against the lower case field names
and returned nothing. Environment settings only took effect after the
next configuration setup.

* docs: changelog for config priority fixes

* fix(config): preserve device identities and storage costs during migration

* fix(devices): preserve charge-rate typing and public import compatibility

* ruff format fix

* fix(config): satisfy typed device conversion and migration contracts

* docs(config): refresh validated configuration prerequisite schemas

---------

Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
Co-authored-by: Bobby Noelte <b0661n0e17e@gmail.com>
Co-authored-by: r0b2g1t <r0b2g1t@users.noreply.github.com>
This commit is contained in:
Andreas
2026-09-17 17:51:40 +02:00
committed by GitHub
co-authored by Bobby Noelte r0b2g1t
parent 431d7d57e5
commit 8224c64654
55 changed files with 5214 additions and 2170 deletions
@@ -0,0 +1,271 @@
"""Battery and electric vehicle device settings.
Note: Used for the GENETIC and GENETIC0 algorithm.
"""
import re
from typing import TYPE_CHECKING, Any, Optional
import numpy as np
from numpydantic import NDArray, Shape
from pydantic import Field, computed_field, field_validator, model_validator
from akkudoktoreos.devices.settings.devicebasesettings import DevicesBaseSettings
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0ElectricVehicleParameters,
Genetic0SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.genetic.battery import (
ElectricVehicleParameters,
SolarPanelBatteryParameters,
)
# Default charge rates for battery
BATTERY_DEFAULT_CHARGE_RATES: list[float] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
class BatteriesCommonSettings(DevicesBaseSettings):
"""Battery and electric vehicle device settings.
Used for both stationary batteries and EV battery packs.
Note: Used for the GENETIC and GENETIC0 algorithm.
"""
capacity_wh: int = Field(
default=8000,
gt=0,
json_schema_extra={"description": "Capacity [Wh].", "examples": [8000]},
)
charging_efficiency: float = Field(
default=0.88,
gt=0,
le=1,
json_schema_extra={
"description": "Charging efficiency [0.01 ... 1.00].",
"examples": [0.88],
},
)
discharging_efficiency: float = Field(
default=0.88,
gt=0,
le=1,
json_schema_extra={
"description": "Discharge efficiency [0.01 ... 1.00].",
"examples": [0.88],
},
)
levelized_cost_of_storage_amt_kwh: float = Field(
default=0.0,
json_schema_extra={
"description": (
"Levelized cost of storage (LCOS), the average lifetime cost "
"of delivering one kWh [€/kWh]."
),
"examples": [0.12],
},
)
max_charge_power_w: Optional[float] = Field(
default=5000,
gt=0,
json_schema_extra={
"description": "Maximum charging power [W].",
"examples": [5000],
},
)
min_charge_power_w: Optional[float] = Field(
default=50,
gt=0,
json_schema_extra={
"description": "Minimum charging power [W].",
"examples": [50],
},
)
charge_rates: Optional[list[float]] = Field(
default=BATTERY_DEFAULT_CHARGE_RATES,
json_schema_extra={
"description": (
"Charge rates as factor of maximum charging power [0.00 ... 1.00]. "
"None triggers fallback to default charge-rates."
),
"examples": [[0.0, 0.25, 0.5, 0.75, 1.0], None],
},
)
min_soc_percentage: int = Field(
default=0,
ge=0,
le=100,
json_schema_extra={
"description": (
"Minimum state of charge (SOC) as percentage of capacity [%]. "
"This is the target SoC for charging."
),
"examples": [10],
},
)
max_soc_percentage: int = Field(
default=100,
ge=0,
le=100,
json_schema_extra={
"description": "Maximum state of charge (SOC) as percentage of capacity [%].",
"examples": [100],
},
)
# ------------------------------------------------------------------
# GENETIC domain conversion
# ------------------------------------------------------------------
def to_genetic_pv_bat_param(self) -> "SolarPanelBatteryParameters":
"""Return SolarPanelBatteryParameters for the GENETIC optimizer."""
from akkudoktoreos.devices.genetic.battery import SolarPanelBatteryParameters
return SolarPanelBatteryParameters(
device_id=self.device_id,
capacity_wh=self.capacity_wh,
charging_efficiency=self.charging_efficiency,
discharging_efficiency=self.discharging_efficiency,
max_charge_power_w=self.max_charge_power_w,
min_soc_percentage=self.min_soc_percentage,
max_soc_percentage=self.max_soc_percentage,
)
def to_genetic_ev_bat_param(self) -> "ElectricVehicleParameters":
"""Return ElectricVehicleParameters for the GENETIC optimizer."""
from akkudoktoreos.devices.genetic.battery import ElectricVehicleParameters
return ElectricVehicleParameters(
device_id=self.device_id,
capacity_wh=self.capacity_wh,
charging_efficiency=self.charging_efficiency,
discharging_efficiency=self.discharging_efficiency,
charge_rates=self.charge_rates,
max_charge_power_w=self.max_charge_power_w,
min_soc_percentage=self.min_soc_percentage,
max_soc_percentage=self.max_soc_percentage,
)
# ------------------------------------------------------------------
# GENETIC0 domain conversion
# ------------------------------------------------------------------
def to_genetic0_pv_bat_param(self) -> "Genetic0SolarPanelBatteryParameters":
"""Return Genetic0SolarPanelBatteryParameters for the GENETIC0 optimizer."""
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0SolarPanelBatteryParameters,
)
return Genetic0SolarPanelBatteryParameters(
device_id=self.device_id,
capacity_wh=self.capacity_wh,
charging_efficiency=self.charging_efficiency,
discharging_efficiency=self.discharging_efficiency,
max_charge_power_w=self.max_charge_power_w,
min_soc_percentage=self.min_soc_percentage,
max_soc_percentage=self.max_soc_percentage,
)
def to_genetic0_ev_bat_param(self) -> "Genetic0ElectricVehicleParameters":
"""Return Genetic0ElectricVehicleParameters for the GENETI0C optimizer."""
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0ElectricVehicleParameters,
)
return Genetic0ElectricVehicleParameters(
device_id=self.device_id,
capacity_wh=self.capacity_wh,
charging_efficiency=self.charging_efficiency,
discharging_efficiency=self.discharging_efficiency,
charge_rates=self.charge_rates,
max_charge_power_w=self.max_charge_power_w,
min_soc_percentage=self.min_soc_percentage,
max_soc_percentage=self.max_soc_percentage,
)
@field_validator("charge_rates", mode="before")
def validate_and_sort_charge_rates(cls, v: Any) -> NDArray[Shape["*"], float]:
# None means fallback to default values
if v is None:
return np.asarray(BATTERY_DEFAULT_CHARGE_RATES, dtype=float).copy()
# Convert to numpy array
if isinstance(v, str):
# Remove brackets and split by comma or whitespace
numbers = re.split(r"[,\s]+", v.strip("[]"))
# Filter out any empty strings and convert to floats
arr = np.array([float(x) for x in numbers if x])
else:
arr = np.array(v, dtype=float)
# Must not be empty
if arr.size == 0:
raise ValueError("charge_rates must contain at least one value.")
# Enforce bounds: 0.0 ≤ x ≤ 1.0
if (arr < 0.0).any() or (arr > 1.0).any():
raise ValueError("charge_rates must be within [0.0, 1.0].")
# Remove duplicates + sort
arr = np.unique(arr)
arr.sort()
return arr
@model_validator(mode="after")
def _validate_soc_range(self) -> "BatteriesCommonSettings":
if self.min_soc_percentage >= self.max_soc_percentage:
raise ValueError("min_soc_percentage must be < max_soc_percentage")
if (
self.min_charge_power_w is not None
and self.max_charge_power_w is not None
and self.min_charge_power_w > self.max_charge_power_w
):
raise ValueError("min_charge_power_w must be <= max_charge_power_w")
return self
@computed_field # type: ignore[prop-decorator]
@property
def measurement_key_soc_factor(self) -> str:
"""Measurement key for SoC as factor of total capacity [0.0 ... 1.0]."""
return f"{self.device_id}-soc-factor"
@computed_field # type: ignore[prop-decorator]
@property
def measurement_key_power_l1_w(self) -> str:
"""Measurement key for L1 power [W]."""
return f"{self.device_id}-power-l1-w"
@computed_field # type: ignore[prop-decorator]
@property
def measurement_key_power_l2_w(self) -> str:
"""Measurement key for L2 power [W]."""
return f"{self.device_id}-power-l2-w"
@computed_field # type: ignore[prop-decorator]
@property
def measurement_key_power_l3_w(self) -> str:
"""Measurement key for L3 power [W]."""
return f"{self.device_id}-power-l3-w"
@computed_field # type: ignore[prop-decorator]
@property
def measurement_key_power_3_phase_sym_w(self) -> str:
"""Measurement key for symmetric 3-phase power [W]."""
return f"{self.device_id}-power-3-phase-sym-w"
@computed_field # type: ignore[prop-decorator]
@property
def measurement_keys(self) -> list[str]:
"""All measurement keys for this battery."""
return [
self.measurement_key_soc_factor,
self.measurement_key_power_l1_w,
self.measurement_key_power_l2_w,
self.measurement_key_power_l3_w,
self.measurement_key_power_3_phase_sym_w,
]
@@ -0,0 +1,39 @@
"""Base classe for all device settings.
This module contains the building blocks that every device settings class
depends on.:
- ``DevicesBaseSettings``: common ``device_id`` field for all devices.
Nothing in this module is optimizer-specific.
"""
import secrets
import string
from pydantic import Field
from akkudoktoreos.config.configabc import SettingsBaseModel
# ============================================================
# Base settings
# ============================================================
def device_default_id() -> str:
"""Provide random default device id."""
alphabet = string.ascii_letters + string.digits
device_id = "".join(secrets.choice(alphabet) for _ in range(10))
return device_id
class DevicesBaseSettings(SettingsBaseModel):
"""Base devices setting."""
device_id: str = Field(
default_factory=device_default_id,
json_schema_extra={
"description": "ID of device",
"examples": ["battery1", "ev1", "inverter1", "dishwasher"],
},
)
@@ -0,0 +1,258 @@
"""Controllable home appliance device settings.
Note: Used for the GENETIC and GENETIC0 algorithm.
"""
from typing import TYPE_CHECKING, Optional
from pydantic import Field, computed_field, model_validator
from akkudoktoreos.config.configabc import ConfigScope, CycleTimeWindowSequence
from akkudoktoreos.devices.settings.devicebasesettings import DevicesBaseSettings
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
Genetic0HomeApplianceParameters,
)
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
class HomeApplianceCommonSettings(DevicesBaseSettings):
"""Controllable home appliance device settings.
Represents a shiftable load whose start time — and optionally the
start times for multiple sequential runs — can be deferred by the
optimiser within per-cycle allowed time windows.
The number of remaining cycles to plan is determined at runtime by
reading ``cycles_completed_measurement_key`` from the measurement
store inside ``HomeApplianceDevice.setup_run``.
``num_cycles`` is required when ``cycle_time_windows`` is ``None``
(unconstrained); when windows are provided it is derived from
``cycle_time_windows.num_cycles()``.
Single-cycle, unconstrained (start any time)
---------------------------------------------
::
device_id: dishwasher
consumption_wh: 1500
duration_h: 2
num_cycles: 1
ports:
- port_id: p_ac
bus_id: bus_ac
direction: sink
Single-cycle, constrained to one window
----------------------------------------
Each window's ``value`` field carries the **cycle index** (0-based).
Windows without a ``value`` are ignored by the optimizer::
device_id: dishwasher
consumption_wh: 1500
duration_h: 2
ports:
- port_id: p_ac
bus_id: bus_ac
direction: sink
cycle_time_windows:
windows:
- start_time: "10:00"
duration: "12 hours"
value: 0
Multi-cycle, per-cycle windows
--------------------------------
Two cycles, each with its own window. Cycle 0 runs in the morning,
cycle 1 in the evening::
device_id: washing_machine
consumption_wh: 2000
duration_h: 2
min_cycle_gap_h: 1
ports:
- port_id: p_ac
bus_id: bus_ac
direction: sink
cycle_time_windows:
windows:
- start_time: "07:00"
duration: "5 hours"
value: 0
- start_time: "17:00"
duration: "5 hours"
value: 1
Multi-cycle, shared window (both cycles may run any time 10:00-20:00)
-----------------------------------------------------------------------
Assign the same-shaped windows to distinct cycle indices so the
optimizer can place them independently::
cycle_time_windows:
windows:
- start_time: "10:00"
duration: "10 hours"
value: 0
- start_time: "10:00"
duration: "10 hours"
value: 1
"""
consumption_wh: int = Field(
default=3000,
gt=0,
json_schema_extra={
"description": "Energy consumption per run cycle [Wh].",
"examples": [2000],
"x-scope": [str(ConfigScope.GENETIC), str(ConfigScope.GENETIC0)],
},
)
duration_h: int = Field(
default=3,
gt=0,
le=24,
json_schema_extra={
"description": "Run duration per cycle [h] (1-24).",
"examples": [2],
"x-scope": [str(ConfigScope.GENETIC), str(ConfigScope.GENETIC0)],
},
)
num_cycles: int = Field(
default=1,
ge=1,
json_schema_extra={
"description": (
"Number of times the appliance must run within the horizon. "
"Required when cycle_time_windows is null (unconstrained). "
"Ignored when cycle_time_windows is provided -- the number "
"of distinct cycle indices in the windows defines num_cycles. "
"Defaults to 1."
),
"examples": [1, 2],
"x-scope": [str(ConfigScope.GENETIC), str(ConfigScope.GENETIC0)],
},
)
cycle_time_windows: Optional[CycleTimeWindowSequence] = Field(
default=None,
json_schema_extra={
"description": (
"Per-cycle allowed scheduling time windows. "
"Each window's value field specifies the cycle index (0-based). "
"When null, the appliance may start at any step and num_cycles "
"must be set explicitly."
),
"examples": [
None,
{
"windows": [
{"start_time": "07:00", "duration": "5 hours", "value": 0},
{"start_time": "17:00", "duration": "5 hours", "value": 1},
]
},
],
"x-scope": [
str(ConfigScope.GENETIC),
],
},
)
min_cycle_gap_h: int = Field(
default=0,
ge=0,
json_schema_extra={
"description": (
"Minimum idle time between the end of one cycle and the start "
"of the next [h]. Applies uniformly between all consecutive cycles. "
"0 means back-to-back runs are permitted."
),
"examples": [0, 1, 4],
"x-scope": [
str(ConfigScope.GENETIC),
],
},
)
cycles_completed_measurement_key: Optional[str] = Field(
default=None,
json_schema_extra={
"description": (
"Measurement store key holding the number of cycles already "
"completed in the current planning day. Read by "
"HomeApplianceDevice.setup_run via context.resolve_measurement. "
"Defaults to '{device_id}.cycles_completed' when null."
),
"examples": ["dishwasher.cycles_completed", None],
"x-scope": [
str(ConfigScope.GENETIC),
],
},
)
@model_validator(mode="after")
def _validate_num_cycles_specified(self) -> "HomeApplianceCommonSettings":
"""Require num_cycles when windows are not provided."""
if self.cycle_time_windows is None and self.num_cycles is None:
raise ValueError(
"num_cycles must be set when cycle_time_windows is null. "
"Provide either cycle_time_windows (windows define cycle count) "
"or set num_cycles explicitly."
)
return self
@computed_field # type: ignore[prop-decorator]
@property
def effective_num_cycles(self) -> int:
"""Number of cycles as seen by the optimizer.
Derived from cycle_time_windows.num_cycles() when windows are
provided; falls back to the explicit num_cycles field otherwise.
"""
if self.cycle_time_windows is not None:
return self.cycle_time_windows.num_cycles()
return self.num_cycles
# ------------------------------------------------------------------
# GENETIC domain conversion
# ------------------------------------------------------------------
def to_genetic_param(self) -> "HomeApplianceParameters":
"""Return HomeApplianceParameters for the GENETIC optimizer."""
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
return HomeApplianceParameters(
device_id=self.device_id,
consumption_wh=self.consumption_wh,
duration_h=self.duration_h,
num_cycles=self.effective_num_cycles,
min_cycle_gap_h=self.min_cycle_gap_h,
time_windows=self.cycle_time_windows,
)
# ------------------------------------------------------------------
# GENETIC0 domain conversion
# ------------------------------------------------------------------
def to_genetic0_param(self) -> "Genetic0HomeApplianceParameters":
"""Return Genetic0HomeApplianceParameters for the GENETIC0 optimizer."""
from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
Genetic0HomeApplianceParameters,
)
return Genetic0HomeApplianceParameters(
device_id=self.device_id,
consumption_wh=self.consumption_wh,
duration_h=self.duration_h,
time_windows=self.cycle_time_windows,
)
@computed_field # type: ignore[prop-decorator]
@property
def measurement_keys(self) -> Optional[list[str]]:
"""Measurement keys for the home appliance stati that are measurements."""
keys: list[str] = []
return keys
@@ -0,0 +1,397 @@
"""Inverter device settings."""
from typing import TYPE_CHECKING, Optional
from pydantic import Field, computed_field, model_validator
from akkudoktoreos.config.configabc import ConfigScope
from akkudoktoreos.devices.settings.devicebasesettings import (
DevicesBaseSettings,
)
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic0.genetic0inverter import (
Genetic0InverterParameters,
)
from akkudoktoreos.devices.genetic.inverter import InverterParameters
class InverterCommonSettings(DevicesBaseSettings):
"""Inverter device settings.
An inverter bridges a DC bus (PV / battery) and an AC bus (grid /
household). It must therefore have at least one DC port and one AC
port.
"""
# ------------------------------------------------------------------
# Shared fields (GENETIC + GENETIC0)
# ------------------------------------------------------------------
max_power_w: Optional[float] = Field(
default=None,
gt=0,
json_schema_extra={
"description": "Maximum AC output power [W].",
"examples": [10000],
"x-scope": [str(ConfigScope.GENETIC), str(ConfigScope.GENETIC0)],
},
)
ac_to_dc_efficiency: float = Field(
default=1.0,
ge=0,
le=1,
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."
),
"examples": [0.95, 1.0, 0.0],
"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)],
},
)
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)],
},
)
battery_id: Optional[str] = Field(
default=None,
json_schema_extra={
"description": ("Device ID of the battery."),
"examples": [None],
"x-scope": [str(ConfigScope.GENETIC), str(ConfigScope.GENETIC0)],
},
)
# ------------------------------------------------------------------
# UNUSED-only fields
# ------------------------------------------------------------------
# Auxiliary power consumption
off_state_power_consumption_w: float = Field(
default=0.0,
ge=0,
json_schema_extra={
"description": (
"Standby power consumed when the inverter is fully idle "
"(battery=0 and PV=0) [W]. Default 0.0."
),
"examples": [5.0, 0.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
on_state_power_consumption_w: float = Field(
default=0.0,
ge=0,
json_schema_extra={
"description": (
"Auxiliary power consumed whenever the inverter is active "
"(non-zero AC power) [W]. Default 0.0."
),
"examples": [10.0, 0.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
# PV parameters (used for SOLAR and HYBRID inverter types)
pv_to_ac_efficiency: float = Field(
default=1.0,
gt=0,
le=1,
json_schema_extra={
"description": (
"Efficiency of PV DC→AC conversion (0–1). "
"Required when pv_power_w_key is set (SOLAR or HYBRID). Default 1.0."
),
"examples": [0.97, 1.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
pv_to_battery_efficiency: float = Field(
default=1.0,
gt=0,
le=1,
json_schema_extra={
"description": (
"Efficiency of PV DC→battery charging path (0–1). "
"Used for HYBRID inverters only. Default 1.0."
),
"examples": [0.98, 1.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
pv_max_power_w: Optional[float] = Field(
default=None,
gt=0,
json_schema_extra={
"description": (
"Maximum DC PV power fed into the inverter [W]. "
"Required when pv_power_w_key is set (SOLAR or HYBRID). "
"Values from pv_power_w_key are clipped to this limit."
),
"examples": [8000.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
pv_min_power_w: float = Field(
default=0.0,
ge=0,
json_schema_extra={
"description": (
"Minimum DC PV power threshold [W]. Steps with available PV "
"below this value are treated as zero. Default 0.0."
),
"examples": [50.0, 0.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
pv_power_w_key: Optional[str] = Field(
default=None,
json_schema_extra={
"description": (
"SimulationContext prediction key resolving to a per-step PV "
"power forecast array [W] of shape (horizon,). "
"Set for SOLAR and HYBRID inverter types; leave None for BATTERY."
),
"examples": ["pv_forecast_w", None],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
# Battery parameters (used for BATTERY and HYBRID inverter types)
battery_capacity_wh: Optional[float] = Field(
default=None,
gt=0,
json_schema_extra={
"description": (
"Usable battery capacity [Wh]. Required for BATTERY and HYBRID inverter types."
),
"examples": [10000.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_charge_rates: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": (
"Optional list of discrete charge rate fractions (each in (0, 1]). "
"When set, the battery is constrained to these specific fractions "
"of battery_max_charge_rate. null means continuous charging. "
"All values must be in (0, 1]."
),
"examples": [None, [0.25, 0.5, 1.0]],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_min_charge_rate: float = Field(
default=0.0,
ge=0,
le=1,
json_schema_extra={
"description": (
"Minimum non-zero charge rate as a fraction of the 1C rate "
"(1C = battery_capacity_wh W). "
"Charge commands below this threshold are rounded to zero. Default 0.0."
),
"examples": [0.1, 0.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_max_charge_rate: float = Field(
default=1.0,
gt=0,
le=1,
json_schema_extra={
"description": (
"Maximum charge rate as a fraction of the 1C rate "
"(1C = battery_capacity_wh W). "
"bat_factor=+1 maps to this rate. Default 1.0."
),
"examples": [0.5, 1.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_min_discharge_rate: float = Field(
default=0.0,
ge=0,
le=1,
json_schema_extra={
"description": (
"Minimum discharge rate as a fraction of the 1C rate "
"(1C = battery_capacity_wh W). "
"Discharge commands below this threshold are rounded to zero. Default 0.0."
),
"examples": [0.1, 0.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_max_discharge_rate: float = Field(
default=1.0,
gt=0,
le=1,
json_schema_extra={
"description": (
"Maximum discharge rate as a fraction of the 1C rate. "
"(1C = battery_capacity_wh W). "
"bat_factor=−1 maps to this rate. Default 1.0."
),
"examples": [0.5, 1.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_min_soc_factor: float = Field(
default=0.0,
ge=0,
lt=1,
json_schema_extra={
"description": (
"Minimum allowed state of charge as a fraction of battery_capacity_wh. "
"Must be < battery_max_soc_factor. Default 0.0."
),
"examples": [0.1, 0.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_max_soc_factor: float = Field(
default=1.0,
gt=0,
le=1,
json_schema_extra={
"description": (
"Maximum allowed state of charge as a fraction of battery_capacity_wh. "
"Must be > battery_min_soc_factor. Default 1.0."
),
"examples": [0.9, 1.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_initial_soc_factor_key: str = Field(
default="",
json_schema_extra={
"description": (
"SimulationContext measurement key resolving to the initial battery "
"SoC as a fraction of battery_capacity_wh, in [min_soc_factor, max_soc_factor]. "
"An empty string means the device uses battery_min_soc_factor as the "
"initial SoC (fully depleted to the minimum)."
),
"examples": ["battery1_soc_factor", ""],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_lcos_amt_kwh: float = Field(
default=0.0,
ge=0,
json_schema_extra={
"description": (
"Levelized cost of battery storage [Amt./kWh cycled]. "
"Penalises unnecessary charging/discharging so the GA avoids "
"grid-charge→discharge cycles with no price-spread benefit. "
"Typical residential Li-ion value: 0.05 Amt./kWh. "
"Set to 0.0 to encourage the optimizer to use the battery. "
"Defaults to 0.0."
),
"examples": [0.05, 0.0],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
battery_discharge_reward_amt_kwh: float = Field(
default=0.02,
ge=0,
json_schema_extra={
"description": (
"Shadow price rewarding battery discharge [Amt./kWh discharged AC]. "
"Adds a direct fitness benefit per kWh the battery delivers, on top of "
"the grid import cost reduction already captured by GridConnectionDevice. "
"Helps the GA discover discharge when the load-matching rate is small "
"relative to mutation noise. "
"Suggested value: import_price - export_price - lcos "
"(e.g. 0.30 - 0.08 - 0.05 = 0.17). Set to 0.0 to disable."
),
"examples": [0.0, 0.17],
"x-scope": [str(ConfigScope.UNUSED)],
},
)
# ------------------------------------------------------------------
# Validators
# ------------------------------------------------------------------
@model_validator(mode="after")
def _validate_soc_factors(self) -> "InverterCommonSettings":
if self.battery_min_soc_factor >= self.battery_max_soc_factor:
raise ValueError(
"battery_min_soc_factor must be strictly less than battery_max_soc_factor"
)
return self
# ------------------------------------------------------------------
# GENETIC domain conversion
# ------------------------------------------------------------------
def to_genetic_param(self) -> "InverterParameters":
"""Return InverterParameters for the GENETIC optimizer."""
from akkudoktoreos.devices.genetic.inverter import InverterParameters
if self.max_power_w is None:
raise ValueError("Inverter max_power_w is required for optimization")
return InverterParameters(
device_id=self.device_id,
max_power_wh=self.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,
)
# ------------------------------------------------------------------
# GENETIC0 domain conversion
# ------------------------------------------------------------------
def to_genetic0_param(self) -> "Genetic0InverterParameters":
"""Return Genetic0InverterParameters for the GENETIC0 optimizer."""
from akkudoktoreos.devices.genetic0.genetic0inverter import (
Genetic0InverterParameters,
)
if self.max_power_w is None:
raise ValueError("Inverter max_power_w is required for optimization")
return Genetic0InverterParameters(
device_id=self.device_id,
max_power_wh=self.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,
)
@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.
"""
if self.battery_initial_soc_factor_key:
return [self.battery_initial_soc_factor_key]
return []