feat(devices): add battery profiles

A battery profile describes a battery model: the charge and discharge limit
maps over temperature and SoC, the charge and discharge efficiency curves
over C-rate, the technical SoC bounds, the hard temperature cutoffs and,
for a model, its nominal capacity and power limits. EOS packages the
generic profile generic-lfp; users add their own profiles.

A battery or electric vehicle selects its profile by battery_profile and
describes how the installation differs from it in profile_adjustment
(capacity, power limits of the installation, periodic full charge). The
effective values are resolved from both at the measured operating point
(temperature, SoC, power) and shown as effective_* fields.

The GENETIC simulation uses the limits and efficiencies of the profile over
SoC, with precomputed tables as a fast path; GENETIC0 gets the values at the
operating point. Optimization parameters are always valid: a battery whose
profile is missing, unreadable or invalid uses the packaged generic-lfp
profile, and the former defaults only if that is not usable either; each is
logged as error, and an optimization run is never cancelled because of a
battery.

Additional changes
- Add a generic device profile store: user and packaged profiles, atomic
  saves, compiled profiles cached per file and checked again at most once a
  second, plain file names as profile names ('schema' is reserved). On
  Windows, a save or read that collides with the other is retried briefly.
- Add the REST API /v1/profile to list the profile kinds and to list, read
  (document and JSON schema), save and delete profiles.
- Check the hard temperature cutoffs on the exact temperature.
- Resolve inhibited charging or discharging to a power of 0, e.g. for a cold
  battery; give GENETIC0 its own discharge limit for that.
- Limit generic profiles without own power limits to the former 5000 W.
- Accept only the implemented units; current limits need the nominal
  voltage.
- Migrate legacy battery settings into the profile adjustment, keep the
  former charge power limit as discharge limit (also for a Home Assistant
  entity on it) and report dropped efficiencies as errors.
- Limit GENETIC battery discharge by the discharge power.
- Allow battery profile lookups while the configuration is created.
- Resolve a battery once per configuration dump.
- Package the bundled profiles, document battery profiles and regenerate
  the configuration and OpenAPI documentation.
