mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-12-02 18:36:28 +01:00
docs(optimization): add optimizer architecture ADRs, skill and test (#1572)
Additional changes - Add the optimizer terms to the glossary. - Point to the skill from AGENTS.md, docs/develop/ai.md and the energy-domain skill. - Match module names case-exactly, also on case-insensitive file systems. 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
1159501713
commit
9adf7b8be2
@@ -51,6 +51,7 @@ Detailed rules live in `ai/skills/`. Load the relevant skill for the task:
|
|||||||
| `ai/skills/commit-messages/SKILL.md` | Creating/checking commit messages |
|
| `ai/skills/commit-messages/SKILL.md` | Creating/checking commit messages |
|
||||||
| `ai/skills/energy-domain/SKILL.md` | Optimization, adapters, units/signs |
|
| `ai/skills/energy-domain/SKILL.md` | Optimization, adapters, units/signs |
|
||||||
| `ai/skills/filename-conventions/SKILL.md` | Creating/renaming files |
|
| `ai/skills/filename-conventions/SKILL.md` | Creating/renaming files |
|
||||||
|
| `ai/skills/optimizer-architecture/SKILL.md` | Optimizers, their parameter preparation, simulation, solution conversion |
|
||||||
| `ai/skills/python-environment/SKILL.md` | Before running uv, make, pytest, mypy, ruff or any Python |
|
| `ai/skills/python-environment/SKILL.md` | Before running uv, make, pytest, mypy, ruff or any Python |
|
||||||
| `ai/skills/python-quality/SKILL.md` | Writing/modifying Python |
|
| `ai/skills/python-quality/SKILL.md` | Writing/modifying Python |
|
||||||
| `ai/skills/rest-api/SKILL.md` | Adding/changing REST endpoints, API error responses |
|
| `ai/skills/rest-api/SKILL.md` | Adding/changing REST endpoints, API error responses |
|
||||||
|
|||||||
+54
@@ -6,10 +6,64 @@ user-facing docs use another name, it is listed under _Avoid_.
|
|||||||
|
|
||||||
## Optimization
|
## Optimization
|
||||||
|
|
||||||
|
**Optimizer**:
|
||||||
|
One optimization algorithm (such as GENETIC or GENETIC0) together with its parameter preparation,
|
||||||
|
simulation, simulation devices and solution conversion.
|
||||||
|
_Avoid_: optimization algorithm (for the whole), optimization
|
||||||
|
|
||||||
|
**Parameter preparation**:
|
||||||
|
The part of an optimizer that derives its optimization parameters from configuration, predictions,
|
||||||
|
measurements, the run start and the warm start, once before each optimization run; the only part of
|
||||||
|
an optimizer that reads configuration, predictions or measurements.
|
||||||
|
_Avoid_: parameter creation, request building
|
||||||
|
|
||||||
|
**Solution conversion**:
|
||||||
|
The part of an optimizer that turns the outcome of an optimization run into the optimization
|
||||||
|
solution and the energy management plan.
|
||||||
|
_Avoid_: solution post-processing
|
||||||
|
|
||||||
|
**Optimization request**:
|
||||||
|
The input a client sends to start an optimization run through the API; parameter preparation
|
||||||
|
completes it into optimization parameters.
|
||||||
|
_Avoid_: optimization parameters (for client input)
|
||||||
|
|
||||||
|
**Optimization result**:
|
||||||
|
The output of an optimizer's run, specific to that optimizer, before solution conversion.
|
||||||
|
_Avoid_: solution (for this)
|
||||||
|
|
||||||
|
**Optimization solution**:
|
||||||
|
The optimizer-independent outcome of an optimization run that the energy management publishes,
|
||||||
|
together with the energy management plan.
|
||||||
|
_Avoid_: result (for this)
|
||||||
|
|
||||||
|
**Warm start**:
|
||||||
|
The result of an optimizer's previous optimization run, used to seed its next run.
|
||||||
|
_Avoid_: start solution, previous solution
|
||||||
|
|
||||||
**Optimization parameters**:
|
**Optimization parameters**:
|
||||||
The complete, valid input set handed to one optimizer for one optimization run.
|
The complete, valid input set handed to one optimizer for one optimization run.
|
||||||
_Avoid_: optimization input, request parameters
|
_Avoid_: optimization input, request parameters
|
||||||
|
|
||||||
|
**Simulation device**:
|
||||||
|
An optimizer's own model of a device (battery, inverter, home appliance, ...) that its simulation
|
||||||
|
steps through an optimization run, built only from the optimization parameters.
|
||||||
|
_Avoid_: device (for this), device settings
|
||||||
|
|
||||||
|
**EMS state**:
|
||||||
|
What the energy management keeps between optimization runs, such as the run start, the last
|
||||||
|
results and the run cache; it reaches an optimizer only as arguments of parameter preparation.
|
||||||
|
_Avoid_: EMS data
|
||||||
|
|
||||||
|
**Golden input**:
|
||||||
|
A stored optimizer input whose expected output (optimization solution or optimization result) is
|
||||||
|
kept with it, so a test can show that a refactoring does not change results.
|
||||||
|
_Avoid_: test fixture (for this), reference data
|
||||||
|
|
||||||
|
**Replay file**:
|
||||||
|
A golden input made of complete optimization parameters plus the expected optimization result, so
|
||||||
|
an optimization run can be repeated without configuration, predictions or measurements.
|
||||||
|
_Avoid_: snapshot, recording
|
||||||
|
|
||||||
**Fallback value**:
|
**Fallback value**:
|
||||||
A default or heuristic value that replaces an invalid or missing input while the optimization
|
A default or heuristic value that replaces an invalid or missing input while the optimization
|
||||||
parameters are prepared, always reported as an error.
|
parameters are prepared, always reported as an error.
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ description: Use when working on optimization logic, adapters, controllers, devi
|
|||||||
|
|
||||||
- Keep optimization logic separate from device-specific communication where
|
- Keep optimization logic separate from device-specific communication where
|
||||||
practical.
|
practical.
|
||||||
|
- How an optimizer is structured, what it may read and import, and how it
|
||||||
|
stays independent of other optimizers: see the `optimizer-architecture`
|
||||||
|
skill.
|
||||||
- Follow existing adapter and controller interfaces.
|
- Follow existing adapter and controller interfaces.
|
||||||
- Respect the distinction between long-horizon energy optimization and fast
|
- Respect the distinction between long-horizon energy optimization and fast
|
||||||
local device control.
|
local device control.
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
---
|
||||||
|
name: optimizer-architecture
|
||||||
|
description: Use when creating, changing, refactoring or removing an optimizer (GENETIC, GENETIC0 or a new one), its parameter preparation, simulation, simulation devices, solution conversion, or the code that runs optimizers.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Optimizer Architecture
|
||||||
|
|
||||||
|
Terms as in `GLOSSARY.md`: **optimizer**, **parameter preparation**, **optimization
|
||||||
|
parameters**, **solution conversion**, **warm start**. The decisions and their reasons are in
|
||||||
|
`docs/adr/` 0003 to 0011; read the ADR before deviating from a rule here, and flag any conflict.
|
||||||
|
|
||||||
|
## One optimizer, four parts
|
||||||
|
|
||||||
|
| Part | May use |
|
||||||
|
|---|---|
|
||||||
|
| Parameter preparation (`<name>prepare.py` or `prepare/`) | configuration, predictions, measurements, and the run start and warm start passed in as arguments |
|
||||||
|
| Algorithm (`run()`) | the optimization parameters only |
|
||||||
|
| Simulation and simulation devices | the optimization parameters only |
|
||||||
|
| Solution conversion (`convert()`) | the optimization parameters and the result of the run only |
|
||||||
|
|
||||||
|
- **Hard rule:** outside parameter preparation, an optimizer never reads
|
||||||
|
configuration, predictions, measurements or EMS state, directly or through a
|
||||||
|
helper that does (e.g. `configured_grid_interpolator_backend()`, the EMS run
|
||||||
|
cache in `core.cache`). This includes data only needed to present the
|
||||||
|
solution: time zone, device IDs, run start and the prediction series the run
|
||||||
|
used travel in the optimization parameters. The modules and names this
|
||||||
|
covers are listed once, in `WORLD_MODULES`, `WORLD_NAMES` and `EMS_*` of
|
||||||
|
`tests/test_optimizerarchitecture.py`; that list is authoritative. Among
|
||||||
|
them: `config`, `prediction`, `measurement`, `adapter`, `server`,
|
||||||
|
`core.ems`, `core.cache`, the `core.*settings` and database modules, the
|
||||||
|
`core.coreabc` mixins and getters, `OptimizationBase` and the shared device
|
||||||
|
configuration (`devices.settings`, `devices.profile`, `devices.devices`,
|
||||||
|
`devices.devicesabc`). From `optimization.optimization` only the contract
|
||||||
|
class `OptimizationSolution` may be imported (`CONTRACT_NAMES`).
|
||||||
|
- Parameter preparation runs once per run, never fails, never returns `None` and follows the
|
||||||
|
"Optimization parameters are always valid" rules of the `energy-domain` skill.
|
||||||
|
- Parameter preparation does not read EMS state either (`core.ems`,
|
||||||
|
`get_ems()`, `EnergyManagementSystemMixin`, `StartMixin`); the energy
|
||||||
|
management passes the run start and the warm start as arguments. No part of
|
||||||
|
an optimizer, its preparation included, imports `akkudoktoreos.server`.
|
||||||
|
- Only `<name>optimizer.py`, the package `__init__.py` and the parameter
|
||||||
|
preparation itself import the parameter preparation. Any other module would
|
||||||
|
reach the configuration through it. The package and `<name>optimizer.py`
|
||||||
|
may re-export the preparation, so the other modules import neither; only
|
||||||
|
the package imports `<name>optimizer.py`.
|
||||||
|
|
||||||
|
## The interface
|
||||||
|
|
||||||
|
This is the one maintained copy of the interface; ADR 0006 records the decision and links here.
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Optimizer(Protocol[P, Q, R]):
|
||||||
|
name: str
|
||||||
|
async def prepare(self, start_datetime: DateTime, warm_start: R | None) -> P
|
||||||
|
async def prepare_from_request(
|
||||||
|
self, request: Q, start_datetime: DateTime, warm_start: R | None
|
||||||
|
) -> P
|
||||||
|
def run(self, parameters: P) -> R
|
||||||
|
def convert(self, parameters: P, result: R) -> tuple[OptimizationSolution, EnergyManagementPlan]
|
||||||
|
```
|
||||||
|
|
||||||
|
- `run()` is deterministic: the same optimization parameters give the same result. Generations,
|
||||||
|
individuals, seed and penalties are part of the optimization parameters; apply a REST override
|
||||||
|
(e.g. `?ngen=`) to the parameters before `run()`, never beside them.
|
||||||
|
- **Optimization parameters (`P`), including the simulation's device
|
||||||
|
parameters, are plain dataclasses, never Pydantic models** (ADR 0009). They
|
||||||
|
are valid because parameter preparation builds them valid, not because a
|
||||||
|
model validates them. Optimization requests (`Q`) and settings models are
|
||||||
|
Pydantic models: validation and public schemas belong where external input
|
||||||
|
arrives.
|
||||||
|
- **Optimization requests never go straight into `run()`.** A REST endpoint
|
||||||
|
passes the client's optimization request (`Q`) to the optimizer's
|
||||||
|
`prepare_from_request()`, which
|
||||||
|
completes it from the configuration with the same fallback rules as
|
||||||
|
`prepare()`. Keep the request's public schema unchanged; add fields the run
|
||||||
|
needs to the optimization parameters, not to the request.
|
||||||
|
- A run must be reproducible from its stored optimization parameters alone. Add a test that runs
|
||||||
|
from a stored parameter file when you change what goes into the parameters.
|
||||||
|
|
||||||
|
## Layout and names (ADR 0010)
|
||||||
|
|
||||||
|
Everything of an optimizer lives in `src/akkudoktoreos/optimization/<name>/`,
|
||||||
|
`<name>` being the optimizer's name in lowercase (`genetic`, `genetic0`); its
|
||||||
|
simulation devices in `devices/` below it. Modules are `<name><role>.py`,
|
||||||
|
classes `<Name><Role>`. This table is the one maintained copy; ADR 0010 links here.
|
||||||
|
|
||||||
|
| Role | Module | Class | Kind |
|
||||||
|
|---|---|---|---|
|
||||||
|
| settings | `<name>settings.py` | `<Name>Settings` | Pydantic, `optimization.<name>` |
|
||||||
|
| request | `<name>request.py` | `<Name>Request` | Pydantic, public API |
|
||||||
|
| parameters | `<name>parameters.py` | `<Name>Parameters` | dataclass, input of `run()` |
|
||||||
|
| preparation | `<name>prepare.py` | `prepare()`, `prepare_from_request()` | |
|
||||||
|
| optimizer | `<name>optimizer.py` | `<Name>Optimizer` | implements the interface |
|
||||||
|
| algorithm | `<name>algorithm.py` | | the search |
|
||||||
|
| result | `<name>result.py` | `<Name>Result` | dataclass, output of `run()` |
|
||||||
|
| simulation | `<name>simulation.py`, `devices/<name><device>.py` | `<Name><Device>`, `<Name><Device>Parameters` | dataclass parameters |
|
||||||
|
| conversion | `<name>convert.py` | `convert()` | |
|
||||||
|
| visualization | `<name>visualize.py` | | renders parameters and result |
|
||||||
|
| API | `<name>api.py` | REST router | fed by FastAPI dependencies |
|
||||||
|
|
||||||
|
- A new module that fits no role still gets the `<name>` prefix. Do not
|
||||||
|
invent a second name for an existing role.
|
||||||
|
- Dataclasses are `@dataclass(frozen=True, slots=True)`. A run never changes
|
||||||
|
its inputs.
|
||||||
|
- Only `<name>settings.py`, `<name>request.py`, parameter preparation and
|
||||||
|
`<name>api.py` may import `pydantic` or `akkudoktoreos.core.pydantic`.
|
||||||
|
|
||||||
|
## Independence
|
||||||
|
|
||||||
|
- An optimizer never imports another optimizer.
|
||||||
|
- **Duplicate code instead of sharing it.** Simulation physics (efficiency curves, AC/DC energy
|
||||||
|
solvers, device models) is copied into each optimizer that needs it. Never move simulation code
|
||||||
|
into a shared module, and never merge copies across optimizers to remove duplication. A fix in
|
||||||
|
one copy reaches another optimizer only through a deliberate change to that optimizer.
|
||||||
|
- An optimizer may import: generic utilities (such as `datetimeutil`; Pydantic only in the roles allowed above), the
|
||||||
|
output contract (`OptimizationSolution`, the energy management plan) and, in parameter
|
||||||
|
preparation only, the configuration settings, including the shared operation-mode enums and
|
||||||
|
settings-side resolution such as battery profiles. Translate those into the optimizer's own
|
||||||
|
types during parameter preparation; do not pass settings objects or enums from the
|
||||||
|
configuration into the simulation.
|
||||||
|
- Code outside an optimizer imports nothing from it but its package
|
||||||
|
(`optimization/<name>/__init__.py`), which exports what the registry and the
|
||||||
|
settings field need. Converting device
|
||||||
|
settings into an optimizer's device parameters belongs to that optimizer's parameter
|
||||||
|
preparation, not to `devices/settings/`: the shared device configuration
|
||||||
|
(`devices.settings`, `devices.profile`, `devices.devices`, `devices.devicesabc`)
|
||||||
|
never imports an optimizer, not even its package.
|
||||||
|
|
||||||
|
## What an optimizer owns
|
||||||
|
|
||||||
|
Its package holds everything specific to it: the settings model `optimization.<name>` and the
|
||||||
|
validation of its horizons, parameter preparation, run, simulation, simulation devices, solution
|
||||||
|
conversion, visualization, its REST endpoints (contributed as a router) and its EOSdash wizard
|
||||||
|
steps. The energy management, the server and EOSdash use only the registry and the interface;
|
||||||
|
never add a branch per optimizer there.
|
||||||
|
|
||||||
|
None of these gets an exception from the hard rule (ADR 0011):
|
||||||
|
|
||||||
|
- `<name>visualize.py` renders from the optimization parameters and result
|
||||||
|
only, like `convert()`.
|
||||||
|
- `<name>api.py` fetches nothing itself. It declares placeholder dependency
|
||||||
|
functions for the last parameters and result and the run trigger; the
|
||||||
|
generic server fills them in through `app.dependency_overrides` from the
|
||||||
|
registry. It imports FastAPI, Pydantic and its request, never
|
||||||
|
configuration, EMS state or `akkudoktoreos.server`.
|
||||||
|
- Wizard steps are field metadata in `<name>settings.py` that EOSdash reads;
|
||||||
|
no EOSdash code inside an optimizer.
|
||||||
|
|
||||||
|
Removing an optimizer touches exactly four places in the production code: its directory, its
|
||||||
|
registry entry, its static settings field in `OptimizationCommonSettings`, and a configuration
|
||||||
|
migration step that drops `optimization.<name>` and switches `optimization.algorithm` to a
|
||||||
|
remaining optimizer. If a change makes removal need anything else, it breaks this rule. What
|
||||||
|
belongs only to the optimizer goes with it: its tests, its test data and, while the architecture
|
||||||
|
test's `BASELINE` lists violations of the optimizer, those entries. The remaining optimizers'
|
||||||
|
tests pass unchanged.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
`tests/test_optimizerarchitecture.py` (ADR 0007) checks the import rules above
|
||||||
|
against `BASELINE`, the violations that existed when it was introduced.
|
||||||
|
|
||||||
|
- Parameter preparation is recognised by file name:
|
||||||
|
`optimization/<name>/<name>prepare.py` or a subpackage
|
||||||
|
`optimization/<name>/prepare/` (a package; a plain `prepare.py` does not
|
||||||
|
count). Only there may an optimizer import the modules and names of the hard
|
||||||
|
rule, except EMS state and the server.
|
||||||
|
- When you find another module or helper that reads configuration,
|
||||||
|
predictions, measurements or EMS state, add it to the list in the test.
|
||||||
|
That is the only case in which `BASELINE` may grow: by the existing uses the
|
||||||
|
new list entry reveals, in the same commit, and named in the pull request.
|
||||||
|
- `optimization/<name>/<name>settings.py` may import `config.configabc` to define
|
||||||
|
`optimization.<name>`, nothing else from the configuration.
|
||||||
|
- Otherwise never add an entry to `BASELINE`, and never rename a module to
|
||||||
|
`*prepare.py` or `*settings.py` just to pass the test. Remove the entries
|
||||||
|
your change fixes; the test fails on stale entries.
|
||||||
|
- The test discovers optimizers (every package under `optimization/`); do not
|
||||||
|
hard-code optimizer names in it.
|
||||||
|
- It cannot detect simulation physics moved into a new shared module, nor a
|
||||||
|
helper that reads the configuration but is missing from the list. Both are
|
||||||
|
enforced by review: treat them as hard violations.
|
||||||
|
- A failing architecture test is a hard violation.
|
||||||
|
|
||||||
|
## Refactoring versus behaviour change (ADR 0008)
|
||||||
|
|
||||||
|
- **Refactoring an optimizer never changes its results.** With a fixed seed,
|
||||||
|
every golden input (`tests/testdata/<optimizer>/optimize_result_*.json`,
|
||||||
|
replay files) gives the same solution as before. Never regenerate or edit
|
||||||
|
golden data in a refactoring; if a golden test fails, the refactoring is
|
||||||
|
wrong.
|
||||||
|
- A change that alters results is a behaviour change: its own pull request,
|
||||||
|
declared as such, never mixed with refactoring.
|
||||||
|
- **GENETIC0 is frozen.** No bug fixes, no behaviour changes, no tuning. Only
|
||||||
|
structural changes needed to follow this architecture, each proven
|
||||||
|
result-identical by its golden tests. Fix a GENETIC0 bug in GENETIC instead,
|
||||||
|
and report it to the user.
|
||||||
|
- Before refactoring an optimizer, add replay files: complete optimization
|
||||||
|
parameters in the new parameter type plus the expected result.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Optimizers see only their optimization parameters
|
||||||
|
|
||||||
|
Configuration, predictions, measurements and EMS state change while an optimization run is in
|
||||||
|
progress, and an optimizer that reads them live can optimize against one state and report the plan
|
||||||
|
against another. So the parameter preparation of an optimizer is the only part of it that reads
|
||||||
|
configuration, predictions or measurements (EMS state reaches it only as arguments, see
|
||||||
|
[0006](0006-optimizer-interface-prepare-run-convert.md)); it runs once before the optimization run and
|
||||||
|
puts everything the run needs into the optimization parameters. The algorithm, the simulation, the
|
||||||
|
simulation devices and the solution conversion use nothing but the optimization parameters and the
|
||||||
|
results of the run, never configuration, predictions, measurements or EMS state, neither directly
|
||||||
|
nor through a helper that reads them (the complete list of modules and names is kept in the
|
||||||
|
architecture test, see [0007](0007-architecture-test-with-shrinking-baseline.md)). This includes information
|
||||||
|
that is only needed to present the solution, such as the time zone, device IDs, the start of the
|
||||||
|
run and the prediction series the run was optimized against.
|
||||||
|
|
||||||
|
## Considered Options
|
||||||
|
|
||||||
|
- **Let the solution conversion read the configuration and predictions**: rejected. A prediction
|
||||||
|
update during the run pairs the solution with a forecast it was not optimized for, and display
|
||||||
|
details such as the time zone can change between preparation and conversion as well.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- An optimizer can be run, tested and replayed from a stored set of optimization parameters alone.
|
||||||
|
- The optimization parameters grow to carry presentation data (time zone, device IDs, start
|
||||||
|
datetime, the prediction series used).
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Optimizers duplicate code instead of sharing it
|
||||||
|
|
||||||
|
Each optimizer must be removable, and must keep its results, when another optimizer is changed or
|
||||||
|
removed. So dependencies run one way only. An optimizer may import generic utilities (such as
|
||||||
|
`datetimeutil`; Pydantic only where
|
||||||
|
[0009](0009-optimization-parameters-are-dataclasses.md) allows it), the output contract (the optimization solution and
|
||||||
|
the energy management plan) and, in its parameter preparation only, the configuration settings
|
||||||
|
(including the shared operation-mode enums and settings-side resolution such as battery profiles),
|
||||||
|
predictions and measurements. It never imports another optimizer, and it does not share simulation
|
||||||
|
physics: helpers such as efficiency curve interpolation or the AC/DC energy solvers are copied into
|
||||||
|
each optimizer that needs them. Code outside an optimizer never imports the optimizer's internals;
|
||||||
|
converting device settings into an optimizer's device parameters is part of that optimizer's
|
||||||
|
parameter preparation, not of the settings: the shared device configuration never imports an
|
||||||
|
optimizer, not even its package.
|
||||||
|
|
||||||
|
## Considered Options
|
||||||
|
|
||||||
|
- **Shared simulation physics in `devicesabc`**: rejected. A fix or model change for one optimizer
|
||||||
|
would silently change the results of the others, and no optimizer could be reasoned about alone.
|
||||||
|
- **Settings that build each optimizer's parameters (`to_genetic_parameters()` and similar)**:
|
||||||
|
rejected. It makes the configuration depend on every optimizer, so removing one breaks the
|
||||||
|
settings.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- Duplicated code is deliberate. Do not merge copies of simulation code across optimizers to
|
||||||
|
remove the duplication; a fix in one copy is applied to another only by a deliberate change to
|
||||||
|
that optimizer.
|
||||||
|
- The output contract still lives in `optimization/optimization.py` together with
|
||||||
|
`OptimizationCommonSettings`; it moves to a module of its own during the migration. Until then
|
||||||
|
only the contract classes (`OptimizationSolution`) may be imported from there outside parameter
|
||||||
|
preparation; the architecture test lists 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
|
||||||
|
parameter preparation.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Optimizers plug in through one registry
|
||||||
|
|
||||||
|
Removing an optimizer must not require changes all over the code base. So every optimizer
|
||||||
|
implements the same small interface and is listed in one registry; the energy management, the
|
||||||
|
server and EOSdash use only the registry and the interface and never name a specific optimizer.
|
||||||
|
An optimizer is one directory, `optimization/<name>/`
|
||||||
|
([0010](0010-one-directory-and-one-naming-scheme-per-optimizer.md)); outside code imports only its
|
||||||
|
package itself (`__init__.py`), which exports what the registry and the settings field need.
|
||||||
|
The optimizer's package owns everything specific to it: its settings model
|
||||||
|
(`optimization.<name>`) including the validation of its horizons, its parameter preparation, run
|
||||||
|
and solution conversion, its own REST endpoints (contributed as a router), its visualization and
|
||||||
|
its wizard steps and its simulation devices. Removing an optimizer touches exactly four places in
|
||||||
|
the production code: its package, its registry entry, its settings field in
|
||||||
|
`OptimizationCommonSettings`, and a configuration migration step that drops `optimization.<name>`
|
||||||
|
from existing configurations and switches `optimization.algorithm` to a remaining optimizer. What
|
||||||
|
belongs only to the optimizer goes with it: its tests, its test data and, while the baseline of the
|
||||||
|
architecture test ([0007](0007-architecture-test-with-shrinking-baseline.md)) still lists
|
||||||
|
violations of the optimizer, their entries. The tests of the remaining optimizers pass unchanged.
|
||||||
|
|
||||||
|
## Considered Options
|
||||||
|
|
||||||
|
- **Settings fields added dynamically from the registry**: rejected. A Pydantic model assembled at
|
||||||
|
runtime is harder to type-check and to document; a static field per optimizer costs one more
|
||||||
|
line to delete on removal.
|
||||||
|
- **One branch per optimizer in the energy management and the server**: rejected. Each new or
|
||||||
|
removed optimizer would touch shared code, and the branches drift apart.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Optimizers implement prepare, run and convert
|
||||||
|
|
||||||
|
Every optimizer follows the same three-step interface, 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 and the warm start), `run()` and `convert()`, the latter returning the optimization solution
|
||||||
|
and the energy management plan. Its current signature is kept in one place, the
|
||||||
|
`optimizer-architecture` skill (`ai/skills/optimizer-architecture/SKILL.md`).
|
||||||
|
|
||||||
|
- `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.
|
||||||
|
All algorithm settings (generations, individuals, seed, penalties) are part of the optimization
|
||||||
|
parameters; a REST override such as `?ngen=` is applied to the parameters before `run()`.
|
||||||
|
- `convert()` is the solution conversion and uses only the parameters and the result.
|
||||||
|
|
||||||
|
The energy management is the only owner of run state. It keeps the last result per optimizer and
|
||||||
|
passes the run start and that result (the warm start) to `prepare()` as arguments, so no part of an
|
||||||
|
optimizer reads EMS state; 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
|
||||||
|
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
|
||||||
|
applies the same fallback rules as `prepare()`. A malformed request is still rejected (422) before
|
||||||
|
preparation; a request that is valid but incomplete is completed, never rejected. So `run()` and
|
||||||
|
`convert()` only ever see complete optimization parameters, whatever the entry point.
|
||||||
|
|
||||||
|
## 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
|
||||||
|
reproduced from its parameters alone.
|
||||||
|
- **Algorithm settings passed beside the parameters**: rejected. A stored parameter set would not
|
||||||
|
be enough to replay a run.
|
||||||
|
- **Clients send complete optimization parameters**: rejected. The presentation data required by
|
||||||
|
[0003](0003-optimizers-see-only-their-optimization-parameters.md) would break every existing
|
||||||
|
client of the public API.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- The energy management stores results per optimizer in one generic slot, not one attribute per
|
||||||
|
optimizer.
|
||||||
|
- An optimization run that cannot be reproduced from its stored optimization parameters is a bug.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# An architecture test with a shrinking baseline enforces the optimizer boundaries
|
||||||
|
|
||||||
|
The optimizer rules ([0003](0003-optimizers-see-only-their-optimization-parameters.md) to
|
||||||
|
[0006](0006-optimizer-interface-prepare-run-convert.md)) are mostly import rules, and a skill alone
|
||||||
|
does not stop an agent or a contributor from breaking them. So `tests/test_optimizerarchitecture.py`
|
||||||
|
parses the imports of the source tree with `ast` and fails when
|
||||||
|
|
||||||
|
- an optimizer imports another optimizer,
|
||||||
|
- code outside an optimizer imports anything from it but its packages themselves (`__init__.py`),
|
||||||
|
- the shared device configuration imports an optimizer at all, so settings cannot build optimization
|
||||||
|
parameters ([0004](0004-optimizers-duplicate-code-instead-of-sharing-it.md)),
|
||||||
|
- a module of an optimizer other than its parameter preparation imports a module or name that
|
||||||
|
reads configuration, predictions, measurements or EMS state,
|
||||||
|
- parameter preparation imports EMS state or the server,
|
||||||
|
- a module of an optimizer other than `<name>optimizer.py`, its package `__init__.py` and the
|
||||||
|
parameter preparation itself imports the parameter preparation, the optimizer's own package or
|
||||||
|
`<name>optimizer.py` (both may re-export it; only the package imports `<name>optimizer.py`), so
|
||||||
|
no other module reaches the configuration through it,
|
||||||
|
- a module other than settings, request, preparation and API
|
||||||
|
([0010](0010-one-directory-and-one-naming-scheme-per-optimizer.md)) imports Pydantic
|
||||||
|
([0009](0009-optimization-parameters-are-dataclasses.md)).
|
||||||
|
|
||||||
|
The test holds the one authoritative list of these modules and names, including helpers that read
|
||||||
|
the configuration, the server (`akkudoktoreos.server`,
|
||||||
|
[0011](0011-optimizer-api-visualization-and-wizard-get-no-exception.md)), the shared device
|
||||||
|
configuration (`devices.settings`, `devices.profile`, `devices.devices`, `devices.devicesabc`) and
|
||||||
|
the contract classes that may be imported from a module that mixes them with configuration
|
||||||
|
(`optimization.optimization`). Parameter preparation is recognized by its file name,
|
||||||
|
`optimization/<name>/<name>prepare.py` or a subpackage `optimization/<name>/prepare/` (a plain
|
||||||
|
module `prepare.py` does not count); the settings
|
||||||
|
model `optimization/<name>/<name>settings.py` may import `config.configabc` to define
|
||||||
|
`optimization.<name>`. The test discovers the optimizers (every package under `optimization/`), so
|
||||||
|
adding one does not touch it; until the simulation devices have moved into the optimizer
|
||||||
|
directory, `devices/<name>` counts as part of the optimizer.
|
||||||
|
|
||||||
|
The violations that exist when the test lands are listed in a baseline in the test file. A
|
||||||
|
violation missing from the baseline fails, and so does a baseline entry that no longer occurs, so
|
||||||
|
the baseline only shrinks and every exception is visible in review. The one exception: when a
|
||||||
|
module or helper that reads the configuration is added to the list, the existing uses it reveals
|
||||||
|
are added to the baseline in the same commit. The test cannot see simulation physics moved into a
|
||||||
|
new shared module, nor a helper missing from its list; both rely on review.
|
||||||
|
|
||||||
|
## Considered Options
|
||||||
|
|
||||||
|
- **`import-linter`**: rejected, it adds a dependency for checks a short `ast` walk can do.
|
||||||
|
- **Refactor first, then add the test without a baseline**: rejected, the boundaries would stay
|
||||||
|
unprotected for the whole migration.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Optimizer refactoring preserves results, and GENETIC0 is frozen
|
||||||
|
|
||||||
|
An optimization result is a charge schedule for real devices, so a refactoring that silently
|
||||||
|
changes results is a defect in production, not a code-quality issue. Refactoring an optimizer,
|
||||||
|
including the migration to the architecture of ADRs
|
||||||
|
[0003](0003-optimizers-see-only-their-optimization-parameters.md) to
|
||||||
|
[0007](0007-architecture-test-with-shrinking-baseline.md), is therefore behaviour-preserving: with
|
||||||
|
a fixed seed every stored input gives the same solution as before. A change that alters a golden
|
||||||
|
result (`tests/testdata/<optimizer>/optimize_result_*.json` or a replay file) is a behaviour
|
||||||
|
change and goes in its own, explicitly declared pull request; a refactoring pull request never
|
||||||
|
regenerates golden data. GENETIC0 is frozen: its results never change. It gets no bug fixes and no
|
||||||
|
behaviour changes, only the structural changes needed to follow the optimizer architecture, each
|
||||||
|
proven result-identical by its golden tests.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- Before an optimizer is refactored, its golden tests are extended with replay files: complete
|
||||||
|
optimization parameters in the new parameter type plus the expected result.
|
||||||
|
- GENETIC0 is migrated first, as the pilot; the registry and the interface arrive with its first
|
||||||
|
migration pull request. GENETIC follows.
|
||||||
|
- A GENETIC0 bug that matters to users is fixed in GENETIC (or a new optimizer), not in GENETIC0.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Optimization parameters are dataclasses, optimization requests are Pydantic models
|
||||||
|
|
||||||
|
The optimization parameters are read in the innermost loops of an optimization run, and they no
|
||||||
|
longer cross the public API: clients send optimization requests, which parameter preparation
|
||||||
|
completes into optimization parameters ([0006](0006-optimizer-interface-prepare-run-convert.md)).
|
||||||
|
So the optimization parameters, including the device parameters of the simulation, are plain
|
||||||
|
Python dataclasses (`@dataclass(frozen=True, slots=True)`: a run never changes its inputs, and
|
||||||
|
slots keep attribute access fast), never Pydantic models; they are valid by construction because parameter
|
||||||
|
preparation always builds a valid set (see the `energy-domain` skill), not because a model
|
||||||
|
validates them. Validation and the public schema live where external input arrives: optimization
|
||||||
|
requests are Pydantic models, and the settings models of the configuration stay Pydantic models.
|
||||||
|
|
||||||
|
## Considered Options
|
||||||
|
|
||||||
|
- **Pydantic models for the optimization parameters**: rejected. Attribute access and copies of
|
||||||
|
Pydantic models cost time in the run, and the validation they offer is redundant behind a
|
||||||
|
parameter preparation that never produces an invalid set.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- An invalid optimization parameter set is a bug in parameter preparation, found by its tests,
|
||||||
|
not a validation error at run time.
|
||||||
|
- Replay files need an explicit (de)serialization of the dataclasses instead of Pydantic's.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# One directory and one naming scheme per optimizer
|
||||||
|
|
||||||
|
Removing an optimizer ([0005](0005-optimizers-plug-in-through-one-registry.md)) and telling the
|
||||||
|
optimizers apart in code, tracebacks and search results is easiest when every optimizer has the
|
||||||
|
same shape. So everything that belongs to an optimizer, its simulation devices included, lives in
|
||||||
|
one directory `src/akkudoktoreos/optimization/<name>/`, named after the optimizer in lowercase
|
||||||
|
(`genetic`, `genetic0`). Its simulation devices live in the subdirectory `devices/`; the top-level
|
||||||
|
`devices/` package keeps only the shared device configuration (`settings/`, `profile/`,
|
||||||
|
`devices.py`, `devicesabc.py`). Every module is named `<name><role>.py` and every class
|
||||||
|
`<Name><Role>`, with one fixed set of roles: settings, request, parameters, preparation, optimizer,
|
||||||
|
algorithm, result, simulation (with its devices), conversion, visualization and API. The table of
|
||||||
|
roles with their modules, classes and kinds is kept in one place, the `optimizer-architecture`
|
||||||
|
skill (`ai/skills/optimizer-architecture/SKILL.md`).
|
||||||
|
|
||||||
|
The package's `__init__.py` is the only module outside code imports. Further modules that do not
|
||||||
|
fit a role use the `<name>` prefix as well, also inside subdirectories such as `devices/` or a
|
||||||
|
`prepare/` subpackage for a large parameter preparation.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- The public classes are renamed (e.g. `GeneticOptimizationParameters` → `GeneticRequest`,
|
||||||
|
`GeneticCommonSettings` → `GeneticSettings`). Field names and payloads stay unchanged; the
|
||||||
|
schema names in OpenAPI and the configuration documentation change.
|
||||||
|
- `devices/genetic/` and `devices/genetic0/` move into the optimizer directories. For the frozen
|
||||||
|
GENETIC0 ([0008](0008-optimizer-refactoring-preserves-results.md)) the moves and renames are
|
||||||
|
structural changes, proven by its golden tests.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Optimizer API, visualization and wizard steps get no exception
|
||||||
|
|
||||||
|
An optimizer owns its REST endpoints, its visualization and its EOSdash wizard steps
|
||||||
|
([0005](0005-optimizers-plug-in-through-one-registry.md)), and all three read configuration or EMS
|
||||||
|
state today. None of them gets an exception from
|
||||||
|
[0003](0003-optimizers-see-only-their-optimization-parameters.md):
|
||||||
|
|
||||||
|
- The visualization (`<name>visualize.py`) is part of the solution conversion and renders from the
|
||||||
|
optimization parameters and the optimization result only.
|
||||||
|
- The REST router (`<name>api.py`) never fetches anything itself. It declares placeholder
|
||||||
|
dependency functions for what it needs: the optimizer's last optimization parameters and result,
|
||||||
|
kept by the energy management, and the call that starts a run. The generic server fills them in
|
||||||
|
through FastAPI's `app.dependency_overrides`, using the registry. The router may import FastAPI,
|
||||||
|
Pydantic and its own optimization request, never configuration, EMS state or the server
|
||||||
|
(`akkudoktoreos.server`). No other part of the optimizer, its parameter preparation included,
|
||||||
|
imports the server either.
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
## Considered Options
|
||||||
|
|
||||||
|
- **An "integration" role that may read configuration and EMS state**: rejected. It would become
|
||||||
|
the place where optimizer code quietly reaches the outside world again, and removing an
|
||||||
|
optimizer would still mean finding its integration code in the server and EOSdash.
|
||||||
|
- **The router imports its dependency functions from the server**: rejected. The optimizer would
|
||||||
|
depend on the server, and a server helper is an easy way back to the configuration.
|
||||||
@@ -54,6 +54,7 @@ Agents get their project knowledge from two places in the repository:
|
|||||||
| `filename-conventions` | File name rules enforced by `scripts/lint_filenames.py` |
|
| `filename-conventions` | File name rules enforced by `scripts/lint_filenames.py` |
|
||||||
| `application-configuration` | Configuration models, defaults and migration |
|
| `application-configuration` | Configuration models, defaults and migration |
|
||||||
| `energy-domain` | Optimization, adapters, units and sign conventions |
|
| `energy-domain` | Optimization, adapters, units and sign conventions |
|
||||||
|
| `optimizer-architecture` | Optimizer structure, boundaries and independence |
|
||||||
| `rest-api` | REST endpoints and error responses |
|
| `rest-api` | REST endpoints and error responses |
|
||||||
| `commit-messages` | Conventional Commits as checked by `commitizen` |
|
| `commit-messages` | Conventional Commits as checked by `commitizen` |
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user