Files
EOS/src/akkudoktoreos/optimization/optimization.py
T
560370281f perf(prediction): optional SciPy-free evaluation of the self-consumption tables (#1378)
* perf(prediction): evaluate self-consumption tables without SciPy

The GENETIC inverter (and the GENETIC0 one) evaluates a pickled
scipy.interpolate.RegularGridInterpolator for the self-consumption
probabilities. SciPy is used nowhere else in EOS, yet loading it costs
about 35 MB RSS (21 MB anonymous) on Linux arm64, which every
optimization run pays.

Add utils/gridinterpolator.py:

- LinearGridInterpolator: 2-D linear interpolation with the same steps
  as SciPy's linear 2-D path (interval search, normalised distances,
  corner weights summed in the same order, fill value outside the grid,
  NaN for NaN input).
- load_grid_interpolator(): reads the shipped pickles with a restricted
  unpickler that maps the SciPy class to a stand-in and accepts only
  the NumPy globals needed for the arrays. SciPy is not imported, and
  the data files no longer depend on SciPy's private module paths.

Results are bit-identical to SciPy on Linux (aarch64, checked on 3.6M
points per table including the query pattern of the inverter). The
macOS arm64 SciPy wheel fuses multiply-add, so there SciPy itself
differs by <= 1.1e-16; GENETIC plans for fixed seeds are unchanged on
both platforms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(prediction): make the SciPy-free table evaluation opt-in

Add optimization.self_consumption_interpolator (scipy | numpy, default scipy).
The default keeps evaluating the self-consumption tables with SciPy's
RegularGridInterpolator, built from the same grid, values and fill value the
pickle holds, so results are unchanged. With numpy the tables are evaluated by
LinearGridInterpolator and SciPy is never imported. The backend is read on
every evaluation, so a config change applies to the next run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Christin <christin@BigBrother.bikini.bottom.zone>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Andreas <drbacke@gmx.de>
2026-10-11 09:38:14 +02:00

181 lines
6.8 KiB
Python

