mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-12-02 18:36:28 +01:00
refactor(genetic): refactor GENETIC to the consolidated optimizer architecture
Pin result, conversion, plan and visualization of golden runs. Drive GENETIC through the optimizer interface and registry. Move GENETIC into one directory with role-named modules. Prepare every run input once, run from the parameters. Fall back instead of cancelling the optimization run. Simulate battery, EV and inverter from frozen dataclasses. Simulate the home appliance from frozen dataclasses. Convert and visualize from the parameters and result only. Serve GENETIC from its own router. Return a frozen result, build responses in the API. Echo the request as sent, not with an invented time window. Additional changes - Pin that the result does not depend on the number of evaluation workers. - Run the golden module in UTC: until the request date-times are held in UTC they render in the host time zone. - Add Optimizer.run_clock(), so the EMS gets slot length and time zone without GENETIC settings. - Rename ConfigOptimizationRequest, RuntimeForecasts and GeneticCommonSettings as ADR 0010 asks. - Correct the request example in ADR 0010. - Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide. - Add replay files that reproduce each golden result from its parameters. - Drop OptimizationBase from the algorithm. - Give the replay and worker tests own review files against xdist races. - Handle a failing preparation in the EMS like a failing run, no separate cancel path. - Record the fallbacks in CHANGELOG.md and the upgrade guide. - Without an inverter, buy the whole load from the grid instead of planning it at no cost. - Do not charge from the grid without any known price. - Treat an infinite value after the control horizon as a gap. - Correct the documentation that said missing forecasts cancel the run. - Copy the efficiency helpers and the self-consumption table evaluation into GENETIC. - Add CycleTimeWindowSequence, ConsumerScheduleMode and ConsumerDeadlinePolicy as contract names. - Hold the date-times of battery, EV and home appliance requests in UTC, so they render the same on every host. - Drop the UTC pin of the GENETIC golden module; the request date-times no longer depend on the host. - Copy the time window logic GENETIC needs into genetictimewindow.py. - Add ValueTimeWindow as a contract name. - Move the settings' to_genetic_*() converters into the preparation. - Drop the conversion's prediction reads and configuration fallbacks, which runs never reached. - Make the moved docstrings valid reST. - Remove the generic optimization solution route; each optimizer serves its own path. - Import the GENETIC settings from the package. - Record the removed route in CHANGELOG.md and the upgrade guide. - Make the terminal and tail value models frozen dataclasses. - Move the response models into geneticapi; remove geneticsolution and geneticabc. - Remove the legacy appliance start arrays and API, which read the wall clock. - Remove the time window helpers only they used. - Echo a start_solution without start_solution_datetime as sent. - Carry the previous solution's start in the run parameters. - Plan the home appliance cycles that fit, or leave the appliance out, instead of failing. - Move the appliance layout rules into geneticappliancelayout for the preparation. - Leave out a DAILY home appliance whose open windows leave no room for a run, with an error log, instead of silently. - Name the reason of the SoC fallback instead of Python's exception text. - Answer a solution request for an unknown algorithm with a 404 problem response. - Record the fixes in CHANGELOG.md and the upgrade guide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b108335ee4
commit
b3d5334d3e
@@ -9,7 +9,7 @@
|
||||
| ---- | -------------------- | ---- | --------- | ------- | ----------- |
|
||||
| algorithm | `EOS_OPTIMIZATION__ALGORITHM` | `<enum 'OptimizationAlgorithm'>` | `rw` | `required` | Optimization algorithm [GENETIC | GENETIC0]. Defaults to GENETIC. |
|
||||
| algorithms | | `list[str]` | `ro` | `N/A` | Available optimization algorithms. |
|
||||
| genetic | `EOS_OPTIMIZATION__GENETIC` | `GeneticCommonSettings` | `rw` | `required` | GENETIC optimization algorithm configuration. |
|
||||
| genetic | `EOS_OPTIMIZATION__GENETIC` | `GeneticSettings` | `rw` | `required` | GENETIC optimization algorithm configuration. |
|
||||
| genetic0 | `EOS_OPTIMIZATION__GENETIC0` | `Genetic0Settings` | `rw` | `required` | GENETIC0 optimization algorithm configuration. |
|
||||
| keys | | `list[str]` | `ro` | `N/A` | The keys of the solution. |
|
||||
| self_consumption_interpolator | `EOS_OPTIMIZATION__SELF_CONSUMPTION_INTERPOLATOR` | `<enum 'GridInterpolatorBackend'>` | `rw` | `scipy` | 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. |
|
||||
|
||||
+24
-35
@@ -1,6 +1,6 @@
|
||||
# Akkudoktor-EOS
|
||||
|
||||
**Version**: `v0.3.0.dev2611151515912129`
|
||||
**Version**: `v0.3.0.dev2611261279306014`
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
**Description**: This project provides a comprehensive solution for simulating and optimizing an energy system based on renewable energy sources. With a focus on photovoltaic (PV) systems, battery storage (batteries), load management (consumer requirements), heat pumps, electric vehicles, and consideration of electricity price data, this system enables forecasting and optimization of energy flow and costs over a specified period.
|
||||
@@ -750,6 +750,28 @@ Get the latest solution of the optimization.
|
||||
|
||||
---
|
||||
|
||||
## GET /v1/energy-management/optimization/solution/GENETIC
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
**Links**: [local](http://localhost:8503/docs#/default/fastapi_energy_management_optimization_solution_genetic_get_v1_energy-management_optimization_solution_genetic_get), [eos](https://petstore3.swagger.io/?url=https://raw.githubusercontent.com/Akkudoktor-EOS/EOS/refs/heads/main/openapi.json#/default/fastapi_energy_management_optimization_solution_genetic_get_v1_energy-management_optimization_solution_genetic_get)
|
||||
<!-- pyml enable line-length -->
|
||||
|
||||
Fastapi Energy Management Optimization Solution Genetic Get
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
```python
|
||||
"""
|
||||
Get the latest GENETIC specific solution of the optimization.
|
||||
"""
|
||||
```
|
||||
<!-- pyml enable line-length -->
|
||||
|
||||
**Responses**:
|
||||
|
||||
- **200**: Successful Response
|
||||
|
||||
---
|
||||
|
||||
## GET /v1/energy-management/optimization/solution/GENETIC/pdf
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
@@ -798,39 +820,6 @@ Get the latest GENETIC0 specific solution of the optimization.
|
||||
|
||||
---
|
||||
|
||||
## GET /v1/energy-management/optimization/solution/{algorithm}
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
**Links**: [local](http://localhost:8503/docs#/default/fastapi_energy_management_optimization_solution_algorithm_get_v1_energy-management_optimization_solution__algorithm__get), [eos](https://petstore3.swagger.io/?url=https://raw.githubusercontent.com/Akkudoktor-EOS/EOS/refs/heads/main/openapi.json#/default/fastapi_energy_management_optimization_solution_algorithm_get_v1_energy-management_optimization_solution__algorithm__get)
|
||||
<!-- pyml enable line-length -->
|
||||
|
||||
Fastapi Energy Management Optimization Solution Algorithm Get
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
```python
|
||||
"""
|
||||
Get the latest algorithm specific solution of the optimization.
|
||||
|
||||
Optimizers of the registry serve their own solution path (e.g. ``.../solution/GENETIC0``).
|
||||
|
||||
Args:
|
||||
algorithm: Optimization algorithm
|
||||
"""
|
||||
```
|
||||
<!-- pyml enable line-length -->
|
||||
|
||||
**Parameters**:
|
||||
|
||||
- `algorithm` (path, required): No description provided.
|
||||
|
||||
**Responses**:
|
||||
|
||||
- **200**: Successful Response
|
||||
|
||||
- **422**: Validation Error
|
||||
|
||||
---
|
||||
|
||||
## GET /v1/energy-management/plan
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
@@ -1420,7 +1409,7 @@ The deprecated /optimize endpoint continues to run hourly GENETIC0.
|
||||
**Request Body**:
|
||||
|
||||
- `application/json`: {
|
||||
"$ref": "#/components/schemas/ConfigOptimizationRequest"
|
||||
"$ref": "#/components/schemas/GeneticRequest"
|
||||
}
|
||||
|
||||
**Responses**:
|
||||
|
||||
@@ -31,8 +31,9 @@ optimizer, not even its package.
|
||||
only the contract classes (`OptimizationSolution`) may be imported from there outside parameter
|
||||
preparation; the architecture test lists them. The same holds for the contract types that live
|
||||
in otherwise banned modules: the solution's `PydanticDateTimeDataFrame`, the operation-mode enums
|
||||
the plan's instructions name and the request schema's time windows (`TimeWindow`,
|
||||
`TimeWindowSequence`), but only in the modules that build the output or define the request; the
|
||||
the plan's instructions name and the request schema's time windows and consumer enums
|
||||
(`TimeWindow`, `TimeWindowSequence`, ...; the architecture test lists them), but only in the
|
||||
modules that build the output or define the request; the
|
||||
parameters and the simulation never see them.
|
||||
- The operation-mode enums and settings-side resolution stay shared because they describe the
|
||||
configuration, not an optimizer; an optimizer translates them into its own types during
|
||||
|
||||
@@ -3,14 +3,19 @@
|
||||
Every optimizer follows the same three-step interface (prepare, run, convert), so the energy management can drive any of
|
||||
them the same way and every run can be replayed from its optimization parameters. The interface is
|
||||
a `Protocol` generic in the optimizer's optimization parameters `P`, optimization request `Q` and
|
||||
optimization result `R`, with `prepare()` and `prepare_from_request()` (asynchronous, given the run
|
||||
start, the observation time, the warm start and run-time overrides), `run()`, `convert()`
|
||||
optimization result `R`, with `run_clock()` (the slot length and time zone of the next run),
|
||||
`prepare()` and `prepare_from_request()` (asynchronous, given the run start, the observation
|
||||
time, the warm start and run-time overrides), `run()`, `convert()`
|
||||
(asynchronous), which returns the optimization solution and the energy management plan, and
|
||||
`api()`, which hands out the optimizer's REST router
|
||||
([0011](0011-optimizer-api-visualization-and-wizard-get-no-exception.md)). Its current signature
|
||||
is kept in one place, the `optimizer-architecture` skill
|
||||
(`ai/skills/optimizer-architecture/SKILL.md`).
|
||||
|
||||
- `run_clock()` gives the energy management the optimizer's slot length and, for a run without
|
||||
an explicit start, the time zone to take the current time in; the energy management rounds the
|
||||
start down to a slot boundary before `prepare()`. The optimizer reads both from its settings
|
||||
through its parameter preparation; the energy management knows no optimizer's settings.
|
||||
- `prepare()` is the parameter preparation. It never fails and never returns `None` (see the
|
||||
`energy-domain` skill); the energy management never cancels a run because of it.
|
||||
- `run()` is CPU-bound and deterministic: the same optimization parameters give the same result.
|
||||
@@ -25,7 +30,7 @@ result (the warm start) to `prepare()` as arguments, so no part of an optimizer
|
||||
the warm start and its start datetime travel into `run()` inside the optimization parameters.
|
||||
|
||||
Optimization requests from clients (the parameters accepted by `POST /optimize` and the GENETIC0
|
||||
legacy endpoint, and `ConfigOptimizationRequest`) never go straight into `run()`. They keep their
|
||||
legacy endpoint, and `GeneticRequest`) never go straight into `run()`. They keep their
|
||||
public schema (`Q`) and go through the optimizer's parameter preparation,
|
||||
`prepare_from_request()`, which fills everything the
|
||||
request does not carry (time zone, device IDs, algorithm settings) from the configuration and
|
||||
@@ -36,7 +41,7 @@ preparation; a request that is valid but incomplete is completed, never rejected
|
||||
## Considered Options
|
||||
|
||||
- **Preparation reads the previous result from the energy management**: rejected. It keeps the
|
||||
optimizer coupled to EMS internals (today `get_ems().genetic_solution()`), and a run cannot be
|
||||
optimizer coupled to EMS internals (as GENETIC's `get_ems().genetic_solution()` did), and a run cannot be
|
||||
reproduced from its parameters alone.
|
||||
- **Algorithm settings passed beside the parameters**: rejected. A stored parameter set would not
|
||||
be enough to replay a run.
|
||||
|
||||
@@ -18,7 +18,7 @@ fit a role use the `<name>` prefix as well, also inside subdirectories such as `
|
||||
|
||||
## Consequences
|
||||
|
||||
- The public classes are renamed (e.g. `GeneticOptimizationParameters` → `GeneticRequest`,
|
||||
- The public classes are renamed (e.g. `ConfigOptimizationRequest` → `GeneticRequest`,
|
||||
`GeneticCommonSettings` → `GeneticSettings`). Field names and payloads stay unchanged; the
|
||||
schema names in OpenAPI and the configuration documentation change. Nested request models are
|
||||
renamed `<Name><Thing>Request` as well (e.g. `Genetic0InverterParameters` →
|
||||
|
||||
@@ -16,8 +16,8 @@ state today. None of them gets an exception from
|
||||
imports the server either. It reports errors as the generic `OptimizerProblem`, which the server
|
||||
renders like its own problem responses, and it holds the public response models, built from the
|
||||
optimization parameters and result. The server includes the optimizers' routers before its own
|
||||
routes, so an optimizer's specific path (`.../solution/GENETIC0`) wins over a generic one
|
||||
(`.../solution/{algorithm}`).
|
||||
routes, so an optimizer's specific path (e.g. `.../solution/GENETIC0`) wins over any generic
|
||||
one; each optimizer serves its own solution path.
|
||||
- Wizard steps are not code. They are metadata on the fields of `<name>settings.py` (which fields
|
||||
the wizard asks for, and in which order), which EOSdash reads; an optimizer contains no EOSdash
|
||||
code.
|
||||
|
||||
@@ -412,12 +412,11 @@ as `feed_in_tariff_wh` in EUR/Wh, converted from the API's EUR/MWh prices. These
|
||||
are raw market prices; no import charges or VAT are added.
|
||||
|
||||
Only published prices are stored. If the data does not cover the configured
|
||||
GENETIC control horizon, automatic optimization cancels with a missing tariff error
|
||||
instead of extending the final known price. GENETIC0 carries the last known tariff
|
||||
forward and logs the missing tariff as an error. Request, response, and storage
|
||||
GENETIC or GENETIC0 control horizon, automatic optimization carries the last known
|
||||
tariff forward and logs the missing tariff as an error. Request, response, and storage
|
||||
errors also fail the update, including when older prices are already stored.
|
||||
Set the control horizon within the published day-ahead window to use this
|
||||
provider for automatic optimization.
|
||||
Set the control horizon within the published day-ahead window to plan with the
|
||||
published tariffs.
|
||||
|
||||
Example configuration:
|
||||
|
||||
|
||||
@@ -35,7 +35,9 @@ automations and scripts do not. Check those paths and the saved configuration af
|
||||
migration. Battery wear cost is named `levelized_cost_of_storage_amt_kwh`.
|
||||
|
||||
The new GENETIC currently supports one inverter, one stationary battery, one EV and
|
||||
multiple household appliances. It rejects unsupported counts or inconsistent links.
|
||||
multiple household appliances. Surplus devices and a battery not linked to the inverter are
|
||||
left out of the run, and each is logged as an error; without a usable inverter the run plans
|
||||
grid energy only. Check the log after migrating your devices.
|
||||
|
||||
### 2. The two optimizer endpoints have different contracts
|
||||
|
||||
@@ -59,7 +61,7 @@ in the body and query-string overrides are rejected. Do not migrate by changing
|
||||
The legacy endpoint remains available, but the surrounding configuration has changed.
|
||||
That is not a promise that every old script works unchanged.
|
||||
|
||||
### 3. SoC measurements are optional; complete forecasts are required
|
||||
### 3. Missing SoC measurements and forecasts get logged fallbacks
|
||||
|
||||
Request SoC values are integer percentages from 0 to 100, keyed by device ID. Automatic
|
||||
measurement lookup instead reads a factor from 0 to 1 using the configured measurement
|
||||
@@ -76,10 +78,14 @@ The default measurement freshness limit is 300 seconds, controlled by
|
||||
`optimization.genetic.measurement_max_age_seconds`. This limit determines whether a
|
||||
measurement can be used; it does not require an update before every run.
|
||||
|
||||
Missing forecasts within the control period also stop the run. A shorter forecast
|
||||
continuation is allowed and reported. Failed calls return an error; they no longer look
|
||||
like a successful new run by returning an older result. Existing automations should
|
||||
handle errors and verify the timestamp of any separately retrieved stored plan.
|
||||
Missing or invalid forecasts within the control period do not stop the run either. A
|
||||
forecast value that is missing, NaN or infinite within the control horizon gets a fallback:
|
||||
PV 0, an even load of 3000 kWh per year, a price or feed-in tariff carried forward (else the
|
||||
next known value, else 0); a negative PV or load value becomes 0. Each fallback is logged as
|
||||
an error: check the log after setting up your forecasts. A shorter forecast continuation is
|
||||
allowed and reported. Failed calls return an error; they no longer look like a successful
|
||||
new run by returning an older result. Existing automations should handle errors and verify
|
||||
the timestamp of any separately retrieved stored plan.
|
||||
|
||||
A charging target may equal the configured maximum SoC. For example,
|
||||
`devices.electric_vehicles.car.min_soc_percentage = 100` is valid when
|
||||
@@ -110,12 +116,20 @@ time, charging power and supported charge rates.
|
||||
legacy GENETIC0 response format.
|
||||
- The OpenAPI schema names of the optimizers follow one scheme; fields and paths are unchanged:
|
||||
GENETIC0's `Genetic0OptimizationParameters` is `Genetic0Request`, its device and forecast
|
||||
models are `Genetic0<Thing>Request` and `Genetic0CommonSettings` is `Genetic0Settings`.
|
||||
Clients generated from `openapi.json` must follow the new names.
|
||||
models are `Genetic0<Thing>Request` and `Genetic0CommonSettings` is `Genetic0Settings`;
|
||||
GENETIC's `ConfigOptimizationRequest` is `GeneticRequest`, `RuntimeForecasts` is
|
||||
`GeneticForecastsRequest`, its device and forecast models are `Genetic<Thing>Request` (e.g.
|
||||
`SolarPanelBatteryParameters` is `GeneticBatteryRequest`) and `GeneticCommonSettings` is
|
||||
`GeneticSettings`. Clients generated from `openapi.json` must follow the new names.
|
||||
- The `parameters` echoed in a GENETIC result are the request as sent: a home appliance without
|
||||
time windows shows `time_windows: null`, no placeholder window.
|
||||
|
||||
The new report endpoint is
|
||||
`GET /v1/energy-management/optimization/solution/GENETIC/pdf`. It renders the stored
|
||||
GENETIC result and returns 404 if none exists. The legacy PDF endpoint remains separate.
|
||||
The stored GENETIC result itself is `GET /v1/energy-management/optimization/solution/GENETIC`
|
||||
(GENETIC0: `.../solution/GENETIC0`). The generic route `.../solution/{algorithm}` is gone; use
|
||||
the algorithm's own path. Any other algorithm name gets a 404 problem response (formerly 422).
|
||||
|
||||
### 5. Costs and schedules may change even with the same forecasts
|
||||
|
||||
@@ -154,8 +168,9 @@ storage interfaces: await those methods. HTTP clients continue to exchange JSON.
|
||||
compare units, timestamps, expected energy flows and costs before applying commands.
|
||||
4. Try an EV deadline and a household-appliance window if you use them. Check the stored
|
||||
result, execution plan and PDF agree. Test the legacy endpoint if you still rely on it.
|
||||
5. Test one missing-forecast or stale-measurement case. Confirm your automation handles
|
||||
the error and does not execute an old plan as a new one.
|
||||
5. Test one missing-forecast or stale-measurement case. Confirm the run reports its fallback
|
||||
in the log, and that your automation handles failed calls and does not execute an old plan
|
||||
as a new one.
|
||||
|
||||
Automated tests cover the model and API contracts. They do not replace checking your
|
||||
actual Home Assistant entities, Node-RED flows, forecast sources and connected devices.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
This package depends on the device-map and algorithm-converter configuration work
|
||||
from PR #1256 and the runtime settings foundation from PR #1305. Parameter classes
|
||||
remain in `devices/genetic`; settings remain in `devices/settings`.
|
||||
remain in `optimization/genetic/devices`; settings remain in `devices/settings`.
|
||||
|
||||
Battery and inverter models accept a slot duration, apply power limits as energy
|
||||
per slot, and preserve the total battery charge/discharge budget across multiple
|
||||
|
||||
@@ -46,8 +46,8 @@ the earlier `integration/eos-consolidation-20260916` is a historical checkpoint.
|
||||
- Automatic GENETIC runs use the site's timezone derived from its coordinates;
|
||||
explicit run starts and warmstart timestamps retain their timezone/instant.
|
||||
Configure device IDs and schedules against this timezone, including DST.
|
||||
- GET `/v1/energy-management/optimization/solution/{algorithm}` returns the stored
|
||||
algorithm-specific result. Native/generic results and execution plans publish
|
||||
- GET `/v1/energy-management/optimization/solution/GENETIC` (and `.../GENETIC0`) returns
|
||||
the stored algorithm-specific result. Native/generic results and execution plans publish
|
||||
atomically for the successful run. Failed Optimize calls return errors rather
|
||||
than a previous successful result.
|
||||
- GET `/v1/energy-management/optimization/solution/GENETIC/pdf` renders the stored
|
||||
|
||||
@@ -33,7 +33,8 @@ Use `interval_sec: 3600` for hourly operation. AUTO evaluates available forecast
|
||||
continuation; FIXED uses `terminal_value_euro_per_kwh`. Battery wear/LCOS remains a
|
||||
separate cost. The tail affects scoring, never the emitted control horizon.
|
||||
`prediction.hours` must cover the control horizon; shorter available tails are
|
||||
clipped with diagnostics. Missing control forecasts cancel the run.
|
||||
clipped with diagnostics. Missing control forecasts do not cancel the run: each
|
||||
gets a fallback for the run, logged as an error naming the forecast.
|
||||
|
||||
Old feature settings such as `optimization.interval` and flat terminal-value fields
|
||||
migrate into `optimization.genetic`; explicit nested settings win. Check the saved
|
||||
|
||||
Reference in New Issue
Block a user