mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 23:16:18 +01:00
* 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(measurement): restore JSON records into the existing singleton * fix(devices): preserve charge-rate typing and public import compatibility * feat(measurement): integrate typed energy quality and capacity APIs Port the locally backed-up measurement extensions to main async storage and PR #1256 device maps. Preserve runtime capacity estimates across #1305 bulk updates. Confirm JSON singleton restore defect on unchanged main and add regression. No production configuration or measurements included. Co-authored-by: Andreas <drbacke@gmx.de> * docs(measurement): describe household settings and consolidate regression coverage * docs(measurement): regenerate configuration and API contracts * test(measurement): isolate capacity database state between tests * ruff format fix * test(measurement): assert restored timestamps before timezone conversion * docs(measurement): align API version with refreshed prerequisites * fix(config): satisfy typed device conversion and migration contracts * docs(config): refresh validated configuration prerequisite schemas * fix(measurement): enforce typed capacity and sample validation * style(measurement): normalize imports for CI * docs(measurement): refresh typed measurement API 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>
214 lines
8.8 KiB
Python
214 lines
8.8 KiB
Python
"""Estimate effective model capacity from independent SoC anchors and DC power."""
|
|
|
|
from datetime import datetime
|
|
from math import isfinite
|
|
from typing import TYPE_CHECKING, Literal
|
|
|
|
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator
|
|
|
|
from akkudoktoreos.config.configabc import SettingsBaseModel
|
|
from akkudoktoreos.measurement.quality import SampleQuality
|
|
|
|
if TYPE_CHECKING:
|
|
from akkudoktoreos.measurement.measurement import MeasurementChannelSettings
|
|
|
|
|
|
class BatteryCapacityEstimationSettings(SettingsBaseModel):
|
|
"""Only a battery-terminal DC power channel is supported, not inverter AC."""
|
|
|
|
power_key: str = Field(min_length=1)
|
|
positive_power: Literal["charging", "discharging"]
|
|
measurement_boundary: Literal["battery_dc"] = "battery_dc"
|
|
min_soc_change_percentage: float = Field(default=20, gt=0, le=100)
|
|
max_duration_hours: float = Field(default=168, gt=0, le=744)
|
|
|
|
|
|
class CapacityModel(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
|
|
|
|
|
|
class BatteryCapacityRequest(CapacityModel):
|
|
"""Caller attests both anchors are independent of the capacity being fitted.
|
|
|
|
End is the first confirmed full point when using the default end SoC.
|
|
Voltage/current anchors must be independently established for the chemistry.
|
|
"""
|
|
|
|
start: AwareDatetime
|
|
end: AwareDatetime
|
|
start_soc_percentage: float = Field(ge=0, le=100)
|
|
end_soc_percentage: float = Field(default=100, ge=0, le=100)
|
|
soc_reference: Literal["bms", "external_calibration", "voltage_current_anchor"]
|
|
store_estimate: bool = False
|
|
|
|
@model_validator(mode="after")
|
|
def ordered(self) -> "BatteryCapacityRequest":
|
|
if self.end.timestamp() <= self.start.timestamp():
|
|
raise ValueError("end must be after start.")
|
|
return self
|
|
|
|
|
|
class BatteryCapacityEstimate(CapacityModel):
|
|
battery_id: str
|
|
start: AwareDatetime
|
|
end: AwareDatetime
|
|
soc_reference: str
|
|
start_soc_percentage: float
|
|
end_soc_percentage: float
|
|
estimated_capacity_wh: float
|
|
configured_capacity_wh: float
|
|
capacity_change_percentage: float
|
|
model_end_soc_percentage_unclipped: float
|
|
model_soc_error_percentage_points: float
|
|
charge_energy_wh: float
|
|
discharge_energy_wh: float
|
|
stored_energy_change_wh: float
|
|
charging_efficiency: float
|
|
discharging_efficiency: float
|
|
power_key: str
|
|
positive_power: str
|
|
integration_method: str
|
|
coverage_seconds: float
|
|
samples_used: int
|
|
warnings: list[str]
|
|
|
|
|
|
def estimate_capacity(
|
|
request: BatteryCapacityRequest,
|
|
settings: BatteryCapacityEstimationSettings,
|
|
channel: "MeasurementChannelSettings",
|
|
samples: list[tuple[datetime, float | None, SampleQuality]],
|
|
*,
|
|
battery_id: str,
|
|
capacity_wh: float,
|
|
charging_efficiency: float,
|
|
discharging_efficiency: float,
|
|
) -> BatteryCapacityEstimate:
|
|
"""Fit C in C * delta_soc = eta_c * E_charge - E_discharge / eta_d.
|
|
|
|
No clipping at 0/100%, extrapolation, gap filling or efficiency fitting.
|
|
Linear segments are split at zero before applying directional efficiencies.
|
|
"""
|
|
left, right = request.start.timestamp(), request.end.timestamp()
|
|
if right - left > settings.max_duration_hours * 3600:
|
|
raise ValueError("Requested period exceeds capacity_estimation.max_duration_hours.")
|
|
delta_soc = (request.end_soc_percentage - request.start_soc_percentage) / 100
|
|
if abs(delta_soc) * 100 + 1e-9 < settings.min_soc_change_percentage:
|
|
raise ValueError(
|
|
"Independent SoC change is too small; full-to-full cannot identify capacity."
|
|
)
|
|
if channel.quantity != "power":
|
|
raise ValueError("Capacity estimation requires signed battery DC power in W or kW.")
|
|
max_gap_seconds = channel.max_gap_seconds
|
|
integration_method = channel.integration_method
|
|
if max_gap_seconds is None or integration_method is None:
|
|
raise ValueError("Power channels require an integration method and maximum sample gap.")
|
|
if not isfinite(capacity_wh) or capacity_wh <= 0:
|
|
raise ValueError("Configured capacity must be positive and finite.")
|
|
if not all(isfinite(e) and 0 < e <= 1 for e in (charging_efficiency, discharging_efficiency)):
|
|
raise ValueError("Battery efficiencies must be finite and in (0, 1].")
|
|
points = []
|
|
for time, value, quality in samples:
|
|
if time.tzinfo is None or time.utcoffset() is None:
|
|
raise ValueError("Explicit sample timezone required.")
|
|
points.append((time.timestamp(), value, quality))
|
|
points.sort(key=lambda row: row[0])
|
|
if any(a[0] == b[0] for a, b in zip(points, points[1:])):
|
|
raise ValueError("Duplicate power sample timestamps.")
|
|
factor = (1000 if channel.unit == "kW" else 1) * (
|
|
1 if settings.positive_power == "charging" else -1
|
|
)
|
|
charge = discharge = coverage = 0.0
|
|
cumulative_net = 0.0
|
|
minimum_net = maximum_net = 0.0
|
|
used: set[float] = set()
|
|
cursor = left
|
|
for (a, va, qa), (b, vb, qb) in zip(points, points[1:]):
|
|
lo, hi = max(left, a), min(right, b)
|
|
if hi <= lo:
|
|
continue
|
|
if lo > cursor + 1e-6 or b - a > max_gap_seconds:
|
|
raise ValueError("Incomplete power coverage or sample gap exceeds max_gap_seconds.")
|
|
if (
|
|
va is None
|
|
or vb is None
|
|
or any(isinstance(v, bool) or not isfinite(v) for v in (va, vb))
|
|
or qa.status != "measured"
|
|
or qb.status != "measured"
|
|
):
|
|
raise ValueError(
|
|
"Capacity estimation requires finite measured power samples throughout."
|
|
)
|
|
if qb.reset or qa.generation != qb.generation:
|
|
raise ValueError("Power sensor reset or generation change within the period.")
|
|
p, q = va * factor, vb * factor
|
|
if integration_method == "linear":
|
|
slope = (q - p) / (b - a)
|
|
p, q = p + slope * (lo - a), p + slope * (hi - a)
|
|
else:
|
|
q = p
|
|
duration = hi - lo
|
|
if p * q < 0:
|
|
first = duration * abs(p) / (abs(p) + abs(q))
|
|
parts = [(p * first / 7200), (q * (duration - first) / 7200)]
|
|
else:
|
|
parts = [(p + q) * duration / 7200]
|
|
charge += sum(max(0, energy) for energy in parts)
|
|
discharge += sum(max(0, -energy) for energy in parts)
|
|
for energy in parts:
|
|
cumulative_net += (
|
|
energy * charging_efficiency if energy >= 0 else energy / discharging_efficiency
|
|
)
|
|
minimum_net = min(minimum_net, cumulative_net)
|
|
maximum_net = max(maximum_net, cumulative_net)
|
|
coverage += duration
|
|
cursor = hi
|
|
used.update((a, b))
|
|
if cursor < right - 1e-6 or abs(coverage - (right - left)) > 1e-6:
|
|
raise ValueError("Incomplete power coverage; no extrapolation to the SoC anchors.")
|
|
net = charge * charging_efficiency - discharge / discharging_efficiency
|
|
capacity = net / delta_soc
|
|
if not isfinite(capacity) or capacity <= 0:
|
|
raise ValueError("Energy flow disagrees with SoC change; check polarity and anchors.")
|
|
if (
|
|
request.start_soc_percentage + minimum_net / capacity * 100 < -1e-6
|
|
or request.start_soc_percentage + maximum_net / capacity * 100 > 100 + 1e-6
|
|
):
|
|
raise ValueError(
|
|
"Fitted SoC leaves 0..100% within the period; check anchors and use the first full point."
|
|
)
|
|
model_end = request.start_soc_percentage + net / capacity_wh * 100
|
|
warnings = [
|
|
"Conditional estimate: SoC anchors, DC measurement boundary and configured efficiencies must be correct.",
|
|
"A single interval cannot independently identify both capacity and efficiencies.",
|
|
"The active capacity_wh is unchanged.",
|
|
]
|
|
if request.soc_reference == "voltage_current_anchor":
|
|
warnings.append(
|
|
"Voltage/current anchors depend on chemistry, temperature and operating conditions."
|
|
)
|
|
return BatteryCapacityEstimate(
|
|
battery_id=battery_id,
|
|
start=request.start,
|
|
end=request.end,
|
|
soc_reference=request.soc_reference,
|
|
start_soc_percentage=request.start_soc_percentage,
|
|
end_soc_percentage=request.end_soc_percentage,
|
|
estimated_capacity_wh=capacity,
|
|
configured_capacity_wh=capacity_wh,
|
|
capacity_change_percentage=(capacity / capacity_wh - 1) * 100,
|
|
model_end_soc_percentage_unclipped=model_end,
|
|
model_soc_error_percentage_points=model_end - request.end_soc_percentage,
|
|
charge_energy_wh=charge,
|
|
discharge_energy_wh=discharge,
|
|
stored_energy_change_wh=net,
|
|
charging_efficiency=charging_efficiency,
|
|
discharging_efficiency=discharging_efficiency,
|
|
power_key=settings.power_key,
|
|
positive_power=settings.positive_power,
|
|
integration_method=integration_method,
|
|
coverage_seconds=coverage,
|
|
samples_used=len(used),
|
|
warnings=warnings,
|
|
)
|