from enum import StrEnum
from typing import Any, Optional
from pydantic import Field, computed_field, model_validator
from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.core.pydantic import (
PydanticBaseModel,
PydanticDateTimeDataFrame,
)
from akkudoktoreos.optimization.genetic0.genetic0settings import Genetic0CommonSettings
from akkudoktoreos.optimization.genetic.geneticsettings import (
GeneticCommonSettings,
normalize_genetic_settings,
)
from akkudoktoreos.utils.datetimeutil import DateTime
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
class OptimizationAlgorithm(StrEnum):
"""Optimization Algorithm."""
GENETIC = "GENETIC"
GENETIC0 = "GENETIC0"
def optimization_default_algorithm() -> OptimizationAlgorithm:
"""Provide default optimization algorithm."""
return OptimizationAlgorithm.GENETIC
class OptimizationCommonSettings(SettingsBaseModel):
"""General Optimization Configuration."""
@model_validator(mode="before")
@classmethod
def normalize_old_genetic_settings(cls, value: Any) -> Any:
"""Accept the feature branch's flat GENETIC settings without losing values."""
return normalize_genetic_settings(value)
algorithm: OptimizationAlgorithm = Field(
default_factory=optimization_default_algorithm,
json_schema_extra={
"description": (
f"Optimization algorithm "
f"[{' | '.join(mode.value for mode in OptimizationAlgorithm)}]. "
f"Defaults to {optimization_default_algorithm()}."
),
"examples": ["GENETIC", "GENETIC0"],
},
)
genetic: GeneticCommonSettings = Field(
default_factory=GeneticCommonSettings,
json_schema_extra={
"description": "GENETIC optimization algorithm configuration.",
"examples": [{"individuals": 400, "seed": None, "penalties": {"ev_soc_miss": 10}}],
},
)
genetic0: Genetic0CommonSettings = Field(
default_factory=Genetic0CommonSettings,
json_schema_extra={
"description": "GENETIC0 optimization algorithm configuration.",
"examples": [{"individuals": 400, "seed": None, "penalties": {"ev_soc_miss": 10}}],
},
)
self_consumption_interpolator: GridInterpolatorBackend = Field(
default=GridInterpolatorBackend.SCIPY,
json_schema_extra={
"description": (
"How the inverter's self-consumption probability table is evaluated "
"[scipy | numpy]. 'scipy' (default) uses scipy.interpolate. 'numpy' gives "
"the same values without importing SciPy, which saves about 35 MB RSS "
"after the first optimization run (useful on devices with little RAM); "
"a run takes about 2.5 % longer."
),
"examples": ["scipy", "numpy"],
},
)
# Computed fields
@computed_field # type: ignore[prop-decorator]
@property
def algorithms(self) -> list[str]:
"""Available optimization algorithms."""
return [algo.value for algo in OptimizationAlgorithm]
@computed_field # type: ignore[prop-decorator]
@property
def keys(self) -> list[str]:
"""The keys of the solution."""
try:
ems_eos = get_ems()
except Exception:
# ems might not be initialized
return []
key_list = []
optimization_solution = ems_eos.optimization_solution()
if optimization_solution:
# Prepare mapping
df = optimization_solution.solution.to_dataframe()
key_list = df.columns.tolist()
return sorted(set(key_list))
class OptimizationSolution(PydanticBaseModel):
"""General Optimization Solution."""
id: str = Field(
..., json_schema_extra={"description": "Unique ID for the optimization solution."}
)
generated_at: DateTime = Field(
..., json_schema_extra={"description": "Timestamp when the solution was generated."}
)
comment: Optional[str] = Field(
default=None,
json_schema_extra={"description": "Optional comment or annotation for the solution."},
)
valid_from: Optional[DateTime] = Field(
default=None, json_schema_extra={"description": "Start time of the optimization solution."}
)
valid_until: Optional[DateTime] = Field(
default=None, json_schema_extra={"description": "End time of the optimization solution."}
)
total_losses_energy_wh: float = Field(
json_schema_extra={"description": "The total losses in watt-hours over the entire period."}
)
total_revenues_amt: float = Field(
json_schema_extra={"description": "The total revenues [money amount]."}
)
total_costs_amt: float = Field(
json_schema_extra={"description": "The total costs [money amount]."}
)
fitness_score: set[float] = Field(
json_schema_extra={"description": "The fitness score as a set of fitness values."}
)
prediction: PydanticDateTimeDataFrame = Field(
json_schema_extra={
"description": (
"Datetime data frame with time series prediction data per optimization interval:"
"- pv_energy_wh: PV energy prediction (positive) in wh"
"- elec_price_amt_kwh: Electricity price prediction in money per kwh"
"- feed_in_tariff_amt_kwh: Feed in tariff prediction in money per kwh"
"- weather_temp_air_celcius: Temperature in °C"
"- loadforecast_energy_wh: Load mean energy prediction in wh"
"- loadakkudoktor_std_energy_wh: Load energy standard deviation prediction in wh"
"- loadakkudoktor_mean_energy_wh: Load mean energy prediction in wh"
)
}
)
solution: PydanticDateTimeDataFrame = Field(
json_schema_extra={
"description": (
"Datetime data frame with time series solution data per optimization interval:"
"- load_energy_wh: Load of all energy consumers in wh"
"- grid_energy_wh: Grid energy feed in (negative) or consumption (positive) in wh"
"- costs_amt: Costs in money amount"
"- revenue_amt: Revenue in money amount"
"- losses_energy_wh: Energy losses in wh"
"- <device-id>_operation_mode_id: Operation mode id of the device."
"- <device-id>_operation_mode_factor: Operation mode factor of the device."
"- <device-id>_soc_factor: State of charge of a battery/ electric vehicle device as factor of total capacity."
"- <device-id>_energy_wh: Energy consumption (positive) of a device in wh."
)
}
)