- Ignore the report PDFs written by the visualization tests.

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 dd41e5d57c
commit e255f987bf
56 changed files with 11381 additions and 619 deletions
@@ -13,6 +13,7 @@ from akkudoktoreos.core.coreabc import (
PredictionMixin,
get_ems,
)
from akkudoktoreos.devices.settings.batteryresolution import BatteryFullCharge
from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettings
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
from akkudoktoreos.optimization.genetic.fullcharge import (
@@ -137,9 +138,11 @@ class ConfigOptimizationRequest(
)
return 0
async def full_charge(device: BatteriesCommonSettings) -> Optional[DateTime]:
async def full_charge(
device: BatteriesCommonSettings, policy: BatteryFullCharge
) -> Optional[DateTime]:
"""Deadline of the next periodic full charge, None if disabled or unknown."""
interval_days = device.full_charge_interval_days
interval_days = policy.interval_days
if interval_days is None:
return None
try:
@@ -155,7 +158,7 @@ class ConfigOptimizationRequest(
zip(dates, values),
now=observation_time,
interval_days=interval_days,
detect_percentage=device.full_charge_detect_percentage,
detect_percentage=policy.detect_percentage,
)
if deadline is None:
logger.warning(
@@ -164,18 +167,25 @@ class ConfigOptimizationRequest(
)
return deadline
# A battery configuration error does not cancel the run: the battery gets
# default values for what cannot be resolved, and an error is logged.
battery = None
if groups["batteries"]:
device = groups["batteries"][0]
battery = device.to_genetic_pv_bat_param()
(
operating_parameters,
use_profile_tables,
) = await device.resolve_current_operating_parameters_or_defaults(observation_time)
battery = device.to_genetic_pv_bat_param(operating_parameters, use_profile_tables)
battery.initial_soc_percentage = await state(device)
deadline = await full_charge(device)
policy = device.resolve_full_charge()
deadline = await full_charge(device, policy)
horizon_end = start.add(seconds=settings.horizon * settings.interval_sec)
if deadline is not None and deadline.timestamp() <= horizon_end.timestamp():
# Due within the horizon: lift the upper limit so the battery may
# reach the target, and enforce the target only if grid charging
# is allowed for it.
target = device.full_charge_soc_percentage
# is allowed for it. The target is within the technical SOC bounds.
target = policy.soc_percentage
battery.max_soc_percentage = max(battery.max_soc_percentage, target)
if device.full_charge_allow_grid:
enforced = enforced_full_charge_deadline(deadline, observation_time)
@@ -198,7 +208,11 @@ class ConfigOptimizationRequest(
ev = None
if groups["electric_vehicles"]:
device = groups["electric_vehicles"][0]
ev = device.to_genetic_ev_bat_param()
(
operating_parameters,
use_profile_tables,
) = await device.resolve_current_operating_parameters_or_defaults(observation_time)
ev = device.to_genetic_ev_bat_param(operating_parameters, use_profile_tables)
ev.initial_soc_percentage = await state(device)
inverter = None
if groups["inverters"]:
@@ -745,8 +745,14 @@ class GeneticSimulation(PydanticBaseModel):
battery_lcos_direct = False
if battery_fast is not None and type(battery_fast) is Battery:
battery_lcos_direct = True
battery_discharged_raw_fast = battery_fast._discharged_raw_wh_per_slot
battery_discharging_efficiency_fast = battery_fast.discharging_efficiency
if battery_fast._curves is None:
battery_discharged_raw_fast = battery_fast._discharged_raw_wh_per_slot
battery_discharging_efficiency_fast = battery_fast.discharging_efficiency
else:
# With power dependent efficiencies the delivered energy is kept
# per slot (see Battery.discharged_energy_wh()).
battery_discharged_raw_fast = battery_fast._curves.discharged_dc_wh_per_slot
battery_discharging_efficiency_fast = 1.0
for hour in range(start_hour, end_hour):
hour_idx = hour - start_hour
@@ -74,6 +74,10 @@ class ElectricVehicleResult(DeviceOptimizeResult):
max_charge_power_w: int = Field(
json_schema_extra={"description": "Maximum charging power in watts."}
)
max_discharge_power_w: Optional[float] = Field(
default=None,
json_schema_extra={"description": "Maximum discharging power in watts."},
)
soc_wh: float = Field(
json_schema_extra={
"description": "State of charge of the battery in watt-hours at the start of the simulation."
@@ -553,9 +557,10 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
max(float(battery_grid_export_factor), 0.0), 1.0
)
# (0,0,1) -> Discharge for local load only
# (0,0,1) -> Discharge for local load only: serve local demand, no grid
# charging and no export.
if ac_charge <= 0.0 and dc_charge <= 0.0 and discharge_allowed:
return BatteryOperationMode.PEAK_SHAVING, 1.0
return BatteryOperationMode.SELF_CONSUMPTION, 1.0
# (ac>0,0,0) → AC charge only
if ac_charge > 0.0 and dc_charge <= 0.0 and not discharge_allowed:
@@ -614,13 +619,20 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
- Battery grid export: blocked when SOC is at or below min SOC.
"""
parameters = getattr(self, "parameters", None)
bat_list = (
[parameters.pv_battery]
if parameters is not None and parameters.pv_battery is not None
else list((self.config.devices.batteries or {}).values())
if parameters is None
else []
)
# Without parameters, convert the battery settings: they hold no
# capacity / efficiency / power fields, these come from the battery profile.
# A configuration error gives the defaults of the parameter preparation;
# the configuration check already reported it.
bat_list = []
if parameters is not None:
if parameters.pv_battery is not None:
bat_list = [parameters.pv_battery]
else:
for settings in list((self.config.devices.batteries or {}).values())[:1]:
snapshot, use_tables = settings.resolve_operating_parameters_or_defaults(
report=False
)
bat_list.append(settings.to_genetic_pv_bat_param(snapshot, use_tables))
if not bat_list:
return ac_charge, dc_charge, discharge_allowed, battery_grid_export_allowed
@@ -679,8 +691,8 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
- battery_grid_export_allowed: discharge to grid
The following battery modes are supported:
- SELF_CONSUMPTION: dc_charge > 0 and discharge_allowed == 1
- PEAK_SHAVING: ac_charge == 0 and discharge_allowed == 1
- SELF_CONSUMPTION: discharge_allowed == 1 and ac_charge == 0
(with or without dc_charge)
- GRID_SUPPORT_EXPORT: battery_grid_export_allowed == 1
- GRID_SUPPORT_IMPORT: ac_charge > 0 and discharge_allowed == 0 or 1
"""
@@ -50,6 +50,8 @@ def _simulate_action(
bat.soc_wh = float(energy_wh)
bat._charged_raw_wh_per_slot[:] = [0.0] * len(bat._charged_raw_wh_per_slot)
bat._discharged_raw_wh_per_slot[:] = [0.0] * len(bat._discharged_raw_wh_per_slot)
if bat._curves is not None:
bat._curves.reset(len(bat._charged_raw_wh_per_slot))
bat._charge_limit_raw_wh_per_slot[:] = [float("inf")] * len(bat._charge_limit_raw_wh_per_slot)
ac_enabled = inv.ac_to_dc_efficiency > 0 and (
inv.max_ac_charge_power_w is None or inv.max_ac_charge_power_w > 0
@@ -84,7 +86,7 @@ def _simulate_action(
"reward_euro": reward,
"grid_export_wh": sold,
"grid_import_wh": bought,
"battery_charge_wh": (bat._charged_raw_wh_per_slot[0] * bat.charging_efficiency),
"battery_charge_wh": bat.charged_energy_wh(0),
"battery_discharge_wh": discharged_wh,
"losses_wh": losses,
"ac_grid_charge_wh": ac_grid_charge_wh,
@@ -37,6 +37,7 @@ from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
Genetic0HomeApplianceParameters,
)
from akkudoktoreos.devices.genetic0.genetic0inverter import Genetic0InverterParameters
from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettings
from akkudoktoreos.optimization.genetic0.genetic0abc import Genetic0ParametersBaseModel
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
from akkudoktoreos.utils.datetimeutil import DateTime, to_duration
@@ -46,6 +47,20 @@ from akkudoktoreos.utils.datetimeutil import DateTime, to_duration
# StartMixin - Creates circular dependency with ems.py
# Demo devices: used if no device is configured, and for this run only if the
# configured device cannot be prepared.
DEMO_BATTERY_SETTINGS: dict = {
"device_id": "battery1",
"profile_adjustment": {"nominal_capacity_wh": 8000},
}
DEMO_ELECTRIC_VEHICLE_SETTINGS: dict = {
"device_id": "ev1",
"profile_adjustment": {"nominal_capacity_wh": 50000},
"charge_rates": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
"min_soc_percentage": 70,
}
class Genetic0EnergyManagementParameters(Genetic0ParametersBaseModel):
"""Encapsulates energy-related forecasts and costs used in GENETIC optimization."""
@@ -577,30 +592,30 @@ class Genetic0OptimizationParameters(
else:
if cls.config.devices.batteries is None:
logger.info("No battery device data available - defaulting to demo data.")
cls.config.devices.batteries = {
"battery1": {
"device_id": "battery1",
"capacity_wh": 8000,
},
}
cls.config.devices.batteries = {"battery1": dict(DEMO_BATTERY_SETTINGS)}
# Take first battery
battery_config = list(cls.config.devices.batteries.values())[0]
try:
# Take first battery
battery_config = list(cls.config.devices.batteries.values())[0]
battery_params = battery_config.to_genetic0_pv_bat_param()
# A configuration error gives default values, reported as error.
(
battery_parameters,
_,
) = await battery_config.resolve_current_operating_parameters_or_defaults()
battery_params = battery_config.to_genetic0_pv_bat_param(battery_parameters)
except Exception as e:
logger.info(
"No battery device data available - defaulting to demo data. Parameter preparation attempt {}: {}",
attempt,
# Never cancel the run and never change the user's configuration:
# optimize with the demo battery for this run only.
logger.error(
"Battery '{}' cannot be prepared for the optimization: {} "
"Using the demo battery for this run.",
battery_config.device_id,
e,
)
cls.config.devices.batteries = {
"battery1": {
"device_id": "battery1",
"capacity_wh": 8000,
},
}
# Retry
continue
battery_config = BatteriesCommonSettings(**DEMO_BATTERY_SETTINGS)
battery_parameters, _ = (
battery_config.resolve_operating_parameters_or_defaults()
)
battery_params = battery_config.to_genetic0_pv_bat_param(battery_parameters)
# Levelized cost of ownership
if battery_config.levelized_cost_of_storage_amt_kwh is None:
logger.info(
@@ -644,34 +659,38 @@ class Genetic0OptimizationParameters(
)
cls.config.devices.max_electric_vehicles = 1
cls.config.devices.electric_vehicles = {
"ev1": {
"device_id": "ev1",
"capacity_wh": 50000,
"charge_rates": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
"min_soc_percentage": 70,
},
"ev1": dict(DEMO_ELECTRIC_VEHICLE_SETTINGS)
}
# Take first electric_vehicle
electric_vehicle_config = list(cls.config.devices.electric_vehicles.values())[0]
try:
# Take first electric_vehicle
electric_vehicle_config = list(cls.config.devices.electric_vehicles.values())[0]
electric_vehicle_params = electric_vehicle_config.to_genetic0_ev_bat_param()
# A configuration error gives default values, reported as error.
(
ev_parameters,
_,
) = await electric_vehicle_config.resolve_current_operating_parameters_or_defaults()
electric_vehicle_params = electric_vehicle_config.to_genetic0_ev_bat_param(
ev_parameters
)
except Exception as e:
logger.info(
"No electric_vehicle device data available - defaulting to demo data. Parameter preparation attempt {}: {}",
attempt,
# Never cancel the run and never change the user's configuration:
# optimize with the demo electric vehicle for this run only.
logger.error(
"Electric vehicle '{}' cannot be prepared for the optimization: {} "
"Using the demo electric vehicle for this run.",
electric_vehicle_config.device_id,
e,
)
cls.config.devices.max_electric_vehicles = 1
cls.config.devices.electric_vehicles = {
"ev1": {
"device_id": "ev1",
"capacity_wh": 50000,
"charge_rates": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
"min_soc_percentage": 70,
},
}
# Retry
continue
electric_vehicle_config = BatteriesCommonSettings(
**DEMO_ELECTRIC_VEHICLE_SETTINGS
)
(
ev_parameters,
_,
) = electric_vehicle_config.resolve_operating_parameters_or_defaults()
electric_vehicle_params = electric_vehicle_config.to_genetic0_ev_bat_param(
ev_parameters
)
# Initial SOC
try:
initial_soc_factor = await cls._nearest_soc_factor(
@@ -529,16 +529,34 @@ class Genetic0Solution(ConfigMixin, Genetic0ParametersBaseModel):
- DC charge factor (PV): zeroed when battery is at or above max SOC
(the inverter curtails automatically, but this makes intent clear).
- Discharge: blocked when SOC is at or below min SOC.
The battery values are the optimizer parameters the solution was computed
with (capacity, efficiency, power limit and SOC range as resolved from the
battery profile), not the raw battery settings.
"""
bat_dict = self.config.devices.batteries
if bat_dict is None or len(bat_dict) <= 0:
parameters = getattr(self, "parameters", None)
if parameters is not None:
bat = parameters.pv_battery
else:
bat_dict = self.config.devices.batteries or {}
bat = None
if bat_dict:
# A configuration error gives the defaults of the parameter
# preparation; the configuration check already reported it.
settings = list(bat_dict.values())[0]
snapshot, _ = settings.resolve_operating_parameters_or_defaults(report=False)
bat = settings.to_genetic0_pv_bat_param(snapshot)
if bat is None:
return ac_charge, dc_charge, discharge_allowed
bat = list(bat_dict.values())[0]
min_soc = float(bat.min_soc_percentage)
max_soc = float(bat.max_soc_percentage)
capacity_wh = float(bat.capacity_wh)
ch_eff = float(bat.charging_efficiency)
# Same fallback as the GENETIC0 battery simulation.
bat_max_charge_power_w = (
float(bat.max_charge_power_w) if bat.max_charge_power_w is not None else capacity_wh
)
headroom_wh = max(0.0, (max_soc - soc_pct) / 100.0 * capacity_wh)
# --- AC charge: scale to available headroom ---
@@ -553,7 +571,7 @@ class Genetic0Solution(ConfigMixin, Genetic0ParametersBaseModel):
max_ac_cp_w = (
float(inv.max_ac_charge_power_w)
if inv and inv.max_ac_charge_power_w is not None
else float(bat.max_charge_power_w)
else bat_max_charge_power_w
)
max_dc_per_h_wh = effective_ac * max_ac_cp_w * ac_to_dc_eff * ch_eff
if max_dc_per_h_wh > headroom_wh: