refactor(genetic0): refactor GENETIC0 to consolidated optimizer architecture

Pin the conversion, plan and visualization of golden runs.
Drive GENETIC0 through the optimizer registry.
Move GENETIC0 into one directory with role-named modules.
Prepare every run input once, run from the parameters.
Fall back on bad inputs instead of cancelling the run.
Simulate from frozen device dataclasses, not settings.
Convert and visualize from the parameters and result only.
Serve GENETIC0 from its own router, return a frozen result.

Additional changes
- Fix the run start of the golden runs and add a run across the DST switch.
- Configure a home appliance so the conversion covers it.
- Pass the warm start to the legacy preparation instead of reading the EMS.
- Replace EnergyManagement.genetic0_solution() by optimizer_result(name).
- Cover the warm start of the parameter preparation.
- Rename Genetic0OptimizationParameters to Genetic0Request, Genetic0CommonSettings to Genetic0Settings.
- Say in ADR 0007 and the skill that a move relabels baseline entries one to one.
- Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide.
- Add the observation time to the optimizer interface.
- Cache the load interpolator by its backend instead of in the EMS run cache.
- Add replay files that reproduce each golden result from its parameters.
- Stop writing demo providers, demo devices and defaults into the configuration.
- Count a NaN state of charge as invalid.
- Remove the unused electricity fee check.
- Record the fallbacks in CHANGELOG.md instead of the former demo providers.
- Leave out a battery that is not linked to the inverter.
- Count infinite forecast values as missing.
- Extend a prediction.hours that leaves fewer than two hours after the start hour.
- Do not charge from the grid without any known price.
- Without an inverter, buy the whole load from the grid instead of planning it at no cost.
- Keep the zone of the run start in the replay files.
- Correct the DVhub documentation that said a missing tariff cancels the run.
- Rename the request models to <Name><Thing>Request.
- Move the settings' to_genetic0_*() converters into the preparation.
- Remove the solution's unreachable configuration fallbacks.
- Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide.
- Add EnergyManagement.optimizer_run() and render the PDF from the run's own start.
- Read the presentation series from the earlier of the run's start hours.
- Render the PDF report for runs of any length, not only 48 hours.
- Add the generic OptimizerProblem, rendered like EOSProblem.
- Move Genetic0ParametersBaseModel into genetic0request.py.

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-27 13:55:41 +01:00
co-authored by Claude Opus 5.5
parent 9adf7b8be2
commit 40d0fab9d2
89 changed files with 44476 additions and 3933 deletions
+17 -4
View File
@@ -144,8 +144,6 @@ test procedure. These changes are not yet a tagged release.
`dc_to_ac_efficiency_curve`), `ac_charge_limits_total_charge` and `cell_chemistry` are dropped
with an error log: the profile values apply. A generic profile without own power limits is
limited to the former default of 5000 W. Home Assistant configuration paths follow.
- GENETIC0 no longer replaces configured devices by demo devices; a device that cannot be
prepared is left out of the run.
- GENETIC rejects incomplete control forecasts instead of inventing usable inputs. Unsupported
device counts and inconsistent battery links also fail explicitly. A missing, future, invalid
or stale state of charge no longer cancels the run: an explicit SoC in the request takes
@@ -156,8 +154,15 @@ test procedure. These changes are not yet a tagged release.
battery/inverter limits, losses and wear costs can change the chosen plan and its costs.
- The electricity-fee framework replaces old `elecprice.charges_kwh` / `vat_rate` fields.
Those old fields are dropped during migration: configure and verify fees explicitly.
- Without PV or price predictions, the GENETIC0 parameter preparation falls back to demo
providers that need no internet service: `PVForecastPVLib` and `ElecPriceFixed`.
- GENETIC0's parameter preparation never cancels a run and never writes the configuration. A
missing or invalid input (location, horizon, a prediction) gets a fallback for the run, logged
as an error naming it, and a device that cannot be prepared is left out of the run. It no
longer switches to demo providers or writes defaults and demo devices into the configuration:
configure providers and devices explicitly. A NaN or infinite forecast value counts as missing,
a battery not linked to the inverter is left out of the run, and a `prediction.hours` that
leaves fewer than two hours after the start hour is extended to the control horizon. Without
any known electricity price (fallback price 0) the run does not charge the battery from the
grid.
- The configuration is saved to the configuration file automatically by default.
- Quarter-hour clients must use the returned timestamps and interval, not assume 24 hourly
values. Runtime forecast energy is Wh per slot and prices are currency per Wh.
@@ -191,6 +196,10 @@ test procedure. These changes are not yet a tagged release.
calibration, the PV snow feedback and the load adjustment skip it, and `/v1/measurement/energy`
and `/v1/measurement/household` report it as missing. Set it to `null` for the former behaviour, e.g.
for a feeder that only sends a reading when the meter value changes.
- 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.
### Fixed
@@ -198,6 +207,10 @@ test procedure. These changes are not yet a tagged release.
belonged to the failed run; successful results and plans are published together.
- The optimization no longer fails after a server restart.
- The device IDs in the solution follow the configuration.
- Without a usable inverter GENETIC0 buys the whole load from the grid instead of planning it at
no cost.
- The GENETIC0 PDF report (`/visualization_results.pdf`) renders runs of any length, not only
runs with `prediction.hours` 48.
- Restored JSON measurements retain their timestamps and values.
- Configuration updates made at runtime, e.g. by `PUT /v1/config`, are no longer discarded when the
same configuration key is set in the EOS configuration file or in the environment
+32 -10
View File
@@ -13,7 +13,7 @@ parameters**, **solution conversion**, **warm start**. The decisions and their r
| Part | May use |
|---|---|
| Parameter preparation (`<name>prepare.py` or `prepare/`) | configuration, predictions, measurements, and the run start and warm start passed in as arguments |
| Parameter preparation (`<name>prepare.py` or `prepare/`) | configuration, predictions, measurements, and the run start, observation time 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 |
@@ -51,17 +51,33 @@ This is the one maintained copy of the interface; ADR 0006 records the decision
```python
class Optimizer(Protocol[P, Q, R]):
name: str
async def prepare(self, start_datetime: DateTime, warm_start: R | None) -> P
async def prepare(
self, start_datetime: DateTime, observation_datetime: DateTime,
warm_start: R | None, overrides: Mapping[str, Any] | None = None,
) -> P
async def prepare_from_request(
self, request: Q, start_datetime: DateTime, warm_start: R | None
self, request: Q, start_datetime: DateTime, observation_datetime: DateTime,
warm_start: R | None, overrides: Mapping[str, Any] | None = None,
) -> P
def run(self, parameters: P) -> R
def convert(self, parameters: P, result: R) -> tuple[OptimizationSolution, EnergyManagementPlan]
def api(self) -> OptimizerApi | None
async def convert(
self, parameters: P, result: R
) -> tuple[OptimizationSolution, EnergyManagementPlan]
```
The code is `akkudoktoreos.optimization.optimizer.Optimizer`; the energy management finds an
optimizer through `akkudoktoreos.optimization.optimizerregistry.get_optimizer(name)` and keeps
the last parameters and result per optimizer (`OptimizerRun`); the result is the next warm start.
`start_datetime` is the start of the run's first slot; `observation_datetime` is the unrounded
moment of the run that measurements (e.g. a measured state of charge) refer to.
- `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.
individuals, seed and penalties are part of the optimization parameters. A run-time override
(e.g. `?ngen=`) reaches the preparation as `overrides` (`{"generations": 10}`), never beside the
parameters; the preparation applies the keys it knows and logs an error for any other key.
- `convert()` is `async`, so that an optimizer can migrate step by step while its conversion
still awaits reads; once it uses only the parameters and the result, it awaits nothing.
- **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
@@ -139,10 +155,14 @@ 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`.
functions for the last parameters and result and the run trigger and hands
them out with its router as `OptimizerApi(router, last_run, run)` through
`api()`; the generic server includes every registered router (before its own
routes, so a specific path wins) and fills the placeholders through
`app.dependency_overrides`. Errors are `OptimizerProblem`s, which the server
renders like its own RFC 7807 problems. It imports FastAPI, Pydantic and its
request, never configuration, EMS state or `akkudoktoreos.server`. The public
response models live there and are built from the parameters and the result.
- Wizard steps are field metadata in `<name>settings.py` that EOSdash reads;
no EOSdash code inside an optimizer.
@@ -173,6 +193,8 @@ against `BASELINE`, the violations that existed when it was introduced.
- 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.
- Moving or splitting a module relabels its entries to the new module one to
one, in the same commit and named in the pull request; it adds none.
- 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
+1 -1
View File
@@ -10,7 +10,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. |
| genetic0 | `EOS_OPTIMIZATION__GENETIC0` | `Genetic0CommonSettings` | `rw` | `required` | GENETIC0 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. |
:::
+33 -1
View File
@@ -143,7 +143,7 @@ Note:
**Request Body**:
- `application/json`: {
"$ref": "#/components/schemas/Genetic0OptimizationParameters-Input"
"$ref": "#/components/schemas/Genetic0Request-Input"
}
**Responses**:
@@ -776,6 +776,28 @@ The legacy /visualization_results.pdf route continues to serve GENETIC0.
---
## GET /v1/energy-management/optimization/solution/GENETIC0
<!-- pyml disable line-length -->
**Links**: [local](http://localhost:8503/docs#/default/fastapi_energy_management_optimization_solution_genetic0_get_v1_energy-management_optimization_solution_genetic0_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_genetic0_get_v1_energy-management_optimization_solution_genetic0_get)
<!-- pyml enable line-length -->
Fastapi Energy Management Optimization Solution Genetic0 Get
<!-- pyml disable line-length -->
```python
"""
Get the latest GENETIC0 specific solution of the optimization.
"""
```
<!-- pyml enable line-length -->
**Responses**:
- **200**: Successful Response
---
## GET /v1/energy-management/optimization/solution/{algorithm}
<!-- pyml disable line-length -->
@@ -789,6 +811,8 @@ Fastapi Energy Management Optimization Solution Algorithm Get
"""
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
"""
@@ -2380,6 +2404,14 @@ Return:
Get Pdf
<!-- pyml disable line-length -->
```python
"""
PDF report of the latest GENETIC0 run.
"""
```
<!-- pyml enable line-length -->
**Responses**:
- **200**: Successful Response
@@ -4,21 +4,23 @@ Every optimizer follows the same three-step interface, so the energy management
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
start, the observation time, the warm start and run-time overrides), `run()` and `convert()`
(asynchronous), 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()`.
parameters; a REST override such as `?ngen=` is passed to the preparation as an override and
so becomes part of 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.
passes the run start, the observation time (the unrounded moment measurements refer to) 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
@@ -37,8 +37,10 @@ The violations that exist when the test lands are listed in a baseline in the te
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.
are added to the baseline in the same commit. Moving or splitting a module is no exception: its
entries are relabelled to the new module one to one, in the same commit and named in the pull
request, and no entry is added. 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
@@ -19,3 +19,7 @@ proven result-identical by its golden tests.
- 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.
- One declared exception: GENETIC0's parameter preparation follows the "optimization parameters
are always valid" rule of the `energy-domain` skill, in a behaviour-change pull request of its
own. It no longer writes demo providers or devices into the configuration and no longer cancels
a run; results with a complete configuration stay the same.
+3 -2
View File
@@ -412,8 +412,9 @@ 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 or GENETIC0 control horizon, automatic optimization cancels with a
missing tariff error instead of extending the final known price. Request, response, and storage
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
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.
+4
View File
@@ -108,6 +108,10 @@ time, charging power and supported charge rates.
- Pass the previous plan's timestamp with a warmstart so it can be aligned to the new run.
Recheck custom parsers of GENETIC results; its native result and report are not the
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.
The new report endpoint is
`GET /v1/energy-management/optimization/solution/GENETIC/pdf`. It renders the stored
+355 -340
View File
@@ -817,6 +817,128 @@
}
}
},
"/optimize": {
"post": {
"tags": [
"optimize"
],
"summary": "Fastapi Optimize",
"description": "Deprecated: Optimize.\n\nEndpoint to handle optimization.\n\nUses the `classic` GENETIC0 optimisation algorithm (__NO__ 15-minutes slots).\n\nNote:\n Use automatic optimization instead.\n \"v1/energy-management/optimization/solution/GENETIC0\"",
"operationId": "fastapi_optimize_optimize_post",
"parameters": [
{
"name": "start_hour",
"in": "query",
"required": false,
"schema": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"description": "Defaults to current hour of the day.",
"title": "Start Hour"
},
"description": "Defaults to current hour of the day."
},
{
"name": "ngen",
"in": "query",
"required": false,
"schema": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"description": "Number of indivuals to generate for genetic algorithm.",
"title": "Ngen"
},
"description": "Number of indivuals to generate for genetic algorithm."
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Genetic0Request-Input"
}
}
}
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Genetic0SolutionLegacy"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
}
}
},
"/v1/energy-management/optimization/solution/GENETIC0": {
"get": {
"tags": [
"energy-management"
],
"summary": "Fastapi Energy Management Optimization Solution Genetic0 Get",
"description": "Get the latest GENETIC0 specific solution of the optimization.",
"operationId": "fastapi_energy_management_optimization_solution_genetic0_get_v1_energy_management_optimization_solution_GENETIC0_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Genetic0Solution"
}
}
}
}
}
}
},
"/visualization_results.pdf": {
"get": {
"tags": [
"optimize"
],
"summary": "Get Pdf",
"description": "PDF report of the latest GENETIC0 run.",
"operationId": "get_pdf_visualization_results_pdf_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {}
}
}
}
}
}
},
"/v1/admin/cache/clear": {
"post": {
"tags": [
@@ -3291,7 +3413,7 @@
"energy-management"
],
"summary": "Fastapi Energy Management Optimization Solution Algorithm Get",
"description": "Get the latest algorithm specific solution of the optimization.\n\nArgs:\n algorithm: Optimization algorithm",
"description": "Get the latest algorithm specific solution of the optimization.\n\nOptimizers of the registry serve their own solution path (e.g. ``.../solution/GENETIC0``).\n\nArgs:\n algorithm: Optimization algorithm",
"operationId": "fastapi_energy_management_optimization_solution_algorithm_get_v1_energy_management_optimization_solution__algorithm__get",
"parameters": [
{
@@ -3309,15 +3431,7 @@
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"$ref": "#/components/schemas/GeneticSolution"
},
{
"$ref": "#/components/schemas/Genetic0Solution"
}
],
"title": "Response Fastapi Energy Management Optimization Solution Algorithm Get V1 Energy Management Optimization Solution Algorithm Get"
"$ref": "#/components/schemas/GeneticSolution"
}
}
}
@@ -3559,105 +3673,6 @@
}
}
}
},
"/optimize": {
"post": {
"tags": [
"optimize"
],
"summary": "Fastapi Optimize",
"description": "Deprecated: Optimize.\n\nEndpoint to handle optimization.\n\nUses the `classic` GENETIC0 optimisation algorithm (__NO__ 15-minutes slots).\n\nNote:\n Use automatic optimization instead.\n \"v1/energy-management/optimization/solution/GENETIC0\"",
"operationId": "fastapi_optimize_optimize_post",
"parameters": [
{
"name": "start_hour",
"in": "query",
"required": false,
"schema": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"description": "Defaults to current hour of the day.",
"title": "Start Hour"
},
"description": "Defaults to current hour of the day."
},
{
"name": "ngen",
"in": "query",
"required": false,
"schema": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"description": "Number of indivuals to generate for genetic algorithm.",
"title": "Ngen"
},
"description": "Number of indivuals to generate for genetic algorithm."
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Genetic0OptimizationParameters-Input"
}
}
}
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Genetic0SolutionLegacy"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
}
}
},
"/visualization_results.pdf": {
"get": {
"tags": [
"optimize"
],
"summary": "Get Pdf",
"operationId": "get_pdf_visualization_results_pdf_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {}
}
}
}
}
}
}
},
"components": {
@@ -8000,205 +8015,7 @@
"title": "GeneralSettings",
"description": "General settings."
},
"Genetic0CommonSettings-Input": {
"properties": {
"horizon_hours": {
"type": "integer",
"minimum": 0.0,
"title": "Horizon Hours",
"description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.",
"default": 24,
"examples": [
24
]
},
"individuals": {
"anyOf": [
{
"type": "integer",
"minimum": 10.0
},
{
"type": "null"
}
],
"title": "Individuals",
"description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.",
"default": 300,
"examples": [
300
]
},
"generations": {
"anyOf": [
{
"type": "integer",
"minimum": 10.0
},
{
"type": "null"
}
],
"title": "Generations",
"description": "Number of generations to evolve [>= 10]. Defaults to 400.",
"default": 400,
"examples": [
400
]
},
"seed": {
"anyOf": [
{
"type": "integer",
"minimum": 0.0
},
{
"type": "null"
}
],
"title": "Seed",
"description": "Random seed for reproducibility. None = random.",
"examples": [
null,
42
]
},
"penalties": {
"additionalProperties": {
"anyOf": [
{
"type": "number"
},
{
"type": "integer"
},
{
"type": "string"
}
]
},
"type": "object",
"title": "Penalties",
"description": "Penalty parameters used in fitness evaluation.",
"examples": [
{
"ev_soc_miss": 10
}
]
}
},
"type": "object",
"title": "Genetic0CommonSettings",
"description": "GENETIC0 Optimization Algorithm Configuration."
},
"Genetic0CommonSettings-Output": {
"properties": {
"horizon_hours": {
"type": "integer",
"minimum": 0.0,
"title": "Horizon Hours",
"description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.",
"default": 24,
"examples": [
24
]
},
"individuals": {
"anyOf": [
{
"type": "integer",
"minimum": 10.0
},
{
"type": "null"
}
],
"title": "Individuals",
"description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.",
"default": 300,
"examples": [
300
]
},
"generations": {
"anyOf": [
{
"type": "integer",
"minimum": 10.0
},
{
"type": "null"
}
],
"title": "Generations",
"description": "Number of generations to evolve [>= 10]. Defaults to 400.",
"default": 400,
"examples": [
400
]
},
"seed": {
"anyOf": [
{
"type": "integer",
"minimum": 0.0
},
{
"type": "null"
}
],
"title": "Seed",
"description": "Random seed for reproducibility. None = random.",
"examples": [
null,
42
]
},
"penalties": {
"additionalProperties": {
"anyOf": [
{
"type": "number"
},
{
"type": "integer"
},
{
"type": "string"
}
]
},
"type": "object",
"title": "Penalties",
"description": "Penalty parameters used in fitness evaluation.",
"examples": [
{
"ev_soc_miss": 10
}
]
},
"interval_sec": {
"type": "integer",
"title": "Interval Sec",
"description": "The optimization interval [sec]. Fixed to 1 hour (3600 seconds).",
"readOnly": true
},
"horizon": {
"type": "integer",
"title": "Horizon",
"description": "Number of optimization steps.",
"readOnly": true
}
},
"type": "object",
"required": [
"interval_sec",
"horizon"
],
"title": "Genetic0CommonSettings",
"description": "GENETIC0 Optimization Algorithm Configuration."
},
"Genetic0ElectricVehicleParameters": {
"Genetic0ElectricVehicleRequest": {
"properties": {
"device_id": {
"type": "string",
@@ -8342,7 +8159,7 @@
"device_id",
"capacity_wh"
],
"title": "Genetic0ElectricVehicleParameters",
"title": "Genetic0ElectricVehicleRequest",
"description": "Battery Electric Vehicle Device Simulation Configuration."
},
"Genetic0ElectricVehicleResult": {
@@ -8428,7 +8245,7 @@
"title": "Genetic0ElectricVehicleResult",
"description": "Result class containing information related to the electric vehicle's charging and discharging behavior."
},
"Genetic0EnergyManagementParameters-Input": {
"Genetic0EnergyManagementRequest-Input": {
"properties": {
"pv_forecast_wh": {
"items": {
@@ -8483,10 +8300,10 @@
"price_per_wh_battery",
"total_load"
],
"title": "Genetic0EnergyManagementParameters",
"title": "Genetic0EnergyManagementRequest",
"description": "Encapsulates energy-related forecasts and costs used in GENETIC optimization."
},
"Genetic0EnergyManagementParameters-Output": {
"Genetic0EnergyManagementRequest-Output": {
"properties": {
"pv_forecast_wh": {
"items": {
@@ -8600,10 +8417,10 @@
"preis_euro_pro_wh_akku",
"gesamtlast"
],
"title": "Genetic0EnergyManagementParameters",
"title": "Genetic0EnergyManagementRequest",
"description": "Encapsulates energy-related forecasts and costs used in GENETIC optimization."
},
"Genetic0HomeApplianceParameters-Input": {
"Genetic0HomeApplianceRequest-Input": {
"properties": {
"device_id": {
"type": "string",
@@ -8674,10 +8491,10 @@
"consumption_wh",
"duration_h"
],
"title": "Genetic0HomeApplianceParameters",
"title": "Genetic0HomeApplianceRequest",
"description": "Home Appliance Device Simulation Configuration."
},
"Genetic0HomeApplianceParameters-Output": {
"Genetic0HomeApplianceRequest-Output": {
"properties": {
"device_id": {
"type": "string",
@@ -8748,10 +8565,10 @@
"consumption_wh",
"duration_h"
],
"title": "Genetic0HomeApplianceParameters",
"title": "Genetic0HomeApplianceRequest",
"description": "Home Appliance Device Simulation Configuration."
},
"Genetic0InverterParameters": {
"Genetic0InverterRequest": {
"properties": {
"device_id": {
"type": "string",
@@ -8851,18 +8668,18 @@
"device_id",
"max_power_wh"
],
"title": "Genetic0InverterParameters",
"title": "Genetic0InverterRequest",
"description": "Inverter Device Simulation Configuration."
},
"Genetic0OptimizationParameters-Input": {
"Genetic0Request-Input": {
"properties": {
"ems": {
"$ref": "#/components/schemas/Genetic0EnergyManagementParameters-Input"
"$ref": "#/components/schemas/Genetic0EnergyManagementRequest-Input"
},
"pv_battery": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0SolarPanelBatteryParameters"
"$ref": "#/components/schemas/Genetic0SolarPanelBatteryRequest"
},
{
"type": "null"
@@ -8873,7 +8690,7 @@
"inverter": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0InverterParameters"
"$ref": "#/components/schemas/Genetic0InverterRequest"
},
{
"type": "null"
@@ -8883,7 +8700,7 @@
"ev": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0ElectricVehicleParameters"
"$ref": "#/components/schemas/Genetic0ElectricVehicleRequest"
},
{
"type": "null"
@@ -8894,7 +8711,7 @@
"dishwasher": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0HomeApplianceParameters-Input"
"$ref": "#/components/schemas/Genetic0HomeApplianceRequest-Input"
},
{
"type": "null"
@@ -8946,18 +8763,18 @@
"inverter",
"ev"
],
"title": "Genetic0OptimizationParameters",
"title": "Genetic0Request",
"description": "Main parameter class for running the genetic energy optimization.\n\nCollects all model and configuration parameters necessary to run the\noptimization process, such as forecasts, pricing, battery and appliance models."
},
"Genetic0OptimizationParameters-Output": {
"Genetic0Request-Output": {
"properties": {
"ems": {
"$ref": "#/components/schemas/Genetic0EnergyManagementParameters-Output"
"$ref": "#/components/schemas/Genetic0EnergyManagementRequest-Output"
},
"pv_battery": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0SolarPanelBatteryParameters"
"$ref": "#/components/schemas/Genetic0SolarPanelBatteryRequest"
},
{
"type": "null"
@@ -8968,7 +8785,7 @@
"inverter": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0InverterParameters"
"$ref": "#/components/schemas/Genetic0InverterRequest"
},
{
"type": "null"
@@ -8978,7 +8795,7 @@
"ev": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0ElectricVehicleParameters"
"$ref": "#/components/schemas/Genetic0ElectricVehicleRequest"
},
{
"type": "null"
@@ -8989,7 +8806,7 @@
"dishwasher": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0HomeApplianceParameters-Output"
"$ref": "#/components/schemas/Genetic0HomeApplianceRequest-Output"
},
{
"type": "null"
@@ -9036,7 +8853,7 @@
"pv_akku": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0SolarPanelBatteryParameters"
"$ref": "#/components/schemas/Genetic0SolarPanelBatteryRequest"
},
{
"type": "null"
@@ -9049,7 +8866,7 @@
"eauto": {
"anyOf": [
{
"$ref": "#/components/schemas/Genetic0ElectricVehicleParameters"
"$ref": "#/components/schemas/Genetic0ElectricVehicleRequest"
},
{
"type": "null"
@@ -9069,9 +8886,207 @@
"pv_akku",
"eauto"
],
"title": "Genetic0OptimizationParameters",
"title": "Genetic0Request",
"description": "Main parameter class for running the genetic energy optimization.\n\nCollects all model and configuration parameters necessary to run the\noptimization process, such as forecasts, pricing, battery and appliance models."
},
"Genetic0Settings-Input": {
"properties": {
"horizon_hours": {
"type": "integer",
"minimum": 0.0,
"title": "Horizon Hours",
"description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.",
"default": 24,
"examples": [
24
]
},
"individuals": {
"anyOf": [
{
"type": "integer",
"minimum": 10.0
},
{
"type": "null"
}
],
"title": "Individuals",
"description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.",
"default": 300,
"examples": [
300
]
},
"generations": {
"anyOf": [
{
"type": "integer",
"minimum": 10.0
},
{
"type": "null"
}
],
"title": "Generations",
"description": "Number of generations to evolve [>= 10]. Defaults to 400.",
"default": 400,
"examples": [
400
]
},
"seed": {
"anyOf": [
{
"type": "integer",
"minimum": 0.0
},
{
"type": "null"
}
],
"title": "Seed",
"description": "Random seed for reproducibility. None = random.",
"examples": [
null,
42
]
},
"penalties": {
"additionalProperties": {
"anyOf": [
{
"type": "number"
},
{
"type": "integer"
},
{
"type": "string"
}
]
},
"type": "object",
"title": "Penalties",
"description": "Penalty parameters used in fitness evaluation.",
"examples": [
{
"ev_soc_miss": 10
}
]
}
},
"type": "object",
"title": "Genetic0Settings",
"description": "GENETIC0 Optimization Algorithm Configuration."
},
"Genetic0Settings-Output": {
"properties": {
"horizon_hours": {
"type": "integer",
"minimum": 0.0,
"title": "Horizon Hours",
"description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.",
"default": 24,
"examples": [
24
]
},
"individuals": {
"anyOf": [
{
"type": "integer",
"minimum": 10.0
},
{
"type": "null"
}
],
"title": "Individuals",
"description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.",
"default": 300,
"examples": [
300
]
},
"generations": {
"anyOf": [
{
"type": "integer",
"minimum": 10.0
},
{
"type": "null"
}
],
"title": "Generations",
"description": "Number of generations to evolve [>= 10]. Defaults to 400.",
"default": 400,
"examples": [
400
]
},
"seed": {
"anyOf": [
{
"type": "integer",
"minimum": 0.0
},
{
"type": "null"
}
],
"title": "Seed",
"description": "Random seed for reproducibility. None = random.",
"examples": [
null,
42
]
},
"penalties": {
"additionalProperties": {
"anyOf": [
{
"type": "number"
},
{
"type": "integer"
},
{
"type": "string"
}
]
},
"type": "object",
"title": "Penalties",
"description": "Penalty parameters used in fitness evaluation.",
"examples": [
{
"ev_soc_miss": 10
}
]
},
"interval_sec": {
"type": "integer",
"title": "Interval Sec",
"description": "The optimization interval [sec]. Fixed to 1 hour (3600 seconds).",
"readOnly": true
},
"horizon": {
"type": "integer",
"title": "Horizon",
"description": "Number of optimization steps.",
"readOnly": true
}
},
"type": "object",
"required": [
"interval_sec",
"horizon"
],
"title": "Genetic0Settings",
"description": "GENETIC0 Optimization Algorithm Configuration."
},
"Genetic0SimulationResult": {
"properties": {
"load_wh_per_hour": {
@@ -9351,7 +9366,7 @@
"title": "Genetic0SimulationResult",
"description": "This object contains the results of the simulation and provides insights into various parameters over the entire forecast period."
},
"Genetic0SolarPanelBatteryParameters": {
"Genetic0SolarPanelBatteryRequest": {
"properties": {
"device_id": {
"type": "string",
@@ -9495,13 +9510,13 @@
"device_id",
"capacity_wh"
],
"title": "Genetic0SolarPanelBatteryParameters",
"title": "Genetic0SolarPanelBatteryRequest",
"description": "PV battery device simulation configuration."
},
"Genetic0Solution": {
"properties": {
"parameters": {
"$ref": "#/components/schemas/Genetic0OptimizationParameters-Output",
"$ref": "#/components/schemas/Genetic0Request-Output",
"description": "Optimization parameters used to generate solution."
},
"ac_charge": {
@@ -14496,7 +14511,7 @@
]
},
"genetic0": {
"$ref": "#/components/schemas/Genetic0CommonSettings-Input",
"$ref": "#/components/schemas/Genetic0Settings-Input",
"description": "GENETIC0 optimization algorithm configuration.",
"examples": [
{
@@ -14544,7 +14559,7 @@
]
},
"genetic0": {
"$ref": "#/components/schemas/Genetic0CommonSettings-Output",
"$ref": "#/components/schemas/Genetic0Settings-Output",
"description": "GENETIC0 optimization algorithm configuration.",
"examples": [
{
+69 -75
View File
@@ -3,9 +3,10 @@ import threading
import traceback
import urllib.request
from asyncio import Lock, get_running_loop
from collections.abc import Mapping
from concurrent.futures import ThreadPoolExecutor
from enum import StrEnum
from typing import ClassVar, Optional, cast
from typing import Any, ClassVar, Optional, cast
from loguru import logger
from pydantic import computed_field
@@ -20,10 +21,6 @@ from akkudoktoreos.core.coreabc import (
from akkudoktoreos.core.emplan import EnergyManagementPlan
from akkudoktoreos.core.emsettings import EnergyManagementMode
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0OptimizationParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
from akkudoktoreos.optimization.genetic.geneticparams import (
@@ -34,6 +31,8 @@ from akkudoktoreos.optimization.optimization import (
OptimizationAlgorithm,
OptimizationSolution,
)
from akkudoktoreos.optimization.optimizer import OptimizerRun
from akkudoktoreos.optimization.optimizerregistry import get_optimizer
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
# The executor to execute the CPU heavy energy management run
@@ -126,9 +125,9 @@ class EnergyManagement(
# For classic API
_genetic_solution: ClassVar[Optional[GeneticSolution]] = None
# Solution of the genetic0 algorithm of latest energy management run with optimization
# For classic API
_genetic0_solution: ClassVar[Optional[Genetic0Solution]] = None
# Parameters and result of the latest run per optimizer of the registry, by optimizer name.
# The result is the warm start of the optimizer's next run.
_optimizer_runs: ClassVar[dict[str, OptimizerRun[Any, Any]]] = {}
# energy management lock (for energy management run)
_run_lock: ClassVar[Lock] = Lock()
@@ -227,13 +226,29 @@ class EnergyManagement(
return cls._genetic_solution
@classmethod
def genetic0_solution(cls) -> Optional[Genetic0Solution]:
"""Get the latest solution of the genetic0 algorithm.
def optimizer_run(cls, name: str) -> Optional[OptimizerRun[Any, Any]]:
"""Get the parameters and result of the latest successful run of an optimizer.
Args:
name: The optimizer's name, e.g. ``"GENETIC0"``.
Returns:
Optional[Genetic0Solution]: The latest solution of the genetic algorithm.
The optimizer's latest run, or None if it has not run yet.
"""
return cls._genetic0_solution
return cls._optimizer_runs.get(name)
@classmethod
def optimizer_result(cls, name: str) -> Optional[Any]:
"""Get the result of the latest successful run of an optimizer of the registry.
Args:
name: The optimizer's name, e.g. ``"GENETIC0"``.
Returns:
The optimizer's native optimization result, or None if it has not run yet.
"""
run = cls._optimizer_runs.get(name)
return None if run is None else run.result
async def run(
self,
@@ -246,12 +261,11 @@ class EnergyManagement(
genetic_generations: Optional[int] = None,
genetic_individuals: Optional[int] = None,
genetic_seed: Optional[int] = None,
genetic0_parameters: Optional[Genetic0OptimizationParameters] = None,
genetic0_generations: Optional[int] = None,
genetic0_seed: Optional[int] = None,
request: Optional[Any] = None,
overrides: Optional[Mapping[str, Any]] = None,
force_enable: Optional[bool] = False,
force_update: Optional[bool] = False,
) -> Optional[GeneticSolution | Genetic0Solution]:
) -> Optional[Any]:
"""Run the energy management.
This method initializes the energy management run by setting its
@@ -281,14 +295,11 @@ class EnergyManagement(
genetic_individuals (int, optional): Population size override for this run.
genetic_seed (int, optional): The seed for the `GENETIC` algorithm. Defaults
to the algorithm's internal random seed if not specified.
genetic0_parameters (Genetic0OptimizationParameters, optional): The
parameter set for the `GENETIC0` algorithm. If not provided, it will
be constructed based on the current configuration and predictions.
genetic0_generations (int, optional): The number of generations for the
`GENETIC0` algorithm. Defaults to the algorithm's internal default (400)
if not specified.
genetic0_seed (int, optional): The seed for the `GENETIC0` algorithm. Defaults
to the algorithm's internal random seed if not specified.
request (optional): An optimization request for an optimizer of the registry
(e.g. `GENETIC0`), completed by its `prepare_from_request()`. If not provided,
the optimizer prepares its parameters from configuration and predictions.
overrides (Mapping, optional): Run-time overrides of the settings of an optimizer
of the registry, e.g. ``{"generations": 10, "seed": 42}``.
force_enable (bool, optional): If True, bypasses any disabled state
to force the update process. This is mostly applicable to
prediction providers.
@@ -374,7 +385,10 @@ class EnergyManagement(
if algorithm is None:
algorithm = self.config.optimization.algorithm
run_solution: GeneticSolution | Genetic0Solution
run_solution: Any
optimizer = (
None if algorithm == OptimizationAlgorithm.GENETIC else get_optimizer(algorithm)
)
# --- GENETIC algorithm ---
if algorithm == OptimizationAlgorithm.GENETIC:
@@ -446,59 +460,41 @@ class EnergyManagement(
EnergyManagement._genetic_solution,
)
# --- GENETIC0 algorithm ---
elif algorithm == OptimizationAlgorithm.GENETIC0:
# --- Optimizers of the registry ---
elif optimizer is not None:
# Prepare optimization parameters
# This also creates default configurations for missing values and updates the predictions
logger.info(f"{algorithm}: Starting optimzation parameter preparation.")
if genetic0_parameters is None:
genetic0_parameters = await Genetic0OptimizationParameters.prepare()
if genetic0_parameters is None:
logger.error(
f"{algorithm}: Energy management run canceled. "
"Could not prepare optimisation parameters."
)
EnergyManagement._stage = EnergyManagementStage.IDLE
return None
# Take values from config if not given
if genetic0_generations is None:
genetic0_generations = self.config.optimization.genetic0.generations
if genetic0_seed is None:
genetic0_seed = self.config.optimization.genetic0.seed
if EnergyManagement._start_datetime is None: # Make mypy happy - already set by us
raise RuntimeError(f"{algorithm}: Start datetime not set.")
start = EnergyManagement._start_datetime
observation = EnergyManagement._observation_datetime or start
previous = EnergyManagement._optimizer_runs.get(optimizer.name)
warm_start = None if previous is None else previous.result
try:
if request is None:
parameters = await optimizer.prepare(
start, observation, warm_start, overrides
)
else:
parameters = await optimizer.prepare_from_request(
request, start, observation, warm_start, overrides
)
except Exception:
# Until every optimizer's preparation never fails (ADR 0006).
logger.exception(
f"{algorithm}: Energy management run canceled. "
"Could not prepare optimisation parameters."
)
EnergyManagement._stage = EnergyManagementStage.IDLE
return None
# --- Optimization (CPU-bound → MUST offload) ---
try:
# Imported on first use: a server that runs GENETIC never needs
# the GENETIC0 optimizer and its simulation.
from akkudoktoreos.optimization.genetic0.genetic0 import (
Genetic0Optimization,
)
genetic0_optimization = Genetic0Optimization(
verbose=bool(self.config.server.verbose),
fixed_seed=genetic0_seed,
)
loop = get_running_loop()
start_hour = EnergyManagement._start_datetime.hour
genetic0_solution = await loop.run_in_executor(
None,
lambda: genetic0_optimization.optimize_ems(
start_hour=start_hour,
parameters=cast(
Genetic0OptimizationParameters, genetic0_parameters
), # cast for mypy
ngen=genetic0_generations,
),
)
result = await loop.run_in_executor(None, optimizer.run, parameters)
# Build all representations before publishing any of them.
optimization_solution = await genetic0_solution.optimization_solution()
plan = genetic0_solution.energy_management_plan()
optimization_solution, plan = await optimizer.convert(parameters, result)
except Exception:
logger.exception(f"{algorithm}: Energy management optimization failed.")
@@ -506,16 +502,14 @@ class EnergyManagement(
return None
# Publish a consistent set without yielding to another coroutine.
EnergyManagement._genetic0_solution = genetic0_solution
EnergyManagement._optimizer_runs[optimizer.name] = OptimizerRun(
parameters=parameters, result=result
)
EnergyManagement._optimization_solution = optimization_solution
EnergyManagement._plan = plan
run_solution = genetic0_solution
run_solution = result
logger.debug(
"{}: Energy management genetic solution:\n{}",
algorithm,
EnergyManagement._genetic0_solution,
)
logger.debug("{}: Energy management optimizer result:\n{}", algorithm, result)
else:
logger.error(f"Unknown optimization algorithm: '{algorithm}'. Skipping.")
@@ -1,136 +0,0 @@
from typing import Optional
import numpy as np
from pydantic import Field
from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence
from akkudoktoreos.optimization.genetic0.genetic0devices import Genetic0DeviceParameters
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time
class Genetic0HomeApplianceParameters(Genetic0DeviceParameters):
"""Home Appliance Device Simulation Configuration."""
device_id: str = Field(
json_schema_extra={"description": "ID of home appliance", "examples": ["dishwasher"]}
)
consumption_wh: int = Field(
gt=0,
json_schema_extra={
"description": "An integer representing the energy consumption of a household device in watt-hours.",
"examples": [2000],
},
)
duration_h: int = Field(
gt=0,
json_schema_extra={
"description": "An integer representing the usage duration of a household device in hours.",
"examples": [3],
},
)
time_windows: Optional[TimeWindowSequence] = Field(
default=None,
json_schema_extra={
"description": "List of allowed time windows. Defaults to optimization general time window.",
"examples": [
[
{"start_time": "10:00", "duration": "3 hours"},
],
],
},
)
class Genetic0HomeAppliance:
def __init__(
self,
parameters: Genetic0HomeApplianceParameters,
optimization_hours: int,
prediction_hours: int,
):
self.parameters: Genetic0HomeApplianceParameters = parameters
self.prediction_hours = prediction_hours
self._setup()
def _setup(self) -> None:
"""Sets up the home appliance parameters based provided parameters."""
self.load_curve = np.zeros(self.prediction_hours) # Initialize the load curve with zeros
self.duration_h = self.parameters.duration_h
self.consumption_wh = self.parameters.consumption_wh
# setup possible start times
if self.parameters.time_windows is None:
self.parameters.time_windows = TimeWindowSequence(
windows=[
TimeWindow(
start_time=to_time("00:00"),
duration=to_duration(f"{self.prediction_hours} hours"),
),
]
)
start_datetime = to_datetime().set(hour=0, minute=0, second=0)
duration = to_duration(f"{self.duration_h} hours")
self.start_allowed: list[bool] = []
for hour in range(0, self.prediction_hours):
self.start_allowed.append(
self.parameters.time_windows.contains(
start_datetime.add(hours=hour), duration=duration
)
)
start_earliest = self.parameters.time_windows.earliest_start_time(duration, start_datetime)
if start_earliest:
self.start_earliest = start_earliest.hour
else:
self.start_earliest = 0
start_latest = self.parameters.time_windows.latest_start_time(duration, start_datetime)
if start_latest:
self.start_latest = start_latest.hour
else:
self.start_latest = 23
def set_starting_time(self, start_hour: int, global_start_hour: int = 0) -> int:
"""Sets the start time of the device and generates the corresponding load curve.
:param start_hour: The hour at which the device should start.
"""
if not self.start_allowed[start_hour]:
# It is not allowed (by the time windows) to start the application at this time
if global_start_hour <= self.start_latest:
# There is a time window left to start the appliance. Use it
start_hour = self.start_latest
else:
# There is no time window left to run the application
# Set the start into tomorrow
start_hour = self.start_earliest + 24
self.reset_load_curve()
# Calculate power per hour based on total consumption and duration
power_per_hour = self.consumption_wh / self.duration_h # Convert to watt-hours
# Set the power for the duration of use in the load curve array
if start_hour < len(self.load_curve):
end_hour = min(start_hour + self.duration_h, self.prediction_hours)
self.load_curve[start_hour:end_hour] = power_per_hour
return start_hour
def reset_load_curve(self) -> None:
"""Resets the load curve."""
self.load_curve = np.zeros(self.prediction_hours)
def get_load_curve(self) -> np.ndarray:
"""Returns the current load curve."""
return self.load_curve
def get_load_for_hour(self, hour: int) -> float:
"""Returns the load for a specific hour.
:param hour: The hour for which the load is queried.
:return: The load in watts for the specified hour.
"""
if hour < 0 or hour >= self.prediction_hours:
raise ValueError(
f"The specified hour {hour} is outside the available time frame {self.prediction_hours}."
)
return self.load_curve[hour]
@@ -120,10 +120,6 @@ from akkudoktoreos.measurement.batterycapacity import (
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0ElectricVehicleParameters,
Genetic0SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.genetic.battery import (
ElectricVehicleParameters,
SolarPanelBatteryParameters,
@@ -1085,77 +1081,6 @@ class BatteriesCommonSettings(DevicesBaseSettings):
**self._genetic_power_parameters(p, profile),
)
# ------------------------------------------------------------------
# GENETIC0 domain conversion
# ------------------------------------------------------------------
def to_genetic0_pv_bat_param(
self, operating_parameters: Optional[BatteryOperatingParameters] = None
) -> "Genetic0SolarPanelBatteryParameters":
"""Return Genetic0SolarPanelBatteryParameters for the GENETIC0 optimizer.
Args:
operating_parameters: Resolved snapshot to convert, e.g. from
``resolve_current_operating_parameters``. None resolves at the
reference operating point.
Raises:
BatteryResolutionError: See ``resolve_operating_parameters``.
"""
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0SolarPanelBatteryParameters,
)
p = (
operating_parameters
if operating_parameters is not None
else self.resolve_operating_parameters()
)
return Genetic0SolarPanelBatteryParameters(
device_id=self.device_id,
capacity_wh=p.capacity_wh,
charging_efficiency=p.charging_efficiency,
discharging_efficiency=p.discharging_efficiency,
max_charge_power_w=p.max_charge_power_w,
max_discharge_power_w=p.max_discharge_power_w,
min_soc_percentage=p.min_soc_percentage,
max_soc_percentage=p.max_soc_percentage,
)
def to_genetic0_ev_bat_param(
self, operating_parameters: Optional[BatteryOperatingParameters] = None
) -> "Genetic0ElectricVehicleParameters":
"""Return Genetic0ElectricVehicleParameters for the GENETIC0 optimizer.
Args:
operating_parameters: Resolved snapshot to convert, e.g. from
``resolve_current_operating_parameters``. None resolves at the
reference operating point.
Raises:
BatteryResolutionError: See ``resolve_operating_parameters``.
"""
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0ElectricVehicleParameters,
)
p = (
operating_parameters
if operating_parameters is not None
else self.resolve_operating_parameters()
)
return Genetic0ElectricVehicleParameters(
device_id=self.device_id,
capacity_wh=p.capacity_wh,
charging_efficiency=p.charging_efficiency,
discharging_efficiency=p.discharging_efficiency,
charge_rates=self.charge_rates,
max_charge_power_w=p.max_charge_power_w,
max_discharge_power_w=p.max_discharge_power_w,
min_soc_percentage=p.min_soc_percentage,
max_soc_percentage=p.max_soc_percentage,
)
@field_validator("charge_rates", mode="before")
def validate_and_sort_charge_rates(cls, v: Any) -> NDArray[Shape["*"], float]:
# None means fallback to default values
@@ -21,9 +21,6 @@ from akkudoktoreos.devices.settings.devicebasesettings import DevicesBaseSetting
from akkudoktoreos.utils.datetimeutil import DateTime, compare_datetimes, to_datetime
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
Genetic0HomeApplianceParameters,
)
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
@@ -395,27 +392,6 @@ class HomeApplianceCommonSettings(DevicesBaseSettings):
deadline_policy=self.deadline_policy,
)
# ------------------------------------------------------------------
# GENETIC0 domain conversion
# ------------------------------------------------------------------
def to_genetic0_param(self) -> "Genetic0HomeApplianceParameters":
"""Return Genetic0HomeApplianceParameters for the GENETIC0 optimizer."""
from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
Genetic0HomeApplianceParameters,
)
if self.load_profile_power_w is not None:
raise ValueError("Explicit appliance load profiles require the GENETIC optimizer.")
if self.consumption_wh is None or self.duration_h is None:
raise ValueError("GENETIC0 requires a flat appliance load definition.")
return Genetic0HomeApplianceParameters(
device_id=self.device_id,
consumption_wh=self.consumption_wh,
duration_h=self.duration_h,
time_windows=self.cycle_time_windows,
)
@computed_field # type: ignore[prop-decorator]
@property
def measurement_keys(self) -> Optional[list[str]]:
@@ -43,9 +43,6 @@ from akkudoktoreos.devices.settings.inverterresolution import (
from akkudoktoreos.utils.datetimeutil import DateTime
if TYPE_CHECKING:
from akkudoktoreos.devices.genetic0.genetic0inverter import (
Genetic0InverterParameters,
)
from akkudoktoreos.devices.genetic.inverter import InverterParameters
from akkudoktoreos.devices.profile.inverterprofile import InverterProfile
@@ -713,35 +710,6 @@ class InverterCommonSettings(DevicesBaseSettings):
ac_charge_limits_total_charge=p.ac_charge_limits_total_charge,
)
# ------------------------------------------------------------------
# GENETIC0 domain conversion
# ------------------------------------------------------------------
def to_genetic0_param(
self, operating_parameters: Optional[InverterOperatingParameters] = None
) -> "Genetic0InverterParameters":
"""Return Genetic0InverterParameters for the GENETIC0 optimizer.
GENETIC0 uses constant efficiencies: the DC→AC efficiency at the
reference load fraction and the AC→DC efficiency at the AC charge limit.
Raises:
InverterResolutionError: See ``to_genetic_param``.
"""
from akkudoktoreos.devices.genetic0.genetic0inverter import (
Genetic0InverterParameters,
)
p = operating_parameters or self.resolve_operating_parameters()
return Genetic0InverterParameters(
device_id=self.device_id,
max_power_wh=p.max_power_w,
battery_id=self.battery_id,
ac_to_dc_efficiency=p.ac_to_dc_efficiency,
dc_to_ac_efficiency=p.dc_to_ac_efficiency,
max_ac_charge_power_w=p.max_ac_charge_power_w,
)
@computed_field # type: ignore[prop-decorator]
@property
def measurement_key_temperature_degc(self) -> str:
@@ -0,0 +1,29 @@
"""GENETIC0 optimizer: the only module code outside the optimizer imports (ADR 0005).
``Genetic0Optimizer`` and ``Genetic0Settings`` are loaded on first access, so importing the package
does not load the optimizer and its simulation.
"""
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from akkudoktoreos.optimization.genetic0.genetic0optimizer import Genetic0Optimizer
from akkudoktoreos.optimization.genetic0.genetic0settings import Genetic0Settings
__all__ = ["Genetic0Optimizer", "Genetic0Settings"]
def __getattr__(name: str) -> Any:
if name == "Genetic0Optimizer":
from akkudoktoreos.optimization.genetic0.genetic0optimizer import (
Genetic0Optimizer,
)
return Genetic0Optimizer
if name == "Genetic0Settings":
from akkudoktoreos.optimization.genetic0.genetic0settings import (
Genetic0Settings,
)
return Genetic0Settings
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -1,121 +1,71 @@
"""GENETIC0 battery simulation device (stationary battery or electric vehicle)."""
from dataclasses import dataclass
from typing import Any, Iterator, Optional
import numpy as np
from pydantic import Field
from akkudoktoreos.devices.settings.batterysettings import BATTERY_DEFAULT_CHARGE_RATES
from akkudoktoreos.optimization.genetic0.genetic0devices import Genetic0DeviceParameters
# Charge rates of a battery that has none; copied from the battery settings, optimizers share no
# code with the configuration (ADR 0004).
BATTERY_DEFAULT_CHARGE_RATES: tuple[float, ...] = (
0.0,
0.1,
0.2,
0.3,
0.4,
0.5,
0.6,
0.7,
0.8,
0.9,
1.0,
)
def max_charging_power_field(description: Optional[str] = None) -> float:
if description is None:
description = "Maximum charging power in watts."
# 0: the battery may not charge, e.g. the profile inhibits it at a low temperature.
return Field(default=5000, ge=0, json_schema_extra={"description": description})
@dataclass(frozen=True, slots=True)
class Genetic0BatteryParameters:
"""Parameters of a simulated battery.
Attributes:
device_id: ID of the battery.
capacity_wh: Capacity in watt-hours.
charging_efficiency: Charging efficiency (0, 1].
discharging_efficiency: Discharging efficiency (0, 1].
max_charge_power_w: Maximum charging power in watts; ``None`` uses the capacity.
max_discharge_power_w: Maximum discharging power in watts; ``None`` uses the charging
power.
initial_soc_percentage: State of charge at the start of the run in percent.
min_soc_percentage: Minimum state of charge in percent.
max_soc_percentage: Maximum state of charge in percent.
charge_rates: Available charge rates as factors of the charging power; ``None`` or empty
gives the default rates.
stationary: A stationary (PV) battery keeps its minimum state of charge; an electric
vehicle may be discharged to 0.
"""
def initial_soc_percentage_field(description: str) -> int:
return Field(
default=0, ge=0, le=100, json_schema_extra={"description": description, "examples": [42]}
)
def discharging_efficiency_field(default_value: float) -> float:
return Field(
default=default_value,
gt=0,
le=1,
json_schema_extra={
"description": "A float representing the discharge efficiency of the battery."
},
)
class Genetic0BaseBatteryParameters(Genetic0DeviceParameters):
"""Battery Device Simulation Configuration."""
device_id: str = Field(
json_schema_extra={"description": "ID of battery", "examples": ["battery1"]}
)
capacity_wh: int = Field(
gt=0,
json_schema_extra={
"description": "An integer representing the capacity of the battery in watt-hours.",
"examples": [8000],
},
)
charging_efficiency: float = Field(
default=0.88,
gt=0,
le=1,
json_schema_extra={
"description": "A float representing the charging efficiency of the battery."
},
)
discharging_efficiency: float = discharging_efficiency_field(0.88)
max_charge_power_w: Optional[float] = max_charging_power_field()
max_discharge_power_w: Optional[float] = Field(
default=None,
ge=0,
json_schema_extra={
"description": (
"Maximum discharging power in watts. 0: the battery may not discharge. "
"None uses max_charge_power_w."
),
"examples": [None, 4000],
},
)
initial_soc_percentage: int = initial_soc_percentage_field(
"An integer representing the state of charge of the battery at the **start** of the current hour (not the current state)."
)
min_soc_percentage: int = Field(
default=0,
ge=0,
le=100,
json_schema_extra={
"description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.",
"examples": [10],
},
)
max_soc_percentage: int = Field(
default=100,
ge=0,
le=100,
json_schema_extra={
"description": "An integer representing the maximum state of charge (SOC) of the battery in percentage."
},
)
charge_rates: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": "Charge rates as factor of maximum charging power [0.00 ... 1.00]. None denotes all charge rates are available.",
"examples": [[0.0, 0.25, 0.5, 0.75, 1.0], None],
},
)
class Genetic0SolarPanelBatteryParameters(Genetic0BaseBatteryParameters):
"""PV battery device simulation configuration."""
max_charge_power_w: Optional[float] = max_charging_power_field()
class Genetic0ElectricVehicleParameters(Genetic0BaseBatteryParameters):
"""Battery Electric Vehicle Device Simulation Configuration."""
device_id: str = Field(
json_schema_extra={"description": "ID of electric vehicle", "examples": ["ev1"]}
)
discharging_efficiency: float = discharging_efficiency_field(1.0)
initial_soc_percentage: int = initial_soc_percentage_field(
"An integer representing the current state of charge (SOC) of the battery in percentage."
)
device_id: str
capacity_wh: int
charging_efficiency: float
discharging_efficiency: float
max_charge_power_w: Optional[float]
max_discharge_power_w: Optional[float]
initial_soc_percentage: int
min_soc_percentage: int
max_soc_percentage: int
charge_rates: Optional[tuple[float, ...]]
stationary: bool
class Genetic0Battery:
"""Represents a battery device with methods to simulate energy charging and discharging."""
def __init__(self, parameters: Genetic0BaseBatteryParameters, prediction_hours: int):
def __init__(self, parameters: Genetic0BatteryParameters, prediction_hours: int) -> None:
"""Set up the battery.
Args:
parameters: Battery parameters.
prediction_hours: Length of the simulated arrays.
"""
self.parameters = parameters
self.prediction_hours = prediction_hours
self._setup()
@@ -137,9 +87,7 @@ class Genetic0Battery:
# Only assign for storage battery
self.min_soc_percentage = (
self.parameters.min_soc_percentage
if isinstance(self.parameters, Genetic0SolarPanelBatteryParameters)
else 0
self.parameters.min_soc_percentage if self.parameters.stationary else 0
)
self.max_soc_percentage = self.parameters.max_soc_percentage
@@ -0,0 +1,103 @@
"""GENETIC0 home appliance simulation device."""
from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True, slots=True)
class Genetic0HomeApplianceParameters:
"""Parameters of a simulated home appliance.
Attributes:
device_id: ID of the appliance.
consumption_wh: Energy of one run in watt-hours.
duration_h: Duration of one run in hours.
start_allowed: Per hour of the arrays, whether a run may start then.
start_earliest: Earliest hour of the day a run may start.
start_latest: Latest hour of the day a run may start.
"""
device_id: str
consumption_wh: int
duration_h: int
start_allowed: tuple[bool, ...]
start_earliest: int
start_latest: int
class Genetic0HomeAppliance:
def __init__(
self,
parameters: Genetic0HomeApplianceParameters,
optimization_hours: int,
prediction_hours: int,
) -> None:
"""Set up the home appliance.
Args:
parameters: Home appliance parameters.
optimization_hours: Optimization horizon in hours (unused).
prediction_hours: Length of the simulated arrays.
"""
self.parameters: Genetic0HomeApplianceParameters = parameters
self.prediction_hours = prediction_hours
self._setup()
def _setup(self) -> None:
"""Sets up the home appliance parameters based provided parameters."""
self.load_curve = np.zeros(self.prediction_hours) # Initialize the load curve with zeros
self.duration_h = self.parameters.duration_h
self.consumption_wh = self.parameters.consumption_wh
# Possible start times, evaluated from the time windows by the parameter preparation.
self.start_allowed: list[bool] = list(self.parameters.start_allowed)
self.start_earliest = self.parameters.start_earliest
self.start_latest = self.parameters.start_latest
def set_starting_time(self, start_hour: int, global_start_hour: int = 0) -> int:
"""Sets the start time of the device and generates the corresponding load curve.
:param start_hour: The hour at which the device should start.
"""
if not self.start_allowed[start_hour]:
# It is not allowed (by the time windows) to start the application at this time
if global_start_hour <= self.start_latest:
# There is a time window left to start the appliance. Use it
start_hour = self.start_latest
else:
# There is no time window left to run the application
# Set the start into tomorrow
start_hour = self.start_earliest + 24
self.reset_load_curve()
# Calculate power per hour based on total consumption and duration
power_per_hour = self.consumption_wh / self.duration_h # Convert to watt-hours
# Set the power for the duration of use in the load curve array
if start_hour < len(self.load_curve):
end_hour = min(start_hour + self.duration_h, self.prediction_hours)
self.load_curve[start_hour:end_hour] = power_per_hour
return start_hour
def reset_load_curve(self) -> None:
"""Resets the load curve."""
self.load_curve = np.zeros(self.prediction_hours)
def get_load_curve(self) -> np.ndarray:
"""Returns the current load curve."""
return self.load_curve
def get_load_for_hour(self, hour: int) -> float:
"""Returns the load for a specific hour.
:param hour: The hour for which the load is queried.
:return: The load in watts for the specified hour.
"""
if hour < 0 or hour >= self.prediction_hours:
raise ValueError(
f"The specified hour {hour} is outside the available time frame {self.prediction_hours}."
)
return self.load_curve[hour]
@@ -1,63 +1,36 @@
"""GENETIC0 inverter simulation device."""
from dataclasses import dataclass
from typing import Optional
from loguru import logger
from pydantic import Field
from akkudoktoreos.devices.genetic0.genetic0battery import Genetic0Battery
from akkudoktoreos.optimization.genetic0.genetic0devices import Genetic0DeviceParameters
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import Genetic0Battery
from akkudoktoreos.optimization.genetic0.genetic0loadinterpolator import (
get_genetic0_load_interpolator,
)
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
class Genetic0InverterParameters(Genetic0DeviceParameters):
"""Inverter Device Simulation Configuration."""
@dataclass(frozen=True, slots=True)
class Genetic0InverterParameters:
"""Parameters of a simulated inverter.
device_id: str = Field(
json_schema_extra={"description": "ID of inverter", "examples": ["inverter1"]}
)
max_power_wh: float = Field(gt=0, json_schema_extra={"examples": [10000]})
battery_id: Optional[str] = Field(
default=None,
json_schema_extra={"description": "ID of battery", "examples": [None, "battery1"]},
)
ac_to_dc_efficiency: float = Field(
default=1.0,
ge=0,
le=1,
json_schema_extra={
"description": (
"Efficiency of AC to DC conversion (for AC/grid charging of battery). "
"Set to 0 to disable AC charging via inverter. "
"Default 1.0 for backward compatibility (no additional inverter loss)."
),
"examples": [0.95, 1.0, 0.0],
},
)
dc_to_ac_efficiency: float = Field(
default=1.0,
gt=0,
le=1,
json_schema_extra={
"description": (
"Efficiency of DC to AC conversion (for battery discharging to AC load/grid). "
"Default 1.0 for backward compatibility (no additional inverter loss)."
),
"examples": [0.95, 1.0],
},
)
max_ac_charge_power_w: Optional[float] = Field(
default=None,
ge=0,
json_schema_extra={
"description": (
"Maximum AC charging power in watts. "
"None means no additional limit (battery's own max_charge_power_w applies). "
"Set to 0 to disable AC charging."
),
"examples": [None, 0, 5000],
},
)
Attributes:
device_id: ID of the inverter.
max_power_wh: Maximum power the inverter can handle per hour.
battery_id: ID of the battery behind the inverter, if any.
ac_to_dc_efficiency: Efficiency of AC charging.
dc_to_ac_efficiency: Efficiency of DC to AC conversion.
max_ac_charge_power_w: Maximum AC charging power in watts; ``None`` uses the battery's.
"""
device_id: str
max_power_wh: float
battery_id: Optional[str]
ac_to_dc_efficiency: float
dc_to_ac_efficiency: float
max_ac_charge_power_w: Optional[float]
class Genetic0Inverter:
@@ -65,9 +38,22 @@ class Genetic0Inverter:
self,
parameters: Genetic0InverterParameters,
battery: Optional[Genetic0Battery] = None,
):
self_consumption_interpolator: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY,
) -> None:
"""Set up the inverter simulation.
Args:
parameters: Inverter parameters.
battery: Battery behind the inverter, if any.
self_consumption_interpolator: How the self-consumption table is evaluated; the run
settings pass the configured backend.
Raises:
ValueError: The battery is not the one the inverter parameters name.
"""
self.parameters: Genetic0InverterParameters = parameters
self.battery: Optional[Genetic0Battery] = battery
self.self_consumption_interpolator = self_consumption_interpolator
self._setup()
def _setup(self) -> None:
@@ -75,7 +61,9 @@ class Genetic0Inverter:
error_msg = f"Battery ID mismatch - {self.parameters.battery_id} is configured; got {self.battery.parameters.device_id}."
logger.error(error_msg)
raise ValueError(error_msg)
self.self_consumption_predictor = get_genetic0_load_interpolator()
self.self_consumption_predictor = get_genetic0_load_interpolator(
self.self_consumption_interpolator
)
self.max_power_wh = (
self.parameters.max_power_wh
) # Maximum power that the inverter can handle
@@ -1,11 +0,0 @@
"""Genetic0 optimization algorithm abstract and base classes."""
from pydantic import ConfigDict
from akkudoktoreos.core.pydantic import PydanticBaseModel
class Genetic0ParametersBaseModel(PydanticBaseModel):
"""Pydantic base model for parameters for the GENETIC algorithm."""
model_config = ConfigDict(extra="forbid")
@@ -1,453 +1,56 @@
"""Genetic0 algorithm."""
"""GENETIC0 algorithm: the genetic search over the simulation."""
import random
import time
from typing import Any, Optional
from typing import Any, Optional, cast
import numpy as np
from deap import algorithms, base, creator, tools
from loguru import logger
from numpydantic import NDArray, Shape
from pydantic import ConfigDict, Field
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.devices.genetic0.genetic0battery import Genetic0Battery
from akkudoktoreos.devices.genetic0.genetic0homeappliance import Genetic0HomeAppliance
from akkudoktoreos.devices.genetic0.genetic0inverter import Genetic0Inverter
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0EnergyManagementParameters,
Genetic0OptimizationParameters,
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import Genetic0Battery
from akkudoktoreos.optimization.genetic0.devices.genetic0homeappliance import (
Genetic0HomeAppliance,
)
from akkudoktoreos.optimization.genetic0.genetic0solution import (
Genetic0SimulationResult,
Genetic0Solution,
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
Genetic0Inverter,
)
from akkudoktoreos.optimization.optimizationabc import OptimizationBase
from akkudoktoreos.optimization.genetic0.genetic0parameters import (
Genetic0Parameters,
Genetic0RunSettings,
)
from akkudoktoreos.optimization.genetic0.genetic0result import (
Genetic0ElectricVehicleState,
Genetic0Result,
Genetic0SimulationOutput,
float_list,
int_list,
)
from akkudoktoreos.optimization.genetic0.genetic0simulation import Genetic0Simulation
class Genetic0Simulation(PydanticBaseModel):
"""Device simulation for GENETIC optimization algorithm."""
class Genetic0Optimization:
"""GENETIC algorithm to solve energy optimization.
# Disable validation on assignment to speed up simulation runs.
model_config = ConfigDict(
validate_assignment=False,
)
Reads nothing but its run settings and the parameters passed to ``optimize_ems()``.
"""
start_hour: int = Field(
default=0,
ge=0,
le=23,
json_schema_extra={"description": "Starting hour on day for optimizations."},
)
def __init__(self, settings: Genetic0RunSettings):
"""Initialize the optimization problem with the settings of the run.
optimization_hours: Optional[int] = Field(
default=24,
ge=0,
json_schema_extra={"description": "Number of hours into the future for optimizations."},
)
prediction_hours: Optional[int] = Field(
default=48,
ge=0,
json_schema_extra={"description": "Number of hours into the future for predictions"},
)
load_energy_array: Optional[NDArray[Shape["*"], float]] = Field(
default=None,
json_schema_extra={
"description": "An array of floats representing the total load (consumption) in watts for different time intervals."
},
)
pv_prediction_wh: Optional[NDArray[Shape["*"], float]] = Field(
default=None,
json_schema_extra={
"description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals."
},
)
elect_price_hourly: Optional[NDArray[Shape["*"], float]] = Field(
default=None,
json_schema_extra={
"description": "An array of floats representing the electricity price per watt-hour for different time intervals."
},
)
elect_revenue_per_hour_arr: Optional[NDArray[Shape["*"], float]] = Field(
default=None,
json_schema_extra={
"description": "An array of floats representing the feed-in compensation per watt-hour."
},
)
battery: Optional[Genetic0Battery] = Field(
default=None, json_schema_extra={"description": "TBD."}
)
ev: Optional[Genetic0Battery] = Field(default=None, json_schema_extra={"description": "TBD."})
home_appliance: Optional[Genetic0HomeAppliance] = Field(
default=None, json_schema_extra={"description": "TBD."}
)
inverter: Optional[Genetic0Inverter] = Field(
default=None, json_schema_extra={"description": "TBD."}
)
ac_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(
default=None, json_schema_extra={"description": "TBD"}
)
dc_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(
default=None, json_schema_extra={"description": "TBD"}
)
bat_discharge_hours: Optional[NDArray[Shape["*"], float]] = Field(
default=None, json_schema_extra={"description": "TBD"}
)
ev_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(
default=None, json_schema_extra={"description": "TBD"}
)
ev_discharge_hours: Optional[NDArray[Shape["*"], float]] = Field(
default=None, json_schema_extra={"description": "TBD"}
)
home_appliance_start_hour: Optional[int] = Field(
default=None,
json_schema_extra={"description": "Home appliance start hour - None denotes no start."},
)
def prepare(
self,
parameters: Genetic0EnergyManagementParameters,
optimization_hours: int,
prediction_hours: int,
ev: Optional[Genetic0Battery] = None,
home_appliance: Optional[Genetic0HomeAppliance] = None,
inverter: Optional[Genetic0Inverter] = None,
) -> None:
"""Prepare simulation runs.
Populate internal arrays and device references used during simulation.
Args:
settings: Algorithm settings of the run.
"""
self.optimization_hours = optimization_hours
self.prediction_hours = prediction_hours
# Load arrays from provided EMS parameters
self.load_energy_array = np.array(parameters.total_load, float)
self.pv_prediction_wh = np.array(parameters.pv_forecast_wh, float)
self.elect_price_hourly = np.array(parameters.electricity_price_per_wh, float)
self.elect_revenue_per_hour_arr = (
np.asarray(parameters.feed_in_tariff_per_wh, dtype=float)
if isinstance(parameters.feed_in_tariff_per_wh, list)
else np.full(len(self.load_energy_array), parameters.feed_in_tariff_per_wh, float)
)
# Associate devices
if inverter:
self.battery = inverter.battery
else:
self.battery = None
self.ev = ev
self.home_appliance = home_appliance
self.inverter = inverter
# Initialize per-hour action arrays for the prediction horizon
self.ac_charge_hours = np.full(self.prediction_hours, 0.0)
self.dc_charge_hours = np.full(self.prediction_hours, 0.0)
self.bat_discharge_hours = np.full(self.prediction_hours, 0.0)
self.ev_charge_hours = np.full(self.prediction_hours, 0.0)
self.ev_discharge_hours = np.full(self.prediction_hours, 0.0)
self.home_appliance_start_hour = None
def reset(self) -> None:
if self.ev:
self.ev.reset()
if self.battery:
self.battery.reset()
self.home_appliance_start_hour = None
def simulate(self, start_hour: int) -> dict[str, Any]:
"""Simulate energy usage and costs for the given start hour.
battery_soc_per_hour begin of the hour, initial hour state!
load_wh_per_hour integral of last hour (end state)
"""
# Remember start hour
self.start_hour = start_hour
# Provide fast (3x..5x) local read access (vs. self.xxx) for repetitive read access
load_energy_array_fast = self.load_energy_array
ev_charge_hours_fast = self.ev_charge_hours
ev_discharge_hours_fast = self.ev_discharge_hours
ac_charge_hours_fast = self.ac_charge_hours
dc_charge_hours_fast = self.dc_charge_hours
bat_discharge_hours_fast = self.bat_discharge_hours
elect_price_hourly_fast = self.elect_price_hourly
elect_revenue_per_hour_arr_fast = self.elect_revenue_per_hour_arr
pv_prediction_wh_fast = self.pv_prediction_wh
battery_fast = self.battery
ev_fast = self.ev
home_appliance_fast = self.home_appliance
inverter_fast = self.inverter
# Check for simulation integrity (in a way that mypy understands)
if (
load_energy_array_fast is None
or pv_prediction_wh_fast is None
or elect_price_hourly_fast is None
or ev_charge_hours_fast is None
or ac_charge_hours_fast is None
or dc_charge_hours_fast is None
or elect_revenue_per_hour_arr_fast is None
or bat_discharge_hours_fast is None
or ev_discharge_hours_fast is None
):
missing = []
if load_energy_array_fast is None:
missing.append("Load Energy Array")
if pv_prediction_wh_fast is None:
missing.append("PV Prediction Wh")
if elect_price_hourly_fast is None:
missing.append("Electricity Price Hourly")
if ev_charge_hours_fast is None:
missing.append("EV Charge Hours")
if ac_charge_hours_fast is None:
missing.append("AC Charge Hours")
if dc_charge_hours_fast is None:
missing.append("DC Charge Hours")
if elect_revenue_per_hour_arr_fast is None:
missing.append("Electricity Revenue Per Hour")
if bat_discharge_hours_fast is None:
missing.append("Genetic0Battery Discharge Hours")
if ev_discharge_hours_fast is None:
missing.append("EV Discharge Hours")
msg = ", ".join(missing)
logger.error("Mandatory data missing - %s", msg)
raise ValueError(f"Mandatory data missing: {msg}")
if not (
len(load_energy_array_fast)
== len(pv_prediction_wh_fast)
== len(elect_price_hourly_fast)
):
error_msg = f"Array sizes do not match: Load Curve = {len(load_energy_array_fast)}, PV Forecast = {len(pv_prediction_wh_fast)}, Electricity Price = {len(elect_price_hourly_fast)}"
logger.error(error_msg)
raise ValueError(error_msg)
end_hour = len(load_energy_array_fast)
total_hours = end_hour - start_hour
# Pre-allocate arrays for the results, optimized for speed
loads_energy_per_hour = np.full((total_hours), np.nan)
feedin_energy_per_hour = np.full((total_hours), np.nan)
consumption_energy_per_hour = np.full((total_hours), np.nan)
costs_per_hour = np.full((total_hours), np.nan)
revenue_per_hour = np.full((total_hours), np.nan)
losses_wh_per_hour = np.full((total_hours), np.nan)
electricity_price_per_hour = np.full((total_hours), np.nan)
# Set initial state
if battery_fast:
# Pre-allocate arrays for the results, optimized for speed
soc_per_hour = np.full((total_hours), np.nan)
soc_per_hour[0] = battery_fast.current_soc_percentage()
# Determine AC charging availability from inverter parameters
if inverter_fast:
ac_to_dc_eff_fast = inverter_fast.ac_to_dc_efficiency
dc_to_ac_eff_fast = inverter_fast.dc_to_ac_efficiency
max_ac_charge_w_fast = inverter_fast.max_ac_charge_power_w
else:
ac_to_dc_eff_fast = 1.0
dc_to_ac_eff_fast = 1.0
max_ac_charge_w_fast = None
ac_charging_possible = ac_to_dc_eff_fast > 0 and (
max_ac_charge_w_fast is None or max_ac_charge_w_fast > 0
)
# If AC charging is disabled via inverter, zero out AC charge hours
if not ac_charging_possible:
ac_charge_hours_fast = np.zeros_like(ac_charge_hours_fast)
# Fill the charge array of the battery
dc_charge_hours_fast[0:start_hour] = 0
dc_charge_hours_fast[end_hour:] = 0
ac_charge_hours_fast[0:start_hour] = 0
ac_charge_hours_fast[end_hour:] = 0
battery_fast.charge_array = np.where(
ac_charge_hours_fast != 0, ac_charge_hours_fast, dc_charge_hours_fast
)
# Fill the discharge array of the battery
bat_discharge_hours_fast[0:start_hour] = 0
bat_discharge_hours_fast[end_hour:] = 0
battery_fast.discharge_array = bat_discharge_hours_fast
else:
# Default return if no battery is available
soc_per_hour = np.full((total_hours), 0)
ac_to_dc_eff_fast = 1.0
dc_to_ac_eff_fast = 1.0
max_ac_charge_w_fast = None
ac_charging_possible = False
if ev_fast:
# Pre-allocate arrays for the results, optimized for speed
soc_ev_per_hour = np.full((total_hours), np.nan)
soc_ev_per_hour[0] = ev_fast.current_soc_percentage()
# Fill the charge array of the ev
ev_charge_hours_fast[0:start_hour] = 0
ev_charge_hours_fast[end_hour:] = 0
ev_fast.charge_array = ev_charge_hours_fast
# Fill the discharge array of the ev
ev_discharge_hours_fast[0:start_hour] = 0
ev_discharge_hours_fast[end_hour:] = 0
ev_fast.discharge_array = ev_discharge_hours_fast
else:
# Default return if no electric vehicle is available
soc_ev_per_hour = np.full((total_hours), 0)
if home_appliance_fast and self.home_appliance_start_hour is not None:
home_appliance_enabled = True
# Pre-allocate arrays for the results, optimized for speed
home_appliance_wh_per_hour = np.full((total_hours), np.nan)
self.home_appliance_start_hour = home_appliance_fast.set_starting_time(
self.home_appliance_start_hour, start_hour
)
else:
home_appliance_enabled = False
# Default return if no home appliance is available
home_appliance_wh_per_hour = np.full((total_hours), 0)
for hour in range(start_hour, end_hour):
hour_idx = hour - start_hour
# Accumulate loads and PV generation
consumption = load_energy_array_fast[hour]
losses_wh_per_hour[hour_idx] = 0.0
# Home appliances
if home_appliance_enabled:
ha_load = home_appliance_fast.get_load_for_hour(hour) # type: ignore[union-attr]
consumption += ha_load
home_appliance_wh_per_hour[hour_idx] = ha_load
# E-Auto handling
if ev_fast:
soc_ev_per_hour[hour_idx] = ev_fast.current_soc_percentage() # save begin state
if ev_charge_hours_fast[hour] > 0:
loaded_energy_ev, ev_charge_losses = ev_fast.charge_energy(
wh=None, hour=hour, charge_factor=ev_charge_hours_fast[hour]
)
consumption += loaded_energy_ev
losses_wh_per_hour[hour_idx] += ev_charge_losses
# Save battery SOC before inverter processing = true begin-of-interval state.
# Must be recorded here (before DC charge/discharge) so the displayed SOC at
# timestamp T reflects what the battery actually had at the START of interval T,
# not the post-DC result. Consistent with the EV SOC convention above.
if battery_fast:
soc_per_hour[hour_idx] = battery_fast.current_soc_percentage()
# Process inverter logic
energy_feedin_grid_actual = energy_consumption_grid_actual = losses = (
self_consumption
) = 0.0
if inverter_fast:
energy_produced = pv_prediction_wh_fast[hour]
(
energy_feedin_grid_actual,
energy_consumption_grid_actual,
losses,
self_consumption,
) = inverter_fast.process_energy(energy_produced, consumption, hour)
# AC PV Battery Charge
if battery_fast:
hour_ac_charge = ac_charge_hours_fast[hour]
if hour_ac_charge > 0.0 and ac_charging_possible:
# Cap charge factor by max_ac_charge_power_w if set
effective_charge_factor = hour_ac_charge
if max_ac_charge_w_fast is not None and battery_fast.max_charge_power_w > 0:
# DC power = max_charge_power_w * factor
# AC power = DC power / ac_to_dc_eff
# AC power must be <= max_ac_charge_power_w
max_dc_factor = (
max_ac_charge_w_fast * ac_to_dc_eff_fast
) / battery_fast.max_charge_power_w
effective_charge_factor = min(effective_charge_factor, max_dc_factor)
if effective_charge_factor > 0:
battery_charged_energy_actual, battery_losses_actual = (
battery_fast.charge_energy(
None, hour, charge_factor=effective_charge_factor
)
)
# DC energy entering the battery (before battery internal efficiency)
dc_energy = battery_charged_energy_actual + battery_losses_actual
# AC energy consumed from grid (accounts for AC→DC conversion loss)
ac_energy = dc_energy / ac_to_dc_eff_fast
# Genetic0Inverter AC→DC conversion losses
inverter_charge_losses = ac_energy - dc_energy
consumption += ac_energy
energy_consumption_grid_actual += ac_energy
losses_wh_per_hour[hour_idx] += (
battery_losses_actual + inverter_charge_losses
)
# Update hourly arrays
feedin_energy_per_hour[hour_idx] = energy_feedin_grid_actual
consumption_energy_per_hour[hour_idx] = energy_consumption_grid_actual
losses_wh_per_hour[hour_idx] += losses
loads_energy_per_hour[hour_idx] = consumption
hourly_electricity_price = elect_price_hourly_fast[hour]
electricity_price_per_hour[hour_idx] = hourly_electricity_price
# Financial calculations
costs_per_hour[hour_idx] = energy_consumption_grid_actual * hourly_electricity_price
revenue_per_hour[hour_idx] = (
energy_feedin_grid_actual * elect_revenue_per_hour_arr_fast[hour]
)
total_cost = np.nansum(costs_per_hour)
total_losses = np.nansum(losses_wh_per_hour)
total_revenue = np.nansum(revenue_per_hour)
# Prepare output dictionary
return {
"Last_Wh_pro_Stunde": loads_energy_per_hour,
"Netzeinspeisung_Wh_pro_Stunde": feedin_energy_per_hour,
"Netzbezug_Wh_pro_Stunde": consumption_energy_per_hour,
"Kosten_Euro_pro_Stunde": costs_per_hour,
"akku_soc_pro_stunde": soc_per_hour,
"Einnahmen_Euro_pro_Stunde": revenue_per_hour,
"Gesamtbilanz_Euro": total_cost - total_revenue, # Fitness score ("FitnessMin")
"EAuto_SoC_pro_Stunde": soc_ev_per_hour,
"Gesamteinnahmen_Euro": total_revenue,
"Gesamtkosten_Euro": total_cost,
"Verluste_Pro_Stunde": losses_wh_per_hour,
"Gesamt_Verluste": total_losses,
"Home_appliance_wh_per_hour": home_appliance_wh_per_hour,
"Electricity_price": electricity_price_per_hour,
}
class Genetic0Optimization(OptimizationBase):
"""GENETIC algorithm to solve energy optimization."""
def __init__(
self,
verbose: bool = False,
fixed_seed: Optional[int] = None,
):
"""Initialize the optimization problem with the required parameters."""
self.settings = settings
self.start_hour = 0
self.opti_param: dict[str, Any] = {}
self.fixed_ev_hours = (
self.config.prediction.hours - self.config.optimization.genetic0.horizon_hours
)
self.fixed_ev_hours = settings.prediction_hours - settings.horizon_hours
self.ev_possible_charge_values: list[float] = [1.0]
# Separate charge-level list for battery AC charging (independent of EV rates).
# Populated from parameters.pv_battery.charge_rates in optimize_ems.
self.bat_possible_charge_values: list[float] = [1.0]
self.verbose = verbose
self.fix_seed = fixed_seed
self.verbose = settings.verbose
self.fix_seed = settings.seed
self.optimize_ev = True
self.optimize_dc_charge = False
self.fitness_history: dict[str, Any] = {}
@@ -517,23 +120,23 @@ class Genetic0Optimization(OptimizationBase):
total_states = 3 * len_bat
# 1. Mutating the charge_discharge part
charge_discharge_part = individual[: self.config.prediction.hours]
charge_discharge_part = individual[: self.settings.prediction_hours]
(charge_discharge_mutated,) = self.toolbox.mutate_charge_discharge(charge_discharge_part)
# Instead of a fixed clamping to 0..8 or 0..6 dynamically:
charge_discharge_mutated = np.clip(charge_discharge_mutated, 0, total_states - 1)
individual[: self.config.prediction.hours] = charge_discharge_mutated
individual[: self.settings.prediction_hours] = charge_discharge_mutated
# 2. Mutating the EV charge part, if active
if self.optimize_ev:
ev_charge_part = individual[
self.config.prediction.hours : self.config.prediction.hours * 2
self.settings.prediction_hours : self.settings.prediction_hours * 2
]
(ev_charge_part_mutated,) = self.toolbox.mutate_ev_charge_index(ev_charge_part)
ev_charge_part_mutated[self.config.prediction.hours - self.fixed_ev_hours :] = [
ev_charge_part_mutated[self.settings.prediction_hours - self.fixed_ev_hours :] = [
0
] * self.fixed_ev_hours
individual[self.config.prediction.hours : self.config.prediction.hours * 2] = (
individual[self.settings.prediction_hours : self.settings.prediction_hours * 2] = (
ev_charge_part_mutated
)
@@ -549,13 +152,13 @@ class Genetic0Optimization(OptimizationBase):
def create_individual(self) -> list[int]:
# Start with discharge states for the individual
individual_components = [
self.toolbox.attr_discharge_state() for _ in range(self.config.prediction.hours)
self.toolbox.attr_discharge_state() for _ in range(self.settings.prediction_hours)
]
# Add EV charge index values if optimize_ev is True
if self.optimize_ev:
individual_components += [
self.toolbox.attr_ev_charge_index() for _ in range(self.config.prediction.hours)
self.toolbox.attr_ev_charge_index() for _ in range(self.settings.prediction_hours)
]
# Add the start time of the household appliance if it's being optimized
@@ -588,7 +191,7 @@ class Genetic0Optimization(OptimizationBase):
individual.extend(ev_charge_hours_index.tolist())
elif self.optimize_ev:
# If optimize_ev is active but no EV data is available, append zeros
individual.extend([0] * self.config.prediction.hours)
individual.extend([0] * self.settings.prediction_hours)
# Add dishwasher start time if applicable
if self.opti_param.get("home_appliance", 0) > 0 and washingstart_int is not None:
@@ -610,13 +213,13 @@ class Genetic0Optimization(OptimizationBase):
3. Dishwasher start time (integer if applicable).
"""
# Discharge hours as a NumPy array of ints
discharge_hours_bin = np.array(individual[: self.config.prediction.hours], dtype=int)
discharge_hours_bin = np.array(individual[: self.settings.prediction_hours], dtype=int)
# EV charge hours as a NumPy array of ints (if optimize_ev is True)
ev_charge_hours_index = (
# append ev charging states to individual
np.array(
individual[self.config.prediction.hours : self.config.prediction.hours * 2],
individual[self.settings.prediction_hours : self.settings.prediction_hours * 2],
dtype=int,
)
if self.optimize_ev
@@ -722,7 +325,7 @@ class Genetic0Optimization(OptimizationBase):
if self.optimize_dc_charge:
self.simulation.dc_charge_hours = dc_charge_hours
else:
self.simulation.dc_charge_hours = np.full(self.config.prediction.hours, 1)
self.simulation.dc_charge_hours = np.full(self.settings.prediction_hours, 1)
self.simulation.ac_charge_hours = ac_charge_hours
if ev_charge_hours_index is not None:
@@ -734,15 +337,15 @@ class Genetic0Optimization(OptimizationBase):
self.simulation.ev_charge_hours = ev_charge_hours_float
else:
# discharge is set to 0 by default
self.simulation.ev_charge_hours = np.full(self.config.prediction.hours, 0)
self.simulation.ev_charge_hours = np.full(self.settings.prediction_hours, 0)
# Do the simulation and return result.
return self.simulation.simulate(self.ems.start_datetime.hour)
return self.simulation.simulate(self.start_hour)
def evaluate(
self,
individual: list[int],
parameters: Genetic0OptimizationParameters,
parameters: Genetic0Parameters,
start_hour: int,
worst_case: bool,
) -> tuple[float]:
@@ -755,9 +358,9 @@ class Genetic0Optimization(OptimizationBase):
Args:
individual (list[int]):
The genome representing one candidate solution.
parameters (Genetic0EnergyManagementParameters):
Optimization parameters that influence simulation behavior,
constraints, and scoring logic.
parameters (Genetic0Parameters):
Optimization parameters of the run: forecasts, devices and settings that
influence simulation behavior, constraints, and scoring logic.
start_hour (int):
The simulation start hour (0–23 or domain-specific).
Used to initialize time-based scheduling or constraints.
@@ -926,9 +529,7 @@ class Genetic0Optimization(OptimizationBase):
# Configurable penalty multiplier (default 1 = economic loss in currency units)
try:
ac_penalty_factor = float(
self.config.optimization.genetic0.penalties["ac_charge_break_even"]
)
ac_penalty_factor = float(self.settings.penalties["ac_charge_break_even"])
except Exception:
ac_penalty_factor = 1.0
@@ -975,7 +576,7 @@ class Genetic0Optimization(OptimizationBase):
if self.optimize_ev and parameters.ev and self.simulation.ev:
try:
penalty = self.config.optimization.genetic0.penalties["ev_soc_miss"]
penalty = self.settings.penalties["ev_soc_miss"]
except Exception:
# Use default
penalty = 10
@@ -987,7 +588,9 @@ class Genetic0Optimization(OptimizationBase):
ev_soc_percentage < parameters.ev.min_soc_percentage
or ev_soc_percentage > parameters.ev.max_soc_percentage
):
total_balance += abs(parameters.ev.min_soc_percentage - ev_soc_percentage) * penalty
total_balance += abs(parameters.ev.min_soc_percentage - ev_soc_percentage) * cast(
float, penalty
)
return (total_balance,)
@@ -1002,7 +605,7 @@ class Genetic0Optimization(OptimizationBase):
"""
# Set the number of inviduals in a generation
try:
individuals = self.config.optimization.genetic0.individuals
individuals = self.settings.individuals
if individuals is None:
raise
except Exception:
@@ -1057,28 +660,23 @@ class Genetic0Optimization(OptimizationBase):
def optimize_ems(
self,
parameters: Genetic0OptimizationParameters,
start_hour: Optional[int] = None,
parameters: Genetic0Parameters,
worst_case: bool = False,
ngen: Optional[int] = None,
) -> Genetic0Solution:
"""Perform EMS (Energy Management System) optimization and visualize results."""
if start_hour is None:
start_hour = self.ems.start_datetime.hour
# Start hour has to be in sync with energy management
if start_hour != self.ems.start_datetime.hour:
raise ValueError(
f"Start hour not synced. EMS {self.ems.start_datetime.hour} vs. GENETIC0 {start_hour}."
)
) -> Genetic0Result:
"""Perform EMS (Energy Management System) optimization.
Args:
parameters: The optimization parameters of the run.
worst_case: Evaluate the worst case.
Returns:
The solution of the run.
"""
start_hour = parameters.start_hour
self.start_hour = start_hour
# Set the number of generations
generations = ngen
if generations is None:
try:
generations = self.config.optimization.genetic0.generations
except Exception:
generations = 400
logger.error("Generations not configured. Using {}.", generations)
generations = self.settings.generations
self.simulation.reset()
@@ -1087,31 +685,25 @@ class Genetic0Optimization(OptimizationBase):
if parameters.pv_battery:
battery = Genetic0Battery(
parameters.pv_battery,
prediction_hours=self.config.prediction.hours,
prediction_hours=self.settings.prediction_hours,
)
battery.set_charge_per_hour(np.full(self.config.prediction.hours, 0))
battery.set_charge_per_hour(np.full(self.settings.prediction_hours, 0))
ev: Optional[Genetic0Battery] = None
if parameters.ev:
ev = Genetic0Battery(
parameters.ev,
prediction_hours=self.config.prediction.hours,
prediction_hours=self.settings.prediction_hours,
)
ev.set_charge_per_hour(np.full(self.config.prediction.hours, 1))
ev.set_charge_per_hour(np.full(self.settings.prediction_hours, 1))
self.optimize_ev = (
parameters.ev.min_soc_percentage - parameters.ev.initial_soc_percentage >= 0
)
# electrical vehicle charge rates
if parameters.ev.charge_rates is not None:
self.ev_possible_charge_values = parameters.ev.charge_rates
elif (
self.config.devices.electric_vehicles
and len(self.config.devices.electric_vehicles) > 0
and list(self.config.devices.electric_vehicles.values())[0].charge_rates is not None
):
self.ev_possible_charge_values = list(
self.config.devices.electric_vehicles.values()
)[0].charge_rates
self.ev_possible_charge_values = list(parameters.ev.charge_rates)
elif self.settings.ev_charge_rates is not None:
self.ev_possible_charge_values = list(self.settings.ev_charge_rates)
else:
warning_msg = "No charge rates provided for electric vehicle - using default."
logger.warning(warning_msg)
@@ -1138,13 +730,9 @@ class Genetic0Optimization(OptimizationBase):
self.bat_possible_charge_values = [
r for r in parameters.pv_battery.charge_rates if r > 0.0
] or [1.0]
elif (
self.config.devices.batteries
and len(self.config.devices.batteries) > 0
and list(self.config.devices.batteries.values())[0].charge_rates
):
elif self.settings.battery_charge_rates:
self.bat_possible_charge_values = [
r for r in list(self.config.devices.batteries.values())[0].charge_rates if r > 0.0
r for r in self.settings.battery_charge_rates if r > 0.0
] or [1.0]
else:
self.bat_possible_charge_values = [1.0]
@@ -1154,8 +742,8 @@ class Genetic0Optimization(OptimizationBase):
dishwasher = (
Genetic0HomeAppliance(
parameters=parameters.dishwasher,
optimization_hours=self.config.optimization.genetic0.horizon_hours,
prediction_hours=self.config.prediction.hours,
optimization_hours=self.settings.horizon_hours,
prediction_hours=self.settings.prediction_hours,
)
if parameters.dishwasher is not None
else None
@@ -1167,13 +755,14 @@ class Genetic0Optimization(OptimizationBase):
inverter = Genetic0Inverter(
parameters.inverter,
battery=battery,
self_consumption_interpolator=self.settings.self_consumption_interpolator,
)
# Prepare device simulation
self.simulation.prepare(
parameters=parameters.ems,
optimization_hours=self.config.optimization.genetic0.horizon_hours,
prediction_hours=self.config.prediction.hours,
optimization_hours=self.settings.horizon_hours,
prediction_hours=self.settings.prediction_hours,
inverter=inverter, # battery is part of inverter
ev=ev,
home_appliance=dishwasher,
@@ -1187,7 +776,11 @@ class Genetic0Optimization(OptimizationBase):
)
start_time = time.time()
start_solution, extra_data = self.optimize(parameters.start_solution, ngen=generations)
# None (not configured) is passed on as before.
start_solution, extra_data = self.optimize(
None if parameters.start_solution is None else list(parameters.start_solution),
ngen=generations, # type: ignore[arg-type]
)
elapsed_time = time.time() - start_time
logger.debug(f"Time evaluate inner: {elapsed_time:.4f} sec.")
@@ -1225,20 +818,23 @@ class Genetic0Optimization(OptimizationBase):
else []
)
return Genetic0Solution(
**{
"parameters": parameters,
"ac_charge": ac_charge_hours,
"dc_charge": dc_charge_hours,
"discharge_allowed": discharge,
"ev_charge_hours_float": ev_charge_hours_float,
"result": Genetic0SimulationResult(**simulation_result),
"ev_obj": self.simulation.ev,
"start_hour": start_hour,
"start_solution": start_solution,
"washingstart": washingstart_int,
"extra_data": extra_data,
"fitness_history": self.fitness_history,
"fixed_seed": self.fix_seed,
}
return Genetic0Result(
ac_charge=float_list(ac_charge_hours),
dc_charge=float_list(dc_charge_hours),
discharge_allowed=int_list(discharge),
ev_charge_hours_float=(
None if ev_charge_hours_float is None else float_list(ev_charge_hours_float)
),
result=Genetic0SimulationOutput.from_simulation(simulation_result),
ev_obj=(
None
if self.simulation.ev is None
else Genetic0ElectricVehicleState.from_battery(self.simulation.ev.to_dict())
),
start_hour=start_hour,
start_solution=None if start_solution is None else float_list(start_solution),
washingstart=None if washingstart_int is None else int(washingstart_int),
extra_data=extra_data,
fitness_history=self.fitness_history,
fixed_seed=self.fix_seed,
)
@@ -0,0 +1,592 @@
"""REST API of GENETIC0 (ADR 0005, 0011): its router and public response models.
The router fetches nothing itself: the generic server fills the placeholder dependencies
``last_run()`` and ``run()`` through ``app.dependency_overrides``. The response models are built
from the optimization parameters and the result of a run.
"""
import dataclasses
from typing import Annotated, Any, Optional, Union
from fastapi import APIRouter, Depends, Query, Response
from pydantic import AliasChoices, ConfigDict, Field, computed_field, field_validator
from akkudoktoreos.optimization.genetic0.genetic0parameters import Genetic0Parameters
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0ParametersBaseModel,
Genetic0Request,
)
from akkudoktoreos.optimization.genetic0.genetic0result import (
Genetic0ElectricVehicleState,
Genetic0Result,
)
from akkudoktoreos.optimization.optimizer import (
OptimizerApi,
OptimizerProblem,
OptimizerRun,
RunTrigger,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
from akkudoktoreos.utils.utils import NumpyEncoder
class DeviceOptimizeResult(Genetic0ParametersBaseModel):
device_id: str = Field(
json_schema_extra={"description": "ID of device", "examples": ["device1"]}
)
hours: int = Field(
gt=0,
json_schema_extra={"description": "Number of hours in the simulation.", "examples": [24]},
)
class Genetic0ElectricVehicleResult(DeviceOptimizeResult):
"""Result class containing information related to the electric vehicle's charging and discharging behavior."""
device_id: str = Field(
json_schema_extra={"description": "ID of electric vehicle", "examples": ["ev1"]}
)
charge_array: list[float] = Field(
json_schema_extra={
"description": "Hourly charging status (0 for no charging, 1 for charging)."
}
)
discharge_array: list[int] = Field(
json_schema_extra={
"description": "Hourly discharging status (0 for no discharging, 1 for discharging)."
}
)
discharging_efficiency: float = Field(
json_schema_extra={"description": "The discharge efficiency as a float.."}
)
capacity_wh: int = Field(
json_schema_extra={"description": "Capacity of the EV’s battery in watt-hours."}
)
charging_efficiency: float = Field(
json_schema_extra={"description": "Charging efficiency as a float.."}
)
max_charge_power_w: int = Field(
json_schema_extra={"description": "Maximum charging 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."
}
)
initial_soc_percentage: int = Field(
json_schema_extra={
"description": "State of charge at the start of the simulation in percentage."
}
)
@field_validator("discharge_array", "charge_array", mode="before")
def convert_numpy(cls, field: Any) -> Any:
return NumpyEncoder.convert_numpy(field)[0]
class Genetic0SimulationResult(Genetic0ParametersBaseModel):
"""This object contains the results of the simulation and provides insights into various parameters over the entire forecast period."""
model_config = ConfigDict(populate_by_name=True, extra="ignore")
load_wh_per_hour: list[float] = Field(
validation_alias=AliasChoices("load_wh_per_hour", "Last_Wh_pro_Stunde"),
json_schema_extra={"description": "The load in watt-hours per hour."},
)
ev_soc_per_hour: list[float] = Field(
validation_alias=AliasChoices("ev_soc_per_hour", "EAuto_SoC_pro_Stunde"),
json_schema_extra={"description": "The state of charge of the EV for each hour."},
)
revenue_per_hour: list[float] = Field(
validation_alias=AliasChoices("revenue_per_hour", "Einnahmen_Euro_pro_Stunde"),
json_schema_extra={
"description": "The revenue from grid feed-in or other sources per hour."
},
)
total_losses: float = Field(
validation_alias=AliasChoices("total_losses", "Gesamt_Verluste"),
json_schema_extra={"description": "The total losses in watt-hours over the entire period."},
)
total_balance: float = Field(
validation_alias=AliasChoices("total_balance", "Gesamtbilanz_Euro"),
json_schema_extra={"description": "The total balance of revenues minus costs."},
)
total_revenue: float = Field(
validation_alias=AliasChoices("total_revenue", "Gesamteinnahmen_Euro"),
json_schema_extra={"description": "The total revenues."},
)
total_costs: float = Field(
validation_alias=AliasChoices("total_costs", "Gesamtkosten_Euro"),
json_schema_extra={"description": "The total costs."},
)
home_appliance_wh_per_hour: list[Optional[float]] = Field(
validation_alias=AliasChoices("home_appliance_wh_per_hour", "Home_appliance_wh_per_hour"),
json_schema_extra={
"description": "The energy consumption of a household appliance in watt-hours per hour."
},
)
costs_per_hour: list[float] = Field(
validation_alias=AliasChoices("costs_per_hour", "Kosten_Euro_pro_Stunde"),
json_schema_extra={"description": "The costs per hour."},
)
grid_consumption_wh_per_hour: list[float] = Field(
validation_alias=AliasChoices("grid_consumption_wh_per_hour", "Netzbezug_Wh_pro_Stunde"),
json_schema_extra={"description": "The grid energy drawn in watt-hours per hour."},
)
grid_feed_in_wh_per_hour: list[float] = Field(
validation_alias=AliasChoices("grid_feed_in_wh_per_hour", "Netzeinspeisung_Wh_pro_Stunde"),
json_schema_extra={"description": "The energy fed into the grid in watt-hours per hour."},
)
losses_per_hour: list[float] = Field(
validation_alias=AliasChoices("losses_per_hour", "Verluste_Pro_Stunde"),
json_schema_extra={"description": "The losses in watt-hours per hour."},
)
battery_soc_per_hour: list[float] = Field(
validation_alias=AliasChoices("battery_soc_per_hour", "akku_soc_pro_stunde"),
json_schema_extra={
"description": "The state of charge of the battery (not the EV) in percentage per hour."
},
)
electricity_price: list[float] = Field(
validation_alias=AliasChoices("electricity_price", "Electricity_price"),
json_schema_extra={"description": "Used Electricity Price, including predictions"},
)
# Computed fields for backward compatibility (deprecated German names)
@computed_field(json_schema_extra={"deprecated": True})
def Last_Wh_pro_Stunde(self) -> list[float]:
"""Deprecated: Use load_wh_per_hour instead."""
return self.load_wh_per_hour
@computed_field(json_schema_extra={"deprecated": True})
def EAuto_SoC_pro_Stunde(self) -> list[float]:
"""Deprecated: Use ev_soc_per_hour instead."""
return self.ev_soc_per_hour
@computed_field(json_schema_extra={"deprecated": True})
def Einnahmen_Euro_pro_Stunde(self) -> list[float]:
"""Deprecated: Use revenue_per_hour instead."""
return self.revenue_per_hour
@computed_field(json_schema_extra={"deprecated": True})
def Gesamt_Verluste(self) -> float:
"""Deprecated: Use total_losses instead."""
return self.total_losses
@computed_field(json_schema_extra={"deprecated": True})
def Gesamtbilanz_Euro(self) -> float:
"""Deprecated: Use total_balance instead."""
return self.total_balance
@computed_field(json_schema_extra={"deprecated": True})
def Gesamteinnahmen_Euro(self) -> float:
"""Deprecated: Use total_revenue instead."""
return self.total_revenue
@computed_field(json_schema_extra={"deprecated": True})
def Gesamtkosten_Euro(self) -> float:
"""Deprecated: Use total_costs instead."""
return self.total_costs
@computed_field(json_schema_extra={"deprecated": True})
def Home_appliance_wh_per_hour(self) -> list[Optional[float]]:
"""Deprecated: Use home_appliance_wh_per_hour instead."""
return self.home_appliance_wh_per_hour
@computed_field(json_schema_extra={"deprecated": True})
def Kosten_Euro_pro_Stunde(self) -> list[float]:
"""Deprecated: Use costs_per_hour instead."""
return self.costs_per_hour
@computed_field(json_schema_extra={"deprecated": True})
def Netzbezug_Wh_pro_Stunde(self) -> list[float]:
"""Deprecated: Use grid_consumption_wh_per_hour instead."""
return self.grid_consumption_wh_per_hour
@computed_field(json_schema_extra={"deprecated": True})
def Netzeinspeisung_Wh_pro_Stunde(self) -> list[float]:
"""Deprecated: Use grid_feed_in_wh_per_hour instead."""
return self.grid_feed_in_wh_per_hour
@computed_field(json_schema_extra={"deprecated": True})
def Verluste_Pro_Stunde(self) -> list[float]:
"""Deprecated: Use losses_per_hour instead."""
return self.losses_per_hour
@computed_field(json_schema_extra={"deprecated": True})
def akku_soc_pro_stunde(self) -> list[float]:
"""Deprecated: Use battery_soc_per_hour instead."""
return self.battery_soc_per_hour
@computed_field(json_schema_extra={"deprecated": True})
def Electricity_price(self) -> list[float]:
"""Deprecated: Use electricity_price instead."""
return self.electricity_price
@field_validator(
"load_wh_per_hour",
"grid_feed_in_wh_per_hour",
"battery_soc_per_hour",
"grid_consumption_wh_per_hour",
"costs_per_hour",
"revenue_per_hour",
"ev_soc_per_hour",
"losses_per_hour",
"home_appliance_wh_per_hour",
"electricity_price",
mode="before",
)
def convert_numpy(cls, field: Any) -> Any:
return NumpyEncoder.convert_numpy(field)[0]
# Legacy GENETIC solution dataset. To keep the /optimize endpoint compatible.
class Genetic0SolutionLegacy(Genetic0ParametersBaseModel):
"""GENETIC0 solution legacy dataset."""
model_config = ConfigDict(populate_by_name=True, extra="ignore")
ac_charge: list[float] = Field(
json_schema_extra={
"description": "Array with AC charging values as relative power (0.0-1.0), other values set to 0."
}
)
dc_charge: list[float] = Field(
json_schema_extra={
"description": "Array with DC charging values as relative power (0-1), other values set to 0."
}
)
discharge_allowed: list[int] = Field(
json_schema_extra={
"description": "Array with discharge values (1 for discharge, 0 otherwise)."
}
)
ev_charge_hours_float: Optional[list[float]] = Field(
validation_alias=AliasChoices("ev_charge_hours_float", "eautocharge_hours_float"),
json_schema_extra={
"description": "Array with EV charging values as relative power (0.0-1.0), or `null` if no EV is optimized."
},
)
result: Genetic0SimulationResult
ev_obj: Optional[Genetic0ElectricVehicleResult] = Field(
validation_alias=AliasChoices("ev_obj", "eauto_obj"),
json_schema_extra={"description": "Electric vehicle state after optimization."},
)
start_solution: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": "An array of binary values (0 or 1) representing a possible starting solution for the simulation."
},
)
washingstart: Optional[int] = Field(
default=None,
json_schema_extra={
"description": "Can be `null` or contain an object representing the start of washing (if applicable)."
},
)
# Computed fields for backward compatibility (deprecated German names)
@computed_field(json_schema_extra={"deprecated": True})
def eautocharge_hours_float(self) -> Optional[list[float]]:
"""Deprecated: Use ev_charge_hours_float instead."""
return self.ev_charge_hours_float
@computed_field(json_schema_extra={"deprecated": True})
def eauto_obj(self) -> Optional[Genetic0ElectricVehicleResult]:
"""Deprecated: Use ev_obj instead."""
return self.ev_obj
@field_validator(
"ac_charge",
"dc_charge",
"discharge_allowed",
mode="before",
)
def convert_numpy(cls, field: Any) -> Any:
return NumpyEncoder.convert_numpy(field)[0]
@field_validator(
"ev_obj",
mode="before",
)
def convert_eauto(cls, field: Any) -> Any:
if isinstance(field, Genetic0ElectricVehicleState):
return Genetic0ElectricVehicleResult(**dataclasses.asdict(field))
return field
class Genetic0Solution(Genetic0ParametersBaseModel):
"""**Note**: The first value of "load_wh_per_hour", "grid_feed_in_wh_per_hour", and "grid_consumption_wh_per_hour", will be set to null in the JSON output and represented as NaN or None in the corresponding classes' data returns. This approach is adopted to ensure that the current hour's processing remains unchanged."""
model_config = ConfigDict(populate_by_name=True, extra="ignore")
parameters: Genetic0Request = Field(
json_schema_extra={"description": "Optimization parameters used to generate solution."}
)
ac_charge: list[float] = Field(
json_schema_extra={
"description": "Array with AC charging values as relative power (0.0-1.0), other values set to 0."
}
)
dc_charge: list[float] = Field(
json_schema_extra={
"description": "Array with DC charging values as relative power (0-1), other values set to 0."
}
)
discharge_allowed: list[int] = Field(
json_schema_extra={
"description": "Array with discharge values (1 for discharge, 0 otherwise)."
}
)
ev_charge_hours_float: Optional[list[float]] = Field(
validation_alias=AliasChoices("ev_charge_hours_float", "eautocharge_hours_float"),
json_schema_extra={
"description": "Array with EV charging values as relative power (0.0-1.0), or `null` if no EV is optimized."
},
)
result: Genetic0SimulationResult
ev_obj: Optional[Genetic0ElectricVehicleResult] = Field(
validation_alias=AliasChoices("ev_obj", "eauto_obj"),
json_schema_extra={"description": "Electric vehicle state after optimization."},
)
start_hour: int = Field(
default=0,
json_schema_extra={"description": "Start hour."},
)
start_solution: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": "An array of binary values (0 or 1) representing a possible starting solution for the simulation."
},
)
washingstart: Optional[int] = Field(
default=None,
json_schema_extra={
"description": "Can be `null` or contain an object representing the start of washing (if applicable)."
},
)
extra_data: Optional[dict[str, Union[list[int], list[float]]]] = Field(
default=None,
json_schema_extra={
"description": ("Dictionary of balance: TBD, losses: TBD, constraints: TBD.")
},
)
fitness_history: Optional[dict[str, Union[list[int], list[float]]]] = Field(
default=None,
json_schema_extra={
"description": (
"Dictionary of "
"gen: Generation numbers (X-axis), "
"avg: Average fitness for each generation (Y-axis), "
"max: Maximum fitness for each generation (Y-axis), "
"min: Minimum fitness for each generation (Y-axis)."
)
},
)
fixed_seed: Optional[int] = Field(
default=None,
json_schema_extra={"description": "Fixed seed."},
)
# Computed fields for backward compatibility (deprecated German names)
@computed_field(json_schema_extra={"deprecated": True})
def eautocharge_hours_float(self) -> Optional[list[float]]:
"""Deprecated: Use ev_charge_hours_float instead."""
return self.ev_charge_hours_float
@computed_field(json_schema_extra={"deprecated": True})
def eauto_obj(self) -> Optional[Genetic0ElectricVehicleResult]:
"""Deprecated: Use ev_obj instead."""
return self.ev_obj
@field_validator(
"ac_charge",
"dc_charge",
"discharge_allowed",
mode="before",
)
def convert_numpy(cls, field: Any) -> Any:
return NumpyEncoder.convert_numpy(field)[0]
@field_validator(
"ev_obj",
mode="before",
)
def convert_eauto(cls, field: Any) -> Any:
if isinstance(field, Genetic0ElectricVehicleState):
return Genetic0ElectricVehicleResult(**dataclasses.asdict(field))
return field
def solution_response(parameters: Genetic0Parameters, result: Genetic0Result) -> Genetic0Solution:
"""The public solution of a run.
Args:
parameters: The optimization parameters of the run; their request is echoed.
result: The result of the run.
Returns:
The solution as the REST API returns it.
"""
return Genetic0Solution.model_validate(
{
"parameters": parameters.request,
"ac_charge": result.ac_charge,
"dc_charge": result.dc_charge,
"discharge_allowed": result.discharge_allowed,
"ev_charge_hours_float": result.ev_charge_hours_float,
"result": dataclasses.asdict(result.result),
"ev_obj": result.ev_obj,
"start_hour": result.start_hour,
"start_solution": result.start_solution,
"washingstart": result.washingstart,
"extra_data": result.extra_data,
"fitness_history": result.fitness_history,
"fixed_seed": result.fixed_seed,
}
)
def legacy_response(result: Genetic0Result) -> Genetic0SolutionLegacy:
"""The solution of a run as the deprecated ``POST /optimize`` returns it.
Args:
result: The result of the run.
Returns:
The legacy solution.
"""
return Genetic0SolutionLegacy.model_validate(
{
"ac_charge": result.ac_charge,
"dc_charge": result.dc_charge,
"discharge_allowed": result.discharge_allowed,
"ev_charge_hours_float": result.ev_charge_hours_float,
"result": dataclasses.asdict(result.result),
"ev_obj": result.ev_obj,
"start_solution": result.start_solution,
"washingstart": result.washingstart,
}
)
# ----------------------------------------------------------------------------------------------
# Router
# ----------------------------------------------------------------------------------------------
router = APIRouter()
def last_run() -> Optional[OptimizerRun[Genetic0Parameters, Genetic0Result]]:
"""Placeholder dependency: the latest GENETIC0 run, filled by the server.
Raises:
NotImplementedError: The server did not fill the placeholder.
"""
raise NotImplementedError("Filled by the server through app.dependency_overrides.")
def run() -> RunTrigger:
"""Placeholder dependency: starts a GENETIC0 run, filled by the server.
Raises:
NotImplementedError: The server did not fill the placeholder.
"""
raise NotImplementedError("Filled by the server through app.dependency_overrides.")
def api() -> OptimizerApi:
"""The REST API of GENETIC0 for the server.
Returns:
The router and its placeholder dependencies.
"""
return OptimizerApi(router=router, last_run=last_run, run=run)
@router.post("/optimize", tags=["optimize"])
async def fastapi_optimize(
parameters: Genetic0Request,
start_hour: Annotated[
Optional[int], Query(description="Defaults to current hour of the day.")
] = None,
ngen: Annotated[
Optional[int], Query(description="Number of indivuals to generate for genetic algorithm.")
] = None,
trigger: RunTrigger = Depends(run),
) -> Genetic0SolutionLegacy:
"""Deprecated: Optimize.
Endpoint to handle optimization.
Uses the `classic` GENETIC0 optimisation algorithm (__NO__ 15-minutes slots).
Note:
Use automatic optimization instead.
"v1/energy-management/optimization/solution/GENETIC0"
"""
if start_hour is None:
start_datetime = None
else:
start_datetime = to_datetime().set(hour=start_hour)
# Ensure there is only one optimization/ energy management run at a time
result = await trigger(
start_datetime=start_datetime,
request=parameters,
overrides={"generations": ngen},
)
if result is None:
raise OptimizerProblem(
status=404,
title="Optimization solution retrieval failed",
detail="Can not get the 'GENETIC0' optimization solution.",
)
# Create compatible solution.
return legacy_response(result)
@router.get("/v1/energy-management/optimization/solution/GENETIC0", tags=["energy-management"])
async def fastapi_energy_management_optimization_solution_genetic0_get(
latest: Optional[OptimizerRun[Genetic0Parameters, Genetic0Result]] = Depends(last_run),
) -> Genetic0Solution:
"""Get the latest GENETIC0 specific solution of the optimization."""
if latest is None:
raise OptimizerProblem(
status=404,
title="Algorithm specific optimization solution retrieval failed",
detail=(
"Can not get the 'GENETIC0' optimization solution.\n"
"Did you configure automatic 'GENETIC0' optimization?\n"
"Did you run the optimization/ energy management?"
),
)
return solution_response(latest.parameters, latest.result)
@router.get("/visualization_results.pdf", tags=["optimize"])
def get_pdf(
latest: Optional[OptimizerRun[Genetic0Parameters, Genetic0Result]] = Depends(last_run),
) -> Response:
"""PDF report of the latest GENETIC0 run."""
if latest is None:
raise OptimizerProblem(
status=404,
title="Optimization solution report retrieval failed",
detail="Can not get the 'GENETIC0' optimization solution.",
)
# matplotlib is only needed for the PDF report; import it on first use.
from akkudoktoreos.optimization.genetic0.genetic0visualize import (
genetic0_prepare_visualize,
)
pdf = genetic0_prepare_visualize(parameters=latest.parameters, solution=latest.result)
return Response(
content=pdf,
media_type="application/pdf",
headers={"Content-Disposition": 'inline; filename="optimization-report.pdf"'},
)
@@ -0,0 +1,647 @@
"""Solution conversion of GENETIC0 (ADR 0003, 0006).
Turns the result of a run into the optimization solution and the energy management plan, from
the optimization parameters and the result alone: the start, time zone, device IDs and
prediction series come from the parameters' presentation data, not from the configuration,
the predictions or the EMS.
"""
from typing import Optional
import numpy as np
import pandas as pd
from loguru import logger
from akkudoktoreos.core.emplan import (
DDBCInstruction,
EnergyManagementPlan,
FRBCInstruction,
)
from akkudoktoreos.core.pydantic import PydanticDateTimeDataFrame
from akkudoktoreos.core.types import (
FillMethod,
)
from akkudoktoreos.devices.devicesabc import (
ApplianceOperationMode,
BatteryOperationMode,
)
from akkudoktoreos.optimization.genetic0.genetic0parameters import Genetic0Parameters
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0InverterRequest,
)
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
from akkudoktoreos.optimization.optimization import OptimizationSolution
from akkudoktoreos.utils.datetimeutil import to_datetime
async def convert(
parameters: Genetic0Parameters, result: Genetic0Result
) -> tuple[OptimizationSolution, EnergyManagementPlan]:
"""Convert the result of a run into the optimization solution and the plan.
Args:
parameters: The optimization parameters of the run.
result: The result of the run.
Returns:
The optimization solution and the energy management plan.
"""
return await optimization_solution(parameters, result), energy_management_plan(
parameters, result
)
def _battery_operation_from_solution(
parameters: Genetic0Parameters,
result: Genetic0Result,
ac_charge: float,
dc_charge: float,
discharge_allowed: bool,
) -> tuple[BatteryOperationMode, float]:
"""Maps low-level solution to a representative operation mode and factor.
Args:
ac_charge (float): Allowed AC-side charging power (relative units).
dc_charge (float): Allowed DC-side charging power (relative units).
discharge_allowed (bool): Whether discharging is permitted.
Returns:
tuple[BatteryOperationMode, float]: A tuple containing
- `BatteryOperationMode`: the representative high-level operation mode.
- `float`: the operation factor corresponding to the active signal.
Notes:
- The mapping prioritizes AC charge > DC charge > discharge.
- Multiple strategies can produce the same low-level signals; this function
returns a representative mode based on a defined priority order.
"""
# (0,0,0) → Nothing allowed
if ac_charge <= 0.0 and dc_charge <= 0.0 and not discharge_allowed:
return BatteryOperationMode.IDLE, 1.0
# (0,0,1) → Discharge only
if ac_charge <= 0.0 and dc_charge <= 0.0 and discharge_allowed:
return BatteryOperationMode.PEAK_SHAVING, 1.0
# (ac>0,0,0) → AC charge only
if ac_charge > 0.0 and dc_charge <= 0.0 and not discharge_allowed:
return BatteryOperationMode.GRID_SUPPORT_IMPORT, ac_charge
# (0,dc>0,0) → DC charge only
if ac_charge <= 0.0 and dc_charge > 0.0 and not discharge_allowed:
return BatteryOperationMode.NON_EXPORT, dc_charge
# (ac>0,dc>0,0) → Both charge paths, no discharge
if ac_charge > 0.0 and dc_charge > 0.0 and not discharge_allowed:
return BatteryOperationMode.FORCED_CHARGE, ac_charge
# (ac>0,0,1) → AC charge + discharge - does not make sense
if ac_charge > 0.0 and dc_charge <= 0.0 and discharge_allowed:
raise ValueError(
f"Illegal state: ac_charge: {ac_charge} and discharge_allowed: {discharge_allowed}"
)
# (0,dc>0,1) → DC charge + discharge
if ac_charge <= 0.0 and dc_charge > 0.0 and discharge_allowed:
return BatteryOperationMode.SELF_CONSUMPTION, dc_charge
# (ac>0,dc>0,1) → Fully flexible - does not make sense
if ac_charge > 0.0 and dc_charge > 0.0 and discharge_allowed:
raise ValueError(
f"Illegal state: ac_charge: {ac_charge} and discharge_allowed: {discharge_allowed}"
)
# Fallback → safe idle
return BatteryOperationMode.IDLE, 1.0
def _inverter_parameters(parameters: Genetic0Parameters) -> Optional[Genetic0InverterRequest]:
"""Return the inverter parameters the solution was computed with."""
return parameters.request.inverter
def _soc_clamped_operation_factors(
parameters: Genetic0Parameters,
result: Genetic0Result,
ac_charge: float,
dc_charge: float,
discharge_allowed: bool,
soc_pct: float,
) -> tuple[float, float, bool]:
"""Clamp raw genetic gene values by the battery's actual SOC at that hour.
The raw gene values represent the optimizer's *intent* and are stored
verbatim in the ``genetic_*`` solution columns. This method derives
the *effective* values that can physically be executed given the
battery's state of charge, used for the ``battery1_*_op_*`` columns
and for ``energy_management_plan`` instructions.
Clamping rules:
- AC charge factor: scaled down proportionally when the battery
headroom (max_soc − current_soc) is smaller than what the
commanded factor would store in one hour. Set to 0 when full.
- 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 = parameters.request.pv_battery
if bat is None:
return ac_charge, dc_charge, discharge_allowed
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 ---
effective_ac = ac_charge
if effective_ac > 0.0:
if headroom_wh <= 0.0:
effective_ac = 0.0
else:
inv = _inverter_parameters(parameters)
ac_to_dc_eff = float(inv.ac_to_dc_efficiency) if inv else 1.0
max_ac_cp_w = (
float(inv.max_ac_charge_power_w)
if inv and inv.max_ac_charge_power_w is not None
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:
effective_ac = effective_ac * (headroom_wh / max_dc_per_h_wh)
# --- DC charge (PV): zero when battery is full ---
effective_dc = dc_charge
if effective_dc > 0.0 and headroom_wh <= 0.0:
effective_dc = 0.0
# --- Discharge: block at min SOC ---
effective_dis = discharge_allowed and (soc_pct > min_soc)
return effective_ac, effective_dc, effective_dis
async def optimization_solution(
parameters: Genetic0Parameters,
result: Genetic0Result,
) -> OptimizationSolution:
"""Provide the genetic solution as a general optimization solution.
The battery modes are controlled by the grid control triggers:
- ac_charge: charge from grid
- discharge_allowed: discharge to grid
The following battery modes are supported:
- SELF_CONSUMPTION: ac_charge == 0 and discharge_allowed == 0
- GRID_SUPPORT_EXPORT: ac_charge == 0 and discharge_allowed == 1
- GRID_SUPPORT_IMPORT: ac_charge > 0 and discharge_allowed == 0 or 1
Args:
parameters: The optimization parameters of the run.
result: The result of the run.
Returns:
The optimization solution.
"""
start_datetime = parameters.presentation.start_datetime
start_day_hour = to_datetime(start_datetime, in_timezone=parameters.presentation.timezone).hour
interval_hours = 1
power_to_energy_per_interval_factor = 1.0
# --- Create index based on list length and interval ---
# Ensure we only use the minimum of results and commands if differing
periods = min(len(result.result.costs_per_hour), len(result.ac_charge) - start_day_hour)
time_index = pd.date_range(
start=start_datetime,
periods=periods,
freq=f"{interval_hours}h",
)
n_points = len(time_index)
# Fill solution into dataframe with correct column names
# - 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>_op_mode: Operation mode of the device (1.0 when active)."
# - <device-id>_<operation>_op_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."
solution = pd.DataFrame(
{
"date_time": time_index,
# result starts at start_day_hour
"load_energy_wh": result.result.load_wh_per_hour[:n_points],
"grid_feedin_energy_wh": result.result.grid_feed_in_wh_per_hour[:n_points],
"grid_consumption_energy_wh": result.result.grid_consumption_wh_per_hour[:n_points],
"costs_amt": result.result.costs_per_hour[:n_points],
"revenue_amt": result.result.revenue_per_hour[:n_points],
"losses_energy_wh": result.result.losses_per_hour[:n_points],
},
index=time_index,
)
# Add battery data
battery_device_id = parameters.presentation.battery_device_id
solution[f"{battery_device_id}_soc_factor"] = [
v / 100
for v in result.result.battery_soc_per_hour[:n_points] # result starts at start_day_hour
]
operation: dict[str, list[float]] = {
"genetic_ac_charge_factor": [],
"genetic_dc_charge_factor": [],
"genetic_discharge_allowed_factor": [],
}
# ac_charge, dc_charge, discharge_allowed start at hour 0 of start day
for hour_idx, rate in enumerate(result.ac_charge):
if hour_idx < start_day_hour:
continue
if hour_idx >= start_day_hour + n_points:
break
ac_charge_hour = result.ac_charge[hour_idx]
dc_charge_hour = result.dc_charge[hour_idx]
discharge_allowed_hour = bool(result.discharge_allowed[hour_idx])
# Raw genetic gene values — optimizer intent, stored verbatim
operation["genetic_ac_charge_factor"].append(ac_charge_hour)
operation["genetic_dc_charge_factor"].append(dc_charge_hour)
operation["genetic_discharge_allowed_factor"].append(float(discharge_allowed_hour))
# SOC-clamped effective values — what can physically be executed at
# this hour given the expected battery state of charge.
result_idx = hour_idx - start_day_hour
soc_h_pct = (
result.result.battery_soc_per_hour[result_idx]
if result_idx < len(result.result.battery_soc_per_hour)
else 0.0
)
eff_ac, eff_dc, eff_dis = _soc_clamped_operation_factors(
parameters, result, ac_charge_hour, dc_charge_hour, discharge_allowed_hour, soc_h_pct
)
operation_mode, operation_mode_factor = _battery_operation_from_solution(
parameters, result, eff_ac, eff_dc, eff_dis
)
for mode in BatteryOperationMode:
mode_key = f"{battery_device_id}_{mode.lower()}_op_mode"
factor_key = f"{battery_device_id}_{mode.lower()}_op_factor"
if mode_key not in operation.keys():
operation[mode_key] = []
operation[factor_key] = []
if mode == operation_mode:
operation[mode_key].append(1.0)
operation[factor_key].append(operation_mode_factor)
else:
operation[mode_key].append(0.0)
operation[factor_key].append(0.0)
for key in operation.keys():
if len(operation[key]) != n_points:
error_msg = (
f"instruction {key} has invalid length {len(operation[key])} - expected {n_points}"
)
logger.error(error_msg)
raise ValueError(error_msg)
solution[key] = operation[key]
# Add EV battery solution
# ev_charge_hours_float start at hour 0 of start day
# result.ev_soc_per_hour start at start_datetime.hour
if result.ev_obj:
ev_device_id = parameters.presentation.ev_device_id
if result.ev_charge_hours_float is None:
# Electric vehicle is full enough. No load times.
solution[f"{ev_device_id}_soc_factor"] = [
result.ev_obj.initial_soc_percentage / 100.0
] * n_points
solution["genetic_ev_charge_factor"] = [0.0] * n_points
# operation modes
operation_mode = BatteryOperationMode.IDLE
for mode in BatteryOperationMode:
mode_key = f"{ev_device_id}_{mode.lower()}_op_mode"
factor_key = f"{ev_device_id}_{mode.lower()}_op_factor"
if mode == operation_mode:
solution[mode_key] = [1.0] * n_points
solution[factor_key] = [1.0] * n_points
else:
solution[mode_key] = [0.0] * n_points
solution[factor_key] = [0.0] * n_points
else:
solution[f"{ev_device_id}_soc_factor"] = [
v / 100 for v in result.result.ev_soc_per_hour[:n_points]
]
operation = {
"genetic_ev_charge_factor": [],
}
for hour_idx, rate in enumerate(result.ev_charge_hours_float):
if hour_idx < start_day_hour:
continue
if hour_idx >= start_day_hour + n_points:
break
operation["genetic_ev_charge_factor"].append(rate)
operation_mode, operation_mode_factor = _battery_operation_from_solution(
parameters, result, rate, 0.0, False
)
for mode in BatteryOperationMode:
mode_key = f"{ev_device_id}_{mode.lower()}_op_mode"
factor_key = f"{ev_device_id}_{mode.lower()}_op_factor"
if mode_key not in operation.keys():
operation[mode_key] = []
operation[factor_key] = []
if mode == operation_mode:
operation[mode_key].append(1.0)
operation[factor_key].append(operation_mode_factor)
else:
operation[mode_key].append(0.0)
operation[factor_key].append(0.0)
for key in operation.keys():
if len(operation[key]) != n_points:
error_msg = f"instruction {key} has invalid length {len(operation[key])} - expected {n_points}"
logger.error(error_msg)
raise ValueError(error_msg)
solution[key] = operation[key]
# Add home appliance data
if parameters.presentation.home_appliance_enabled:
# Use the preparation's decision and not result.washingstart, as washingstart
# may be None (no start)
# even if configured to be started.
homeappliance_device_id = parameters.presentation.home_appliance_device_id
# result starts at start_day_hour
solution[f"{homeappliance_device_id}_energy_wh"] = result.result.home_appliance_wh_per_hour[
:n_points
]
operation = {
f"{homeappliance_device_id}_run_op_mode": [],
f"{homeappliance_device_id}_run_op_factor": [],
f"{homeappliance_device_id}_off_op_mode": [],
f"{homeappliance_device_id}_off_op_factor": [],
}
for hour_idx, energy in enumerate(solution[f"{homeappliance_device_id}_energy_wh"]):
if energy > 0.0:
operation[f"{homeappliance_device_id}_run_op_mode"].append(1.0)
operation[f"{homeappliance_device_id}_run_op_factor"].append(1.0)
operation[f"{homeappliance_device_id}_off_op_mode"].append(0.0)
operation[f"{homeappliance_device_id}_off_op_factor"].append(0.0)
else:
operation[f"{homeappliance_device_id}_run_op_mode"].append(0.0)
operation[f"{homeappliance_device_id}_run_op_factor"].append(0.0)
operation[f"{homeappliance_device_id}_off_op_mode"].append(1.0)
operation[f"{homeappliance_device_id}_off_op_factor"].append(1.0)
for key in operation.keys():
if len(operation[key]) != n_points:
error_msg = f"instruction {key} has invalid length {len(operation[key])} - expected {n_points}"
logger.error(error_msg)
raise ValueError(error_msg)
solution[key] = operation[key]
# Fill prediction into dataframe with correct column names
# - pvforecast_ac_energy_wh_energy_wh: PV energy prediction (positive) in wh
# - elec_price_amt_kwh: Electricity price prediction in money per kwh
# - weather_temp_air_celcius: Temperature in °C"
# - loadforecast_energy_wh: Load 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
prediction = pd.DataFrame(
{
"date_time": time_index,
},
index=time_index,
)
prediction_specs: list[tuple[str, FillMethod, str, float]] = [
(
"pvforecast_ac_power",
"linear",
"pvforecast_ac_energy_wh",
power_to_energy_per_interval_factor,
),
(
"pvforecast_dc_power",
"linear",
"pvforecast_dc_energy_wh",
power_to_energy_per_interval_factor,
),
(
"elecprice_marketprice_wh",
"ffill",
"elec_price_amt_kwh",
1000.0,
),
(
"feed_in_tariff_wh",
"ffill",
"feed_in_tariff_amt_kwh",
1000.0,
),
(
"weather_temp_air",
"linear",
"weather_air_temp_celcius",
1.0,
),
(
"loadforecast_power_w",
"linear",
"loadforecast_energy_wh",
power_to_energy_per_interval_factor,
),
(
"loadakkudoktor_std_power_w",
"linear",
"loadakkudoktor_std_energy_wh",
power_to_energy_per_interval_factor,
),
(
"loadakkudoktor_mean_power_w",
"linear",
"loadakkudoktor_mean_energy_wh",
power_to_energy_per_interval_factor,
),
]
# The series were read by the parameter preparation, for exactly these hours.
for pred_key, _, pred_solution_key, pred_solution_factor in prediction_specs:
series = parameters.presentation.prediction_series.get(pred_key)
if series is None:
continue
array = np.asarray(series[:n_points], dtype=float)
if array.size == n_points and array.size > 0 and not np.any(pd.isna(array)):
prediction[pred_solution_key] = (array * pred_solution_factor).tolist()
optimization_solution = OptimizationSolution(
id=f"optimization-genetic@{to_datetime(as_string=True)}",
generated_at=to_datetime(),
comment="Optimization solution derived from GeneticSolution.",
valid_from=start_datetime,
valid_until=start_datetime.add(hours=parameters.settings.horizon_hours),
total_losses_energy_wh=result.result.total_losses,
total_revenues_amt=result.result.total_revenue,
total_costs_amt=result.result.total_costs,
fitness_score={
result.result.total_costs,
},
prediction=PydanticDateTimeDataFrame.from_dataframe(prediction),
solution=PydanticDateTimeDataFrame.from_dataframe(solution),
)
return optimization_solution
def energy_management_plan(
parameters: Genetic0Parameters,
result: Genetic0Result,
) -> EnergyManagementPlan:
"""Provide the genetic solution as an energy management plan.
Args:
parameters: The optimization parameters of the run.
result: The result of the run.
Returns:
The energy management plan.
"""
start_datetime = parameters.presentation.start_datetime
start_day_hour = to_datetime(start_datetime, in_timezone=parameters.presentation.timezone).hour
plan = EnergyManagementPlan(
id=f"plan-genetic@{to_datetime(as_string=True)}",
generated_at=to_datetime(),
instructions=[],
comment="Energy management plan derived from GeneticSolution.",
)
# Add battery instructions (fill rate based control)
last_operation_mode: Optional[str] = None
last_operation_mode_factor: Optional[float] = None
resource_id = parameters.presentation.battery_device_id
# ac_charge, dc_charge, discharge_allowed start at hour 0 of start day
logger.debug("BAT: {} - {}", resource_id, result.ac_charge[start_day_hour:])
for hour_idx, rate in enumerate(result.ac_charge):
if hour_idx < start_day_hour:
continue
# Derive SOC-clamped effective factors so that FRBCInstruction
# operation_mode_factor reflects what can physically be executed,
# while the raw genetic gene values are preserved in the solution
# dataframe (genetic_*_factor columns).
result_idx = hour_idx - start_day_hour
soc_h_pct = (
result.result.battery_soc_per_hour[result_idx]
if result_idx < len(result.result.battery_soc_per_hour)
else 0.0
)
eff_ac, eff_dc, eff_dis = _soc_clamped_operation_factors(
parameters,
result,
result.ac_charge[hour_idx],
result.dc_charge[hour_idx],
bool(result.discharge_allowed[hour_idx]),
soc_h_pct,
)
operation_mode, operation_mode_factor = _battery_operation_from_solution(
parameters, result, eff_ac, eff_dc, eff_dis
)
if (
operation_mode == last_operation_mode
and operation_mode_factor == last_operation_mode_factor
):
# Skip, we already added the instruction
continue
last_operation_mode = operation_mode
last_operation_mode_factor = operation_mode_factor
execution_time = start_datetime.add(hours=hour_idx - start_day_hour)
plan.add_instruction(
FRBCInstruction(
resource_id=resource_id,
execution_time=execution_time,
actuator_id=resource_id,
operation_mode_id=operation_mode,
operation_mode_factor=operation_mode_factor,
)
)
# Add EV battery instructions (fill rate based control)
# ev_charge_hours_float start at hour 0 of start day
if result.ev_obj:
resource_id = parameters.presentation.ev_device_id
if result.ev_charge_hours_float is None:
# Electric vehicle is full enough. No load times.
logger.debug("EV: {} - SoC >= min, no optimization", resource_id)
plan.add_instruction(
FRBCInstruction(
resource_id=resource_id,
execution_time=start_datetime,
actuator_id=resource_id,
operation_mode_id=BatteryOperationMode.IDLE,
operation_mode_factor=1.0,
)
)
else:
last_operation_mode = None
last_operation_mode_factor = None
logger.debug("EV: {} - {}", resource_id, result.ev_charge_hours_float[start_day_hour:])
for hour_idx, rate in enumerate(result.ev_charge_hours_float):
if hour_idx < start_day_hour:
continue
operation_mode, operation_mode_factor = _battery_operation_from_solution(
parameters, result, rate, 0.0, False
)
if (
operation_mode == last_operation_mode
and operation_mode_factor == last_operation_mode_factor
):
# Skip, we already added the instruction
continue
last_operation_mode = operation_mode
last_operation_mode_factor = operation_mode_factor
execution_time = start_datetime.add(hours=hour_idx - start_day_hour)
plan.add_instruction(
FRBCInstruction(
resource_id=resource_id,
execution_time=execution_time,
actuator_id=resource_id,
operation_mode_id=operation_mode,
operation_mode_factor=operation_mode_factor,
)
)
# Add home appliance instructions (demand driven based control)
if parameters.presentation.home_appliance_enabled:
# Use the preparation's decision and not result.washingstart, as washingstart
# may be None (no start)
# even if configured to be started.
resource_id = parameters.presentation.home_appliance_device_id
last_energy: Optional[float] = None
for hours, energy in enumerate(result.result.home_appliance_wh_per_hour):
# hours starts at start_datetime with 0
if energy is None:
raise ValueError(
f"Unexpected value {energy} in {result.result.home_appliance_wh_per_hour}"
)
if last_energy is None or energy != last_energy:
if energy > 0.0:
operation_mode = ApplianceOperationMode.RUN # type: ignore[assignment]
else:
operation_mode = ApplianceOperationMode.OFF # type: ignore[assignment]
operation_mode_factor = 1.0
execution_time = start_datetime.add(hours=hours)
plan.add_instruction(
DDBCInstruction(
resource_id=resource_id,
execution_time=execution_time,
actuator_id=resource_id,
operation_mode_id=operation_mode,
operation_mode_factor=operation_mode_factor,
)
)
last_energy = energy
return plan
@@ -1,19 +0,0 @@
"""Genetic0 optimization algorithm device interfaces/ parameters."""
from typing import Optional
from pydantic import Field
from akkudoktoreos.optimization.genetic0.genetic0abc import Genetic0ParametersBaseModel
class Genetic0DeviceParameters(Genetic0ParametersBaseModel):
device_id: str = Field(json_schema_extra={"description": "ID of device", "examples": "device1"})
hours: Optional[int] = Field(
default=None,
gt=0,
json_schema_extra={
"description": "Number of prediction hours. Defaults to global config prediction hours.",
"examples": [None],
},
)
@@ -0,0 +1,26 @@
"""Hourly forecasts and prices of a GENETIC0 run, as the simulation reads them.
A module of its own so that the request can derive them without importing the simulation.
"""
from dataclasses import dataclass
from typing import Union
@dataclass(frozen=True, slots=True)
class Genetic0EnergyManagementParameters:
"""Hourly forecasts and prices of the simulation, from midnight of the start day.
Attributes:
pv_forecast_wh: PV energy per hour in watt-hours.
electricity_price_per_wh: Electricity price per watt-hour.
feed_in_tariff_per_wh: Feed-in tariff per watt-hour, per hour or one constant value.
price_per_wh_battery: Cost of battery energy per watt-hour.
total_load: Load energy per hour in watt-hours.
"""
pv_forecast_wh: tuple[float, ...]
electricity_price_per_wh: tuple[float, ...]
feed_in_tariff_per_wh: Union[tuple[float, ...], float]
price_per_wh_battery: float
total_load: tuple[float, ...]
@@ -1,27 +1,49 @@
#!/usr/bin/env python
"""Self-consumption probability of the GENETIC0 inverter simulation.
The backend comes from the run settings (``optimization.self_consumption_interpolator``, read by
the parameter preparation), never from the configuration directly (ADR 0003).
"""
import functools
import threading
from pathlib import Path
from typing import Optional
import numpy as np
from akkudoktoreos.core.cache import cache_energy_management
from akkudoktoreos.core.coreabc import SingletonMixin
from akkudoktoreos.utils.gridinterpolator import (
GridInterpolatorBackend,
SwitchableGridInterpolator,
configured_grid_interpolator_backend,
load_grid_interpolator,
)
# Distinct (load, PV) pairs remembered per interpolator; the values never change.
_CACHE_SIZE = 1 << 16
class SelfConsumptionProbabilityInterpolator:
def __init__(self, filepath: str | Path):
def __init__(
self,
filepath: str | Path,
backend: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY,
) -> None:
"""Load the self-consumption table.
Args:
filepath: Pickled table.
backend: How the table is evaluated.
"""
self.filepath = filepath
self.backend = backend
# The table is a pickled SciPy RegularGridInterpolator. It is read
# without SciPy; optimization.self_consumption_interpolator decides
# whether SciPy (default) or NumPy evaluates it.
# without SciPy; the backend decides whether SciPy (default) or NumPy
# evaluates it.
self.interpolator = SwitchableGridInterpolator(
load_grid_interpolator(self.filepath), configured_grid_interpolator_backend
load_grid_interpolator(self.filepath), lambda: self.backend
)
# The table is static, so results can be kept across runs.
self.calculate_self_consumption = functools.lru_cache(maxsize=_CACHE_SIZE)(
self._calculate_self_consumption
)
def _generate_points(
@@ -32,11 +54,10 @@ class SelfConsumptionProbabilityInterpolator:
points = np.array([np.full_like(partial_loads, load_1h_power), partial_loads]).T
return points, partial_loads
@cache_energy_management
def calculate_self_consumption(self, load_1h_power: float, pv_power: float) -> float:
def _calculate_self_consumption(self, load_1h_power: float, pv_power: float) -> float:
"""Calculate the PV self-consumption rate using RegularGridInterpolator.
The results are cached until the start of the next energy management run/ optimization.
Called through ``calculate_self_consumption``, which caches the results.
Args:
- last_1h_power: 1h power levels (W).
@@ -88,27 +109,44 @@ class SelfConsumptionProbabilityInterpolator:
# return self_consumption_rate
class Genetic0LoadInterpolator(SelfConsumptionProbabilityInterpolator, SingletonMixin):
def __init__(self) -> None:
if hasattr(self, "_initialized"):
return
class Genetic0LoadInterpolator(SelfConsumptionProbabilityInterpolator):
"""The self-consumption table shipped with EOS."""
def __init__(self, backend: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY) -> None:
"""Load the shipped table.
Args:
backend: How the table is evaluated.
"""
filename = (
Path(__file__).parent.parent.parent.resolve()
/ "data"
/ "genetic0_load_interpolator.pkl"
)
super().__init__(filename)
super().__init__(filename, backend)
# Created on first use.
_genetic0_load_interpolator: Optional[Genetic0LoadInterpolator] = None
# One interpolator per backend, created on first use.
_genetic0_load_interpolators: dict[GridInterpolatorBackend, Genetic0LoadInterpolator] = {}
_genetic0_load_interpolator_lock = threading.Lock()
def get_genetic0_load_interpolator() -> Genetic0LoadInterpolator:
global _genetic0_load_interpolator
if _genetic0_load_interpolator is None:
def get_genetic0_load_interpolator(
backend: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY,
) -> Genetic0LoadInterpolator:
"""Return the shared interpolator for ``backend``.
Args:
backend: How the table is evaluated.
Returns:
The interpolator, loaded on first use.
"""
interpolator = _genetic0_load_interpolators.get(backend)
if interpolator is None:
with _genetic0_load_interpolator_lock:
if _genetic0_load_interpolator is None:
_genetic0_load_interpolator = Genetic0LoadInterpolator()
return _genetic0_load_interpolator
interpolator = _genetic0_load_interpolators.get(backend)
if interpolator is None:
interpolator = Genetic0LoadInterpolator(backend)
_genetic0_load_interpolators[backend] = interpolator
return interpolator
@@ -0,0 +1,72 @@
"""GENETIC0 behind the optimizer interface (ADR 0006).
Runs ``Genetic0Optimization``; the result is the frozen ``Genetic0Result``.
"""
from collections.abc import Mapping
from typing import Any, Optional
from akkudoktoreos.core.emplan import EnergyManagementPlan
from akkudoktoreos.optimization.genetic0 import genetic0convert, genetic0prepare
from akkudoktoreos.optimization.genetic0.genetic0parameters import Genetic0Parameters
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0Request,
)
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
from akkudoktoreos.optimization.optimization import OptimizationSolution
from akkudoktoreos.optimization.optimizer import OptimizerApi
from akkudoktoreos.utils.datetimeutil import DateTime
class Genetic0Optimizer:
"""The GENETIC0 optimizer."""
name = "GENETIC0"
async def prepare(
self,
start_datetime: DateTime,
observation_datetime: DateTime,
warm_start: Optional[Genetic0Result],
overrides: Optional[Mapping[str, Any]] = None,
) -> Genetic0Parameters:
"""See ``Optimizer.prepare()``."""
return await genetic0prepare.prepare(
start_datetime, observation_datetime, warm_start, overrides
)
async def prepare_from_request(
self,
request: Genetic0Request,
start_datetime: DateTime,
observation_datetime: DateTime,
warm_start: Optional[Genetic0Result],
overrides: Optional[Mapping[str, Any]] = None,
) -> Genetic0Parameters:
"""See ``Optimizer.prepare_from_request()``."""
return await genetic0prepare.prepare_from_request(
request, start_datetime, observation_datetime, warm_start, overrides
)
def run(self, parameters: Genetic0Parameters) -> Genetic0Result:
"""See ``Optimizer.run()``."""
# Imported on first use: the simulation is only needed for a run.
from akkudoktoreos.optimization.genetic0.genetic0algorithm import (
Genetic0Optimization,
)
optimization = Genetic0Optimization(parameters.settings)
return optimization.optimize_ems(parameters)
def api(self) -> OptimizerApi:
"""See ``Optimizer.api()``."""
# Imported on first use: the router is only needed by the server.
from akkudoktoreos.optimization.genetic0 import genetic0api
return genetic0api.api()
async def convert(
self, parameters: Genetic0Parameters, result: Genetic0Result
) -> tuple[OptimizationSolution, EnergyManagementPlan]:
"""See ``Optimizer.convert()``."""
return await genetic0convert.convert(parameters, result)
@@ -0,0 +1,257 @@
"""Optimization parameters of GENETIC0: the complete input of one run (ADR 0003, 0006, 0009).
A run reads nothing but these parameters: the algorithm settings, the forecast and device
parameters, and the data the solution conversion presents (time zone, device IDs, prediction
series). They are prepared once before the run by ``genetic0prepare``.
The simulation reads the forecast and device dataclasses, which are derived from the request
(``Genetic0Request``). The request itself is kept because the result echoes it (until step 5); a
replay file stores the request and the dataclasses are derived again when it is read.
"""
import math
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, Optional, Union
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import (
Genetic0BatteryParameters,
)
from akkudoktoreos.optimization.genetic0.devices.genetic0homeappliance import (
Genetic0HomeApplianceParameters,
)
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
Genetic0InverterParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0energymanagement import (
Genetic0EnergyManagementParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0request import Genetic0Request
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
@dataclass(frozen=True, slots=True)
class Genetic0RunSettings:
"""Algorithm settings of one run, resolved from the configuration and overrides.
Attributes:
prediction_hours: Length of the hourly arrays, from midnight of the start day.
horizon_hours: Optimization horizon in hours.
individuals: Population size; ``None`` uses the algorithm's default.
generations: Number of generations; ``None`` uses the algorithm's default.
seed: Random seed; ``None`` gives a random seed.
penalties: Penalty parameters by name (e.g. ``ev_soc_miss``).
ev_charge_rates: Charge rates of the first configured electric vehicle, used when the
request has none.
battery_charge_rates: Charge rates of the first configured battery, used when the
request has none.
self_consumption_interpolator: How the inverter's self-consumption table is evaluated.
verbose: Log the progress of the run.
"""
prediction_hours: int
horizon_hours: int
individuals: Optional[int]
generations: Optional[int]
seed: Optional[int]
penalties: Mapping[str, Union[float, int, str]]
ev_charge_rates: Optional[tuple[float, ...]]
battery_charge_rates: Optional[tuple[float, ...]]
self_consumption_interpolator: GridInterpolatorBackend
verbose: bool
@dataclass(frozen=True, slots=True)
class Genetic0Presentation:
"""Data the solution conversion presents; not used by the run itself.
Attributes:
start_datetime: Start of the run.
timezone: Time zone the hours of the day refer to; ``None`` is the local time zone.
battery_device_id: Device ID of the battery in the solution.
ev_device_id: Device ID of the electric vehicle in the solution.
home_appliance_device_id: Device ID of the home appliance in the solution.
home_appliance_enabled: Whether the solution contains the home appliance.
prediction_series: Hourly prediction series from the start of the run, by prediction key;
a key without data is missing. Values may be NaN.
"""
start_datetime: DateTime
timezone: Optional[str]
battery_device_id: str
ev_device_id: str
home_appliance_device_id: str
home_appliance_enabled: bool
prediction_series: Mapping[str, tuple[float, ...]]
@dataclass(frozen=True, slots=True)
class Genetic0Parameters:
"""Everything a GENETIC0 run and its solution conversion need.
Attributes:
request: Forecast and device parameters of the run, as requested; echoed in the result.
start_hour: Hour of the day the run starts at; indexes the hourly arrays.
settings: Algorithm settings of the run.
presentation: Data the solution conversion presents.
ems: Hourly forecasts and prices of the simulation.
pv_battery: The stationary battery, if any.
ev: The electric vehicle, if any.
inverter: The inverter, if any.
dishwasher: The home appliance, if any.
start_solution: Start solution of the previous run (warm start), if any.
"""
request: Genetic0Request
start_hour: int
settings: Genetic0RunSettings
presentation: Genetic0Presentation
ems: Genetic0EnergyManagementParameters
pv_battery: Optional[Genetic0BatteryParameters]
ev: Optional[Genetic0BatteryParameters]
inverter: Optional[Genetic0InverterParameters]
dishwasher: Optional[Genetic0HomeApplianceParameters]
start_solution: Optional[tuple[float, ...]]
@classmethod
def from_request(
cls,
request: Genetic0Request,
start_hour: int,
settings: Genetic0RunSettings,
presentation: Genetic0Presentation,
) -> "Genetic0Parameters":
"""Derive the simulation's dataclasses from the request.
Args:
request: Forecast and device parameters of the run.
start_hour: Hour of the day the run starts at.
settings: Algorithm settings of the run.
presentation: Data the solution conversion presents.
Returns:
The parameters of the run.
"""
return cls(
request=request,
start_hour=start_hour,
settings=settings,
presentation=presentation,
ems=request.ems.to_parameters(),
pv_battery=None if request.pv_battery is None else request.pv_battery.to_parameters(),
ev=None if request.ev is None else request.ev.to_parameters(),
inverter=None if request.inverter is None else request.inverter.to_parameters(),
dishwasher=(
None
if request.dishwasher is None
else request.dishwasher.to_parameters(settings.prediction_hours)
),
start_solution=(
None if request.start_solution is None else tuple(request.start_solution)
),
)
def parameters_to_dict(parameters: Genetic0Parameters) -> dict[str, Any]:
"""Serialize the parameters into plain JSON values, e.g. for a replay file.
A NaN or infinite value in the prediction series becomes ``None``.
Args:
parameters: The parameters to serialize.
Returns:
A dictionary that ``parameters_from_dict()`` turns back into equal parameters.
"""
settings = parameters.settings
presentation = parameters.presentation
return {
"request": parameters.request.model_dump(mode="json"),
"start_hour": parameters.start_hour,
"settings": {
"prediction_hours": settings.prediction_hours,
"horizon_hours": settings.horizon_hours,
"individuals": settings.individuals,
"generations": settings.generations,
"seed": settings.seed,
"penalties": dict(settings.penalties),
"ev_charge_rates": _list_or_none(settings.ev_charge_rates),
"battery_charge_rates": _list_or_none(settings.battery_charge_rates),
"self_consumption_interpolator": settings.self_consumption_interpolator.value,
"verbose": settings.verbose,
},
"presentation": {
"start_datetime": _datetime_to_dict(presentation.start_datetime),
"timezone": presentation.timezone,
"battery_device_id": presentation.battery_device_id,
"ev_device_id": presentation.ev_device_id,
"home_appliance_device_id": presentation.home_appliance_device_id,
"home_appliance_enabled": presentation.home_appliance_enabled,
"prediction_series": {
key: [value if math.isfinite(value) else None for value in series]
for key, series in presentation.prediction_series.items()
},
},
}
def parameters_from_dict(data: Mapping[str, Any]) -> Genetic0Parameters:
"""Deserialize parameters written by ``parameters_to_dict()``.
Args:
data: The serialized parameters.
Returns:
The parameters.
"""
settings = data["settings"]
presentation = data["presentation"]
return Genetic0Parameters.from_request(
request=Genetic0Request.model_validate(data["request"]),
start_hour=data["start_hour"],
settings=Genetic0RunSettings(
prediction_hours=settings["prediction_hours"],
horizon_hours=settings["horizon_hours"],
individuals=settings["individuals"],
generations=settings["generations"],
seed=settings["seed"],
penalties=dict(settings["penalties"]),
ev_charge_rates=_tuple_or_none(settings["ev_charge_rates"]),
battery_charge_rates=_tuple_or_none(settings["battery_charge_rates"]),
self_consumption_interpolator=GridInterpolatorBackend(
settings["self_consumption_interpolator"]
),
verbose=settings["verbose"],
),
presentation=Genetic0Presentation(
start_datetime=_datetime_from_dict(presentation["start_datetime"]),
timezone=presentation["timezone"],
battery_device_id=presentation["battery_device_id"],
ev_device_id=presentation["ev_device_id"],
home_appliance_device_id=presentation["home_appliance_device_id"],
home_appliance_enabled=presentation["home_appliance_enabled"],
prediction_series={
key: tuple(math.nan if value is None else float(value) for value in series)
for key, series in presentation["prediction_series"].items()
},
),
)
def _list_or_none(values: Optional[tuple[float, ...]]) -> Optional[list[float]]:
return None if values is None else list(values)
def _tuple_or_none(values: Optional[list[float]]) -> Optional[tuple[float, ...]]:
return None if values is None else tuple(values)
def _datetime_to_dict(value: DateTime) -> dict[str, Optional[str]]:
# The offset alone would lose daylight saving time; keep the named zone as well. It is the
# zone of the date-time itself, which may differ from the configured time zone.
return {"datetime": value.isoformat(), "timezone": value.timezone_name}
def _datetime_from_dict(data: Mapping[str, Optional[str]]) -> DateTime:
return to_datetime(data["datetime"], in_timezone=data["timezone"])
@@ -1,825 +0,0 @@
"""GENETIC0 algorithm paramters.
This module defines the Pydantic-based configuration and input parameter models
used in the energy optimization routines, including photovoltaic forecasts,
electricity pricing, and system component parameters.
It also provides a method to assemble these parameters from predictions,
forecasts, and fallback defaults, preparing them for optimization runs.
"""
import math
from typing import Optional, Union
import pandas as pd
from loguru import logger
from pydantic import (
AliasChoices,
ConfigDict,
Field,
computed_field,
field_validator,
model_validator,
)
from typing_extensions import Self
from akkudoktoreos.core.coreabc import (
ConfigMixin,
MeasurementMixin,
PredictionMixin,
get_ems,
)
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0ElectricVehicleParameters,
Genetic0SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
Genetic0HomeApplianceParameters,
)
from akkudoktoreos.devices.genetic0.genetic0inverter import Genetic0InverterParameters
from akkudoktoreos.optimization.genetic0.genetic0abc import Genetic0ParametersBaseModel
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
from akkudoktoreos.utils.datetimeutil import DateTime, to_duration
# Do not import directly from akkudoktoreos.core.coreabc
# EnergyManagementSystemMixin - Creates circular dependency with ems.py
# StartMixin - Creates circular dependency with ems.py
# Demo devices: used if no device of a kind is configured.
DEMO_BATTERY_SETTINGS: dict = {
"device_id": "battery1",
"profile_adjustment": {"nominal_capacity_wh": 8000},
}
DEMO_INVERTER_SETTINGS: dict = {
"device_id": "inverter1",
"profile_adjustment": {"nominal_power_w": 10000},
}
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."""
model_config = ConfigDict(populate_by_name=True, extra="ignore")
pv_forecast_wh: list[float] = Field(
validation_alias=AliasChoices("pv_forecast_wh", "pv_prognose_wh"),
json_schema_extra={
"description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals."
},
)
electricity_price_per_wh: list[float] = Field(
validation_alias=AliasChoices("electricity_price_per_wh", "strompreis_euro_pro_wh"),
json_schema_extra={
"description": "An array of floats representing the electricity price per watt-hour for different time intervals."
},
)
feed_in_tariff_per_wh: Union[list[float], float] = Field(
validation_alias=AliasChoices("feed_in_tariff_per_wh", "einspeiseverguetung_euro_pro_wh"),
json_schema_extra={
"description": "A float or array of floats representing the feed-in compensation per watt-hour."
},
)
price_per_wh_battery: float = Field(
validation_alias=AliasChoices("price_per_wh_battery", "preis_euro_pro_wh_akku"),
json_schema_extra={
"description": "A float representing the cost of battery energy per watt-hour."
},
)
total_load: list[float] = Field(
validation_alias=AliasChoices("total_load", "gesamtlast"),
json_schema_extra={
"description": "An array of floats representing the total load (consumption) in watts for different time intervals."
},
)
# Computed fields for backward compatibility (deprecated German names)
@computed_field(json_schema_extra={"deprecated": True})
def pv_prognose_wh(self) -> list[float]:
"""Deprecated: Use pv_forecast_wh instead."""
return self.pv_forecast_wh
@computed_field(json_schema_extra={"deprecated": True})
def strompreis_euro_pro_wh(self) -> list[float]:
"""Deprecated: Use electricity_price_per_wh instead."""
return self.electricity_price_per_wh
@computed_field(json_schema_extra={"deprecated": True})
def einspeiseverguetung_euro_pro_wh(self) -> Union[list[float], float]:
"""Deprecated: Use feed_in_tariff_per_wh instead."""
return self.feed_in_tariff_per_wh
@computed_field(json_schema_extra={"deprecated": True})
def preis_euro_pro_wh_akku(self) -> float:
"""Deprecated: Use price_per_wh_battery instead."""
return self.price_per_wh_battery
@computed_field(json_schema_extra={"deprecated": True})
def gesamtlast(self) -> list[float]:
"""Deprecated: Use total_load instead."""
return self.total_load
@model_validator(mode="after")
def validate_list_length(self) -> Self:
"""Validate that all input lists are of the same length.
Raises:
ValueError: If input list lengths differ.
"""
pv_forecast_length = len(self.pv_forecast_wh)
if (
pv_forecast_length != len(self.electricity_price_per_wh)
or pv_forecast_length != len(self.total_load)
or (
isinstance(self.feed_in_tariff_per_wh, list)
and pv_forecast_length != len(self.feed_in_tariff_per_wh)
)
):
raise ValueError("Input lists have different lengths")
return self
class Genetic0OptimizationParameters(
ConfigMixin,
MeasurementMixin,
PredictionMixin,
# EnergyManagementSystemMixin, # Creates circular dependency with ems.py
# StartMixin, # Creates circular dependency with ems.py
Genetic0ParametersBaseModel,
):
"""Main parameter class for running the genetic energy optimization.
Collects all model and configuration parameters necessary to run the
optimization process, such as forecasts, pricing, battery and appliance models.
"""
model_config = ConfigDict(populate_by_name=True, extra="ignore")
ems: Genetic0EnergyManagementParameters
pv_battery: Optional[Genetic0SolarPanelBatteryParameters] = Field(
validation_alias=AliasChoices("pv_battery", "pv_akku"),
json_schema_extra={"description": "PV battery parameters."},
)
inverter: Optional[Genetic0InverterParameters]
ev: Optional[Genetic0ElectricVehicleParameters] = Field(
validation_alias=AliasChoices("ev", "eauto"),
json_schema_extra={"description": "Electric vehicle parameters."},
)
dishwasher: Optional[Genetic0HomeApplianceParameters] = None
temperature_forecast: Optional[list[Optional[float]]] = Field(
default=None,
json_schema_extra={
"description": "An array of floats representing the temperature forecast in degrees Celsius for different time intervals."
},
)
start_solution: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": "Can be `null` or contain a previous solution (if available)."
},
)
# Computed fields for backward compatibility (deprecated German names)
@computed_field(json_schema_extra={"deprecated": True})
def pv_akku(self) -> Optional[Genetic0SolarPanelBatteryParameters]:
"""Deprecated: Use pv_battery instead."""
return self.pv_battery
@computed_field(json_schema_extra={"deprecated": True})
def eauto(self) -> Optional[Genetic0ElectricVehicleParameters]:
"""Deprecated: Use ev instead."""
return self.ev
@model_validator(mode="after")
def validate_list_length(self) -> Self:
"""Ensure that temperature forecast list matches the PV forecast length.
Raises:
ValueError: If list lengths mismatch.
"""
arr_length = len(self.ems.pv_forecast_wh)
if self.temperature_forecast is not None and arr_length != len(self.temperature_forecast):
raise ValueError("Input lists have different lengths")
return self
@field_validator("start_solution")
def validate_start_solution(
cls, start_solution: Optional[list[float]]
) -> Optional[list[float]]:
"""Validate that the starting solution has at least two elements.
Args:
start_solution (list[float]): Optional list of solution values.
Returns:
list[float]: Validated list.
Raises:
ValueError: If the solution is too short.
"""
if start_solution is not None and len(start_solution) < 2:
raise ValueError("Requires at least two values.")
return start_solution
@classmethod
async def _nearest_soc_factor(cls, key: str, target: DateTime) -> float:
"""SoC factor nearest to the run time within +/-24 h.
Readings carry their real time, not the slot start, and records without a
SoC value (e.g. an adapter's meter reading) are skipped (#1447).
"""
window = to_duration("24 hours")
dates, values = await cls.measurement.key_to_lists(
key=key,
start_datetime=target - window,
end_datetime=target + window,
dropna=False,
)
samples = [
(abs(date.timestamp() - target.timestamp()), value)
for date, value in zip(dates, values)
if value is not None and value is not pd.NA
]
if not samples:
raise ValueError(f"No SoC value for '{key}' within 24 hours of {target}.")
# Convert only the selected sample: an unrelated older value must not fail.
return float(min(samples, key=lambda sample: sample[0])[1])
@classmethod
async def prepare(cls) -> "Optional[Genetic0OptimizationParameters]":
"""Prepare optimization parameters from config, forecast and measurement data.
Fills in values needed for optimization from available configuration, predictions and
measurements. If some data is missing, default or demo values are used.
Parameters start by definition of the genetic algorithm at hour 0 of the actual date
(not at start datetime of energy management run)
Returns:
Genetic0OptimizationParameters: The fully prepared optimization parameters.
Raises:
ValueError: If required configuration values like start time are missing.
"""
ems = get_ems()
# The optimization paramters
oparams: "Optional[Genetic0OptimizationParameters]" = None
# Check for run definitions
if ems.start_datetime is None:
error_msg = "Start datetime unknown."
logger.error(error_msg)
raise ValueError(error_msg)
# Check for general predictions conditions
if cls.config.general.latitude is None:
default_latitude = 52.52
logger.info(f"Latitude unknown - defaulting to {default_latitude}.")
cls.config.general.latitude = default_latitude
if cls.config.general.longitude is None:
default_longitude = 13.405
logger.info(f"Longitude unknown - defaulting to {default_longitude}.")
cls.config.general.longitude = default_longitude
if cls.config.prediction.hours is None:
logger.info("Prediction hours unknown - defaulting to 48 hours.")
cls.config.prediction.hours = 48
if cls.config.prediction.historic_hours is None:
logger.info("Prediction historic hours unknown - defaulting to 24 hours.")
cls.config.prediction.historic_hours = 24
# Check optimization definitions. interval_sec is fixed to 1 hour.
if cls.config.optimization.genetic0.horizon_hours is None:
logger.info("Optimization horizon unknown - defaulting to 24 hours.")
cls.config.optimization.genetic0.horizon_hours = 24
# Check genetic algorithm definitions
if cls.config.optimization.genetic0.individuals is None:
logger.info("Genetic individuals unknown - defaulting to 300.")
cls.config.optimization.genetic0.individuals = 300
if cls.config.optimization.genetic0.generations is None:
logger.info("Genetic generations unknown - defaulting to 400.")
cls.config.optimization.genetic0.generations = 400
if "ev_soc_miss" not in cls.config.optimization.genetic0.penalties:
logger.info("Genetic penalties unknown - defaulting to ev_soc_miss = 10.")
cls.config.optimization.genetic0.penalties["ev_soc_miss"] = 10
# Setup some basic providers if not set
if not cls.config.weather.provider:
cls.config.weather.provider = "OpenMeteo"
if not cls.config.load.provider:
cls.config.load.provider = "LoadAkkudoktor"
# Get start solution from last run
start_solution = None
last_solution = ems.genetic0_solution()
if last_solution and last_solution.start_solution:
start_solution = last_solution.start_solution
# Add forecast and device data
interval = to_duration(cls.config.optimization.genetic0.interval_sec)
power_to_energy_per_interval_factor = cls.config.optimization.genetic0.interval_sec / 3600
# GENETIC0 indexes the parameter arrays by wall-clock hour (the simulation
# starts at ``ems.start_datetime.hour``), while the arrays themselves are
# sampled in elapsed time. On a DST transition day local midnight is 23 or
# 25 elapsed hours away from the same wall-clock hour, so step back
# ``hour`` elapsed hours instead of setting the hour to midnight. This keeps
# array index ``ems.start_datetime.hour`` aligned with the start slot.
parameter_start_datetime = ems.start_datetime.set(second=0, microsecond=0).subtract(
hours=ems.start_datetime.hour
)
parameter_end_datetime = parameter_start_datetime.add(hours=cls.config.prediction.hours)
max_retries = 10
for attempt in range(1, max_retries + 1):
# Collect all the data for optimisation, but do not exceed max retries
if attempt > max_retries:
error_msg = f"Maximum retries {max_retries} for parameter collection exceeded. Parameter preparation attempt {attempt}."
logger.error(error_msg)
raise ValueError(error_msg)
# Assure predictions are uptodate
await cls.prediction.update_data()
try: # Try first - predition is also needed by the default PV forecast
array = await cls.prediction.key_to_array(
key="weather_temp_air",
start_datetime=parameter_start_datetime,
end_datetime=parameter_end_datetime,
interval=interval,
fill_method="ffill",
)
weather_temp_air = array.tolist()
except Exception as e:
logger.info(
"No weather forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}",
attempt,
e,
)
cls.config.weather.provider = "OpenMeteo"
# Retry
continue
# Try electricity fees next - predition is also needed by the default electricity price
# If no provider is set the fees default to 0 anyway
if cls.config.elecfee.provider:
try:
array = await cls.prediction.key_to_array(
key="elecfee_consumption_amt_kwh",
start_datetime=parameter_start_datetime,
end_datetime=parameter_end_datetime,
interval=interval,
fill_method="ffill",
)
except Exception as e:
logger.info(
"No electricity fee data available - defaulting to demo data. Parameter preparation attempt {}: {}",
attempt,
e,
)
cls.config.merge_settings_from_dict(
{
"elecfee": {
"provider": "ElecFeeFixed",
"elecfeefixed": {
"consumption_amt_kwh": {
"windows": [
{
"start_time": "00:00",
"duration": "24 hours",
"value": 0.21,
},
]
},
"consumption_percent_amt": {
"windows": [
{
"start_time": "00:00",
"duration": "24 hours",
"value": 19.0,
},
]
},
"feedin_amt_kwh": {
"windows": [
{
"start_time": "00:00",
"duration": "24 hours",
"value": 0.0,
},
]
},
"feedin_percent_amt": {
"windows": [
{
"start_time": "00:00",
"duration": "24 hours",
"value": 0.0,
},
]
},
},
},
}
)
# Retry
continue
try:
array = await cls.prediction.key_to_array(
key="pvforecast_ac_power",
start_datetime=parameter_start_datetime,
end_datetime=parameter_end_datetime,
interval=interval,
fill_method="linear",
)
pvforecast_ac_power = (array * power_to_energy_per_interval_factor).tolist()
except Exception as e:
logger.info(
"No PV forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}",
attempt,
e,
)
cls.config.merge_settings_from_dict(
{
"pvforecast": {
"provider": "PVForecastPVLib",
"max_planes": 4,
"planes": [
{
"surface_tilt": 7,
"surface_azimuth": 170,
"userhorizon": [20, 27, 22, 20],
"peakpower": 5.0,
"module_model": "AXITEC_AC_410MH_144S",
"inverter_model": "Sungrow__SH25T",
"inverter_paco": 10000,
"modules_per_string": 12,
"strings_per_inverter": 1,
},
{
"surface_tilt": 7,
"surface_azimuth": 90,
"userhorizon": [30, 30, 30, 50],
"peakpower": 4.8,
"module_model": "AXITEC_AC_410MH_144S",
"inverter_model": "Sungrow__SH25T",
"inverter_paco": 10000,
"modules_per_string": 12,
"strings_per_inverter": 1,
},
{
"surface_tilt": 60,
"surface_azimuth": 140,
"userhorizon": [60, 30, 0, 30],
"peakpower": 1.4,
"module_model": "AXITEC_AC_410MH_144S",
"inverter_model": "Sungrow__SH25T",
"inverter_paco": 2000,
"modules_per_string": 5,
"strings_per_inverter": 1,
},
{
"surface_tilt": 45,
"surface_azimuth": 185,
"userhorizon": [45, 25, 30, 60],
"peakpower": 1.6,
"module_model": "AXITEC_AC_410MH_144S",
"inverter_model": "Sungrow__SH25T",
"inverter_paco": 1400,
"modules_per_string": 4,
"strings_per_inverter": 1,
},
],
},
}
)
# Retry
continue
try:
array = await cls.prediction.key_to_array(
key="elecprice_marketprice_wh",
start_datetime=parameter_start_datetime,
end_datetime=parameter_end_datetime,
interval=interval,
fill_method="ffill",
)
elecprice_marketprice_wh = array.tolist()
except Exception as e:
logger.info(
"No Electricity Marketprice forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}",
attempt,
e,
)
cls.config.merge_settings_from_dict(
{
"elecprice": {
"elecpricefixed": {
"elecprice_marketprice_amt_kwh": {
"windows": [
{
"duration": "1 day",
"start_time": "00:00:00.000000",
"value": 0.288,
}
]
}
},
"provider": "ElecPriceFixed",
},
},
)
# Retry
continue
try:
array = await cls.prediction.key_to_array(
key="loadforecast_power_w",
start_datetime=parameter_start_datetime,
end_datetime=parameter_end_datetime,
interval=interval,
fill_method="ffill",
)
loadforecast_power_w = array.tolist()
except Exception as e:
logger.info(
"No Load forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}",
attempt,
e,
)
cls.config.merge_settings_from_dict(
{
"load": {
"provider": "LoadAkkudoktor",
"loadakkudoktor": {
"loadakkudoktor_year_energy_kwh": "3000",
},
},
}
)
# Retry
continue
tariff_values = await bounded_forecast_array(
cls.prediction,
key="feed_in_tariff_wh",
start_datetime=parameter_start_datetime,
end_datetime=parameter_end_datetime,
interval=interval,
)
first = int(
(ems.start_datetime - parameter_start_datetime).total_seconds()
/ interval.total_seconds()
)
last = first + cls.config.optimization.genetic0.horizon_hours
if last > len(tariff_values) or not all(
math.isfinite(value) for value in tariff_values[first:last]
):
logger.error(
"Missing feed-in tariff within the GENETIC0 control horizon; "
"canceling optimization with provider {}.",
cls.config.feedintariff.provider,
)
return None
feed_in_tariff_wh = tariff_values.tolist()
# Add device data
# Batteries
# ---------
if cls.config.devices.max_batteries is None:
logger.info("Number of battery devices not configured - defaulting to 1.")
cls.config.devices.max_batteries = 1
if cls.config.devices.max_batteries == 0:
battery_params = None
battery_lcos_kwh = 0
else:
if cls.config.devices.batteries is None:
logger.info("No battery device data available - defaulting to demo data.")
cls.config.devices.batteries = {"battery1": dict(DEMO_BATTERY_SETTINGS)}
# Take first battery
battery_config = list(cls.config.devices.batteries.values())[0]
try:
# 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:
# Never cancel the run, never change the user's configuration and
# never invent a device: optimize without this battery.
logger.error(
"Battery '{}' cannot be prepared for the optimization: {} "
"The battery is left out of this run.",
battery_config.device_id,
e,
)
battery_params = None
battery_lcos_kwh = 0
if battery_params is not None:
# Levelized cost of ownership
if battery_config.levelized_cost_of_storage_amt_kwh is None:
logger.info(
"No battery device LCOS data available - defaulting to 0 [amount/kWh]. Parameter preparation attempt {}.",
attempt,
)
battery_config.levelized_cost_of_storage_amt_kwh = 0
battery_lcos_kwh = battery_config.levelized_cost_of_storage_amt_kwh
# Initial SOC
try:
initial_soc_factor = await cls._nearest_soc_factor(
battery_config.measurement_key_soc_factor, ems.observation_datetime
)
if initial_soc_factor > 1.0 or initial_soc_factor < 0.0:
logger.error(
f"Invalid battery initial SoC factor {initial_soc_factor} - defaulting to 0.0."
)
initial_soc_factor = 0.0
# genetic parameter is 0..100 as int
initial_soc_percentage = int(initial_soc_factor * 100)
except Exception:
initial_soc_percentage = None
if initial_soc_percentage is None:
logger.info(
f"No battery device SoC data (measurement key = '{battery_config.measurement_key_soc_factor}') available - defaulting to 0."
)
initial_soc_percentage = 0
battery_params.initial_soc_percentage = initial_soc_percentage
# Electric Vehicles
# -----------------
if cls.config.devices.max_electric_vehicles is None:
logger.info("Number of electric_vehicle devices not configured - defaulting to 1.")
cls.config.devices.max_electric_vehicles = 1
if cls.config.devices.max_electric_vehicles == 0:
electric_vehicle_params = None
else:
if cls.config.devices.electric_vehicles is None:
logger.info(
"No electric vehicle device data available - defaulting to demo data."
)
cls.config.devices.max_electric_vehicles = 1
cls.config.devices.electric_vehicles = {
"ev1": dict(DEMO_ELECTRIC_VEHICLE_SETTINGS)
}
# Take first electric_vehicle
electric_vehicle_config = list(cls.config.devices.electric_vehicles.values())[0]
try:
# 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:
# Never cancel the run, never change the user's configuration and
# never invent a device: optimize without this electric vehicle.
logger.error(
"Electric vehicle '{}' cannot be prepared for the optimization: {} "
"The electric vehicle is left out of this run.",
electric_vehicle_config.device_id,
e,
)
electric_vehicle_params = None
if electric_vehicle_params is not None:
# Initial SOC
try:
initial_soc_factor = await cls._nearest_soc_factor(
electric_vehicle_config.measurement_key_soc_factor,
ems.observation_datetime,
)
if initial_soc_factor > 1.0 or initial_soc_factor < 0.0:
logger.error(
f"Invalid electric vehicle initial SoC factor {initial_soc_factor} - defaulting to 0.0."
)
initial_soc_factor = 0.0
# genetic parameter is 0..100 as int
initial_soc_percentage = int(initial_soc_factor * 100)
except Exception:
initial_soc_percentage = None
if initial_soc_percentage is None:
logger.info(
f"No electric vehicle device SoC data (measurement key = '{electric_vehicle_config.measurement_key_soc_factor}') available - defaulting to 0."
)
initial_soc_percentage = 0
electric_vehicle_params.initial_soc_percentage = initial_soc_percentage
# Inverters
# ---------
if cls.config.devices.max_inverters is None:
logger.info("Number of inverter devices not configured - defaulting to 1.")
cls.config.devices.max_inverters = 1
if cls.config.devices.max_inverters == 0:
inverter_params = None
else:
if cls.config.devices.inverters is None:
logger.info("No inverter device data available - defaulting to demo data.")
cls.config.devices.inverters = {
"inverter1": {
**DEMO_INVERTER_SETTINGS,
"battery_id": battery_config.device_id,
},
}
# Take first inverter
inverter_config = list(cls.config.devices.inverters.values())[0]
try:
# A configuration error gives default values, reported as error.
inverter_params = inverter_config.to_genetic0_param(
await inverter_config.resolve_current_operating_parameters_or_defaults()
)
except Exception as e:
# Never cancel the run, never change the user's configuration and
# never invent a device: optimize without this inverter.
logger.error(
"Inverter '{}' cannot be prepared for the optimization: {} "
"The inverter is left out of this run.",
inverter_config.device_id,
e,
)
inverter_params = None
# Home Appliances
# ---------------
if cls.config.devices.max_home_appliances is None:
logger.info("Number of home appliance devices not configured - defaulting to 1.")
cls.config.devices.max_home_appliances = 1
if cls.config.devices.max_home_appliances == 0:
home_appliance_params = None
else:
home_appliance_params = None
if cls.config.devices.home_appliances is None:
logger.info(
"No home appliance device data available - defaulting to demo data."
)
cls.config.devices.home_appliances = {
"dishwasher1": {
"device_id": "dishwasher1",
"consumption_wh": 2000,
"duration_h": 3.0,
"cycle_time_windows": {
"windows": [
{
"start_time": "08:00",
"duration": "5 hours",
},
{
"start_time": "15:00",
"duration": "3 hours",
},
],
},
},
}
try:
# Take first appliance
home_appliance_config = list(cls.config.devices.home_appliances.values())[0]
home_appliance_params = home_appliance_config.to_genetic0_param()
except Exception as e:
logger.info(
"No home appliance device data available - defaulting to demo data. Parameter preparation attempt {}: {}",
attempt,
e,
)
cls.config.devices.home_appliances = {
"dishwasher1": {
"device_id": "dishwasher1",
"consumption_wh": 2000,
"duration_h": 3.0,
"cycle_time_windows": None,
},
}
# Retry
continue
# We got all parameter data
try:
oparams = Genetic0OptimizationParameters(
ems=Genetic0EnergyManagementParameters(
pv_forecast_wh=pvforecast_ac_power,
electricity_price_per_wh=elecprice_marketprice_wh,
feed_in_tariff_per_wh=feed_in_tariff_wh,
total_load=loadforecast_power_w,
price_per_wh_battery=battery_lcos_kwh / 1000,
),
temperature_forecast=weather_temp_air,
pv_battery=battery_params,
ev=electric_vehicle_params,
inverter=inverter_params,
dishwasher=home_appliance_params,
start_solution=start_solution,
)
except Exception as e:
logger.info(
"Can not prepare optimization parameters - will retry. Parameter preparation attempt {}: {}",
attempt,
e,
)
oparams = None
# Retry
continue
# Parameters prepared
break
return oparams
@@ -0,0 +1,866 @@
"""Parameter preparation of GENETIC0 (ADR 0003, 0006).
The only part of GENETIC0 that reads configuration, predictions and measurements. It prepares the
optimization parameters once before each run: the request (forecasts and devices), the algorithm
settings and the data the solution conversion presents. The energy management passes the run
start, the observation time, the warm start and run-time overrides as arguments; the preparation
reads no EMS state.
The preparation always creates a valid parameter set (energy-domain skill, "Optimization
parameters are always valid"): it never fails, never cancels the run, never writes the
configuration and never invents devices. A missing or invalid input is replaced by a fallback
value, logged at error level with the input and the substitute.
"""
import math
from collections.abc import Mapping
from typing import Any, Optional
import numpy as np
import pandas as pd
from loguru import logger
from akkudoktoreos.core.coreabc import get_config, get_measurement, get_prediction
from akkudoktoreos.core.types import FillMethod
from akkudoktoreos.devices.settings.batteryresolution import BatteryOperatingParameters
from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettings
from akkudoktoreos.devices.settings.homeappliancesettings import (
HomeApplianceCommonSettings,
)
from akkudoktoreos.devices.settings.inverterresolution import (
InverterOperatingParameters,
)
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
from akkudoktoreos.optimization.genetic0.genetic0parameters import (
Genetic0Parameters,
Genetic0Presentation,
Genetic0RunSettings,
)
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0ElectricVehicleRequest,
Genetic0EnergyManagementRequest,
Genetic0HomeApplianceRequest,
Genetic0InverterRequest,
Genetic0Request,
Genetic0SolarPanelBatteryRequest,
)
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
from akkudoktoreos.utils.datetimeutil import (
DateTime,
Duration,
to_datetime,
to_duration,
)
from akkudoktoreos.utils.gridinterpolator import configured_grid_interpolator_backend
# Settings that a run can override.
OVERRIDE_KEYS = ("generations", "seed")
# Prediction series the solution conversion presents: key and fill method.
PRESENTATION_PREDICTIONS: tuple[tuple[str, FillMethod], ...] = (
("pvforecast_ac_power", "linear"),
("pvforecast_dc_power", "linear"),
("elecprice_marketprice_wh", "ffill"),
("feed_in_tariff_wh", "ffill"),
("weather_temp_air", "linear"),
("loadforecast_power_w", "linear"),
("loadakkudoktor_std_power_w", "linear"),
("loadakkudoktor_mean_power_w", "linear"),
)
# Device IDs of the solution. GENETIC0 looks the configured EV and home appliance up with
# ``dict.values()[0]``, which always fails, so their IDs were always these fallbacks; kept as they
# are (GENETIC0 is frozen, ADR 0008).
FALLBACK_BATTERY_DEVICE_ID = "battery1"
EV_DEVICE_ID = "ev1"
HOME_APPLIANCE_DEVICE_ID = "homeappliance1"
# Fallback values of the preparation (energy-domain skill). Settings use their defaults.
FALLBACK_PREDICTION_HOURS = 48
# The algorithm needs at least two hours after the start hour of the run.
MIN_HOURS_AFTER_START = 2
FALLBACK_INDIVIDUALS = 300
FALLBACK_GENERATIONS = 400
# No price known at all: 0, like a fixed-price provider without time windows.
FALLBACK_PRICE_PER_WH = 0.0
# No feed-in tariff known at all: no feed-in revenue.
FALLBACK_FEED_IN_TARIFF_PER_WH = 0.0
# No load forecast: 3000 kWh per year, spread evenly over the hours of the year.
FALLBACK_LOAD_W = 3000.0 * 1000.0 / 8760.0
async def prepare(
start_datetime: DateTime,
observation_datetime: DateTime,
warm_start: Optional[Genetic0Result],
overrides: Optional[Mapping[str, Any]] = None,
) -> Genetic0Parameters:
"""Prepare the parameters of a run from configuration, predictions and measurements.
Args:
start_datetime: Start of the optimization run.
observation_datetime: Moment of the run that measurements refer to.
warm_start: Result of the previous GENETIC0 run, if any.
overrides: Run-time overrides of ``generations`` and ``seed``.
Returns:
The optimization parameters of the run; always valid, never ``None``.
"""
start_solution = None
if warm_start is not None and warm_start.start_solution:
start_solution = warm_start.start_solution
request = await prepare_request(start_datetime, observation_datetime, start_solution)
# The solution shows the home appliance the preparation put into the request.
return await _complete(
request, start_datetime, overrides, home_appliance_enabled=request.dishwasher is not None
)
async def prepare_from_request(
request: Genetic0Request,
start_datetime: DateTime,
observation_datetime: DateTime,
warm_start: Optional[Genetic0Result],
overrides: Optional[Mapping[str, Any]] = None,
) -> Genetic0Parameters:
"""Complete a client's optimization request into the parameters of a run.
Args:
request: The client's forecast and device parameters, used as they are.
start_datetime: Start of the optimization run.
observation_datetime: Moment of the run; not used, the request carries the device state.
warm_start: Result of the previous GENETIC0 run; not used, the request carries its own
start solution.
overrides: Run-time overrides of ``generations`` and ``seed``.
Returns:
The optimization parameters of the run.
"""
# A client's request is shown with the configured home appliances, as before.
max_home_appliances = get_config().devices.max_home_appliances
return await _complete(
request,
start_datetime,
overrides,
home_appliance_enabled=bool(max_home_appliances and max_home_appliances > 0),
)
async def _complete(
request: Genetic0Request,
start_datetime: DateTime,
overrides: Optional[Mapping[str, Any]],
home_appliance_enabled: bool,
) -> Genetic0Parameters:
settings = _run_settings(overrides, start_datetime.hour)
return Genetic0Parameters.from_request(
request=request,
start_hour=start_datetime.hour,
settings=settings,
presentation=await _presentation(start_datetime, settings, home_appliance_enabled),
)
def _run_settings(overrides: Optional[Mapping[str, Any]], start_hour: int) -> Genetic0RunSettings:
"""Algorithm settings from the configuration, as the algorithm read them before."""
config = get_config()
genetic0 = config.optimization.genetic0
values: dict[str, Any] = {"generations": genetic0.generations, "seed": genetic0.seed}
for key, value in (overrides or {}).items():
if key not in OVERRIDE_KEYS:
logger.error("GENETIC0: Unknown override '{}' ignored.", key)
elif value is not None:
values[key] = value
prediction_hours = _prediction_hours(start_hour)
horizon_hours = genetic0.horizon_hours
individuals = genetic0.individuals
if individuals is None:
individuals = FALLBACK_INDIVIDUALS
logger.error("GENETIC0: optimization.genetic0.individuals not set, using {}.", individuals)
if values["generations"] is None:
values["generations"] = FALLBACK_GENERATIONS
logger.error(
"GENETIC0: optimization.genetic0.generations not set, using {}.", values["generations"]
)
ev_charge_rates = None
electric_vehicles = config.devices.electric_vehicles
if electric_vehicles:
rates = list(electric_vehicles.values())[0].charge_rates
if rates is not None:
ev_charge_rates = tuple(rates)
battery_charge_rates = None
batteries = config.devices.batteries
if batteries:
battery_rates = list(batteries.values())[0].charge_rates
if battery_rates:
battery_charge_rates = tuple(battery_rates)
return Genetic0RunSettings(
prediction_hours=prediction_hours,
horizon_hours=horizon_hours,
individuals=individuals,
generations=values["generations"],
seed=values["seed"],
penalties=dict(genetic0.penalties),
ev_charge_rates=ev_charge_rates,
battery_charge_rates=battery_charge_rates,
self_consumption_interpolator=configured_grid_interpolator_backend(),
verbose=bool(config.server.verbose),
)
async def _presentation(
start_datetime: DateTime, settings: Genetic0RunSettings, home_appliance_enabled: bool
) -> Genetic0Presentation:
"""The data the solution conversion presents, read once before the run."""
config = get_config()
batteries = config.devices.batteries
if batteries:
battery_device_id = list(batteries.values())[0].device_id
else:
battery_device_id = FALLBACK_BATTERY_DEVICE_ID
# The window the conversion covers: from the start to the end of the prediction day(s). The
# conversion counts its hours from the start hour of the run or from the start hour in the
# configured time zone (``None`` means the local zone); read from the earlier of the two, so
# that the series cover every hour the conversion shows. It slices them to its own count.
timezone = config.general.timezone
hours = settings.prediction_hours - min(
start_datetime.hour, to_datetime(start_datetime, in_timezone=timezone).hour
)
end_datetime = start_datetime.add(hours=max(hours, 0))
prediction = get_prediction()
series: dict[str, tuple[float, ...]] = {}
for key, fill_method in PRESENTATION_PREDICTIONS:
if hours <= 0 or key not in prediction.record_keys:
continue
try:
array = await prediction.key_to_array(
key=key,
start_datetime=start_datetime,
end_datetime=end_datetime,
interval=to_duration("1 hours"),
fill_method=fill_method,
)
except Exception as error:
logger.error("GENETIC0: Prediction '{}' not readable, not presented: {}", key, error)
continue
if array is not None:
series[key] = tuple(float(value) for value in np.asarray(array, dtype=float))
return Genetic0Presentation(
start_datetime=start_datetime,
timezone=timezone,
battery_device_id=battery_device_id,
ev_device_id=EV_DEVICE_ID,
home_appliance_device_id=HOME_APPLIANCE_DEVICE_ID,
home_appliance_enabled=home_appliance_enabled,
prediction_series=series,
)
async def bounded_forecast_array(
prediction: Any,
*,
key: str,
start_datetime: DateTime,
end_datetime: DateTime,
interval: Duration,
) -> np.ndarray:
"""Integrate stored interval averages only across completely covered target slots.
Copied from GENETIC's ``forecast`` module: optimizers share no code (ADR 0004).
Source timestamps are interval starts. Infer their smallest positive cadence,
capped at one hour. A missing source interval, explicit NaN or the end of the
available forecast remains missing. UTC elapsed time handles DST transitions.
The returned values retain the input units; callers convert W to slot Wh once.
"""
seconds = int(interval.total_seconds())
start = start_datetime.timestamp()
end = end_datetime.timestamp()
if seconds <= 0 or end <= start or (end - start) % seconds:
raise ValueError("Forecast bounds must contain a positive whole number of slots.")
result = np.full(int((end - start) / seconds), np.nan)
try:
series = await prediction.key_to_raw_series(key=key, dropna=False)
except KeyError:
return result
if series.empty:
return result
series = pd.to_numeric(series, errors="coerce").sort_index()
series = series[~series.index.duplicated(keep="last")]
stamps = pd.to_datetime(series.index, utc=True).as_unit("ns").asi8 / 1e9
values = series.to_numpy(dtype=float)
differences = np.diff(stamps)
cadence = min(3600.0, float(np.min(differences))) if len(differences) else 3600.0
for slot in range(len(result)):
left = start + slot * seconds
right = left + seconds
position = max(0, int(np.searchsorted(stamps, left, side="right")) - 1)
covered = 0.0
weighted = 0.0
while position < len(stamps) and stamps[position] < right:
source_end = stamps[position] + cadence
if position + 1 < len(stamps):
source_end = min(source_end, stamps[position + 1])
overlap = max(0.0, min(right, source_end) - max(left, stamps[position]))
if overlap and np.isfinite(values[position]):
covered += overlap
weighted += (overlap / seconds) * values[position]
position += 1
if abs(covered - seconds) < 1e-6:
result[slot] = weighted
return result
async def _nearest_soc_factor(key: str, target: DateTime) -> float:
"""SoC factor nearest to the run time within +/-24 h.
Readings carry their real time, not the slot start, and records without a
SoC value (e.g. an adapter's meter reading) are skipped (#1447).
"""
window = to_duration("24 hours")
dates, values = await get_measurement().key_to_lists(
key=key,
start_datetime=target - window,
end_datetime=target + window,
dropna=False,
)
samples = [
(abs(date.timestamp() - target.timestamp()), value)
for date, value in zip(dates, values)
if value is not None and value is not pd.NA
]
if not samples:
raise ValueError(f"No SoC value for '{key}' within 24 hours of {target}.")
# Convert only the selected sample: an unrelated older value must not fail.
return float(min(samples, key=lambda sample: sample[0])[1])
async def prepare_request(
start_datetime: DateTime,
observation_datetime: DateTime,
start_solution: Optional[list[float]] = None,
) -> Genetic0Request:
"""Prepare the forecast and device parameters from configuration, predictions and measurements.
Never fails: a missing or invalid input is replaced by a fallback value and logged at error
level. The configuration is never changed and no device is invented.
The parameter arrays start at hour 0 of the start day, not at the start of the run; the
run starts at index ``start_datetime.hour``.
Args:
start_datetime: Start of the optimization run.
observation_datetime: Moment of the run that measured states of charge refer to.
start_solution: Start solution of the previous run (warm start), passed in by the
parameter preparation.
Returns:
The forecast and device parameters of the run.
"""
config = get_config()
prediction = get_prediction()
interval = to_duration(config.optimization.genetic0.interval_sec)
power_to_energy_per_interval_factor = config.optimization.genetic0.interval_sec / 3600
# GENETIC0 indexes the parameter arrays by wall-clock hour (the simulation
# starts at ``start_datetime.hour``), while the arrays themselves are
# sampled in elapsed time. On a DST transition day local midnight is 23 or
# 25 elapsed hours away from the same wall-clock hour, so step back
# ``hour`` elapsed hours instead of setting the hour to midnight. This keeps
# array index ``start_datetime.hour`` aligned with the start slot.
parameter_start_datetime = start_datetime.set(second=0, microsecond=0).subtract(
hours=start_datetime.hour
)
parameter_end_datetime = parameter_start_datetime.add(
hours=_prediction_hours(start_datetime.hour)
)
slots = int(
(parameter_end_datetime - parameter_start_datetime).total_seconds()
/ interval.total_seconds()
)
# Assure predictions are up to date; stored predictions are used if the update fails.
try:
await prediction.update_data()
except Exception as error:
logger.error("GENETIC0: Prediction update failed, using the stored predictions: {}", error)
async def read(key: str, fill_method: FillMethod) -> Optional[np.ndarray]:
try:
array = await prediction.key_to_array(
key=key,
start_datetime=parameter_start_datetime,
end_datetime=parameter_end_datetime,
interval=interval,
fill_method=fill_method,
)
except Exception as error:
logger.error("GENETIC0: Prediction '{}' not available: {}", key, error)
return None
if array is None or len(array) != slots:
logger.error("GENETIC0: Prediction '{}' does not cover the run.", key)
return None
return np.asarray(array, dtype=float)
# Temperature: optional, only presented.
temperature = await read("weather_temp_air", "ffill")
weather_temp_air: Optional[list[Optional[float]]] = None
if temperature is None:
logger.error("GENETIC0: No temperature forecast; the run has none.")
else:
weather_temp_air = [value if math.isfinite(value) else None for value in temperature]
# PV: missing values are 0.
pv = await read("pvforecast_ac_power", "linear")
if pv is None:
logger.error("GENETIC0: No PV forecast; using 0 Wh.")
pv = np.zeros(slots)
elif not np.isfinite(pv).all():
# NaN or infinite: missing.
logger.error("GENETIC0: PV forecast incomplete; using 0 Wh for the missing hours.")
pv = np.where(np.isfinite(pv), pv, 0.0)
pvforecast_ac_power = (pv * power_to_energy_per_interval_factor).tolist()
# Prices: the last known price carried forward.
price = await read("elecprice_marketprice_wh", "ffill")
price_unknown = price is None or not np.isfinite(price).any()
elecprice_marketprice_wh = _carry_forward(
price, slots, FALLBACK_PRICE_PER_WH, "electricity price"
).tolist()
# Load: the load default.
load = await read("loadforecast_power_w", "ffill")
loadforecast_power_w = _carry_forward(load, slots, FALLBACK_LOAD_W, "load forecast").tolist()
# Feed-in tariff: a covered control horizon is used as it is, otherwise carried forward.
try:
tariff_values = await bounded_forecast_array(
prediction,
key="feed_in_tariff_wh",
start_datetime=parameter_start_datetime,
end_datetime=parameter_end_datetime,
interval=interval,
)
except Exception as error:
logger.error("GENETIC0: Feed-in tariff not available: {}", error)
tariff_values = np.full(slots, np.nan)
first = int(
(start_datetime - parameter_start_datetime).total_seconds() / interval.total_seconds()
)
last = first + config.optimization.genetic0.horizon_hours
if last > len(tariff_values) or not all(
math.isfinite(value) for value in tariff_values[first:last]
):
logger.error(
"GENETIC0: Missing feed-in tariff within the control horizon (provider {}); "
"carrying the last known tariff forward.",
config.feedintariff.provider,
)
tariff_values = _carry_forward(
tariff_values, slots, FALLBACK_FEED_IN_TARIFF_PER_WH, "feed-in tariff"
)
feed_in_tariff_wh = tariff_values.tolist()
battery_params, battery_lcos_kwh = await _battery(observation_datetime)
electric_vehicle_params = await _electric_vehicle(observation_datetime)
inverter_params = await _inverter()
if (
battery_params is not None
and inverter_params is not None
and inverter_params.battery_id != battery_params.device_id
):
# The simulation reaches the battery only through its inverter.
logger.error(
"GENETIC0: Battery '{}' is not connected to the inverter (battery_id {}), left out.",
battery_params.device_id,
inverter_params.battery_id,
)
battery_params = None
if price_unknown and inverter_params is not None and inverter_params.max_ac_charge_power_w != 0:
# With the fallback price of 0 charging from the grid would look free.
logger.error(
"GENETIC0: No electricity price known; no charging from the grid in this run "
"(inverter '{}' max_ac_charge_power_w 0).",
inverter_params.device_id,
)
inverter_params = inverter_params.model_copy(update={"max_ac_charge_power_w": 0.0})
home_appliance_params = _home_appliance()
ems = {
"pv_forecast_wh": pvforecast_ac_power,
"electricity_price_per_wh": elecprice_marketprice_wh,
"feed_in_tariff_per_wh": feed_in_tariff_wh,
"total_load": loadforecast_power_w,
}
try:
return Genetic0Request(
ems=Genetic0EnergyManagementRequest(
**ems, price_per_wh_battery=battery_lcos_kwh / 1000
),
temperature_forecast=weather_temp_air,
pv_battery=battery_params,
ev=electric_vehicle_params,
inverter=inverter_params,
dishwasher=home_appliance_params,
start_solution=start_solution,
)
except Exception as error:
logger.error(
"GENETIC0: Parameters with devices are invalid ({}); optimizing without devices, "
"temperature forecast and start solution.",
error,
)
try:
return Genetic0Request(
ems=Genetic0EnergyManagementRequest(**ems, price_per_wh_battery=0.0),
temperature_forecast=None,
pv_battery=None,
ev=None,
inverter=None,
dishwasher=None,
)
except Exception as error:
logger.error(
"GENETIC0: Forecast parameters are invalid ({}); using 0 Wh PV, price and feed-in "
"tariff 0 and the fallback load.",
error,
)
zeros = [0.0] * slots
return Genetic0Request(
ems=Genetic0EnergyManagementRequest(
pv_forecast_wh=zeros,
electricity_price_per_wh=zeros,
feed_in_tariff_per_wh=zeros,
total_load=[FALLBACK_LOAD_W * power_to_energy_per_interval_factor] * slots,
price_per_wh_battery=0.0,
),
temperature_forecast=None,
pv_battery=None,
ev=None,
inverter=None,
dishwasher=None,
)
def _prediction_hours(start_hour: int) -> int:
"""``prediction.hours``, or its fallback.
The hours count from midnight of the start day. If fewer than ``MIN_HOURS_AFTER_START``
of them remain after the start hour, the run covers its control horizon instead.
Args:
start_hour: Hour of the day the run starts at.
Returns:
The hours the parameter arrays cover, from midnight of the start day.
"""
config = get_config()
hours = config.prediction.hours
if hours is None:
logger.error(
"GENETIC0: prediction.hours not configured, using {}.", FALLBACK_PREDICTION_HOURS
)
hours = FALLBACK_PREDICTION_HOURS
if hours < start_hour + MIN_HOURS_AFTER_START:
substitute = start_hour + max(
config.optimization.genetic0.horizon_hours, MIN_HOURS_AFTER_START
)
logger.error(
"GENETIC0: prediction.hours {} leaves fewer than {} hours after the start hour {}; "
"using {}.",
hours,
MIN_HOURS_AFTER_START,
start_hour,
substitute,
)
hours = substitute
return hours
def _carry_forward(
values: Optional[np.ndarray], slots: int, fallback: float, name: str
) -> np.ndarray:
"""Fill gaps with the last known value, leading gaps with the first known one.
Args:
values: The series, or ``None`` if it is missing.
slots: Length of the series.
fallback: Value if nothing is known.
name: Name of the series for the error log.
Returns:
A series of ``slots`` finite values.
"""
if values is None or len(values) != slots:
values = np.full(slots, np.nan)
series = pd.Series(np.asarray(values, dtype=float)).replace([np.inf, -np.inf], np.nan)
if not series.isna().any():
return series.to_numpy()
if series.isna().all():
logger.error("GENETIC0: No {} known; using {}.", name, fallback)
return np.full(slots, fallback)
logger.error("GENETIC0: {} incomplete; carrying the last known value forward.", name)
return series.ffill().bfill().to_numpy()
async def _battery(observation_datetime: DateTime) -> tuple[Optional[Any], float]:
"""Parameters and levelized cost per kWh of the first configured battery, if it can be prepared."""
config = get_config()
batteries = config.devices.batteries
if config.devices.max_batteries == 0 or not batteries:
logger.info("GENETIC0: No battery configured; optimizing without battery.")
return None, 0.0
battery_config = list(batteries.values())[0]
try:
# A configuration error gives default values, reported as error.
(
battery_parameters,
_,
) = await battery_config.resolve_current_operating_parameters_or_defaults()
battery_params = battery_request(battery_config, battery_parameters)
except Exception as error:
logger.error(
"Battery '{}' cannot be prepared for the optimization: {} "
"The battery is left out of this run.",
battery_config.device_id,
error,
)
return None, 0.0
battery_lcos_kwh = battery_config.levelized_cost_of_storage_amt_kwh
if battery_lcos_kwh is None:
logger.error(
"GENETIC0: Battery '{}' has no levelized cost of storage; using 0 per kWh.",
battery_config.device_id,
)
battery_lcos_kwh = 0.0
battery_params.initial_soc_percentage = await _initial_soc_percentage(
"battery", battery_config.measurement_key_soc_factor, observation_datetime
)
return battery_params, float(battery_lcos_kwh)
async def _electric_vehicle(observation_datetime: DateTime) -> Optional[Any]:
"""Parameters of the first configured electric vehicle, if it can be prepared."""
config = get_config()
electric_vehicles = config.devices.electric_vehicles
if config.devices.max_electric_vehicles == 0 or not electric_vehicles:
logger.info("GENETIC0: No electric vehicle configured; optimizing without one.")
return None
electric_vehicle_config = list(electric_vehicles.values())[0]
try:
# 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_request(electric_vehicle_config, ev_parameters)
except Exception as error:
logger.error(
"Electric vehicle '{}' cannot be prepared for the optimization: {} "
"The electric vehicle is left out of this run.",
electric_vehicle_config.device_id,
error,
)
return None
electric_vehicle_params.initial_soc_percentage = await _initial_soc_percentage(
"electric vehicle", electric_vehicle_config.measurement_key_soc_factor, observation_datetime
)
return electric_vehicle_params
async def _inverter() -> Optional[Any]:
"""Parameters of the first configured inverter, if it can be prepared."""
config = get_config()
inverters = config.devices.inverters
if config.devices.max_inverters == 0 or not inverters:
logger.info("GENETIC0: No inverter configured; optimizing without inverter.")
return None
inverter_config = list(inverters.values())[0]
try:
# A configuration error gives default values, reported as error.
return inverter_request(
inverter_config,
await inverter_config.resolve_current_operating_parameters_or_defaults(),
)
except Exception as error:
logger.error(
"Inverter '{}' cannot be prepared for the optimization: {} "
"The inverter is left out of this run.",
inverter_config.device_id,
error,
)
return None
def _home_appliance() -> Optional[Any]:
"""Parameters of the first configured home appliance, if it can be prepared."""
config = get_config()
home_appliances = config.devices.home_appliances
if config.devices.max_home_appliances == 0 or not home_appliances:
logger.info("GENETIC0: No home appliance configured; optimizing without one.")
return None
home_appliance_config = list(home_appliances.values())[0]
try:
return home_appliance_request(home_appliance_config)
except Exception as error:
logger.error(
"Home appliance '{}' cannot be prepared for the optimization: {} "
"The home appliance is left out of this run.",
home_appliance_config.device_id,
error,
)
return None
async def _initial_soc_percentage(kind: str, key: str, observation_datetime: DateTime) -> int:
"""Measured state of charge in percent, or 0 if none is known or it is invalid."""
try:
initial_soc_factor = await _nearest_soc_factor(key, observation_datetime)
except Exception as error:
logger.error(
"GENETIC0: No {} state of charge (measurement key '{}'): {}; using 0 %.",
kind,
key,
error,
)
return 0
if not math.isfinite(initial_soc_factor) or not 0.0 <= initial_soc_factor <= 1.0:
logger.error(
"GENETIC0: Invalid {} state of charge factor {}; using 0 %.", kind, initial_soc_factor
)
return 0
# genetic parameter is 0..100 as int
return int(initial_soc_factor * 100)
def battery_request(
settings: BatteriesCommonSettings,
operating_parameters: Optional[BatteryOperatingParameters] = None,
) -> Genetic0SolarPanelBatteryRequest:
"""GENETIC0 parameters of a stationary battery from its settings.
Args:
settings: The battery settings.
operating_parameters: Resolved snapshot to convert, e.g. from
``resolve_current_operating_parameters``. None resolves at the reference operating
point.
Returns:
The battery parameters of the request.
Raises:
BatteryResolutionError: See ``resolve_operating_parameters``.
"""
p = (
operating_parameters
if operating_parameters is not None
else settings.resolve_operating_parameters()
)
return Genetic0SolarPanelBatteryRequest(
device_id=settings.device_id,
capacity_wh=p.capacity_wh,
charging_efficiency=p.charging_efficiency,
discharging_efficiency=p.discharging_efficiency,
max_charge_power_w=p.max_charge_power_w,
max_discharge_power_w=p.max_discharge_power_w,
min_soc_percentage=p.min_soc_percentage,
max_soc_percentage=p.max_soc_percentage,
)
def electric_vehicle_request(
settings: BatteriesCommonSettings,
operating_parameters: Optional[BatteryOperatingParameters] = None,
) -> Genetic0ElectricVehicleRequest:
"""GENETIC0 parameters of an electric vehicle from its settings.
Args:
settings: The electric vehicle's battery settings.
operating_parameters: Resolved snapshot to convert, e.g. from
``resolve_current_operating_parameters``. None resolves at the reference operating
point.
Returns:
The electric vehicle parameters of the request.
Raises:
BatteryResolutionError: See ``resolve_operating_parameters``.
"""
p = (
operating_parameters
if operating_parameters is not None
else settings.resolve_operating_parameters()
)
return Genetic0ElectricVehicleRequest(
device_id=settings.device_id,
capacity_wh=p.capacity_wh,
charging_efficiency=p.charging_efficiency,
discharging_efficiency=p.discharging_efficiency,
charge_rates=settings.charge_rates,
max_charge_power_w=p.max_charge_power_w,
max_discharge_power_w=p.max_discharge_power_w,
min_soc_percentage=p.min_soc_percentage,
max_soc_percentage=p.max_soc_percentage,
)
def inverter_request(
settings: InverterCommonSettings,
operating_parameters: Optional[InverterOperatingParameters] = None,
) -> Genetic0InverterRequest:
"""GENETIC0 parameters of an inverter from its settings.
GENETIC0 uses constant efficiencies: the DC->AC efficiency at the reference load fraction and
the AC->DC efficiency at the AC charge limit.
Args:
settings: The inverter settings.
operating_parameters: Resolved operating parameters; None resolves them.
Returns:
The inverter parameters of the request.
Raises:
InverterResolutionError: See ``InverterCommonSettings.to_genetic_param``.
"""
p = operating_parameters or settings.resolve_operating_parameters()
return Genetic0InverterRequest(
device_id=settings.device_id,
max_power_wh=p.max_power_w,
battery_id=settings.battery_id,
ac_to_dc_efficiency=p.ac_to_dc_efficiency,
dc_to_ac_efficiency=p.dc_to_ac_efficiency,
max_ac_charge_power_w=p.max_ac_charge_power_w,
)
def home_appliance_request(settings: HomeApplianceCommonSettings) -> Genetic0HomeApplianceRequest:
"""GENETIC0 parameters of a home appliance from its settings.
Args:
settings: The home appliance settings.
Returns:
The home appliance parameters of the request.
Raises:
ValueError: The appliance needs the GENETIC optimizer (explicit load profile) or has no
flat load definition.
"""
if settings.load_profile_power_w is not None:
raise ValueError("Explicit appliance load profiles require the GENETIC optimizer.")
if settings.consumption_wh is None or settings.duration_h is None:
raise ValueError("GENETIC0 requires a flat appliance load definition.")
return Genetic0HomeApplianceRequest(
device_id=settings.device_id,
consumption_wh=settings.consumption_wh,
duration_h=settings.duration_h,
time_windows=settings.cycle_time_windows,
)
@@ -0,0 +1,513 @@
"""GENETIC0 optimization request: the forecast and device parameters a client sends.
This module defines the Pydantic models of the request, including photovoltaic forecasts,
electricity pricing, and system component parameters. The parameter preparation
(``genetic0prepare``) assembles a request from configuration, predictions and measurements.
"""
from typing import Any, Optional, Union
from pydantic import (
AliasChoices,
ConfigDict,
Field,
computed_field,
field_validator,
model_validator,
)
from typing_extensions import Self
from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import (
Genetic0BatteryParameters,
)
from akkudoktoreos.optimization.genetic0.devices.genetic0homeappliance import (
Genetic0HomeApplianceParameters,
)
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
Genetic0InverterParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0energymanagement import (
Genetic0EnergyManagementParameters,
)
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time
class Genetic0ParametersBaseModel(PydanticBaseModel):
"""Pydantic base model of the request and response models of GENETIC0."""
model_config = ConfigDict(extra="forbid")
class Genetic0DeviceRequest(Genetic0ParametersBaseModel):
"""Fields every device of the request has."""
device_id: str = Field(json_schema_extra={"description": "ID of device", "examples": "device1"})
hours: Optional[int] = Field(
default=None,
gt=0,
json_schema_extra={
"description": "Number of prediction hours. Defaults to global config prediction hours.",
"examples": [None],
},
)
def max_charging_power_field(description: Optional[str] = None) -> Any:
"""Pydantic field of a maximum charging power in watts.
Args:
description: Field description; ``None`` uses a generic one.
Returns:
The field definition.
"""
if description is None:
description = "Maximum charging power in watts."
# 0: the battery may not charge, e.g. the profile inhibits it at a low temperature.
return Field(default=5000, ge=0, json_schema_extra={"description": description})
def initial_soc_percentage_field(description: str) -> Any:
"""Pydantic field of an initial state of charge in percent.
Args:
description: Field description.
Returns:
The field definition.
"""
return Field(
default=0, ge=0, le=100, json_schema_extra={"description": description, "examples": [42]}
)
def discharging_efficiency_field(default_value: float) -> Any:
"""Pydantic field of a discharging efficiency (0, 1].
Args:
default_value: Default efficiency.
Returns:
The field definition.
"""
return Field(
default=default_value,
gt=0,
le=1,
json_schema_extra={
"description": "A float representing the discharge efficiency of the battery."
},
)
class Genetic0BaseBatteryRequest(Genetic0DeviceRequest):
"""Battery Device Simulation Configuration."""
device_id: str = Field(
json_schema_extra={"description": "ID of battery", "examples": ["battery1"]}
)
capacity_wh: int = Field(
gt=0,
json_schema_extra={
"description": "An integer representing the capacity of the battery in watt-hours.",
"examples": [8000],
},
)
charging_efficiency: float = Field(
default=0.88,
gt=0,
le=1,
json_schema_extra={
"description": "A float representing the charging efficiency of the battery."
},
)
discharging_efficiency: float = discharging_efficiency_field(0.88)
max_charge_power_w: Optional[float] = max_charging_power_field()
max_discharge_power_w: Optional[float] = Field(
default=None,
ge=0,
json_schema_extra={
"description": (
"Maximum discharging power in watts. 0: the battery may not discharge. "
"None uses max_charge_power_w."
),
"examples": [None, 4000],
},
)
initial_soc_percentage: int = initial_soc_percentage_field(
"An integer representing the state of charge of the battery at the **start** of the current hour (not the current state)."
)
min_soc_percentage: int = Field(
default=0,
ge=0,
le=100,
json_schema_extra={
"description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.",
"examples": [10],
},
)
max_soc_percentage: int = Field(
default=100,
ge=0,
le=100,
json_schema_extra={
"description": "An integer representing the maximum state of charge (SOC) of the battery in percentage."
},
)
charge_rates: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": "Charge rates as factor of maximum charging power [0.00 ... 1.00]. None denotes all charge rates are available.",
"examples": [[0.0, 0.25, 0.5, 0.75, 1.0], None],
},
)
def to_parameters(self) -> Genetic0BatteryParameters:
"""The parameters of the simulated battery.
Returns:
The battery parameters; a stationary battery keeps its minimum state of charge.
"""
return Genetic0BatteryParameters(
device_id=self.device_id,
capacity_wh=self.capacity_wh,
charging_efficiency=self.charging_efficiency,
discharging_efficiency=self.discharging_efficiency,
max_charge_power_w=self.max_charge_power_w,
max_discharge_power_w=self.max_discharge_power_w,
initial_soc_percentage=self.initial_soc_percentage,
min_soc_percentage=self.min_soc_percentage,
max_soc_percentage=self.max_soc_percentage,
charge_rates=None if self.charge_rates is None else tuple(self.charge_rates),
stationary=isinstance(self, Genetic0SolarPanelBatteryRequest),
)
class Genetic0SolarPanelBatteryRequest(Genetic0BaseBatteryRequest):
"""PV battery device simulation configuration."""
max_charge_power_w: Optional[float] = max_charging_power_field()
class Genetic0ElectricVehicleRequest(Genetic0BaseBatteryRequest):
"""Battery Electric Vehicle Device Simulation Configuration."""
device_id: str = Field(
json_schema_extra={"description": "ID of electric vehicle", "examples": ["ev1"]}
)
discharging_efficiency: float = discharging_efficiency_field(1.0)
initial_soc_percentage: int = initial_soc_percentage_field(
"An integer representing the current state of charge (SOC) of the battery in percentage."
)
class Genetic0InverterRequest(Genetic0DeviceRequest):
"""Inverter Device Simulation Configuration."""
device_id: str = Field(
json_schema_extra={"description": "ID of inverter", "examples": ["inverter1"]}
)
max_power_wh: float = Field(gt=0, json_schema_extra={"examples": [10000]})
battery_id: Optional[str] = Field(
default=None,
json_schema_extra={"description": "ID of battery", "examples": [None, "battery1"]},
)
ac_to_dc_efficiency: float = Field(
default=1.0,
ge=0,
le=1,
json_schema_extra={
"description": (
"Efficiency of AC to DC conversion (for AC/grid charging of battery). "
"Set to 0 to disable AC charging via inverter. "
"Default 1.0 for backward compatibility (no additional inverter loss)."
),
"examples": [0.95, 1.0, 0.0],
},
)
dc_to_ac_efficiency: float = Field(
default=1.0,
gt=0,
le=1,
json_schema_extra={
"description": (
"Efficiency of DC to AC conversion (for battery discharging to AC load/grid). "
"Default 1.0 for backward compatibility (no additional inverter loss)."
),
"examples": [0.95, 1.0],
},
)
max_ac_charge_power_w: Optional[float] = Field(
default=None,
ge=0,
json_schema_extra={
"description": (
"Maximum AC charging power in watts. "
"None means no additional limit (battery's own max_charge_power_w applies). "
"Set to 0 to disable AC charging."
),
"examples": [None, 0, 5000],
},
)
def to_parameters(self) -> Genetic0InverterParameters:
"""The parameters of the simulated inverter.
Returns:
The inverter parameters.
"""
return Genetic0InverterParameters(
device_id=self.device_id,
max_power_wh=self.max_power_wh,
battery_id=self.battery_id,
ac_to_dc_efficiency=self.ac_to_dc_efficiency,
dc_to_ac_efficiency=self.dc_to_ac_efficiency,
max_ac_charge_power_w=self.max_ac_charge_power_w,
)
class Genetic0HomeApplianceRequest(Genetic0DeviceRequest):
"""Home Appliance Device Simulation Configuration."""
device_id: str = Field(
json_schema_extra={"description": "ID of home appliance", "examples": ["dishwasher"]}
)
consumption_wh: int = Field(
gt=0,
json_schema_extra={
"description": "An integer representing the energy consumption of a household device in watt-hours.",
"examples": [2000],
},
)
duration_h: int = Field(
gt=0,
json_schema_extra={
"description": "An integer representing the usage duration of a household device in hours.",
"examples": [3],
},
)
time_windows: Optional[TimeWindowSequence] = Field(
default=None,
json_schema_extra={
"description": "List of allowed time windows. Defaults to optimization general time window.",
"examples": [
[
{"start_time": "10:00", "duration": "3 hours"},
],
],
},
)
def to_parameters(self, prediction_hours: int) -> Genetic0HomeApplianceParameters:
"""The parameters of the simulated home appliance.
Evaluates the time windows into the hours a run may start, relative to midnight of
today, as the simulation device did before. Without time windows the request gets a
window over all prediction hours, which the result echoes.
Args:
prediction_hours: Length of the simulated arrays.
Returns:
The home appliance parameters.
"""
if self.time_windows is None:
self.time_windows = TimeWindowSequence(
windows=[
TimeWindow(
start_time=to_time("00:00"),
duration=to_duration(f"{prediction_hours} hours"),
),
]
)
start_datetime = to_datetime().set(hour=0, minute=0, second=0)
duration = to_duration(f"{self.duration_h} hours")
start_allowed = tuple(
self.time_windows.contains(start_datetime.add(hours=hour), duration=duration)
for hour in range(0, prediction_hours)
)
start_earliest = self.time_windows.earliest_start_time(duration, start_datetime)
start_latest = self.time_windows.latest_start_time(duration, start_datetime)
return Genetic0HomeApplianceParameters(
device_id=self.device_id,
consumption_wh=self.consumption_wh,
duration_h=self.duration_h,
start_allowed=start_allowed,
start_earliest=start_earliest.hour if start_earliest else 0,
start_latest=start_latest.hour if start_latest else 23,
)
class Genetic0EnergyManagementRequest(Genetic0ParametersBaseModel):
"""Encapsulates energy-related forecasts and costs used in GENETIC optimization."""
model_config = ConfigDict(populate_by_name=True, extra="ignore")
pv_forecast_wh: list[float] = Field(
validation_alias=AliasChoices("pv_forecast_wh", "pv_prognose_wh"),
json_schema_extra={
"description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals."
},
)
electricity_price_per_wh: list[float] = Field(
validation_alias=AliasChoices("electricity_price_per_wh", "strompreis_euro_pro_wh"),
json_schema_extra={
"description": "An array of floats representing the electricity price per watt-hour for different time intervals."
},
)
feed_in_tariff_per_wh: Union[list[float], float] = Field(
validation_alias=AliasChoices("feed_in_tariff_per_wh", "einspeiseverguetung_euro_pro_wh"),
json_schema_extra={
"description": "A float or array of floats representing the feed-in compensation per watt-hour."
},
)
price_per_wh_battery: float = Field(
validation_alias=AliasChoices("price_per_wh_battery", "preis_euro_pro_wh_akku"),
json_schema_extra={
"description": "A float representing the cost of battery energy per watt-hour."
},
)
total_load: list[float] = Field(
validation_alias=AliasChoices("total_load", "gesamtlast"),
json_schema_extra={
"description": "An array of floats representing the total load (consumption) in watts for different time intervals."
},
)
# Computed fields for backward compatibility (deprecated German names)
@computed_field(json_schema_extra={"deprecated": True})
def pv_prognose_wh(self) -> list[float]:
"""Deprecated: Use pv_forecast_wh instead."""
return self.pv_forecast_wh
@computed_field(json_schema_extra={"deprecated": True})
def strompreis_euro_pro_wh(self) -> list[float]:
"""Deprecated: Use electricity_price_per_wh instead."""
return self.electricity_price_per_wh
@computed_field(json_schema_extra={"deprecated": True})
def einspeiseverguetung_euro_pro_wh(self) -> Union[list[float], float]:
"""Deprecated: Use feed_in_tariff_per_wh instead."""
return self.feed_in_tariff_per_wh
@computed_field(json_schema_extra={"deprecated": True})
def preis_euro_pro_wh_akku(self) -> float:
"""Deprecated: Use price_per_wh_battery instead."""
return self.price_per_wh_battery
@computed_field(json_schema_extra={"deprecated": True})
def gesamtlast(self) -> list[float]:
"""Deprecated: Use total_load instead."""
return self.total_load
@model_validator(mode="after")
def validate_list_length(self) -> Self:
"""Validate that all input lists are of the same length.
Raises:
ValueError: If input list lengths differ.
"""
pv_forecast_length = len(self.pv_forecast_wh)
if (
pv_forecast_length != len(self.electricity_price_per_wh)
or pv_forecast_length != len(self.total_load)
or (
isinstance(self.feed_in_tariff_per_wh, list)
and pv_forecast_length != len(self.feed_in_tariff_per_wh)
)
):
raise ValueError("Input lists have different lengths")
return self
def to_parameters(self) -> Genetic0EnergyManagementParameters:
"""The forecasts and prices of the simulation.
Returns:
The energy management parameters; a constant feed-in tariff stays a single value.
"""
tariff = self.feed_in_tariff_per_wh
return Genetic0EnergyManagementParameters(
pv_forecast_wh=tuple(self.pv_forecast_wh),
electricity_price_per_wh=tuple(self.electricity_price_per_wh),
feed_in_tariff_per_wh=tuple(tariff) if isinstance(tariff, list) else tariff,
price_per_wh_battery=self.price_per_wh_battery,
total_load=tuple(self.total_load),
)
class Genetic0Request(Genetic0ParametersBaseModel):
"""Main parameter class for running the genetic energy optimization.
Collects all model and configuration parameters necessary to run the
optimization process, such as forecasts, pricing, battery and appliance models.
"""
model_config = ConfigDict(populate_by_name=True, extra="ignore")
ems: Genetic0EnergyManagementRequest
pv_battery: Optional[Genetic0SolarPanelBatteryRequest] = Field(
validation_alias=AliasChoices("pv_battery", "pv_akku"),
json_schema_extra={"description": "PV battery parameters."},
)
inverter: Optional[Genetic0InverterRequest]
ev: Optional[Genetic0ElectricVehicleRequest] = Field(
validation_alias=AliasChoices("ev", "eauto"),
json_schema_extra={"description": "Electric vehicle parameters."},
)
dishwasher: Optional[Genetic0HomeApplianceRequest] = None
temperature_forecast: Optional[list[Optional[float]]] = Field(
default=None,
json_schema_extra={
"description": "An array of floats representing the temperature forecast in degrees Celsius for different time intervals."
},
)
start_solution: Optional[list[float]] = Field(
default=None,
json_schema_extra={
"description": "Can be `null` or contain a previous solution (if available)."
},
)
# Computed fields for backward compatibility (deprecated German names)
@computed_field(json_schema_extra={"deprecated": True})
def pv_akku(self) -> Optional[Genetic0SolarPanelBatteryRequest]:
"""Deprecated: Use pv_battery instead."""
return self.pv_battery
@computed_field(json_schema_extra={"deprecated": True})
def eauto(self) -> Optional[Genetic0ElectricVehicleRequest]:
"""Deprecated: Use ev instead."""
return self.ev
@model_validator(mode="after")
def validate_list_length(self) -> Self:
"""Ensure that temperature forecast list matches the PV forecast length.
Raises:
ValueError: If list lengths mismatch.
"""
arr_length = len(self.ems.pv_forecast_wh)
if self.temperature_forecast is not None and arr_length != len(self.temperature_forecast):
raise ValueError("Input lists have different lengths")
return self
@field_validator("start_solution")
def validate_start_solution(
cls, start_solution: Optional[list[float]]
) -> Optional[list[float]]:
"""Validate that the starting solution has at least two elements.
Args:
start_solution (list[float]): Optional list of solution values.
Returns:
list[float]: Validated list.
Raises:
ValueError: If the solution is too short.
"""
if start_solution is not None and len(start_solution) < 2:
raise ValueError("Requires at least two values.")
return start_solution
@@ -0,0 +1,180 @@
"""Optimization result of GENETIC0: the output of one run (ADR 0006, 0009, 0010).
Plain frozen dataclasses. Their values are normalised as the public response models validate them
(``genetic0api``): NumPy arrays become lists, NaN becomes ``None`` and values get the field's
number type, so that a response built from a result is the same as before the result became a
dataclass (ADR 0008).
"""
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, Optional, Union
from akkudoktoreos.utils.utils import NumpyEncoder
# German keys of the simulation output and the field names of the result.
SIMULATION_KEYS: Mapping[str, str] = {
"Last_Wh_pro_Stunde": "load_wh_per_hour",
"EAuto_SoC_pro_Stunde": "ev_soc_per_hour",
"Einnahmen_Euro_pro_Stunde": "revenue_per_hour",
"Gesamt_Verluste": "total_losses",
"Gesamtbilanz_Euro": "total_balance",
"Gesamteinnahmen_Euro": "total_revenue",
"Gesamtkosten_Euro": "total_costs",
"Home_appliance_wh_per_hour": "home_appliance_wh_per_hour",
"Kosten_Euro_pro_Stunde": "costs_per_hour",
"Netzbezug_Wh_pro_Stunde": "grid_consumption_wh_per_hour",
"Netzeinspeisung_Wh_pro_Stunde": "grid_feed_in_wh_per_hour",
"Verluste_Pro_Stunde": "losses_per_hour",
"akku_soc_pro_stunde": "battery_soc_per_hour",
"Electricity_price": "electricity_price",
}
def _values(values: Any) -> list[Any]:
"""NumPy arrays as lists (NaN as ``None``), as ``NumpyEncoder.convert_numpy`` does."""
return list(NumpyEncoder.convert_numpy(values)[0])
def _float(value: Any) -> float:
if isinstance(value, bool) or value is None:
raise ValueError(f"Not a number: {value!r}")
return float(value)
def _int(value: Any) -> int:
number = float(value)
if isinstance(value, bool) or not number.is_integer():
raise ValueError(f"Not an integer: {value!r}")
return int(number)
def float_list(values: Any) -> list[float]:
"""A list of floats, coerced as a ``list[float]`` model field does."""
return [_float(value) for value in _values(values)]
def optional_float_list(values: Any) -> list[Optional[float]]:
"""A list of floats or ``None``, coerced as a ``list[Optional[float]]`` field does."""
return [None if value is None else _float(value) for value in _values(values)]
def int_list(values: Any) -> list[int]:
"""A list of integers, coerced as a ``list[int]`` model field does."""
return [_int(value) for value in _values(values)]
@dataclass(frozen=True, slots=True)
class Genetic0SimulationOutput:
"""Hourly and total values of the simulated best solution, from the start hour."""
load_wh_per_hour: list[float]
ev_soc_per_hour: list[float]
revenue_per_hour: list[float]
total_losses: float
total_balance: float
total_revenue: float
total_costs: float
home_appliance_wh_per_hour: list[Optional[float]]
costs_per_hour: list[float]
grid_consumption_wh_per_hour: list[float]
grid_feed_in_wh_per_hour: list[float]
losses_per_hour: list[float]
battery_soc_per_hour: list[float]
electricity_price: list[float]
@classmethod
def from_simulation(cls, output: Mapping[str, Any]) -> "Genetic0SimulationOutput":
"""Build the output from the simulation's dictionary (German keys).
Args:
output: The dictionary ``Genetic0Simulation.simulate()`` returns.
Returns:
The normalised simulation output.
"""
values = {
SIMULATION_KEYS[key]: value for key, value in output.items() if key in SIMULATION_KEYS
}
totals = ("total_losses", "total_balance", "total_revenue", "total_costs")
fields: dict[str, Any] = {}
for key, value in values.items():
if key in totals:
fields[key] = _float(value)
elif key == "home_appliance_wh_per_hour":
fields[key] = optional_float_list(value)
else:
fields[key] = float_list(value)
return cls(**fields)
@dataclass(frozen=True, slots=True)
class Genetic0ElectricVehicleState:
"""The electric vehicle at the end of the simulated best solution."""
device_id: str
hours: int
charge_array: list[float]
discharge_array: list[int]
discharging_efficiency: float
capacity_wh: int
charging_efficiency: float
max_charge_power_w: int
soc_wh: float
initial_soc_percentage: int
@classmethod
def from_battery(cls, state: Mapping[str, Any]) -> "Genetic0ElectricVehicleState":
"""Build the state from ``Genetic0Battery.to_dict()``.
Args:
state: The battery's dictionary.
Returns:
The normalised electric vehicle state.
"""
return cls(
device_id=str(state["device_id"]),
hours=_int(state["hours"]),
charge_array=float_list(state["charge_array"]),
discharge_array=int_list(state["discharge_array"]),
discharging_efficiency=_float(state["discharging_efficiency"]),
capacity_wh=_int(state["capacity_wh"]),
charging_efficiency=_float(state["charging_efficiency"]),
max_charge_power_w=_int(state["max_charge_power_w"]),
soc_wh=_float(state["soc_wh"]),
initial_soc_percentage=_int(state["initial_soc_percentage"]),
)
@dataclass(frozen=True, slots=True)
class Genetic0Result:
"""Output of one GENETIC0 run.
Attributes:
ac_charge: AC charging factor per hour of the arrays.
dc_charge: DC charging factor per hour of the arrays.
discharge_allowed: 1 where discharging is allowed, per hour of the arrays.
ev_charge_hours_float: EV charging factor per hour, or ``None`` without an EV.
result: Simulated values of the best solution.
ev_obj: The electric vehicle at the end of the simulation, if any.
start_hour: Hour of the day the run started at.
start_solution: Best individual, the warm start of the next run.
washingstart: Start hour of the home appliance, if any.
extra_data: Extra data of the run.
fitness_history: Fitness per generation.
fixed_seed: Seed of the run.
"""
ac_charge: list[float]
dc_charge: list[float]
discharge_allowed: list[int]
ev_charge_hours_float: Optional[list[float]]
result: Genetic0SimulationOutput
ev_obj: Optional[Genetic0ElectricVehicleState]
start_hour: int
start_solution: Optional[list[float]]
washingstart: Optional[int]
extra_data: Optional[dict[str, Union[list[int], list[float]]]]
fitness_history: Optional[dict[str, Union[list[int], list[float]]]]
fixed_seed: Optional[int]
@@ -10,7 +10,7 @@ from pydantic import Field, computed_field
from akkudoktoreos.config.configabc import SettingsBaseModel
class Genetic0CommonSettings(SettingsBaseModel):
class Genetic0Settings(SettingsBaseModel):
"""GENETIC0 Optimization Algorithm Configuration."""
horizon_hours: int = Field(
@@ -0,0 +1,364 @@
"""GENETIC0 simulation of one individual over the horizon."""
from typing import Any, Optional
import numpy as np
from loguru import logger
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import Genetic0Battery
from akkudoktoreos.optimization.genetic0.devices.genetic0homeappliance import (
Genetic0HomeAppliance,
)
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
Genetic0Inverter,
)
from akkudoktoreos.optimization.genetic0.genetic0energymanagement import (
Genetic0EnergyManagementParameters,
)
class Genetic0Simulation:
"""Device simulation for GENETIC optimization algorithm."""
def __init__(self) -> None:
"""Create an empty simulation; ``prepare()`` sets it up for a run."""
self.start_hour: int = 0
self.optimization_hours: Optional[int] = 24
self.prediction_hours: Optional[int] = 48
self.load_energy_array: Optional[np.ndarray] = None
self.pv_prediction_wh: Optional[np.ndarray] = None
self.elect_price_hourly: Optional[np.ndarray] = None
self.elect_revenue_per_hour_arr: Optional[np.ndarray] = None
self.battery: Optional[Genetic0Battery] = None
self.ev: Optional[Genetic0Battery] = None
self.home_appliance: Optional[Genetic0HomeAppliance] = None
self.inverter: Optional[Genetic0Inverter] = None
self.ac_charge_hours: Optional[np.ndarray] = None
self.dc_charge_hours: Optional[np.ndarray] = None
self.bat_discharge_hours: Optional[np.ndarray] = None
self.ev_charge_hours: Optional[np.ndarray] = None
self.ev_discharge_hours: Optional[np.ndarray] = None
self.home_appliance_start_hour: Optional[int] = None
def prepare(
self,
parameters: Genetic0EnergyManagementParameters,
optimization_hours: int,
prediction_hours: int,
ev: Optional[Genetic0Battery] = None,
home_appliance: Optional[Genetic0HomeAppliance] = None,
inverter: Optional[Genetic0Inverter] = None,
) -> None:
"""Prepare simulation runs.
Populate internal arrays and device references used during simulation.
"""
self.optimization_hours = optimization_hours
self.prediction_hours = prediction_hours
# Load arrays from provided EMS parameters
self.load_energy_array = np.array(parameters.total_load, float)
self.pv_prediction_wh = np.array(parameters.pv_forecast_wh, float)
self.elect_price_hourly = np.array(parameters.electricity_price_per_wh, float)
self.elect_revenue_per_hour_arr = (
np.asarray(parameters.feed_in_tariff_per_wh, dtype=float)
if isinstance(parameters.feed_in_tariff_per_wh, tuple)
else np.full(len(self.load_energy_array), parameters.feed_in_tariff_per_wh, float)
)
# Associate devices
if inverter:
self.battery = inverter.battery
else:
self.battery = None
self.ev = ev
self.home_appliance = home_appliance
self.inverter = inverter
# Initialize per-hour action arrays for the prediction horizon
self.ac_charge_hours = np.full(self.prediction_hours, 0.0)
self.dc_charge_hours = np.full(self.prediction_hours, 0.0)
self.bat_discharge_hours = np.full(self.prediction_hours, 0.0)
self.ev_charge_hours = np.full(self.prediction_hours, 0.0)
self.ev_discharge_hours = np.full(self.prediction_hours, 0.0)
self.home_appliance_start_hour = None
def reset(self) -> None:
if self.ev:
self.ev.reset()
if self.battery:
self.battery.reset()
self.home_appliance_start_hour = None
def simulate(self, start_hour: int) -> dict[str, Any]:
"""Simulate energy usage and costs for the given start hour.
battery_soc_per_hour begin of the hour, initial hour state!
load_wh_per_hour integral of last hour (end state)
"""
# Remember start hour
self.start_hour = start_hour
# Provide fast (3x..5x) local read access (vs. self.xxx) for repetitive read access
load_energy_array_fast = self.load_energy_array
ev_charge_hours_fast = self.ev_charge_hours
ev_discharge_hours_fast = self.ev_discharge_hours
ac_charge_hours_fast = self.ac_charge_hours
dc_charge_hours_fast = self.dc_charge_hours
bat_discharge_hours_fast = self.bat_discharge_hours
elect_price_hourly_fast = self.elect_price_hourly
elect_revenue_per_hour_arr_fast = self.elect_revenue_per_hour_arr
pv_prediction_wh_fast = self.pv_prediction_wh
battery_fast = self.battery
ev_fast = self.ev
home_appliance_fast = self.home_appliance
inverter_fast = self.inverter
# Check for simulation integrity (in a way that mypy understands)
if (
load_energy_array_fast is None
or pv_prediction_wh_fast is None
or elect_price_hourly_fast is None
or ev_charge_hours_fast is None
or ac_charge_hours_fast is None
or dc_charge_hours_fast is None
or elect_revenue_per_hour_arr_fast is None
or bat_discharge_hours_fast is None
or ev_discharge_hours_fast is None
):
missing = []
if load_energy_array_fast is None:
missing.append("Load Energy Array")
if pv_prediction_wh_fast is None:
missing.append("PV Prediction Wh")
if elect_price_hourly_fast is None:
missing.append("Electricity Price Hourly")
if ev_charge_hours_fast is None:
missing.append("EV Charge Hours")
if ac_charge_hours_fast is None:
missing.append("AC Charge Hours")
if dc_charge_hours_fast is None:
missing.append("DC Charge Hours")
if elect_revenue_per_hour_arr_fast is None:
missing.append("Electricity Revenue Per Hour")
if bat_discharge_hours_fast is None:
missing.append("Genetic0Battery Discharge Hours")
if ev_discharge_hours_fast is None:
missing.append("EV Discharge Hours")
msg = ", ".join(missing)
logger.error("Mandatory data missing - %s", msg)
raise ValueError(f"Mandatory data missing: {msg}")
if not (
len(load_energy_array_fast)
== len(pv_prediction_wh_fast)
== len(elect_price_hourly_fast)
):
error_msg = f"Array sizes do not match: Load Curve = {len(load_energy_array_fast)}, PV Forecast = {len(pv_prediction_wh_fast)}, Electricity Price = {len(elect_price_hourly_fast)}"
logger.error(error_msg)
raise ValueError(error_msg)
end_hour = len(load_energy_array_fast)
total_hours = end_hour - start_hour
# Pre-allocate arrays for the results, optimized for speed
loads_energy_per_hour = np.full((total_hours), np.nan)
feedin_energy_per_hour = np.full((total_hours), np.nan)
consumption_energy_per_hour = np.full((total_hours), np.nan)
costs_per_hour = np.full((total_hours), np.nan)
revenue_per_hour = np.full((total_hours), np.nan)
losses_wh_per_hour = np.full((total_hours), np.nan)
electricity_price_per_hour = np.full((total_hours), np.nan)
# Set initial state
if battery_fast:
# Pre-allocate arrays for the results, optimized for speed
soc_per_hour = np.full((total_hours), np.nan)
soc_per_hour[0] = battery_fast.current_soc_percentage()
# Determine AC charging availability from inverter parameters
if inverter_fast:
ac_to_dc_eff_fast = inverter_fast.ac_to_dc_efficiency
dc_to_ac_eff_fast = inverter_fast.dc_to_ac_efficiency
max_ac_charge_w_fast = inverter_fast.max_ac_charge_power_w
else:
ac_to_dc_eff_fast = 1.0
dc_to_ac_eff_fast = 1.0
max_ac_charge_w_fast = None
ac_charging_possible = ac_to_dc_eff_fast > 0 and (
max_ac_charge_w_fast is None or max_ac_charge_w_fast > 0
)
# If AC charging is disabled via inverter, zero out AC charge hours
if not ac_charging_possible:
ac_charge_hours_fast = np.zeros_like(ac_charge_hours_fast)
# Fill the charge array of the battery
dc_charge_hours_fast[0:start_hour] = 0
dc_charge_hours_fast[end_hour:] = 0
ac_charge_hours_fast[0:start_hour] = 0
ac_charge_hours_fast[end_hour:] = 0
battery_fast.charge_array = np.where(
ac_charge_hours_fast != 0, ac_charge_hours_fast, dc_charge_hours_fast
)
# Fill the discharge array of the battery
bat_discharge_hours_fast[0:start_hour] = 0
bat_discharge_hours_fast[end_hour:] = 0
battery_fast.discharge_array = bat_discharge_hours_fast
else:
# Default return if no battery is available
soc_per_hour = np.full((total_hours), 0)
ac_to_dc_eff_fast = 1.0
dc_to_ac_eff_fast = 1.0
max_ac_charge_w_fast = None
ac_charging_possible = False
if ev_fast:
# Pre-allocate arrays for the results, optimized for speed
soc_ev_per_hour = np.full((total_hours), np.nan)
soc_ev_per_hour[0] = ev_fast.current_soc_percentage()
# Fill the charge array of the ev
ev_charge_hours_fast[0:start_hour] = 0
ev_charge_hours_fast[end_hour:] = 0
ev_fast.charge_array = ev_charge_hours_fast
# Fill the discharge array of the ev
ev_discharge_hours_fast[0:start_hour] = 0
ev_discharge_hours_fast[end_hour:] = 0
ev_fast.discharge_array = ev_discharge_hours_fast
else:
# Default return if no electric vehicle is available
soc_ev_per_hour = np.full((total_hours), 0)
if home_appliance_fast and self.home_appliance_start_hour is not None:
home_appliance_enabled = True
# Pre-allocate arrays for the results, optimized for speed
home_appliance_wh_per_hour = np.full((total_hours), np.nan)
self.home_appliance_start_hour = home_appliance_fast.set_starting_time(
self.home_appliance_start_hour, start_hour
)
else:
home_appliance_enabled = False
# Default return if no home appliance is available
home_appliance_wh_per_hour = np.full((total_hours), 0)
for hour in range(start_hour, end_hour):
hour_idx = hour - start_hour
# Accumulate loads and PV generation
consumption = load_energy_array_fast[hour]
losses_wh_per_hour[hour_idx] = 0.0
# Home appliances
if home_appliance_enabled:
ha_load = home_appliance_fast.get_load_for_hour(hour) # type: ignore[union-attr]
consumption += ha_load
home_appliance_wh_per_hour[hour_idx] = ha_load
# E-Auto handling
if ev_fast:
soc_ev_per_hour[hour_idx] = ev_fast.current_soc_percentage() # save begin state
if ev_charge_hours_fast[hour] > 0:
loaded_energy_ev, ev_charge_losses = ev_fast.charge_energy(
wh=None, hour=hour, charge_factor=ev_charge_hours_fast[hour]
)
consumption += loaded_energy_ev
losses_wh_per_hour[hour_idx] += ev_charge_losses
# Save battery SOC before inverter processing = true begin-of-interval state.
# Must be recorded here (before DC charge/discharge) so the displayed SOC at
# timestamp T reflects what the battery actually had at the START of interval T,
# not the post-DC result. Consistent with the EV SOC convention above.
if battery_fast:
soc_per_hour[hour_idx] = battery_fast.current_soc_percentage()
# Process inverter logic
energy_feedin_grid_actual = energy_consumption_grid_actual = losses = (
self_consumption
) = 0.0
if inverter_fast:
energy_produced = pv_prediction_wh_fast[hour]
(
energy_feedin_grid_actual,
energy_consumption_grid_actual,
losses,
self_consumption,
) = inverter_fast.process_energy(energy_produced, consumption, hour)
else:
# Without an inverter the grid supplies the whole load; PV is not converted.
energy_consumption_grid_actual = consumption
# AC PV Battery Charge
if battery_fast:
hour_ac_charge = ac_charge_hours_fast[hour]
if hour_ac_charge > 0.0 and ac_charging_possible:
# Cap charge factor by max_ac_charge_power_w if set
effective_charge_factor = hour_ac_charge
if max_ac_charge_w_fast is not None and battery_fast.max_charge_power_w > 0:
# DC power = max_charge_power_w * factor
# AC power = DC power / ac_to_dc_eff
# AC power must be <= max_ac_charge_power_w
max_dc_factor = (
max_ac_charge_w_fast * ac_to_dc_eff_fast
) / battery_fast.max_charge_power_w
effective_charge_factor = min(effective_charge_factor, max_dc_factor)
if effective_charge_factor > 0:
battery_charged_energy_actual, battery_losses_actual = (
battery_fast.charge_energy(
None, hour, charge_factor=effective_charge_factor
)
)
# DC energy entering the battery (before battery internal efficiency)
dc_energy = battery_charged_energy_actual + battery_losses_actual
# AC energy consumed from grid (accounts for AC→DC conversion loss)
ac_energy = dc_energy / ac_to_dc_eff_fast
# Genetic0Inverter AC→DC conversion losses
inverter_charge_losses = ac_energy - dc_energy
consumption += ac_energy
energy_consumption_grid_actual += ac_energy
losses_wh_per_hour[hour_idx] += (
battery_losses_actual + inverter_charge_losses
)
# Update hourly arrays
feedin_energy_per_hour[hour_idx] = energy_feedin_grid_actual
consumption_energy_per_hour[hour_idx] = energy_consumption_grid_actual
losses_wh_per_hour[hour_idx] += losses
loads_energy_per_hour[hour_idx] = consumption
hourly_electricity_price = elect_price_hourly_fast[hour]
electricity_price_per_hour[hour_idx] = hourly_electricity_price
# Financial calculations
costs_per_hour[hour_idx] = energy_consumption_grid_actual * hourly_electricity_price
revenue_per_hour[hour_idx] = (
energy_feedin_grid_actual * elect_revenue_per_hour_arr_fast[hour]
)
total_cost = np.nansum(costs_per_hour)
total_losses = np.nansum(losses_wh_per_hour)
total_revenue = np.nansum(revenue_per_hour)
# Prepare output dictionary
return {
"Last_Wh_pro_Stunde": loads_energy_per_hour,
"Netzeinspeisung_Wh_pro_Stunde": feedin_energy_per_hour,
"Netzbezug_Wh_pro_Stunde": consumption_energy_per_hour,
"Kosten_Euro_pro_Stunde": costs_per_hour,
"akku_soc_pro_stunde": soc_per_hour,
"Einnahmen_Euro_pro_Stunde": revenue_per_hour,
"Gesamtbilanz_Euro": total_cost - total_revenue, # Fitness score ("FitnessMin")
"EAuto_SoC_pro_Stunde": soc_ev_per_hour,
"Gesamteinnahmen_Euro": total_revenue,
"Gesamtkosten_Euro": total_cost,
"Verluste_Pro_Stunde": losses_wh_per_hour,
"Gesamt_Verluste": total_losses,
"Home_appliance_wh_per_hour": home_appliance_wh_per_hour,
"Electricity_price": electricity_price_per_hour,
}
File diff suppressed because it is too large Load Diff
@@ -1,3 +1,5 @@
"""PDF report of a GENETIC0 run, drawn from its optimization parameters and result."""
import json
import textwrap
from collections.abc import Sequence
@@ -8,11 +10,10 @@ import matplotlib
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import pendulum
from matplotlib.backends.backend_pdf import PdfPages
from akkudoktoreos.core.coreabc import ConfigMixin, get_ems
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
from akkudoktoreos.optimization.genetic0.genetic0parameters import Genetic0Parameters
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
matplotlib.use(
@@ -23,11 +24,19 @@ matplotlib.use(
debug_visualize: bool = False
class Genetic0VisualizationReport(ConfigMixin):
class Genetic0VisualizationReport:
def __init__(
self,
version: str = "0.0.1",
timezone: Optional[str] = None,
) -> None:
"""Create an empty report.
Args:
version: Version shown in the report.
timezone: Time zone of the charts' hours; ``None`` is the local time zone.
"""
self.timezone = timezone
# Initialize the report with empty groups
self.groups: list[list[Callable[[], None]]] = [] # Store groups of charts
self.current_group: list[
@@ -39,9 +48,7 @@ class Genetic0VisualizationReport(ConfigMixin):
self.pdf_pages: PdfPages | None = None
self.version = version # overwrite version as test for constant output of pdf for test
self.current_time = to_datetime(
as_string="YYYY-MM-DD HH:mm:ss", in_timezone=self.config.general.timezone
)
self.current_time = to_datetime(as_string="YYYY-MM-DD HH:mm:ss", in_timezone=self.timezone)
def add_chart_to_group(self, chart_func: Callable[[], None], title: str | None) -> None:
"""Add a chart function to the current group and save it as a PNG and SVG."""
@@ -150,18 +157,14 @@ class Genetic0VisualizationReport(ConfigMixin):
# Format the time axis
plt.gca().xaxis.set_major_formatter(
mdates.DateFormatter("%Y-%m-%d", tz=self.config.general.timezone)
mdates.DateFormatter("%Y-%m-%d", tz=self.timezone)
) # Show date and time
plt.gca().xaxis.set_major_locator(
mdates.DayLocator(interval=1, tz=self.config.general.timezone)
mdates.DayLocator(interval=1, tz=self.timezone)
) # Major ticks every day
plt.gca().xaxis.set_minor_locator(
mdates.HourLocator(interval=2, tz=self.config.general.timezone)
)
plt.gca().xaxis.set_minor_locator(mdates.HourLocator(interval=2, tz=self.timezone))
# Minor ticks every 6 hours
plt.gca().xaxis.set_minor_formatter(
mdates.DateFormatter("%H", tz=self.config.general.timezone)
)
plt.gca().xaxis.set_minor_formatter(mdates.DateFormatter("%H", tz=self.timezone))
# plt.gcf().autofmt_xdate(rotation=45, which="major")
# Auto-format the x-axis for readability
@@ -180,7 +183,7 @@ class Genetic0VisualizationReport(ConfigMixin):
plt.grid(True)
# Add vertical line for the current date if within the axis range
current_time = pendulum.now(self.config.general.timezone)
current_time = to_datetime(in_timezone=self.timezone)
if timestamps[0].subtract(hours=2) <= current_time <= timestamps[-1]:
plt.axvline(mdates.date2num(current_time), color="r", linestyle="--", label="Now")
plt.text(
@@ -202,11 +205,11 @@ class Genetic0VisualizationReport(ConfigMixin):
# ax2.set_xticks(timestamps[::48]) # Set ticks every 12 hours
# ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[::48]])
# ax2.set_xticks(timestamps[:: len(timestamps) // 24]) # Select 10 evenly spaced ticks
ax2.set_xticks(
mdates.date2num(timestamps[:: len(timestamps) // 12])
) # Select 10 evenly spaced ticks
# About 12 ticks; every timestamp when there are fewer than 24.
tick_step = max(1, len(timestamps) // 12)
ax2.set_xticks(mdates.date2num(timestamps[::tick_step]))
# ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[:: len(timestamps) // 24]])
ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[:: len(timestamps) // 12]])
ax2.set_xticklabels([f"{int(h)}" for h in hours_since_start[::tick_step]])
if x2label:
ax2.set_xlabel(x2label)
@@ -451,18 +454,28 @@ class Genetic0VisualizationReport(ConfigMixin):
def genetic0_prepare_visualize(
solution: Genetic0Solution,
parameters: Genetic0Parameters,
solution: Genetic0Result,
) -> bytes:
"""Render the PDF report of a run.
Args:
parameters: The optimization parameters of the run; give the start and the time zone.
solution: The result of the run.
Returns:
The PDF document.
"""
global debug_visualize
report = Genetic0VisualizationReport()
next_full_hour_date = get_ems().start_datetime
report = Genetic0VisualizationReport(timezone=parameters.presentation.timezone)
next_full_hour_date = parameters.presentation.start_datetime
start_hour = solution.start_hour
# Group 1:
report.create_line_chart_date(
next_full_hour_date,
[
solution.parameters.ems.total_load[start_hour:],
parameters.request.ems.total_load[start_hour:],
],
title="Load Profile",
# xlabel="Hours", # not enough space
@@ -472,7 +485,7 @@ def genetic0_prepare_visualize(
report.create_line_chart_date(
next_full_hour_date,
[
solution.parameters.ems.pv_forecast_wh[start_hour:],
parameters.request.ems.pv_forecast_wh[start_hour:],
],
title="PV Forecast",
# xlabel="Hours", # not enough space
@@ -483,10 +496,10 @@ def genetic0_prepare_visualize(
next_full_hour_date,
[
np.full(
len(solution.parameters.ems.total_load) - start_hour,
solution.parameters.ems.feed_in_tariff_per_wh[start_hour:]
if isinstance(solution.parameters.ems.feed_in_tariff_per_wh, list)
else solution.parameters.ems.feed_in_tariff_per_wh,
len(parameters.request.ems.total_load) - start_hour,
parameters.request.ems.feed_in_tariff_per_wh[start_hour:]
if isinstance(parameters.request.ems.feed_in_tariff_per_wh, list)
else parameters.request.ems.feed_in_tariff_per_wh,
)
],
title="Remuneration",
@@ -494,11 +507,11 @@ def genetic0_prepare_visualize(
ylabel="amount/Wh",
x2label=None, # not enough space
)
if solution.parameters.temperature_forecast:
if parameters.request.temperature_forecast:
report.create_line_chart_date(
next_full_hour_date,
[
solution.parameters.temperature_forecast[start_hour:],
parameters.request.temperature_forecast[start_hour:],
],
title="Temperature Forecast",
# xlabel="Hours", # not enough space
@@ -547,21 +560,18 @@ def genetic0_prepare_visualize(
)
report.create_line_chart_date(
start_date=next_full_hour_date, # start_date
y_list=[solution.parameters.ems.electricity_price_per_wh[start_hour:]],
y_list=[parameters.request.ems.electricity_price_per_wh[start_hour:]],
# title="Electricity Price", # not enough space
# xlabel="Date", # not enough space
ylabel="Electricity Price (amount/Wh)",
x2label=None, # not enough space
)
labels = list(
item
for sublist in zip(
list(str(i) for i in range(0, 23, 2)), list(str(" ") for i in range(0, 23, 2))
)
for item in sublist
)
labels = labels[start_hour:] + labels
# One label per shown hour: the hour of the day for even hours, blank for odd ones.
labels = [
str(hour % 24) if hour % 2 == 0 else " "
for hour in range(start_hour, start_hour + len(solution.ac_charge[start_hour:]))
]
report.create_bar_chart(
labels=labels,
@@ -801,7 +811,7 @@ def genetic0_generate_example_report(filename: str = "example_report.pdf") -> No
report.finalize_group()
report.create_line_chart_date(
pendulum.now().subtract(hours=0),
to_datetime().subtract(hours=0),
[list(np.random.random(840))],
title="test",
xlabel="test",
@@ -9,7 +9,7 @@ from akkudoktoreos.core.pydantic import (
PydanticBaseModel,
PydanticDateTimeDataFrame,
)
from akkudoktoreos.optimization.genetic0.genetic0settings import Genetic0CommonSettings
from akkudoktoreos.optimization.genetic0 import Genetic0Settings
from akkudoktoreos.optimization.genetic.geneticsettings import (
GeneticCommonSettings,
normalize_genetic_settings,
@@ -59,8 +59,8 @@ class OptimizationCommonSettings(SettingsBaseModel):
},
)
genetic0: Genetic0CommonSettings = Field(
default_factory=Genetic0CommonSettings,
genetic0: Genetic0Settings = Field(
default_factory=Genetic0Settings,
json_schema_extra={
"description": "GENETIC0 optimization algorithm configuration.",
"examples": [{"individuals": 400, "seed": None, "penalties": {"ev_soc_miss": 10}}],
+155
View File
@@ -0,0 +1,155 @@
"""The interface every optimizer implements (ADR 0006).
The energy management drives an optimizer only through this interface and the optimizer
registry (ADR 0005): it prepares the optimization parameters once, runs the optimizer on them and
converts the result into the optimization solution and the energy management plan.
"""
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import Any, Generic, Optional, Protocol, TypeVar
from fastapi import APIRouter
from akkudoktoreos.core.emplan import EnergyManagementPlan
from akkudoktoreos.optimization.optimization import OptimizationSolution
from akkudoktoreos.utils.datetimeutil import DateTime
ParametersT = TypeVar("ParametersT")
RequestT_contra = TypeVar("RequestT_contra", contravariant=True)
ResultT = TypeVar("ResultT")
class Optimizer(Protocol[ParametersT, RequestT_contra, ResultT]):
"""An optimizer, driven by the energy management.
``ParametersT`` are the optimizer's optimization parameters, ``RequestT_contra`` its optimization
request from clients and ``ResultT`` its optimization result.
"""
name: str
async def prepare(
self,
start_datetime: DateTime,
observation_datetime: DateTime,
warm_start: Optional[ResultT],
overrides: Optional[Mapping[str, Any]] = None,
) -> ParametersT:
"""Prepare the optimization parameters from configuration, predictions and measurements.
Args:
start_datetime: Start of the optimization run.
observation_datetime: Moment of the run that measurements refer to (the start is
this moment rounded down to the optimizer's slot).
warm_start: Result of the optimizer's previous run, if any.
overrides: Run-time overrides of settings (e.g. ``{"generations": 10}``). Keys the
optimizer does not know are logged as errors and ignored.
Returns:
Complete optimization parameters for one run.
"""
...
async def prepare_from_request(
self,
request: RequestT_contra,
start_datetime: DateTime,
observation_datetime: DateTime,
warm_start: Optional[ResultT],
overrides: Optional[Mapping[str, Any]] = None,
) -> ParametersT:
"""Complete a client's optimization request into optimization parameters.
Args:
request: The optimization request of a client.
start_datetime: Start of the optimization run.
observation_datetime: Moment of the run that measurements refer to.
warm_start: Result of the optimizer's previous run, if any.
overrides: Run-time overrides of settings, as for ``prepare()``.
Returns:
Complete optimization parameters for one run.
"""
...
def run(self, parameters: ParametersT) -> ResultT:
"""Run the optimization; CPU-bound and deterministic for the same parameters.
Args:
parameters: The optimization parameters of this run.
Returns:
The optimization result.
"""
...
def api(self) -> Optional["OptimizerApi"]:
"""The optimizer's REST API, if it has one (ADR 0005, 0011).
Returns:
The router and its placeholder dependencies, which the server fills.
"""
...
async def convert(
self, parameters: ParametersT, result: ResultT
) -> tuple[OptimizationSolution, EnergyManagementPlan]:
"""Convert the result of a run into the optimization solution and the plan.
Args:
parameters: The optimization parameters of the run.
result: The optimization result of the run.
Returns:
The optimization solution and the energy management plan.
"""
...
@dataclass(frozen=True, slots=True)
class OptimizerRun(Generic[ParametersT, ResultT]):
"""The optimization parameters and the result of an optimizer's latest run."""
parameters: ParametersT
result: ResultT
# Starts an optimization run of one optimizer: (request, overrides, start datetime) -> result.
RunTrigger = Callable[..., Any]
@dataclass(frozen=True, slots=True)
class OptimizerApi:
"""The REST API an optimizer contributes (ADR 0005, 0011).
The router fetches nothing itself. The server includes it and fills the placeholder
dependencies through ``app.dependency_overrides``:
Attributes:
router: The optimizer's endpoints.
last_run: Placeholder dependency that gives the optimizer's latest ``OptimizerRun`` or
None.
run: Placeholder dependency that gives a ``RunTrigger`` starting a run of the optimizer.
"""
router: APIRouter
last_run: Callable[[], Optional[OptimizerRun[Any, Any]]]
run: Callable[[], RunTrigger]
@dataclass(slots=True)
class OptimizerProblem(Exception):
"""An error of an optimizer endpoint, returned as RFC 7807 Problem Details by the server.
Same fields as the server's ``EOSProblem``; optimizers do not import the server (ADR 0011).
"""
status: int
title: str
detail: str
type: str = "about:blank"
cause: Optional[Exception] = None
def __str__(self) -> str:
return self.detail
@@ -0,0 +1,53 @@
"""The registry of optimizers (ADR 0005).
The energy management, the server and EOSdash find an optimizer only here, by its name (the
value of ``optimization.algorithm``). Optimizers are imported on first use, so a server that runs
one optimizer never loads another.
"""
from collections.abc import Callable
from typing import Any, Optional
from akkudoktoreos.optimization.optimizer import Optimizer
def _genetic0() -> Optimizer[Any, Any, Any]:
from akkudoktoreos.optimization.genetic0 import Genetic0Optimizer
return Genetic0Optimizer()
# Optimizer name -> factory. GENETIC joins when it is migrated.
_FACTORIES: dict[str, Callable[[], Optimizer[Any, Any, Any]]] = {
"GENETIC0": _genetic0,
}
_optimizers: dict[str, Optimizer[Any, Any, Any]] = {}
def get_optimizer(name: str) -> Optional[Optimizer[Any, Any, Any]]:
"""Return the optimizer registered under ``name``.
Args:
name: The optimizer's name, e.g. ``"GENETIC0"``.
Returns:
The optimizer, or ``None`` if no optimizer is registered under that name.
"""
optimizer = _optimizers.get(name)
if optimizer is None:
factory = _FACTORIES.get(name)
if factory is None:
return None
optimizer = factory()
_optimizers[name] = optimizer
return optimizer
def optimizer_names() -> list[str]:
"""Names of all registered optimizers.
Returns:
The names, e.g. ``["GENETIC0"]``.
"""
return list(_FACTORIES)
+32 -93
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import asyncio
import functools
import json
import os
import signal
@@ -56,19 +57,14 @@ from akkudoktoreos.core.types import (
)
from akkudoktoreos.core.version import __version__
from akkudoktoreos.devices.devices import ResourceKey
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0OptimizationParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0solution import (
Genetic0Solution,
Genetic0SolutionLegacy,
)
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
from akkudoktoreos.optimization.optimization import (
OptimizationAlgorithm,
OptimizationSolution,
)
from akkudoktoreos.optimization.optimizer import OptimizerRun, RunTrigger
from akkudoktoreos.optimization.optimizerregistry import get_optimizer, optimizer_names
from akkudoktoreos.prediction.elecprice import ElecPriceCommonSettings
from akkudoktoreos.prediction.load import LoadCommonSettings
from akkudoktoreos.prediction.loadakkudoktor import LoadAkkudoktorCommonSettings
@@ -275,6 +271,31 @@ app.include_router(measurement_router)
app.include_router(profile_router)
app.include_router(pvadaptive_router)
def _optimizer_last_run(name: str) -> Optional[OptimizerRun[Any, Any]]:
"""The latest run of the optimizer ``name``; fills its ``last_run`` placeholder."""
return get_ems().optimizer_run(name)
def _optimizer_run_trigger(name: str) -> RunTrigger:
"""Starts a run of the optimizer ``name``; fills its ``run`` placeholder."""
return functools.partial(
get_ems().run,
mode=EnergyManagementMode.OPTIMIZATION,
algorithm=OptimizationAlgorithm(name),
)
# Optimizers contribute their own endpoints (ADR 0005, 0011). They are included before the
# server's routes, so an optimizer's specific path takes precedence over a generic one.
for _name in optimizer_names():
_optimizer = get_optimizer(_name)
_api = None if _optimizer is None else _optimizer.api()
if _api is not None:
app.include_router(_api.router)
app.dependency_overrides[_api.last_run] = functools.partial(_optimizer_last_run, _name)
app.dependency_overrides[_api.run] = functools.partial(_optimizer_run_trigger, _name)
register_problem_handlers(app)
@@ -1851,13 +1872,15 @@ def fastapi_energy_management_optimization_solution_get() -> OptimizationSolutio
@app.get("/v1/energy-management/optimization/solution/{algorithm}", tags=["energy-management"])
async def fastapi_energy_management_optimization_solution_algorithm_get(
algorithm: OptimizationAlgorithm,
) -> Union[GeneticSolution, Genetic0Solution]:
) -> GeneticSolution:
"""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
"""
solution: Optional[Union[GeneticSolution, Genetic0Solution]] = None
solution: Optional[GeneticSolution] = None
if algorithm not in get_config().optimization.algorithms:
raise EOSProblem(
@@ -1868,8 +1891,6 @@ async def fastapi_energy_management_optimization_solution_algorithm_get(
if algorithm == OptimizationAlgorithm.GENETIC:
solution = get_ems().genetic_solution()
elif algorithm == OptimizationAlgorithm.GENETIC0:
solution = get_ems().genetic0_solution()
if solution is None:
raise EOSProblem(
@@ -2266,88 +2287,6 @@ async def fastapi_optimize_config(
return solution
@app.post("/optimize", tags=["optimize"])
async def fastapi_optimize(
parameters: Genetic0OptimizationParameters,
start_hour: Annotated[
Optional[int], Query(description="Defaults to current hour of the day.")
] = None,
ngen: Annotated[
Optional[int], Query(description="Number of indivuals to generate for genetic algorithm.")
] = None,
) -> Genetic0SolutionLegacy:
"""Deprecated: Optimize.
Endpoint to handle optimization.
Uses the `classic` GENETIC0 optimisation algorithm (__NO__ 15-minutes slots).
Note:
Use automatic optimization instead.
"v1/energy-management/optimization/solution/GENETIC0"
"""
if start_hour is None:
start_datetime = None
else:
start_datetime = to_datetime().set(hour=start_hour)
# Ensure there is only one optimization/ energy management run at a time
solution = await get_ems().run(
start_datetime=start_datetime,
mode=EnergyManagementMode.OPTIMIZATION,
algorithm=OptimizationAlgorithm.GENETIC0,
genetic0_parameters=parameters,
genetic0_generations=ngen,
)
if solution is None:
raise EOSProblem(
status=404,
title="Optimization solution retrieval failed",
detail="Can not get the 'GENETIC0' optimization solution.",
)
# Create compatible solution.
legacy_solution = Genetic0SolutionLegacy.model_validate(
{
"ac_charge": solution.ac_charge,
"dc_charge": solution.dc_charge,
"discharge_allowed": solution.discharge_allowed,
"ev_charge_hours_float": solution.ev_charge_hours_float,
"result": solution.result,
"ev_obj": solution.ev_obj,
"start_solution": solution.start_solution,
"washingstart": solution.washingstart,
}
)
return legacy_solution
@app.get("/visualization_results.pdf", tags=["optimize"])
def get_pdf() -> Response:
# Endpoint to serve the generated PDF with visualization results
genetic0_solution = get_ems().genetic0_solution()
if genetic0_solution is None:
raise EOSProblem(
status=404,
title="Optimization solution report retrieval failed",
detail="Can not get the 'GENETIC0' optimization solution.",
)
# matplotlib is only needed for the PDF report; import it on first use.
from akkudoktoreos.optimization.genetic0.genetic0visualize import (
genetic0_prepare_visualize,
)
pdf = genetic0_prepare_visualize(solution=genetic0_solution)
return Response(
content=pdf,
media_type="application/pdf",
headers={"Content-Disposition": 'inline; filename="optimization-report.pdf"'},
)
@app.get("/site-map", include_in_schema=False)
def site_map() -> RedirectResponse:
return RedirectResponse(url="/docs")
+4
View File
@@ -7,6 +7,8 @@ from fastapi.exceptions import HTTPException, RequestValidationError
from fastapi.responses import JSONResponse
from loguru import logger
from akkudoktoreos.optimization.optimizer import OptimizerProblem
@dataclass(slots=True)
class EOSProblem(Exception):
@@ -101,6 +103,8 @@ async def validation_handler(request: Request, exc: Exception) -> JSONResponse:
def register_problem_handlers(app: FastAPI) -> None:
app.add_exception_handler(EOSProblem, eos_problem_handler)
# Errors of optimizer endpoints carry the same fields (ADR 0011).
app.add_exception_handler(OptimizerProblem, eos_problem_handler)
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(Exception, unexpected_exception_handler)
app.add_exception_handler(RequestValidationError, validation_handler)
+10 -11
View File
@@ -14,8 +14,8 @@ from loguru import logger
from akkudoktoreos.core.coreabc import get_config, get_ems, get_prediction
from akkudoktoreos.core.emsettings import EnergyManagementMode
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0OptimizationParameters,
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0Request,
)
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -25,7 +25,7 @@ prediction_eos = get_prediction()
ems_eos = get_ems()
async def prepare_optimization_real_parameters() -> Genetic0OptimizationParameters:
async def prepare_optimization_real_parameters() -> Genetic0Request:
"""Prepare and return optimization parameters with real world data.
Returns:
@@ -170,7 +170,7 @@ async def prepare_optimization_real_parameters() -> Genetic0OptimizationParamete
print(f"start_solution: {start_solution}")
# Define parameters for the optimization problem
return Genetic0OptimizationParameters.model_validate({
return Genetic0Request.model_validate({
"ems": {
"price_per_wh_battery": 0e-05,
"feed_in_tariff_per_wh": 7e-05,
@@ -202,7 +202,7 @@ async def prepare_optimization_real_parameters() -> Genetic0OptimizationParamete
})
def prepare_optimization_parameters() -> Genetic0OptimizationParameters:
def prepare_optimization_parameters() -> Genetic0Request:
"""Prepare and return optimization parameters with predefined data.
Returns:
@@ -364,7 +364,7 @@ def prepare_optimization_parameters() -> Genetic0OptimizationParameters:
start_solution = None
# Define parameters for the optimization problem
return Genetic0OptimizationParameters.model_validate({
return Genetic0Request.model_validate({
"ems": {
"price_per_wh_battery": 0e-05,
"feed_in_tariff_per_wh": 7e-05,
@@ -411,7 +411,7 @@ def run_optimization(
# Prepare parameters
if parameters_file:
with open(parameters_file, "r") as f:
parameters = Genetic0OptimizationParameters(**json.load(f))
parameters = Genetic0Request(**json.load(f))
elif real_world:
parameters = asyncio.run(prepare_optimization_real_parameters())
else:
@@ -429,13 +429,12 @@ def run_optimization(
start_datetime=start_datetime,
mode=EnergyManagementMode.OPTIMIZATION,
algorithm=OptimizationAlgorithm.GENETIC0,
genetic0_parameters=parameters,
genetic0_generations=ngen,
genetic0_seed=seed,
request=parameters,
overrides={"generations": ngen, "seed": seed},
)
)
solution = ems_eos.genetic0_solution()
solution = ems_eos.optimizer_result(OptimizationAlgorithm.GENETIC0)
if solution is None:
return None
return solution.model_dump_json()
+33 -15
View File
@@ -76,6 +76,24 @@ PARAMETER_METHODS = [
"to_genetic0_ev_bat_param",
]
# GENETIC0's conversions live in its parameter preparation (ADR 0004), not in the settings.
GENETIC0_CONVERSIONS = {
"to_genetic0_pv_bat_param": "battery_request",
"to_genetic0_ev_bat_param": "electric_vehicle_request",
}
def converter(settings, method):
"""The conversion ``method`` of the settings, or GENETIC0's function for them."""
if method in GENETIC0_CONVERSIONS:
from akkudoktoreos.optimization.genetic0 import genetic0prepare
function = getattr(genetic0prepare, GENETIC0_CONVERSIONS[method])
return lambda *args, **kwargs: function(settings, *args, **kwargs)
return getattr(settings, method)
COMPUTED_FIELDS = [
"effective_nominal_capacity_wh",
"effective_max_charge_power_w",
@@ -876,7 +894,7 @@ class TestGetBatteryProfile:
):
settings = make_settings(battery_profile="does-not-exist")
with pytest.raises(BatteryResolutionError, match="does-not-exist"):
getattr(settings, method)()
converter(settings, method)()
# --- Maximum charge power -------------------------------------------------------
@@ -951,7 +969,7 @@ class TestMaxChargePower:
parameters = await current(settings)
assert parameters.max_charge_power_w == 0.0
assert settings.to_genetic_pv_bat_param(parameters).max_charge_power_w == 0.0
assert settings.to_genetic0_pv_bat_param(parameters).max_charge_power_w == 0.0
assert converter(settings, "to_genetic0_pv_bat_param")(parameters).max_charge_power_w == 0.0
def test_zero_charge_power_yields_zero(self, make_profiled_settings):
settings = make_profiled_settings(make_profile(charge=0.0), capacity_wh=10000)
@@ -1311,7 +1329,7 @@ class TestOptimizationParameters:
@pytest.mark.parametrize("method", PARAMETER_METHODS)
def test_values_come_from_profile(self, make_profiled_settings, full_profile, method):
settings = make_profiled_settings(full_profile, capacity_wh=10000)
params = getattr(settings, method)()
params = converter(settings, method)()
assert params.device_id == "battery1"
assert params.capacity_wh == 10000
assert params.max_charge_power_w == pytest.approx(5000.0)
@@ -1323,7 +1341,7 @@ class TestOptimizationParameters:
@pytest.mark.parametrize("method", PARAMETER_METHODS)
def test_parameters_match_computed_fields(self, make_profiled_settings, full_profile, method):
settings = make_profiled_settings(full_profile, capacity_wh=10000)
params = getattr(settings, method)()
params = converter(settings, method)()
assert params.capacity_wh == settings.effective_nominal_capacity_wh
assert params.charging_efficiency == pytest.approx(settings.effective_charging_efficiency)
assert params.discharging_efficiency == pytest.approx(settings.effective_discharging_efficiency)
@@ -1340,7 +1358,7 @@ class TestOptimizationParameters:
grid[ROW_0_DEGC] = [0.1] * 10
settings = make_profiled_settings(make_profile(charge=grid), capacity_wh=10000)
measurements["battery1-temperature-degc"] = 0.0
params = getattr(settings, method)(await current(settings))
params = converter(settings, method)(await current(settings))
assert params.max_charge_power_w == pytest.approx(1000.0)
@pytest.mark.parametrize("method", PARAMETER_METHODS)
@@ -1351,7 +1369,7 @@ class TestOptimizationParameters:
measurements["battery1-charge-power-w"] = 2500.0
measurements["battery1-discharge-power-w"] = 2000.0
settings = make_profiled_settings(full_profile, capacity_wh=10000)
params = getattr(settings, method)(await current(settings))
params = converter(settings, method)(await current(settings))
assert params.charging_efficiency == pytest.approx(0.9225)
assert params.discharging_efficiency == pytest.approx(0.9125)
@@ -1362,7 +1380,7 @@ class TestOptimizationParameters:
grid = make_grid(0.5)
grid[ROW_0_DEGC] = [0.1] * 10
settings = make_profiled_settings(make_profile(charge=grid), capacity_wh=10000)
assert getattr(settings, method)().max_charge_power_w == pytest.approx(5000.0)
assert converter(settings, method)().max_charge_power_w == pytest.approx(5000.0)
assert measurement_calls == []
@pytest.mark.parametrize("method", PARAMETER_METHODS)
@@ -1371,7 +1389,7 @@ class TestOptimizationParameters:
snapshot = settings.resolve_operating_parameters(
BatteryOperatingPoint(charge_power_w=2500.0)
)
params = getattr(settings, method)(snapshot)
params = converter(settings, method)(snapshot)
assert params.capacity_wh == snapshot.capacity_wh
assert params.charging_efficiency == pytest.approx(snapshot.charging_efficiency)
assert params.max_charge_power_w == pytest.approx(snapshot.max_charge_power_w)
@@ -1381,7 +1399,7 @@ class TestOptimizationParameters:
self, make_profiled_settings, method
):
profile = make_profile(charge=0.5, nominal_capacity_wh=8000.0)
params = getattr(make_profiled_settings(profile), method)()
params = converter(make_profiled_settings(profile), method)()
assert params.capacity_wh == 8000
assert params.max_charge_power_w == pytest.approx(4000.0)
@@ -1390,7 +1408,7 @@ class TestOptimizationParameters:
settings = make_profiled_settings(
full_profile, capacity_wh=10000, charge_limit_w=2000.0
)
assert getattr(settings, method)().max_charge_power_w == pytest.approx(2000.0)
assert converter(settings, method)().max_charge_power_w == pytest.approx(2000.0)
@pytest.mark.parametrize("method", PARAMETER_METHODS)
def test_user_soc_range_is_clamped_into_technical_bounds(
@@ -1399,7 +1417,7 @@ class TestOptimizationParameters:
settings = make_profiled_settings(
full_profile, capacity_wh=10000, min_soc_percentage=10, max_soc_percentage=90
)
params = getattr(settings, method)()
params = converter(settings, method)()
assert params.min_soc_percentage == 10
assert params.max_soc_percentage == 90
@@ -1408,7 +1426,7 @@ class TestOptimizationParameters:
"""The optimization gets valid parameters that do not allow charging."""
profile = make_profile(hard_cutoffs=charge_inhibited_below_30())
settings = make_profiled_settings(profile, capacity_wh=10000)
assert getattr(settings, method)().max_charge_power_w == 0.0
assert converter(settings, method)().max_charge_power_w == 0.0
def test_genetic_pv_receives_storage_cost(self):
params = make_settings(levelized_cost_of_storage_amt_kwh=0.12).to_genetic_pv_bat_param()
@@ -1809,13 +1827,13 @@ class TestOptimizationDefaults:
settings = make_settings(capacity_wh=10000)
parameters, use_tables = settings.resolve_operating_parameters_or_defaults()
assert use_tables is True
expected = getattr(settings, method)(parameters, use_tables)
expected = converter(settings, method)(parameters, use_tables)
def missing(document_type, name, **options):
raise FileNotFoundError(f"No battery profile for '{name}'")
monkeypatch.setattr(get_profile_store(), "get", missing)
converted = getattr(settings, method)(parameters, use_tables)
converted = converter(settings, method)(parameters, use_tables)
assert converted.model_dump() == expected.model_dump()
def test_inhibited_charging_is_no_configuration_error(
@@ -1850,7 +1868,7 @@ class TestOptimizationDefaults:
def test_conversion_without_profile_tables(self, broken_profile_loader, method):
settings = make_settings(battery_profile="does-not-exist")
parameters, use_tables = settings.resolve_operating_parameters_or_defaults(report=False)
converted = getattr(settings, method)(parameters, use_tables)
converted = converter(settings, method)(parameters, use_tables)
assert converted.capacity_wh == 8000
assert converted.max_charge_power_w == pytest.approx(5000.0)
assert converted.charge_power_limit_w_by_soc is None
+2 -1
View File
@@ -23,6 +23,7 @@ from akkudoktoreos.devices.settings.invertersettings import (
InverterCommonSettings,
InverterProfileAdjustment,
)
from akkudoktoreos.optimization.genetic0 import genetic0prepare
def make_settings(**adjustment: Any) -> InverterCommonSettings:
@@ -245,7 +246,7 @@ class TestConversion:
def test_genetic0_parameters(self, generic):
settings = make_settings(nominal_power_w=10000)
genetic0 = settings.to_genetic0_param()
genetic0 = genetic0prepare.inverter_request(settings)
assert genetic0.max_power_wh == pytest.approx(10000)
assert genetic0.dc_to_ac_efficiency == pytest.approx(settings.effective_dc_to_ac_efficiency)
assert genetic0.ac_to_dc_efficiency == pytest.approx(settings.effective_ac_to_dc_efficiency)
+11 -11
View File
@@ -1,9 +1,9 @@
import numpy as np
import pytest
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0Battery,
Genetic0SolarPanelBatteryParameters,
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import Genetic0Battery
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0SolarPanelBatteryRequest,
)
@@ -19,7 +19,7 @@ def setup_pv_battery():
max_charge_power_w=8000
hours=24
params = Genetic0SolarPanelBatteryParameters(
params = Genetic0SolarPanelBatteryRequest(
device_id=device_id,
capacity_wh=capacity_wh,
initial_soc_percentage=initial_soc_percentage,
@@ -31,7 +31,7 @@ def setup_pv_battery():
hours=hours,
)
battery = Genetic0Battery(
params,
params.to_parameters(),
prediction_hours=48,
)
battery.reset()
@@ -260,11 +260,11 @@ def test_charge_energy_with_charge_factor(setup_pv_battery, wh, charge_factor, e
@pytest.fixture
def setup_car_battery():
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0ElectricVehicleParameters,
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0ElectricVehicleRequest,
)
params = Genetic0ElectricVehicleParameters(
params = Genetic0ElectricVehicleRequest(
device_id="ev1",
capacity_wh=40000,
initial_soc_percentage=60,
@@ -274,7 +274,7 @@ def setup_car_battery():
hours=24,
)
battery = Genetic0Battery(
params,
params.to_parameters(),
prediction_hours=48,
)
battery.reset()
@@ -314,7 +314,7 @@ def test_car_and_pv_battery_discharge_and_max_charge_power(setup_pv_battery, set
def _battery_with_limits(max_charge_power_w, max_discharge_power_w=None) -> Genetic0Battery:
params = Genetic0SolarPanelBatteryParameters(
params = Genetic0SolarPanelBatteryRequest(
device_id="battery1",
capacity_wh=10000,
initial_soc_percentage=50,
@@ -323,7 +323,7 @@ def _battery_with_limits(max_charge_power_w, max_discharge_power_w=None) -> Gene
max_charge_power_w=max_charge_power_w,
max_discharge_power_w=max_discharge_power_w,
)
battery = Genetic0Battery(params, prediction_hours=24)
battery = Genetic0Battery(params.to_parameters(), prediction_hours=24)
battery.reset()
battery.discharge_array = np.full(battery.prediction_hours, 1)
battery.charge_array = np.full(battery.prediction_hours, 1)
+5 -5
View File
@@ -2,10 +2,10 @@ from unittest.mock import Mock, patch
import pytest
from akkudoktoreos.devices.genetic0.genetic0inverter import (
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
Genetic0Inverter,
Genetic0InverterParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0request import Genetic0InverterRequest
@pytest.fixture
@@ -22,13 +22,13 @@ def inverter(mock_battery) -> Genetic0Inverter:
mock_self_consumption_predictor = Mock()
mock_self_consumption_predictor.calculate_self_consumption.return_value = 1.0
with patch(
"akkudoktoreos.devices.genetic0.genetic0inverter.get_genetic0_load_interpolator",
"akkudoktoreos.optimization.genetic0.devices.genetic0inverter.get_genetic0_load_interpolator",
return_value=mock_self_consumption_predictor,
):
iv = Genetic0Inverter(
Genetic0InverterParameters(
Genetic0InverterRequest(
device_id="iv1", max_power_wh=500.0, battery_id=mock_battery.parameters.device_id
),
).to_parameters(),
battery = mock_battery
)
return iv
+46 -40
View File
@@ -17,18 +17,16 @@ from unittest.mock import Mock, patch
import numpy as np
import pytest
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0Battery,
Genetic0SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.genetic0.genetic0inverter import (
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import Genetic0Battery
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
Genetic0Inverter,
Genetic0InverterParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0 import (
Genetic0EnergyManagementParameters,
Genetic0Simulation,
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0EnergyManagementRequest,
Genetic0InverterRequest,
Genetic0SolarPanelBatteryRequest,
)
from akkudoktoreos.optimization.genetic0.genetic0simulation import Genetic0Simulation
# ---------------------------------------------------------------------------
# Helpers / Fixtures
@@ -46,7 +44,7 @@ def _make_inverter(
mock_self_consumption_predictor = Mock()
mock_self_consumption_predictor.calculate_self_consumption.return_value = 1.0
params = Genetic0InverterParameters(
params = Genetic0InverterRequest(
device_id="inv1",
max_power_wh=max_power_wh,
battery_id=mock_battery.parameters.device_id if mock_battery else None,
@@ -55,10 +53,10 @@ def _make_inverter(
max_ac_charge_power_w=max_ac_charge_power_w,
)
with patch(
"akkudoktoreos.devices.genetic0.genetic0inverter.get_genetic0_load_interpolator",
"akkudoktoreos.optimization.genetic0.devices.genetic0inverter.get_genetic0_load_interpolator",
return_value=mock_self_consumption_predictor,
):
return Genetic0Inverter(params, battery=mock_battery)
return Genetic0Inverter(params.to_parameters(), battery=mock_battery)
@pytest.fixture
@@ -79,13 +77,13 @@ class TestInverterParametersDefaults:
"""Verify backward-compatible defaults for new parameters."""
def test_defaults(self):
params = Genetic0InverterParameters(device_id="inv1", max_power_wh=5000)
params = Genetic0InverterRequest(device_id="inv1", max_power_wh=5000)
assert params.dc_to_ac_efficiency == 1.0
assert params.ac_to_dc_efficiency == 1.0
assert params.max_ac_charge_power_w is None
def test_custom_values(self):
params = Genetic0InverterParameters(
params = Genetic0InverterRequest(
device_id="inv1",
max_power_wh=5000,
dc_to_ac_efficiency=0.95,
@@ -97,17 +95,17 @@ class TestInverterParametersDefaults:
assert params.max_ac_charge_power_w == 3000
def test_ac_to_dc_zero_disables_ac_charging(self):
params = Genetic0InverterParameters(
params = Genetic0InverterRequest(
device_id="inv1", max_power_wh=5000, ac_to_dc_efficiency=0.0
)
assert params.ac_to_dc_efficiency == 0.0
def test_dc_to_ac_must_be_positive(self):
with pytest.raises(Exception):
Genetic0InverterParameters(device_id="inv1", max_power_wh=5000, dc_to_ac_efficiency=0.0)
Genetic0InverterRequest(device_id="inv1", max_power_wh=5000, dc_to_ac_efficiency=0.0)
def test_max_ac_charge_power_zero(self):
params = Genetic0InverterParameters(
params = Genetic0InverterRequest(
device_id="inv1", max_power_wh=5000, max_ac_charge_power_w=0
)
assert params.max_ac_charge_power_w == 0
@@ -215,9 +213,11 @@ class TestAcChargingInSimulation:
@pytest.fixture
def simulation_setup(self, config_eos):
"""Set up a minimal GeneticSimulation with battery and inverter."""
from akkudoktoreos.optimization.genetic0.genetic0 import Genetic0Simulation
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0EnergyManagementParameters,
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0EnergyManagementRequest,
)
from akkudoktoreos.optimization.genetic0.genetic0simulation import (
Genetic0Simulation,
)
config_eos.merge_settings_from_dict(
@@ -237,7 +237,7 @@ class TestAcChargingInSimulation:
battery_max_charge_power_w: int = 5000,
):
akku = Genetic0Battery(
Genetic0SolarPanelBatteryParameters(
Genetic0SolarPanelBatteryRequest(
device_id="battery1",
capacity_wh=battery_capacity_wh,
initial_soc_percentage=battery_initial_soc_pct,
@@ -246,32 +246,32 @@ class TestAcChargingInSimulation:
min_soc_percentage=0,
max_soc_percentage=100,
max_charge_power_w=battery_max_charge_power_w,
),
).to_parameters(),
prediction_hours=prediction_hours,
)
akku.reset()
inverter = Genetic0Inverter(
Genetic0InverterParameters(
Genetic0InverterRequest(
device_id="inverter1",
max_power_wh=10000,
battery_id="battery1",
ac_to_dc_efficiency=ac_to_dc_efficiency,
dc_to_ac_efficiency=dc_to_ac_efficiency,
max_ac_charge_power_w=max_ac_charge_power_w,
),
).to_parameters(),
battery=akku,
)
simulation = Genetic0Simulation()
simulation.prepare(
Genetic0EnergyManagementParameters.model_validate(dict(
Genetic0EnergyManagementRequest.model_validate(dict(
pv_prognose_wh=[0.0] * prediction_hours, # No PV
strompreis_euro_pro_wh=[0.0003] * prediction_hours, # ~30ct/kWh
einspeiseverguetung_euro_pro_wh=0.00008,
preis_euro_pro_wh_akku=0.0001,
gesamtlast=[1000.0] * prediction_hours, # 1 kW constant load
)),
)).to_parameters(),
optimization_hours=config_eos.optimization.genetic0.horizon_hours,
prediction_hours=prediction_hours,
inverter=inverter,
@@ -466,13 +466,13 @@ class TestResidualBatteryValue:
def test_current_energy_content_unaffected(self):
"""Battery.current_energy_content() is DC-only; inverter eff applied in optimizer."""
akku = Genetic0Battery(
Genetic0SolarPanelBatteryParameters(
Genetic0SolarPanelBatteryRequest(
device_id="bat1",
capacity_wh=10000,
initial_soc_percentage=50,
discharging_efficiency=0.90,
min_soc_percentage=0,
),
).to_parameters(),
prediction_hours=24,
)
akku.reset()
@@ -550,22 +550,28 @@ def _run_evaluate_with_mocked_sim(
- self.simulation is replaced by mock_sim
Then call evaluate() and return the fitness tuple.
"""
from akkudoktoreos.optimization.genetic0.genetic0 import Genetic0Optimization
config_eos.merge_settings_from_dict(
{
"prediction": {"hours": 48},
"optimization": {"hours": 24},
}
from akkudoktoreos.optimization.genetic0.genetic0algorithm import (
Genetic0Optimization,
)
config_eos.optimization.genetic0.penalties = {
"ev_soc_miss": 10,
"ac_charge_break_even": ac_charge_break_even,
}
from akkudoktoreos.optimization.genetic0.genetic0parameters import (
Genetic0RunSettings,
)
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
optim = Genetic0Optimization.__new__(Genetic0Optimization)
# Minimal __init__ state expected by evaluate()
optim.config = config_eos
optim.settings = Genetic0RunSettings(
prediction_hours=48,
horizon_hours=24,
individuals=None,
generations=None,
seed=None,
penalties={"ev_soc_miss": 10, "ac_charge_break_even": ac_charge_break_even},
ev_charge_rates=None,
battery_charge_rates=None,
self_consumption_interpolator=GridInterpolatorBackend.SCIPY,
verbose=False,
)
optim.optimize_ev = False
optim.verbose = False
optim.opti_param = {"home_appliance": 0}
+366 -50
View File
@@ -1,9 +1,15 @@
import dataclasses
import inspect
import json
import math
import re
from collections.abc import Callable
from io import BytesIO
from pathlib import Path
from typing import Any
from unittest.mock import patch
import numpy as np
import pytest
from pydantic import ValidationError
from pypdf import PdfReader
@@ -11,20 +17,184 @@ from pypdf import PdfReader
from akkudoktoreos.config.config import ConfigEOS
from akkudoktoreos.core.cache import CacheEnergyManagementStore
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic0.genetic0 import Genetic0Optimization
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0OptimizationParameters,
from akkudoktoreos.optimization.genetic0 import genetic0convert
from akkudoktoreos.optimization.genetic0.genetic0api import (
Genetic0Solution,
solution_response,
)
from akkudoktoreos.optimization.genetic0.genetic0optimizer import Genetic0Optimizer
from akkudoktoreos.optimization.genetic0.genetic0parameters import (
parameters_from_dict,
parameters_to_dict,
)
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0Request,
)
from akkudoktoreos.optimization.genetic0.genetic0result import (
Genetic0ElectricVehicleState,
Genetic0Result,
Genetic0SimulationOutput,
)
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
from akkudoktoreos.optimization.genetic0.genetic0visualize import (
Genetic0VisualizationReport,
genetic0_prepare_visualize,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
from akkudoktoreos.utils.datetimeutil import DateTime, Duration, to_datetime
ems_eos = get_ems(init=True) # init once
DIR_TESTDATA = Path(__file__).parent / "testdata" / "genetic0"
# Fixed run starts, so that the date-bearing output can be pinned (ADR 0008).
FIXED_START = "2026-01-14T10:00:00"
# The horizon crosses the switch to daylight saving time (Europe/Berlin, 2026-03-29).
DST_START = "2026-03-28T10:00:00"
# Origin of the fake prediction series: a value depends on its time, not its index.
PREDICTION_ORIGIN = "2026-01-01T00:00:00+00:00"
# The fill method the conversion asks for shifts the fake series, so it is pinned too.
FILL_METHOD_OFFSET = {"linear": 0.0, "ffill": 1000.0}
# Prediction keys the solution conversion reads; each gets its own rising series,
# so a shifted or swapped series changes the pinned output.
PREDICTION_KEYS = (
"pvforecast_ac_power",
"pvforecast_dc_power",
"elecprice_marketprice_wh",
"feed_in_tariff_wh",
"weather_temp_air",
"loadforecast_power_w",
"loadakkudoktor_std_power_w",
"loadakkudoktor_mean_power_w",
)
# Report methods whose arguments are the input of the visualization.
REPORT_METHODS = (
"create_line_chart_date",
"create_line_chart",
"create_scatter_plot",
"create_bar_chart",
"create_violin_plot",
"add_text_page",
"add_json_page",
)
# Placeholder for the wall-clock time of the conversion in IDs and timestamps.
NOW = "<now>"
# Random UUIDs, e.g. in instruction IDs ("battery1@<uuid>").
UUID_PATTERN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
class FakePrediction:
"""Deterministic predictions for the solution conversion."""
record_keys = list(PREDICTION_KEYS)
async def key_to_array(
self,
key: str,
start_datetime: DateTime,
end_datetime: DateTime,
interval: Duration,
fill_method: str,
**kwargs: Any,
) -> np.ndarray:
"""A rising series per key and fill method whose values follow the absolute time."""
step_hours = interval.total_seconds() / 3600
steps = int((end_datetime - start_datetime).total_seconds() // interval.total_seconds())
first_hour = (start_datetime - to_datetime(PREDICTION_ORIGIN)).total_seconds() / 3600
base = 10.0 * (PREDICTION_KEYS.index(key) + 1) + FILL_METHOD_OFFSET[fill_method]
return base + 0.5 * (first_hour + step_hours * np.arange(steps))
def mask_now(dump: dict[str, Any]) -> dict[str, Any]:
"""Replace the wall-clock time of the conversion in ``id`` and ``generated_at``."""
prefix, _, _ = dump["id"].partition("@")
return {**dump, "id": f"{prefix}@{NOW}", "generated_at": NOW}
def to_jsonable(value: Any) -> Any:
"""Convert the output of a run into plain JSON values for golden files."""
if isinstance(value, dict):
return {str(k): to_jsonable(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [to_jsonable(v) for v in value]
if isinstance(value, np.ndarray):
return to_jsonable(value.tolist())
if isinstance(value, np.generic):
return to_jsonable(value.item())
if isinstance(value, float) and math.isnan(value):
return None
if isinstance(value, str):
return UUID_PATTERN.sub("<uuid>", value)
if isinstance(value, (int, float, bool)) or value is None:
return value
return str(value)
def compare_jsonable(actual: Any, expected: Any, path: str = "$") -> None:
"""Compare plain JSON values; numbers approximately."""
if isinstance(expected, dict):
assert isinstance(actual, dict), path
assert set(actual) == set(expected), path
for key, value in expected.items():
compare_jsonable(actual[key], value, f"{path}.{key}")
elif isinstance(expected, list):
assert isinstance(actual, list), path
assert len(actual) == len(expected), path
for index, (a, e) in enumerate(zip(actual, expected)):
compare_jsonable(a, e, f"{path}[{index}]")
elif isinstance(expected, (int, float)) and not isinstance(expected, bool):
assert actual == pytest.approx(expected), path
else:
assert actual == expected, path
def check_golden(actual: Any, golden: str) -> None:
"""Compare ``actual`` with the golden file; write ``new_<golden>`` for review on a miss."""
actual = to_jsonable(actual)
new_file = DIR_TESTDATA / f"new_{golden}"
new_file.write_text(json.dumps(actual, indent=4) + "\n", encoding="utf-8", newline="\n")
golden_file = DIR_TESTDATA / golden
if not golden_file.exists():
pytest.fail(f"Missing golden file {golden_file}\ncp {new_file} {golden_file}\n")
compare_jsonable(actual, json.loads(golden_file.read_text(encoding="utf-8")))
new_file.unlink()
def record_report_calls() -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Spies on the report methods: the recorded calls and the patches to apply."""
calls: list[dict[str, Any]] = []
def spy(name: str, original: Callable[..., Any]) -> Callable[..., Any]:
signature = inspect.signature(original)
def method(self: Any, *args: Any, **kwargs: Any) -> Any:
# Bound by name with defaults, so the call style does not matter.
bound = signature.bind(self, *args, **kwargs)
bound.apply_defaults()
arguments = dict(bound.arguments)
arguments.pop("self")
calls.append({"method": name, "arguments": arguments})
return original(self, *args, **kwargs)
return method
patches = {
name: spy(name, getattr(Genetic0VisualizationReport, name)) for name in REPORT_METHODS
}
return calls, patches
def check_replay(parameters: Any, golden_stem: str, expected_result: str) -> None:
"""Compare the run's parameters with its replay file; write ``new_<replay>`` on a miss."""
replay = {"expected_result": expected_result, "parameters": parameters_to_dict(parameters)}
# Lossless: what is written reads back to the same values.
restored = parameters_from_dict(json.loads(json.dumps(replay["parameters"])))
assert parameters_to_dict(restored) == replay["parameters"]
check_golden(replay, f"replay_{golden_stem}.json")
def compare_dict(actual: dict[str, Any], expected: dict[str, Any]):
assert set(actual) == set(expected)
@@ -41,13 +211,35 @@ def compare_dict(actual: dict[str, Any], expected: dict[str, Any]):
@pytest.mark.asyncio
@pytest.mark.parametrize(
"fn_in, fn_out, ngen, break_even",
"fn_in, fn_out, ngen, break_even, start, golden_stem",
[
("optimize_input_1.json", "optimize_result_1.json", 3, 0),
("optimize_input_2.json", "optimize_result_2.json", 3, 0),
("optimize_input_2.json", "optimize_result_2_full.json", 400, 0),
("optimize_input_1.json", "optimize_result_1_be.json", 3, 1),
("optimize_input_2.json", "optimize_result_2_be.json", 3, 1),
("optimize_input_1.json", "optimize_result_1.json", 3, 0, FIXED_START, "optimize_result_1"),
("optimize_input_2.json", "optimize_result_2.json", 3, 0, FIXED_START, "optimize_result_2"),
(
"optimize_input_2.json",
"optimize_result_2_full.json",
400,
0,
FIXED_START,
"optimize_result_2_full",
),
(
"optimize_input_1.json",
"optimize_result_1_be.json",
3,
1,
FIXED_START,
"optimize_result_1_be",
),
(
"optimize_input_2.json",
"optimize_result_2_be.json",
3,
1,
FIXED_START,
"optimize_result_2_be",
),
("optimize_input_2.json", "optimize_result_2.json", 3, 0, DST_START, "optimize_result_2_dst"),
],
)
async def test_optimize(
@@ -55,6 +247,8 @@ async def test_optimize(
fn_out: str,
ngen: int,
break_even: int,
start: str,
golden_stem: str,
config_eos: ConfigEOS,
is_finalize: bool,
):
@@ -88,6 +282,9 @@ async def test_optimize(
"charge_rates": [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0],
}
},
# Covers the home appliance part of the solution conversion.
"max_home_appliances": 1,
"home_appliances": {"dishwasher1": {"device_id": "dishwasher1"}},
}
}
)
@@ -95,27 +292,40 @@ async def test_optimize(
# Load input and output data
parameter_file = DIR_TESTDATA / fn_in
with parameter_file.open("r") as f_in:
input_data = Genetic0OptimizationParameters(**json.load(f_in))
input_data = Genetic0Request(**json.load(f_in))
# Fake energy management run start datetime
ems_eos.set_start_datetime(to_datetime().set(hour=fixed_start_hour))
ems_eos.set_start_datetime(
to_datetime(start, in_timezone=config_eos.general.timezone)
)
assert ems_eos.start_datetime.hour == fixed_start_hour
# Throw away any cached results of the last energy management run.
CacheEnergyManagementStore().clear()
genetic0_optimization = Genetic0Optimization(fixed_seed=fixed_seed)
# Activate with pytest --finalize
if ngen > 10 and not is_finalize:
pytest.skip()
# Call the optimization function
genetic0_solution = genetic0_optimization.optimize_ems(
parameters=input_data, start_hour=fixed_start_hour, ngen=ngen
)
# Prepare the parameters through the optimizer interface, then run.
optimizer = Genetic0Optimizer()
run_start = ems_eos.start_datetime
with patch(
"akkudoktoreos.optimization.genetic0.genetic0prepare.get_prediction",
return_value=FakePrediction(),
):
parameters = await optimizer.prepare_from_request(
input_data, run_start, run_start, None, {"generations": ngen, "seed": fixed_seed}
)
result = optimizer.run(parameters)
# The public solution, as the REST API returns it, is what the golden files hold.
genetic0_solution = solution_response(parameters, result)
# The parameters of this run are the replay input of test_replay (ADR 0008).
check_replay(parameters, golden_stem, fn_out)
# Write test output to file, so we can take it as new data on intended change
TESTDATA_FILE = DIR_TESTDATA / f"new_{fn_out}"
TESTDATA_FILE = DIR_TESTDATA / f"new_{golden_stem}.json"
with TESTDATA_FILE.open("w", encoding="utf-8", newline="\n") as f_out:
f_out.write(genetic0_solution.model_dump_json(indent=4, exclude_unset=True))
@@ -149,19 +359,29 @@ async def test_optimize(
# Reproducibility and mathematical accuracy should be tested on the level of individual components.
compare_dict(genetic0_solution.model_dump(), expected_result.model_dump())
# Check the correct generic optimization solution is created
optimization_solution = await genetic0_solution.optimization_solution()
# @TODO
# Check the correct generic optimization solution is created; the prediction series were
# read from FakePrediction by the parameter preparation.
optimization_solution = await genetic0convert.optimization_solution(
parameters, result
)
check_golden(
mask_now(optimization_solution.model_dump(mode="json")),
f"{golden_stem}_optimization_solution.json",
)
# Check the correct generic energy management plan is created
plan = genetic0_solution.energy_management_plan()
# @TODO
# Check visualization works
pdf = genetic0_prepare_visualize(
solution=genetic0_solution,
plan = genetic0convert.energy_management_plan(parameters, result)
check_golden(
mask_now(plan.model_dump(mode="json")),
f"{golden_stem}_plan.json",
)
# Check visualization works, and pin what it is drawn from
report_calls, report_patches = record_report_calls()
with patch.multiple(Genetic0VisualizationReport, **report_patches):
pdf = genetic0_prepare_visualize(parameters=parameters, solution=result)
assert pdf.startswith(b"%PDF-")
check_golden(report_calls, f"{golden_stem}_visualize.json")
reader = PdfReader(BytesIO(pdf))
assert len(reader.pages) == 6
@@ -171,6 +391,41 @@ async def test_optimize(
TESTDATA_FILE.unlink()
def result_of(solution: Genetic0Solution) -> Genetic0Result:
"""The run result a public solution was built from."""
simulation = solution.result.model_dump()
output_fields = {field.name for field in dataclasses.fields(Genetic0SimulationOutput)}
ev_fields = {field.name for field in dataclasses.fields(Genetic0ElectricVehicleState)}
return Genetic0Result(
ac_charge=solution.ac_charge,
dc_charge=solution.dc_charge,
discharge_allowed=solution.discharge_allowed,
ev_charge_hours_float=solution.ev_charge_hours_float,
result=Genetic0SimulationOutput(
**{key: value for key, value in simulation.items() if key in output_fields}
),
ev_obj=(
None
if solution.ev_obj is None
else Genetic0ElectricVehicleState(
**{k: v for k, v in solution.ev_obj.model_dump().items() if k in ev_fields}
)
),
start_hour=solution.start_hour,
start_solution=solution.start_solution,
washingstart=solution.washingstart,
extra_data=solution.extra_data,
fitness_history=solution.fitness_history,
fixed_seed=solution.fixed_seed,
)
# The parameters of golden run 1 (optimize_result_1.json), from its replay file.
RUN_1 = parameters_from_dict(
json.loads((DIR_TESTDATA / "replay_optimize_result_1.json").read_text())["parameters"]
)
class TestGenetic0SocClampedOperationFactors:
"""The SOC clamping uses the optimizer battery parameters, not the settings.
@@ -179,7 +434,7 @@ class TestGenetic0SocClampedOperationFactors:
"""
@pytest.fixture
def solution(self, config_eos: ConfigEOS) -> Genetic0Solution:
def solution(self, config_eos: ConfigEOS) -> Genetic0Result:
# A configured battery whose settings differ from the solution parameters.
config_eos.merge_settings_from_dict(
{
@@ -194,17 +449,19 @@ class TestGenetic0SocClampedOperationFactors:
}
)
data = json.loads((DIR_TESTDATA / "optimize_result_1.json").read_text())
return Genetic0Solution.model_validate(data)
return result_of(Genetic0Solution.model_validate(data))
def test_uses_solution_battery_parameters(self, solution):
bat = solution.parameters.pv_battery
bat = RUN_1.request.pv_battery
assert bat is not None
assert bat.capacity_wh == 26400
# 1 % headroom of 26400 Wh against one hour at 5000 W and the charging
# efficiency of the parameters (no inverter configured).
headroom_wh = 0.01 * bat.capacity_wh
assert bat.max_charge_power_w is not None
expected = headroom_wh / (bat.max_charge_power_w * bat.charging_efficiency)
ac, dc, dis = solution._soc_clamped_operation_factors(
ac, dc, dis = genetic0convert._soc_clamped_operation_factors(
RUN_1, solution,
1.0, 1.0, True, float(bat.max_soc_percentage) - 1.0
)
assert ac == pytest.approx(expected)
@@ -212,21 +469,28 @@ class TestGenetic0SocClampedOperationFactors:
assert dis is True
def test_full_and_empty_battery(self, solution):
bat = solution.parameters.pv_battery
assert solution._soc_clamped_operation_factors(
bat = RUN_1.request.pv_battery
assert bat is not None
assert genetic0convert._soc_clamped_operation_factors(
RUN_1, solution,
1.0, 1.0, True, float(bat.max_soc_percentage)
) == (0.0, 0.0, True)
assert solution._soc_clamped_operation_factors(
assert genetic0convert._soc_clamped_operation_factors(
RUN_1, solution,
0.0, 0.0, True, float(bat.min_soc_percentage)
) == (0.0, 0.0, False)
def test_without_battery_parameters_factors_are_unchanged(self, solution):
solution.parameters.pv_battery = None
assert solution._soc_clamped_operation_factors(1.0, 0.5, True, 50.0) == (1.0, 0.5, True)
without_battery = dataclasses.replace(
RUN_1, request=RUN_1.request.model_copy(update={"pv_battery": None})
)
assert genetic0convert._soc_clamped_operation_factors(
without_battery, solution, 1.0, 0.5, True, 50.0
) == (1.0, 0.5, True)
@pytest.mark.asyncio
async def test_optimization_solution_with_configured_battery(self, solution):
optimization_solution = await solution.optimization_solution()
optimization_solution = await genetic0convert.optimization_solution(RUN_1, solution)
assert optimization_solution is not None
@@ -238,7 +502,7 @@ class TestGenetic0SolutionWithProfileInverter:
"""
@pytest.fixture
def solution(self, config_eos: ConfigEOS) -> Genetic0Solution:
def solution(self, config_eos: ConfigEOS) -> Genetic0Result:
config_eos.merge_settings_from_dict(
{
"devices": {
@@ -264,38 +528,90 @@ class TestGenetic0SolutionWithProfileInverter:
}
)
data = json.loads((DIR_TESTDATA / "optimize_result_1.json").read_text())
return Genetic0Solution.model_validate(data)
return result_of(Genetic0Solution.model_validate(data))
def test_uses_solution_inverter_parameters(self, solution):
bat = solution.parameters.pv_battery
inverter = solution.parameters.inverter
bat = RUN_1.request.pv_battery
inverter = RUN_1.request.inverter
assert bat is not None and inverter is not None
assert bat.max_charge_power_w is not None
# The stored inverter has no AC charge limit and efficiency 1.0, unlike
# the configured one: the battery charge power limits the AC charge.
headroom_wh = 0.01 * bat.capacity_wh
expected = headroom_wh / (
bat.max_charge_power_w * inverter.ac_to_dc_efficiency * bat.charging_efficiency
)
ac, _, _ = solution._soc_clamped_operation_factors(
ac, _, _ = genetic0convert._soc_clamped_operation_factors(
RUN_1, solution,
1.0, 1.0, True, float(bat.max_soc_percentage) - 1.0
)
assert ac == pytest.approx(expected)
def test_without_stored_parameters_the_configured_inverter_is_resolved(self, solution):
inverter = solution._inverter_parameters(None)
assert inverter is not None
def test_the_preparation_resolves_the_configured_inverter(self, solution, config_eos):
"""The inverter profile is resolved by the parameter preparation, not by the solution."""
from akkudoktoreos.optimization.genetic0 import genetic0prepare
settings = list(config_eos.devices.inverters.values())[0]
inverter = genetic0prepare.inverter_request(settings)
assert inverter.max_power_wh == pytest.approx(10000)
assert inverter.max_ac_charge_power_w == pytest.approx(2000)
assert 0.0 < inverter.ac_to_dc_efficiency < 1.0
def test_unresolvable_inverter_counts_as_no_inverter(self, solution, config_eos):
def test_the_stored_inverter_is_used_whatever_the_configuration(self, solution, config_eos):
"""The conversion reads no configuration (ADR 0003)."""
config_eos.merge_settings_from_dict(
{"devices": {"inverters": {"inverter1": {"profile_adjustment": {"nominal_power_w": None}}}}}
)
assert solution._inverter_parameters(None) is None
assert genetic0convert._inverter_parameters(RUN_1) is RUN_1.request.inverter
@pytest.mark.asyncio
async def test_optimization_solution_with_configured_inverter(self, solution):
"""Regression: AttributeError 'ac_to_dc_efficiency' on InverterCommonSettings."""
optimization_solution = await solution.optimization_solution()
optimization_solution = await genetic0convert.optimization_solution(RUN_1, solution)
assert optimization_solution is not None
@pytest.mark.parametrize(
"golden_stem",
[
"optimize_result_1",
"optimize_result_2",
"optimize_result_1_be",
"optimize_result_2_be",
"optimize_result_2_dst",
"optimize_result_2_full",
],
)
def test_replay(golden_stem: str, config_eos: ConfigEOS, is_finalize: bool):
"""A run reproduces its golden result from the stored parameters alone (ADR 0006, 0008).
The configuration is set to different values on purpose: the run must not read it.
"""
replay = json.loads((DIR_TESTDATA / f"replay_{golden_stem}.json").read_text())
parameters = parameters_from_dict(replay["parameters"])
if parameters.settings.generations and parameters.settings.generations > 10 and not is_finalize:
pytest.skip()
config_eos.merge_settings_from_dict(
{
"prediction": {"hours": 24},
"optimization": {
"genetic0": {
"horizon_hours": 12,
"individuals": 11,
"generations": 12,
"seed": 1,
"penalties": {"ev_soc_miss": 99, "ac_charge_break_even": 3},
},
"self_consumption_interpolator": "numpy",
},
"devices": {"max_electric_vehicles": 0, "max_home_appliances": 0},
}
)
result = solution_response(parameters, Genetic0Optimizer().run(parameters))
expected = Genetic0Solution(
**json.loads((DIR_TESTDATA / replay["expected_result"]).read_text())
)
assert result.result.Gesamtbilanz_Euro == pytest.approx(expected.result.Gesamtbilanz_Euro)
compare_dict(result.model_dump(), expected.model_dump())
+731 -53
View File
@@ -1,5 +1,9 @@
"""GENETIC0 parameter preparation: time alignment, tariff coverage, and measured SoC."""
import json
import math
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import AsyncMock, Mock, patch
import numpy as np
@@ -9,10 +13,17 @@ import pytest
import pytest_asyncio
from akkudoktoreos.core.coreabc import get_ems, get_measurement
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0OptimizationParameters,
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.optimization.genetic0.genetic0optimizer import Genetic0Optimizer
from akkudoktoreos.optimization.genetic0.genetic0parameters import (
Genetic0Parameters,
parameters_from_dict,
parameters_to_dict,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0Request,
)
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
class TestGenetic0ParameterTimeAlignment:
@@ -66,8 +77,10 @@ class TestGenetic0ParameterTimeAlignment:
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(return_value=prices),
)
with patch.object(Genetic0OptimizationParameters, "prediction", prediction):
parameters = await Genetic0OptimizationParameters.prepare()
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
assert parameters is not None
# Index ``start.hour`` of every array is the start slot.
@@ -84,7 +97,7 @@ class TestGenetic0TariffCoverage:
@pytest.mark.asyncio
@pytest.mark.parametrize("published_hours", [20, 24])
async def test_dvhub_tariff_requires_real_control_horizon(self,
async def test_dvhub_tariff_short_of_the_control_horizon_is_carried_forward(self,
config_eos, published_hours, caplog
):
config_eos.merge_settings_from_dict(
@@ -117,21 +130,25 @@ class TestGenetic0TariffCoverage:
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(return_value=prices),
)
with patch.object(Genetic0OptimizationParameters, "prediction", prediction):
parameters = await Genetic0OptimizationParameters.prepare()
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
prediction.update_data.assert_awaited_once()
assert config_eos.feedintariff.provider == "FeedInTariffDvhubOnline"
tariffs = parameters.ems.feed_in_tariff_per_wh
assert isinstance(tariffs, list)
published = [(4 * hour + 1.5) / 1_000_000 for hour in range(published_hours)]
assert tariffs[:published_hours] == pytest.approx(published)
if published_hours < 24:
assert parameters is None
assert "Missing feed-in tariff within the GENETIC0 control horizon" in caplog.text
else:
assert parameters is not None
tariffs = parameters.ems.feed_in_tariff_per_wh
assert isinstance(tariffs, list)
assert tariffs[:24] == pytest.approx(
[(4 * hour + 1.5) / 1_000_000 for hour in range(24)]
# The run is not cancelled: the last known tariff is carried forward (step 3b).
assert "Missing feed-in tariff within the control horizon" in caplog.text
assert tariffs[published_hours:] == pytest.approx(
[published[-1]] * (48 - published_hours)
)
else:
# A covered control horizon is used as it is.
assert np.isnan(tariffs[24:]).all()
@@ -185,8 +202,10 @@ class TestGenetic0MeasuredSOC:
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(return_value=tariff),
)
with patch.object(Genetic0OptimizationParameters, "prediction", prediction):
parameters = await Genetic0OptimizationParameters.prepare()
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
assert parameters is not None
assert parameters.pv_battery is not None
@@ -232,8 +251,10 @@ class TestGenetic0MeasuredSOC:
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(return_value=tariff),
)
with patch.object(Genetic0OptimizationParameters, "prediction", prediction):
parameters = await Genetic0OptimizationParameters.prepare()
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
assert parameters is not None
assert parameters.pv_battery is not None
@@ -277,8 +298,10 @@ class TestGenetic0MeasuredSOC:
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(return_value=tariff),
)
with patch.object(Genetic0OptimizationParameters, "prediction", prediction):
parameters = await Genetic0OptimizationParameters.prepare()
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
assert parameters is not None
assert parameters.pv_battery is not None
@@ -286,10 +309,10 @@ class TestGenetic0MeasuredSOC:
class TestGenetic0DemoData:
"""Demo device data used when no battery / electric vehicle is configured."""
"""No demo devices: devices that are not configured are left out (step 3b)."""
@pytest.mark.asyncio
async def test_demo_devices_use_nominal_capacity(self, config_eos):
async def test_unconfigured_devices_are_left_out_and_not_written(self, config_eos):
config_eos.merge_settings_from_dict(
{
"prediction": {"hours": 48},
@@ -298,10 +321,12 @@ class TestGenetic0DemoData:
"devices": {
"max_batteries": 1,
"max_electric_vehicles": 1,
"max_inverters": 0,
"max_home_appliances": 0,
"max_inverters": 1,
"max_home_appliances": 1,
"batteries": None,
"electric_vehicles": None,
"inverters": None,
"home_appliances": {},
},
}
)
@@ -318,21 +343,24 @@ class TestGenetic0DemoData:
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(return_value=tariff),
)
with patch.object(Genetic0OptimizationParameters, "prediction", prediction):
parameters = await Genetic0OptimizationParameters.prepare()
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
assert parameters is not None
# The demo capacities must reach the profile adjustment of the settings;
# the generic default profile provides no capacity of its own.
assert config_eos.devices.batteries["battery1"].profile_adjustment.nominal_capacity_wh == 8000
assert (
config_eos.devices.electric_vehicles["ev1"].profile_adjustment.nominal_capacity_wh
== 50000
)
assert parameters.pv_battery is not None
assert parameters.pv_battery.capacity_wh == 8000
assert parameters.ev is not None
assert parameters.ev.capacity_wh == 50000
parameters.pv_battery,
parameters.ev,
parameters.inverter,
parameters.dishwasher,
) == (None, None, None, None)
devices = config_eos.devices
assert (
devices.batteries,
devices.electric_vehicles,
devices.inverters,
devices.home_appliances or None,
) == (None, None, None, None)
@pytest.mark.asyncio
async def test_battery_configuration_error_uses_defaults_not_demo_data(self, config_eos):
@@ -373,8 +401,10 @@ class TestGenetic0DemoData:
lambda message: messages.append(message.record["message"]), level="ERROR"
)
try:
with patch.object(Genetic0OptimizationParameters, "prediction", prediction):
parameters = await Genetic0OptimizationParameters.prepare()
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
finally:
logger.remove(sink_id)
assert parameters is not None
@@ -389,20 +419,19 @@ class TestGenetic0DemoData:
@pytest.mark.asyncio
@pytest.mark.parametrize(
"settings_class, method, field, device_id",
"device, method, field, device_id",
[
("BatteriesCommonSettings", "to_genetic0_pv_bat_param", "pv_battery", "storage"),
("BatteriesCommonSettings", "to_genetic0_ev_bat_param", "ev", "car"),
("InverterCommonSettings", "to_genetic0_param", "inverter", "hybrid"),
("battery", "battery_request", "pv_battery", "storage"),
("electric vehicle", "electric_vehicle_request", "ev", "car"),
("inverter", "inverter_request", "inverter", "hybrid"),
],
)
async def test_device_that_cannot_be_prepared_is_left_out(
self, config_eos, monkeypatch, settings_class, method, field, device_id
self, config_eos, monkeypatch, device, method, field, device_id
):
"""No demo device replaces a configured device that cannot be prepared."""
from loguru import logger
from akkudoktoreos.devices.settings import batterysettings, invertersettings
config_eos.merge_settings_from_dict(
{
@@ -430,12 +459,11 @@ class TestGenetic0DemoData:
}
)
configured = config_eos.devices.model_dump(exclude_computed_fields=True)
module = batterysettings if settings_class == "BatteriesCommonSettings" else invertersettings
def broken(self, *args, **kwargs):
def broken(*args, **kwargs):
raise RuntimeError("conversion failed")
monkeypatch.setattr(getattr(module, settings_class), method, broken)
# The conversion of the settings belongs to GENETIC0's preparation (ADR 0004).
monkeypatch.setattr(genetic0prepare, method, broken)
get_ems().set_start_datetime(to_datetime("2026-08-01T14:00:00+00:00"))
tariff = pd.Series(
0.00008, index=pd.date_range("2026-08-01T00:00:00Z", periods=72 * 4, freq="15min")
@@ -454,8 +482,10 @@ class TestGenetic0DemoData:
lambda message: messages.append(message.record["message"]), level="ERROR"
)
try:
with patch.object(Genetic0OptimizationParameters, "prediction", prediction):
parameters = await Genetic0OptimizationParameters.prepare()
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
finally:
logger.remove(sink_id)
assert parameters is not None
@@ -466,3 +496,651 @@ class TestGenetic0DemoData:
for other in {"pv_battery", "ev", "inverter"} - {field}:
assert getattr(parameters, other) is not None
assert config_eos.devices.model_dump(exclude_computed_fields=True) == configured
@pytest.mark.asyncio
async def test_battery_not_linked_to_the_inverter_is_left_out(self, config_eos, caplog):
"""A battery the inverter does not name is left out; the inverter runs without it."""
config_eos.merge_settings_from_dict(
{
"prediction": {"hours": 48},
"optimization": {"genetic0": {"horizon_hours": 24}},
"elecfee": {"provider": None},
"devices": {
"max_batteries": 1,
"max_electric_vehicles": 0,
"max_inverters": 1,
"max_home_appliances": 0,
"batteries": {
"storage": {"profile_adjustment": {"nominal_capacity_wh": 5000}}
},
"inverters": {
"hybrid": {
"battery_id": "other",
"profile_adjustment": {"nominal_power_w": 6000},
}
},
},
}
)
get_ems().set_start_datetime(to_datetime("2026-08-01T14:00:00+00:00"))
prediction = Mock(
update_data=AsyncMock(),
key_to_array=AsyncMock(return_value=np.full(48, 0.0003)),
key_to_raw_series=AsyncMock(side_effect=KeyError("no tariff")),
)
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
assert parameters.pv_battery is None
assert parameters.inverter is not None
assert parameters.inverter.battery_id == "other"
assert "Battery 'storage' is not connected to the inverter (battery_id other)" in (
caplog.text
)
@pytest.mark.asyncio
@pytest.mark.parametrize("price_known", [True, False])
async def test_without_any_price_the_grid_does_not_charge(self, config_eos, price_known):
"""With the fallback price of 0 grid charging would look free: it is switched off."""
config_eos.merge_settings_from_dict(
{
"prediction": {"hours": 48},
"optimization": {"genetic0": {"horizon_hours": 24}},
"elecfee": {"provider": None},
"devices": {
"max_batteries": 1,
"max_electric_vehicles": 0,
"max_inverters": 1,
"max_home_appliances": 0,
"batteries": {
"storage": {"profile_adjustment": {"nominal_capacity_wh": 5000}}
},
"inverters": {
"hybrid": {
"battery_id": "storage",
"profile_adjustment": {"nominal_power_w": 6000},
}
},
},
}
)
get_ems().set_start_datetime(to_datetime("2026-08-01T14:00:00+00:00"))
async def read_array(*, key, **kwargs):
if key == "elecprice_marketprice_wh" and not price_known:
raise KeyError("no price")
return np.full(48, 0.0003)
prediction = Mock(
update_data=AsyncMock(),
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(side_effect=KeyError("no tariff")),
)
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
assert parameters.inverter is not None
assert parameters.pv_battery is not None
if price_known:
assert parameters.inverter.max_ac_charge_power_w != 0
else:
assert parameters.ems.electricity_price_per_wh == [0.0] * 48
assert parameters.inverter.max_ac_charge_power_w == 0.0
class TestGenetic0PrepareOverrides:
"""Run-time overrides reach the parameters; unknown keys are logged and ignored."""
@pytest.fixture
def request_parameters(self) -> Genetic0Request:
return Genetic0Request.model_validate(
{
"ems": {
"pv_prognose_wh": [0.0, 100.0],
"gesamtlast": [100.0, 100.0],
"strompreis_euro_pro_wh": [0.0003, 0.0003],
"einspeiseverguetung_euro_pro_wh": 0.00008,
"preis_euro_pro_wh_akku": 0.0,
},
"pv_akku": None,
"eauto": None,
"inverter": None,
}
)
@pytest.fixture
def errors(self, monkeypatch) -> list[str]:
logged: list[str] = []
monkeypatch.setattr(
genetic0prepare.logger, "error", lambda message, *args: logged.append(message)
)
return logged
@pytest.mark.asyncio
@pytest.mark.parametrize(
"overrides, generations, seed",
[
(None, 77, 5),
({}, 77, 5),
({"generations": None, "seed": None}, 77, 5),
({"generations": 12}, 12, 5),
({"generations": 12, "seed": 42}, 12, 42),
],
)
async def test_known_overrides_replace_the_settings(
self, config_eos, request_parameters, errors, overrides, generations, seed
):
config_eos.merge_settings_from_dict(
{"optimization": {"genetic0": {"generations": 77, "seed": 5}}}
)
start = to_datetime("2026-01-14T10:00:00", in_timezone="Europe/Berlin")
parameters = await genetic0prepare.prepare_from_request(
request_parameters, start, start, None, overrides
)
assert parameters.request is request_parameters
assert parameters.start_hour == 10
assert (parameters.settings.generations, parameters.settings.seed) == (generations, seed)
assert errors == []
@pytest.mark.asyncio
async def test_unknown_override_is_logged_and_ignored(
self, config_eos, request_parameters, errors
):
config_eos.merge_settings_from_dict(
{"optimization": {"genetic0": {"generations": 77, "seed": 5}}}
)
start = to_datetime("2026-01-14T10:00:00", in_timezone="Europe/Berlin")
parameters = await genetic0prepare.prepare_from_request(
request_parameters, start, start, None, {"individuals": 3, "generations": 12}
)
assert (parameters.settings.generations, parameters.settings.seed) == (12, 5)
assert errors == ["GENETIC0: Unknown override '{}' ignored."]
class TestGenetic0PrepareWarmStart:
"""The start solution of the previous run seeds the next one."""
@pytest.mark.asyncio
@pytest.mark.parametrize(
"warm_start, start_solution",
[
(None, None),
(SimpleNamespace(start_solution=None), None),
(SimpleNamespace(start_solution=[]), None),
(SimpleNamespace(start_solution=[1.0, 0.0, 2.0]), [1.0, 0.0, 2.0]),
],
ids=["no-previous-run", "no-start-solution", "empty-start-solution", "start-solution"],
)
async def test_previous_start_solution_reaches_the_preparation(
self, config_eos, monkeypatch, warm_start, start_solution
):
request = Mock()
legacy_prepare = AsyncMock(return_value=request)
monkeypatch.setattr(genetic0prepare, "prepare_request", legacy_prepare)
monkeypatch.setattr(
genetic0prepare.Genetic0Parameters,
"from_request",
classmethod(lambda cls, **fields: SimpleNamespace(**fields)),
)
start = to_datetime("2026-01-14T10:00:00", in_timezone="Europe/Berlin")
observation = start.add(minutes=7)
parameters = await genetic0prepare.prepare(start, observation, warm_start)
legacy_prepare.assert_awaited_once_with(start, observation, start_solution)
assert parameters.request is request
class TestGenetic0Presentation:
"""The data the solution conversion presents, read once before the run."""
@pytest.mark.asyncio
async def test_window_and_missing_values_survive_the_replay_file(self, config_eos, monkeypatch):
config_eos.merge_settings_from_dict(
{"general": {"timezone_override": "Europe/Berlin"}, "prediction": {"hours": 48}}
)
windows = []
async def key_to_array(*, key, start_datetime, end_datetime, interval, fill_method):
windows.append((key, start_datetime, end_datetime, fill_method))
hours = int((end_datetime - start_datetime).total_seconds() // 3600)
values = np.arange(hours, dtype=float)
values[1] = np.nan
return values
prediction = SimpleNamespace(
record_keys=["pvforecast_ac_power", "feed_in_tariff_wh"], key_to_array=key_to_array
)
monkeypatch.setattr(genetic0prepare, "get_prediction", lambda: prediction)
# 09:00 UTC is 10:00 in Berlin: read from the earlier hour, so the series cover every
# hour the conversion may show (it slices them to its own count).
start = to_datetime("2026-01-14T09:00:00+00:00", in_timezone="UTC")
settings = genetic0prepare._run_settings(None, 0)
presentation = await genetic0prepare._presentation(start, settings, False)
assert [(key, fill) for key, _, _, fill in windows] == [
("pvforecast_ac_power", "linear"),
("feed_in_tariff_wh", "ffill"),
]
assert {(end - begin).total_seconds() for _, begin, end, _ in windows} == {
to_duration("39 hours").total_seconds()
}
assert set(presentation.prediction_series) == {"pvforecast_ac_power", "feed_in_tariff_wh"}
assert presentation.timezone == "Europe/Berlin"
series = presentation.prediction_series["pvforecast_ac_power"]
assert len(series) == 39 and math.isnan(series[1])
request = Genetic0Request.model_validate(
{
"ems": {
"pv_prognose_wh": [0.0, 100.0],
"gesamtlast": [100.0, 100.0],
"strompreis_euro_pro_wh": [0.0003, 0.0003],
"einspeiseverguetung_euro_pro_wh": 0.00008,
"preis_euro_pro_wh_akku": 0.0,
},
"pv_akku": None,
"eauto": None,
"inverter": None,
}
)
parameters = Genetic0Parameters.from_request(
request=request, start_hour=start.hour, settings=settings, presentation=presentation
)
data = json.loads(json.dumps(parameters_to_dict(parameters)))
assert data["presentation"]["prediction_series"]["pvforecast_ac_power"][1] is None
restored = parameters_from_dict(data).presentation
assert restored.start_datetime == presentation.start_datetime
# The zone of the run start, not the configured one.
assert restored.start_datetime.timezone_name == start.timezone_name
restored_series = restored.prediction_series["pvforecast_ac_power"]
assert math.isnan(restored_series[1])
assert restored_series[2:] == series[2:]
def test_unconfigured_prediction_hours_fall_back_to_48(self, monkeypatch):
config = Mock()
config.prediction.hours = None
config.devices.electric_vehicles = None
config.devices.batteries = None
config.optimization.genetic0.penalties = {}
monkeypatch.setattr(genetic0prepare, "get_config", lambda: config)
errors: list[str] = []
monkeypatch.setattr(
genetic0prepare.logger, "error", lambda message, *args: errors.append(message)
)
assert genetic0prepare._run_settings(None, 0).prediction_hours == 48
assert errors == ["GENETIC0: prediction.hours not configured, using {}."]
class TestGenetic0AlwaysValid:
"""The preparation never fails, never cancels and never writes the configuration (step 3b)."""
def _configure(self, config_eos) -> None:
config_eos.merge_settings_from_dict(
{
"general": {"timezone_override": "UTC"},
"prediction": {"hours": 48},
"optimization": {"genetic0": {"horizon_hours": 24}},
"elecfee": {"provider": None},
"devices": {
"max_batteries": 0,
"max_electric_vehicles": 0,
"max_inverters": 0,
"max_home_appliances": 0,
},
}
)
get_ems().set_start_datetime(to_datetime("2026-08-01T10:00:00+00:00", in_timezone="UTC"))
@pytest.mark.asyncio
async def test_missing_predictions_give_fallback_values(self, config_eos, caplog):
self._configure(config_eos)
providers_before = config_eos.model_dump(
include={"weather", "load", "pvforecast", "elecprice", "elecfee", "general"}
)
prediction = Mock(
update_data=AsyncMock(side_effect=RuntimeError("synthetic update failure")),
key_to_array=AsyncMock(side_effect=KeyError("no provider")),
key_to_raw_series=AsyncMock(side_effect=KeyError("no provider")),
)
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
ems = parameters.ems
assert ems.pv_forecast_wh == [0.0] * 48
assert ems.electricity_price_per_wh == [genetic0prepare.FALLBACK_PRICE_PER_WH] * 48
assert ems.feed_in_tariff_per_wh == [genetic0prepare.FALLBACK_FEED_IN_TARIFF_PER_WH] * 48
assert ems.total_load == pytest.approx([3000.0 * 1000.0 / 8760.0] * 48)
assert parameters.temperature_forecast is None
# Nothing written back, no provider switched.
assert config_eos.model_dump(
include={"weather", "load", "pvforecast", "elecprice", "elecfee", "general"}
) == providers_before
assert prediction.update_data.await_count == 1 # no retries
assert "using the stored predictions" in caplog.text
@pytest.mark.asyncio
async def test_gaps_are_carried_forward(self, config_eos):
self._configure(config_eos)
price = np.full(48, np.nan)
price[12:20] = np.arange(8, dtype=float) / 1000
load = np.full(48, 500.0)
load[30:] = np.nan
async def read_array(*, key, **kwargs):
return {
"elecprice_marketprice_wh": price,
"loadforecast_power_w": load,
}.get(key, np.full(48, 1.0))
tariff = pd.Series(
0.00008, index=pd.date_range("2026-08-01T00:00:00Z", periods=72 * 4, freq="15min")
)
prediction = Mock(
update_data=AsyncMock(),
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(return_value=tariff),
)
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
prices = parameters.ems.electricity_price_per_wh
assert prices[:12] == [0.0] * 12 # leading gap: the first known price
assert prices[12:20] == pytest.approx(list(np.arange(8) / 1000))
assert prices[20:] == pytest.approx([0.007] * 28) # carried forward
assert parameters.ems.total_load[30:] == [500.0] * 18
@pytest.mark.asyncio
async def test_prepare_never_raises_without_any_input(self, config_eos, monkeypatch):
self._configure(config_eos)
prediction = Mock(
update_data=AsyncMock(side_effect=RuntimeError("down")),
key_to_array=AsyncMock(side_effect=RuntimeError("down")),
key_to_raw_series=AsyncMock(side_effect=RuntimeError("down")),
record_keys=["pvforecast_ac_power"],
)
monkeypatch.setattr(genetic0prepare, "get_prediction", lambda: prediction)
start = get_ems().start_datetime
parameters = await genetic0prepare.prepare(start, start, None)
assert parameters.request.ems.pv_forecast_wh == [0.0] * 48
assert parameters.presentation.prediction_series == {}
class TestGenetic0Fallbacks:
"""Each fallback of the preparation gives a valid value and logs an error (step 3b)."""
@pytest.fixture
def errors(self, monkeypatch) -> list[str]:
logged: list[str] = []
monkeypatch.setattr(
genetic0prepare.logger, "error", lambda message, *args: logged.append(message)
)
return logged
@pytest.mark.asyncio
@pytest.mark.parametrize(
"measured, percentage, logged",
[
(0.42, 42, False),
(math.nan, 0, True),
(1.5, 0, True),
(-0.1, 0, True),
(KeyError("no reading"), 0, True),
],
ids=["valid", "nan", "above-one", "negative", "missing"],
)
async def test_state_of_charge(self, monkeypatch, errors, measured, percentage, logged):
nearest = AsyncMock(side_effect=[measured] if isinstance(measured, Exception) else None)
if not isinstance(measured, Exception):
nearest.return_value = measured
monkeypatch.setattr(genetic0prepare, "_nearest_soc_factor", nearest)
start = to_datetime("2026-01-14T10:00:00+00:00")
assert await genetic0prepare._initial_soc_percentage("battery", "soc", start) == percentage
assert bool(errors) == logged
@pytest.mark.asyncio
async def test_battery_without_cost_of_storage(self, monkeypatch, errors):
battery_params = SimpleNamespace(initial_soc_percentage=None)
battery = Mock(
device_id="battery1",
levelized_cost_of_storage_amt_kwh=None,
measurement_key_soc_factor="soc",
resolve_current_operating_parameters_or_defaults=AsyncMock(return_value=({}, None)),
)
monkeypatch.setattr(genetic0prepare, "battery_request", Mock(return_value=battery_params))
config = Mock()
config.devices.max_batteries = 1
config.devices.batteries = {"battery1": battery}
monkeypatch.setattr(genetic0prepare, "get_config", lambda: config)
monkeypatch.setattr(genetic0prepare, "_initial_soc_percentage", AsyncMock(return_value=33))
start = to_datetime("2026-01-14T10:00:00+00:00")
params, lcos = await genetic0prepare._battery(start)
assert (params, lcos) == (battery_params, 0.0)
assert battery_params.initial_soc_percentage == 33
assert battery.levelized_cost_of_storage_amt_kwh is None # not written back
assert errors == [
"GENETIC0: Battery '{}' has no levelized cost of storage; using 0 per kWh."
]
def test_unset_algorithm_settings(self, monkeypatch, errors):
config = Mock()
config.prediction.hours = 48
config.devices.electric_vehicles = None
config.devices.batteries = None
config.optimization.genetic0.horizon_hours = 24
config.optimization.genetic0.individuals = None
config.optimization.genetic0.generations = None
config.optimization.genetic0.seed = None
config.optimization.genetic0.penalties = {}
monkeypatch.setattr(genetic0prepare, "get_config", lambda: config)
settings = genetic0prepare._run_settings(None, 0)
assert (settings.individuals, settings.generations) == (300, 400)
assert len(errors) == 2
assert config.optimization.genetic0.individuals is None # not written back
@pytest.mark.asyncio
@pytest.mark.parametrize(
"configured, start_hour, expected",
[
(0, 14, 38), # nothing left: the control horizon of 24 hours
(24, 23, 47), # one hour left
(24, 14, 24), # enough left: unchanged
(6, 0, 6),
],
)
async def test_prediction_hours_leave_room_after_the_start(
self, config_eos, errors, configured, start_hour, expected
):
"""Fewer than two hours after the start hour: the run covers its control horizon."""
TestGenetic0AlwaysValid()._configure(config_eos)
config_eos.merge_settings_from_dict(
{
"prediction": {"hours": configured},
"optimization": {"genetic0": {"individuals": 10, "generations": 10, "seed": 1}},
}
)
start = to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC").add(hours=start_hour)
get_ems().set_start_datetime(start)
prediction = Mock(
update_data=AsyncMock(),
key_to_array=AsyncMock(side_effect=KeyError("no data")),
key_to_raw_series=AsyncMock(side_effect=KeyError("no data")),
record_keys=[],
)
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare(start, start, None)
assert parameters.settings.prediction_hours == expected
assert len(parameters.request.ems.total_load) == expected
logged = any("leaves fewer than" in message for message in errors)
assert logged == (expected != configured)
if expected != configured:
Genetic0Optimizer().run(parameters) # runs instead of failing
@pytest.mark.asyncio
async def test_short_and_incomplete_forecasts(self, config_eos, errors):
TestGenetic0AlwaysValid()._configure(config_eos)
pv = np.full(48, 1000.0)
pv[5:7] = np.nan
pv[7] = np.inf
price = np.full(48, 0.0002)
price[3] = -np.inf
temperature = np.full(48, 20.0)
temperature[4] = np.inf
async def read_array(*, key, **kwargs):
if key == "pvforecast_ac_power":
return pv
if key == "loadforecast_power_w":
return np.full(10, 400.0) # does not cover the run
if key == "elecprice_marketprice_wh":
return price
if key == "weather_temp_air":
return temperature
return np.full(48, 0.0002)
tariff = pd.Series(
0.00008, index=pd.date_range("2026-08-01T00:00:00Z", periods=72 * 4, freq="15min")
)
tariff.iloc[44 * 4] = np.inf # 20:00 on the next day, after the control horizon
prediction = Mock(
update_data=AsyncMock(),
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(return_value=tariff),
)
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime
)
# NaN and infinite values are missing.
assert math.isnan(cast(list[float], parameters.ems.feed_in_tariff_per_wh)[44])
assert parameters.ems.pv_forecast_wh[5:8] == [0.0, 0.0, 0.0]
assert parameters.ems.pv_forecast_wh[8] == 1000.0
assert parameters.ems.electricity_price_per_wh[3] == 0.0002
temperature_forecast = parameters.temperature_forecast
assert temperature_forecast is not None
assert temperature_forecast[4] is None
assert temperature_forecast[5] == 20.0
assert parameters.ems.total_load == pytest.approx([3000.0 * 1000.0 / 8760.0] * 48)
assert "GENETIC0: Prediction '{}' does not cover the run." in errors
assert "GENETIC0: PV forecast incomplete; using 0 Wh for the missing hours." in errors
@pytest.mark.asyncio
@pytest.mark.parametrize("failing_builds", [1, 2])
async def test_invalid_parameters_fall_back(self, config_eos, monkeypatch, errors, failing_builds):
TestGenetic0AlwaysValid()._configure(config_eos)
prediction = Mock(
update_data=AsyncMock(),
key_to_array=AsyncMock(return_value=np.full(48, 0.0002)),
key_to_raw_series=AsyncMock(
return_value=pd.Series(
0.00008,
index=pd.date_range("2026-08-01T00:00:00Z", periods=72 * 4, freq="15min"),
)
),
)
monkeypatch.setattr(genetic0prepare, "get_prediction", lambda: prediction)
real = genetic0prepare.Genetic0EnergyManagementRequest
calls = {"count": 0}
def build(**kwargs):
calls["count"] += 1
if calls["count"] <= failing_builds:
raise ValueError("synthetic invalid parameters")
return real(**kwargs)
monkeypatch.setattr(genetic0prepare, "Genetic0EnergyManagementRequest", build)
parameters = await genetic0prepare.prepare_request(
get_ems().start_datetime, get_ems().observation_datetime, start_solution=[1.0, 2.0]
)
assert parameters.pv_battery is None and parameters.start_solution is None
assert parameters.temperature_forecast is None
if failing_builds == 2:
assert parameters.ems.pv_forecast_wh == [0.0] * 48
assert parameters.ems.total_load == pytest.approx([3000.0 * 1000.0 / 8760.0] * 48)
assert len([message for message in errors if "are invalid" in message]) == failing_builds
class TestGenetic0HomeApplianceShown:
"""The solution shows the home appliance the preparation put into the request (step 3b)."""
@pytest.mark.asyncio
@pytest.mark.parametrize(
"dishwasher, max_home_appliances, automatic, enabled",
[
(object(), None, True, True), # default max: the configured appliance is shown
(None, None, True, False), # nothing configured: nothing invented
(object(), None, False, False), # a client's request: configured count, as before
(object(), 1, False, True),
],
)
async def test_decision(
self, config_eos, monkeypatch, dishwasher, max_home_appliances, automatic, enabled
):
config_eos.devices.max_home_appliances = max_home_appliances
request = SimpleNamespace(dishwasher=dishwasher)
monkeypatch.setattr(genetic0prepare, "prepare_request", AsyncMock(return_value=request))
# The stand-in request has no forecasts to derive the simulation's dataclasses from.
monkeypatch.setattr(
genetic0prepare.Genetic0Parameters,
"from_request",
classmethod(lambda cls, **fields: SimpleNamespace(**fields)),
)
monkeypatch.setattr(
genetic0prepare, "get_prediction", lambda: SimpleNamespace(record_keys=[])
)
start = to_datetime("2026-01-14T10:00:00", in_timezone="Europe/Berlin")
if automatic:
parameters = await genetic0prepare.prepare(start, start, None)
else:
parameters = await genetic0prepare.prepare_from_request(
cast(Any, request), start, start, None
)
assert parameters.presentation.home_appliance_enabled is enabled
@pytest.mark.asyncio
@pytest.mark.parametrize("enabled", [True, False])
async def test_conversion_follows_the_decision(self, enabled):
"""The conversion shows the home appliance as the preparation decided (step 5)."""
import dataclasses
from pathlib import Path
from test_genetic0optimize import result_of
from akkudoktoreos.optimization.genetic0 import genetic0convert
from akkudoktoreos.optimization.genetic0.genetic0api import (
Genetic0Solution,
)
testdata = Path(__file__).parent / "testdata" / "genetic0"
replay = json.loads((testdata / "replay_optimize_result_1.json").read_text())
parameters = parameters_from_dict(replay["parameters"])
parameters = dataclasses.replace(
parameters,
presentation=dataclasses.replace(
parameters.presentation, home_appliance_enabled=enabled
),
)
result = result_of(
Genetic0Solution.model_validate(
json.loads((testdata / replay["expected_result"]).read_text())
)
)
solution = await genetic0convert.optimization_solution(parameters, result)
plan = genetic0convert.energy_management_plan(parameters, result)
columns = next(iter(solution.solution.data.values()))
assert ("homeappliance1_energy_wh" in columns) is enabled
assert any(i.resource_id == "homeappliance1" for i in plan.instructions) is enabled
+256 -64
View File
@@ -9,23 +9,83 @@ import pytest
from akkudoktoreos.core import ems as ems_module
from akkudoktoreos.core.emsettings import EnergyManagementMode
from akkudoktoreos.optimization.genetic0 import genetic0 as genetic0_module
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0OptimizationParameters,
from akkudoktoreos.optimization.genetic0 import genetic0algorithm as genetic0_module
from akkudoktoreos.optimization.genetic0 import genetic0convert, genetic0prepare
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0Request,
)
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
from akkudoktoreos.optimization.optimizer import OptimizerRun
from akkudoktoreos.utils.datetimeutil import to_datetime
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
def _patch_optimizer(monkeypatch, prefix: str, constructor: Any) -> None:
"""Replace the optimizer class that EnergyManagement.run() instantiates.
GENETIC0 is imported on first use inside run(), so it is patched at its source.
GENETIC0 is imported on first use inside its optimizer, so it is patched at its source.
"""
module = genetic0_module if prefix == "Genetic0" else ems_module
monkeypatch.setattr(module, prefix + "Optimization", constructor)
def _patch_prepare(monkeypatch, prefix: str, prepare: Any) -> None:
"""Replace the legacy parameter preparation of GENETIC or GENETIC0."""
if prefix == "Genetic0":
monkeypatch.setattr(genetic0prepare, "prepare_request", prepare)
else:
monkeypatch.setattr(ems_module.GeneticOptimizationParameters, "prepare", prepare)
def _warm_start_of(call: Any) -> Any:
"""The start solution a call of GENETIC0's legacy preparation got."""
start, observation, start_solution = call.args
return start_solution
def _assert_prepared_without_request(prefix: str, prepare: Any) -> None:
"""GENETIC0 passes start, observation time and warm start (none here) into its preparation."""
if prefix == "Genetic0":
prepare.assert_awaited_once()
assert _warm_start_of(prepare.await_args) is None
else:
prepare.assert_awaited_once_with()
def _conversion_arguments(prefix: str) -> dict[str, Any]:
"""Arguments of the stand-in results' conversion methods (none for both optimizers)."""
return {}
def _native_solution(prefix: str) -> Any:
"""The native solution the latest run published for GENETIC or GENETIC0."""
cls = ems_module.EnergyManagement
if prefix == "Genetic0":
return cls.optimizer_result("GENETIC0")
return cls._genetic_solution
def _set_native_solution(monkeypatch, prefix: str, solution: Any) -> None:
"""Publish ``solution`` as the result of a previous run of GENETIC or GENETIC0."""
cls = ems_module.EnergyManagement
if prefix == "Genetic0":
runs = {"GENETIC0": OptimizerRun(parameters=object(), result=solution)}
monkeypatch.setattr(cls, "_optimizer_runs", runs)
else:
monkeypatch.setattr(cls, "_genetic_solution", solution)
def _supplied(prefix: str, parameters: Any, generations: int, seed: int) -> dict[str, Any]:
"""Run arguments that supply the parameters, generations and seed of a run."""
if prefix == "Genetic0":
return {"request": parameters, "overrides": {"generations": generations, "seed": seed}}
return {
"genetic_parameters": parameters,
"genetic_generations": generations,
"genetic_seed": seed,
}
@pytest.fixture
def offline_ems(monkeypatch):
"""Run the actual EMS orchestration with no real adapters or prediction IO."""
@@ -37,20 +97,26 @@ def offline_ems(monkeypatch):
"_plan",
"_optimization_solution",
"_genetic_solution",
"_genetic0_solution",
):
monkeypatch.setattr(cls, name, None)
monkeypatch.setattr(cls, "_optimizer_runs", {})
monkeypatch.setattr(cls, "_stage", ems_module.EnergyManagementStage.IDLE)
monkeypatch.setattr(cls, "_run_lock", Lock())
monkeypatch.setattr(ems_module, "CacheEnergyManagementStore", Mock())
return SimpleNamespace(
ems = SimpleNamespace(
config=SimpleNamespace(
general=SimpleNamespace(timezone="Europe/Berlin"),
ems=SimpleNamespace(mode=EnergyManagementMode.OPTIMIZATION),
optimization=SimpleNamespace(
algorithm=OptimizationAlgorithm.GENETIC,
genetic=SimpleNamespace(generations=3, seed=17, interval_sec=3600, individuals=31),
genetic0=SimpleNamespace(generations=5, seed=29),
genetic0=SimpleNamespace(
generations=5, seed=29, horizon_hours=24, individuals=13, penalties={}
),
),
prediction=SimpleNamespace(hours=48),
devices=SimpleNamespace(
batteries=None, electric_vehicles=None, max_home_appliances=0
),
server=SimpleNamespace(verbose=False),
),
@@ -58,6 +124,33 @@ def offline_ems(monkeypatch):
adapter=SimpleNamespace(update_data=AsyncMock()),
set_start_datetime=cls.set_start_datetime,
)
# GENETIC0's parameter preparation reads the settings and predictions itself.
monkeypatch.setattr(genetic0prepare, "get_config", lambda: ems.config)
monkeypatch.setattr(
genetic0prepare, "get_prediction", lambda: SimpleNamespace(record_keys=[])
)
monkeypatch.setattr(
genetic0prepare,
"configured_grid_interpolator_backend",
lambda: GridInterpolatorBackend.SCIPY,
)
# Stand-in results carry their own conversion methods.
async def optimization_solution(parameters: Any, result: Any) -> Any:
return await result.optimization_solution()
monkeypatch.setattr(genetic0convert, "optimization_solution", optimization_solution)
monkeypatch.setattr(
genetic0convert,
"energy_management_plan",
lambda parameters, result: result.energy_management_plan(),
)
# Stand-in requests have no forecasts to derive the simulation's dataclasses from.
monkeypatch.setattr(
genetic0prepare.Genetic0Parameters,
"from_request",
classmethod(lambda cls, **fields: SimpleNamespace(**fields)),
)
return ems
@pytest.mark.asyncio
@@ -106,9 +199,11 @@ async def test_optimization_routes_only_selected_algorithm(
):
"""Configuration selection and explicit overrides retain isolated async paths."""
selected_name = "Genetic" if algorithm == OptimizationAlgorithm.GENETIC else "Genetic0"
other_name = "Genetic0" if selected_name == "Genetic" else "Genetic"
suffix = "genetic" if algorithm == OptimizationAlgorithm.GENETIC else "genetic0"
other_suffix = "genetic0" if suffix == "genetic" else "genetic"
sentinel_parameters = object()
# GENETIC0's preparation looks at the request's home appliance.
sentinel_parameters = SimpleNamespace(dishwasher=None)
sentinel_result, sentinel_plan = object(), object()
solution = SimpleNamespace(
optimization_solution=AsyncMock(return_value=sentinel_result),
@@ -123,9 +218,7 @@ async def test_optimization_routes_only_selected_algorithm(
_patch_optimizer(monkeypatch, prefix, constructor)
prepare = AsyncMock(return_value=sentinel_parameters)
preparers[prefix] = prepare
monkeypatch.setattr(
getattr(ems_module, prefix + "OptimizationParameters"), "prepare", prepare
)
_patch_prepare(monkeypatch, prefix, prepare)
kwargs: dict[str, Any] = {
"start_datetime": to_datetime("2026-09-16T10:00:00+02:00", in_timezone=timezone)
}
@@ -135,38 +228,50 @@ async def test_optimization_routes_only_selected_algorithm(
offline_ems.config.optimization.algorithm = OptimizationAlgorithm(other_suffix.upper())
kwargs["algorithm"] = algorithm
if supplied:
kwargs[suffix + "_parameters"] = sentinel_parameters
kwargs[suffix + "_generations"] = 7
kwargs[suffix + "_seed"] = 43
kwargs.update(_supplied(selected_name, sentinel_parameters, 7, 43))
if algorithm == OptimizationAlgorithm.GENETIC:
kwargs["genetic_individuals"] = 11
run_result = await ems_module.EnergyManagement.run(offline_ems, **kwargs)
assert run_result is solution
selected = constructors[selected_name]
expected_config = getattr(offline_ems.config.optimization, suffix)
selected.assert_called_once_with(
verbose=False, fixed_seed=43 if supplied else expected_config.seed
)
expected_seed = 43 if supplied else expected_config.seed
expected_generations = 7 if supplied else expected_config.generations
expected_arguments: dict[str, Any] = {
"start_hour": expected_hour,
"parameters": sentinel_parameters,
"ngen": 7 if supplied else expected_config.generations,
}
if algorithm == OptimizationAlgorithm.GENETIC:
selected.assert_called_once_with(verbose=False, fixed_seed=expected_seed)
expected_arguments["ngen"] = expected_generations
else:
# GENETIC0 gets its algorithm settings from the parameters (step 3).
(settings,) = selected.call_args.args
assert (settings.seed, settings.generations, settings.verbose) == (
expected_seed,
expected_generations,
False,
)
if algorithm == OptimizationAlgorithm.GENETIC:
expected_arguments["individuals"] = 11 if supplied else None
selected.return_value.optimize_ems.assert_called_once_with(**expected_arguments)
other_name = "Genetic0" if selected_name == "Genetic" else "Genetic"
selected.return_value.optimize_ems.assert_called_once_with(**expected_arguments)
else:
# GENETIC0 runs from its parameters, which carry the request and the start hour.
(parameters,) = selected.return_value.optimize_ems.call_args.args
assert parameters.request is sentinel_parameters
assert parameters.start_hour == expected_hour
constructors[other_name].assert_not_called()
preparers[other_name].assert_not_awaited()
if supplied:
preparers[selected_name].assert_not_awaited()
else:
preparers[selected_name].assert_awaited_once_with()
solution.optimization_solution.assert_awaited_once_with()
solution.energy_management_plan.assert_called_once_with()
_assert_prepared_without_request(selected_name, preparers[selected_name])
conversion_arguments = _conversion_arguments(selected_name)
solution.optimization_solution.assert_awaited_once_with(**conversion_arguments)
solution.energy_management_plan.assert_called_once_with(**conversion_arguments)
cls = ems_module.EnergyManagement
assert getattr(cls, "_" + suffix + "_solution") is solution
assert getattr(cls, "_" + other_suffix + "_solution") is None
assert _native_solution(selected_name) is solution
assert _native_solution(other_name) is None
assert cls.optimization_solution() is sentinel_result
assert cls.plan() is sentinel_plan
assert cls.stage() == ems_module.EnergyManagementStage.IDLE
@@ -194,16 +299,17 @@ async def test_non_optimization_modes_never_optimize(monkeypatch, offline_ems, m
@pytest.mark.asyncio
@pytest.mark.parametrize("prefix", ["Genetic", "Genetic0"])
@pytest.mark.parametrize("prefix", ["Genetic"])
async def test_missing_preparation_does_not_dispatch_controls(monkeypatch, offline_ems, prefix):
"""GENETIC may still cancel; GENETIC0's preparation never does (TestGenetic0AlwaysValid)."""
constructor = Mock()
_patch_optimizer(monkeypatch, prefix, constructor)
prepare = AsyncMock(return_value=None)
monkeypatch.setattr(getattr(ems_module, prefix + "OptimizationParameters"), "prepare", prepare)
_patch_prepare(monkeypatch, prefix, prepare)
await ems_module.EnergyManagement.run(
offline_ems, algorithm=OptimizationAlgorithm(prefix.upper())
)
prepare.assert_awaited_once_with()
_assert_prepared_without_request(prefix, prepare)
constructor.assert_not_called()
assert offline_ems.adapter.update_data.await_count == 1 # acquisition only
assert ems_module.EnergyManagement.plan() is None
@@ -213,35 +319,42 @@ async def test_missing_preparation_does_not_dispatch_controls(monkeypatch, offli
@pytest.mark.asyncio
@pytest.mark.parametrize("start_hour", [None, 11])
async def test_legacy_optimize_explicitly_uses_genetic0(monkeypatch, start_hour):
"""Even with GENETIC configured, /optimize must never become the new optimizer."""
"""Even with GENETIC configured, /optimize must never become the new optimizer.
The GENETIC0 router gets its run trigger from the server's placeholder override.
"""
from httpx import ASGITransport, AsyncClient
from akkudoktoreos.server import eos
from akkudoktoreos.server.rest.error import EOSProblem
fake = SimpleNamespace(
run=AsyncMock(return_value=None), genetic0_solution=Mock(return_value=None)
run=AsyncMock(return_value=None), optimizer_run=Mock(return_value=None)
)
monkeypatch.setattr(eos, "get_ems", lambda: fake)
parameters = Genetic0OptimizationParameters.model_validate(
{
"ems": {
"pv_prognose_wh": [0.0, 100.0],
"gesamtlast": [100.0, 100.0],
"strompreis_euro_pro_wh": [0.0003, 0.0003],
"einspeiseverguetung_euro_pro_wh": 0.00008,
"preis_euro_pro_wh_akku": 0.0,
},
"pv_akku": None,
"eauto": None,
"inverter": None,
}
)
with pytest.raises(EOSProblem):
await eos.fastapi_optimize(parameters=parameters, start_hour=start_hour, ngen=2)
body = {
"ems": {
"pv_prognose_wh": [0.0, 100.0],
"gesamtlast": [100.0, 100.0],
"strompreis_euro_pro_wh": [0.0003, 0.0003],
"einspeiseverguetung_euro_pro_wh": 0.00008,
"preis_euro_pro_wh_akku": 0.0,
},
"pv_akku": None,
"eauto": None,
"inverter": None,
}
query = "ngen=2" + ("" if start_hour is None else f"&start_hour={start_hour}")
async with AsyncClient(
transport=ASGITransport(app=eos.app, raise_app_exceptions=False), base_url="http://test"
) as client:
response = await client.post(f"/optimize?{query}", json=body)
assert response.status_code == 404
assert response.json()["title"] == "Optimization solution retrieval failed"
kwargs = fake.run.await_args.kwargs
assert kwargs["mode"] == EnergyManagementMode.OPTIMIZATION
assert kwargs["algorithm"] == OptimizationAlgorithm.GENETIC0
assert kwargs["genetic0_parameters"] is parameters
assert kwargs["genetic0_generations"] == 2
assert kwargs["request"].model_dump() == Genetic0Request.model_validate(body).model_dump()
assert kwargs["overrides"] == {"generations": 2}
assert "genetic_parameters" not in kwargs
assert (
kwargs["start_datetime"] is None
@@ -261,7 +374,7 @@ async def test_failed_legacy_http_run_never_reports_previous_solution(
from httpx import ASGITransport, AsyncClient
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
from akkudoktoreos.optimization.genetic0.genetic0api import Genetic0Solution
from akkudoktoreos.server import eos
cls = ems_module.EnergyManagement
@@ -269,7 +382,7 @@ async def test_failed_legacy_http_run_never_reports_previous_solution(
(Path(__file__).parent / "testdata/genetic0/optimize_result_1.json").read_text()
)
previous = Genetic0Solution.model_validate(data)
monkeypatch.setattr(cls, "_genetic0_solution", previous)
_set_native_solution(monkeypatch, "Genetic0", previous)
constructor = Mock()
error = RuntimeError("synthetic " + phase + " failure")
native = SimpleNamespace(
@@ -285,7 +398,7 @@ async def test_failed_legacy_http_run_never_reports_previous_solution(
native.energy_management_plan.side_effect = error
_patch_optimizer(monkeypatch, "Genetic0", constructor)
offline_ems.run = MethodType(cls.run, offline_ems)
offline_ems.genetic0_solution = cls.genetic0_solution
offline_ems.optimizer_result = cls.optimizer_result
monkeypatch.setattr(eos, "get_ems", lambda: offline_ems)
async with AsyncClient(
transport=ASGITransport(app=eos.app, raise_app_exceptions=False), base_url="http://test"
@@ -309,8 +422,7 @@ async def test_conversion_failure_preserves_consistent_previous_results(
):
cls = ems_module.EnergyManagement
previous_specific, previous_generic, previous_plan = object(), object(), object()
suffix = prefix.lower()
monkeypatch.setattr(cls, "_" + suffix + "_solution", previous_specific)
_set_native_solution(monkeypatch, prefix, previous_specific)
monkeypatch.setattr(cls, "_optimization_solution", previous_generic)
monkeypatch.setattr(cls, "_plan", previous_plan)
conversion = AsyncMock(return_value=object())
@@ -322,18 +434,18 @@ async def test_conversion_failure_preserves_consistent_previous_results(
constructor = Mock()
constructor.return_value.optimize_ems.return_value = solution
_patch_optimizer(monkeypatch, prefix, constructor)
supplied_parameters: dict[str, Any] = {suffix + "_parameters": object()}
supplied_parameters = _supplied(prefix, SimpleNamespace(dishwasher=None), 3, 17)
result = await cls.run(
offline_ems,
algorithm=OptimizationAlgorithm(prefix.upper()),
**supplied_parameters,
)
assert result is None
conversion.assert_awaited_once_with()
conversion.assert_awaited_once_with(**_conversion_arguments(prefix))
assert solution.energy_management_plan.call_count == (phase == "plan")
assert offline_ems.adapter.update_data.await_count == 1
assert (
getattr(cls, "_" + suffix + "_solution"),
_native_solution(prefix),
cls.optimization_solution(),
cls.plan(),
cls.stage(),
@@ -352,7 +464,10 @@ async def test_legacy_endpoint_uses_run_return_value_not_last_cached_solution(mo
import json
from pathlib import Path
from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution
from httpx import ASGITransport, AsyncClient
from test_genetic0optimize import result_of
from akkudoktoreos.optimization.genetic0.genetic0api import Genetic0Solution
from akkudoktoreos.server import eos
data = json.loads(
@@ -360,11 +475,88 @@ async def test_legacy_endpoint_uses_run_return_value_not_last_cached_solution(mo
)
produced = Genetic0Solution.model_validate(data)
fake = SimpleNamespace(
run=AsyncMock(return_value=produced),
genetic0_solution=Mock(side_effect=AssertionError("must use this run's result")),
run=AsyncMock(return_value=result_of(produced)),
optimizer_run=Mock(side_effect=AssertionError("must use this run's result")),
)
monkeypatch.setattr(eos, "get_ems", lambda: fake)
result = await eos.fastapi_optimize(parameters=produced.parameters, ngen=1)
assert result.start_solution == produced.start_solution
assert result.result.total_balance == produced.result.total_balance
fake.genetic0_solution.assert_not_called()
async with AsyncClient(
transport=ASGITransport(app=eos.app), base_url="http://test"
) as client:
response = await client.post("/optimize?ngen=1", json=data["parameters"])
assert response.status_code == 200
assert response.json()["start_solution"] == produced.start_solution
assert response.json()["result"]["total_balance"] == produced.result.total_balance
fake.optimizer_run.assert_not_called()
@pytest.mark.asyncio
@pytest.mark.parametrize("prefix", ["Genetic", "Genetic0"])
async def test_raising_preparation_cancels_the_run(monkeypatch, offline_ems, prefix):
"""A preparation that raises cancels the run like one that returns None."""
cls = ems_module.EnergyManagement
previous_specific, previous_generic, previous_plan = object(), object(), object()
_set_native_solution(monkeypatch, prefix, previous_specific)
monkeypatch.setattr(cls, "_optimization_solution", previous_generic)
monkeypatch.setattr(cls, "_plan", previous_plan)
constructor = Mock()
_patch_optimizer(monkeypatch, prefix, constructor)
_patch_prepare(monkeypatch, prefix, AsyncMock(side_effect=RuntimeError("synthetic")))
result = await cls.run(offline_ems, algorithm=OptimizationAlgorithm(prefix.upper()))
assert result is None
constructor.assert_not_called()
assert offline_ems.adapter.update_data.await_count == 1 # acquisition only
assert (
_native_solution(prefix),
cls.optimization_solution(),
cls.plan(),
cls.stage(),
) == (
previous_specific,
previous_generic,
previous_plan,
ems_module.EnergyManagementStage.IDLE,
)
@pytest.mark.asyncio
async def test_previous_genetic0_result_is_the_warm_start_of_the_next_run(
monkeypatch, offline_ems
):
"""The EMS passes the result of the last successful GENETIC0 run into the next preparation.
The optimizer holds no state: the warm start comes from the EMS slot, and a failed run keeps
the previous one.
"""
cls = ems_module.EnergyManagement
first = SimpleNamespace(
start_solution=[1.0, 2.0],
optimization_solution=AsyncMock(return_value=object()),
energy_management_plan=Mock(return_value=object()),
)
second = SimpleNamespace(
start_solution=[3.0, 4.0],
optimization_solution=AsyncMock(return_value=object()),
energy_management_plan=Mock(return_value=object()),
)
constructor = Mock()
constructor.return_value.optimize_ems.side_effect = [
first,
RuntimeError("synthetic optimizer failure"),
second,
second,
]
_patch_optimizer(monkeypatch, "Genetic0", constructor)
prepare = AsyncMock(return_value=SimpleNamespace(dishwasher=None))
_patch_prepare(monkeypatch, "Genetic0", prepare)
for _ in range(3):
await cls.run(offline_ems, algorithm=OptimizationAlgorithm.GENETIC0)
assert cls.optimizer_result("GENETIC0") is second
# Without a stored run there is no warm start.
monkeypatch.setattr(cls, "_optimizer_runs", {})
await cls.run(offline_ems, algorithm=OptimizationAlgorithm.GENETIC0)
assert [_warm_start_of(call) for call in prepare.await_args_list] == [
None,
[1.0, 2.0],
[1.0, 2.0], # the failed second run kept the first as warm start
None,
]
+52 -30
View File
@@ -2,24 +2,24 @@ import numpy as np
import pytest
from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence
from akkudoktoreos.devices.genetic0.genetic0battery import (
Genetic0Battery,
Genetic0ElectricVehicleParameters,
Genetic0SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.genetic0.genetic0homeappliance import (
from akkudoktoreos.optimization.genetic0.devices.genetic0battery import Genetic0Battery
from akkudoktoreos.optimization.genetic0.devices.genetic0homeappliance import (
Genetic0HomeAppliance,
Genetic0HomeApplianceParameters,
)
from akkudoktoreos.devices.genetic0.genetic0inverter import (
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
Genetic0Inverter,
Genetic0InverterParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0 import (
Genetic0EnergyManagementParameters,
Genetic0Simulation,
from akkudoktoreos.optimization.genetic0.genetic0api import (
Genetic0SimulationResult,
)
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0ElectricVehicleRequest,
Genetic0EnergyManagementRequest,
Genetic0HomeApplianceRequest,
Genetic0InverterRequest,
Genetic0SolarPanelBatteryRequest,
)
from akkudoktoreos.optimization.genetic0.genetic0simulation import Genetic0Simulation
from akkudoktoreos.utils.datetimeutil import to_duration, to_time
START_HOUR = 0
@@ -45,38 +45,38 @@ def genetic0_simulation(config_eos) -> Genetic0Simulation:
# Initialize the battery and the inverter
akku = Genetic0Battery(
Genetic0SolarPanelBatteryParameters(
Genetic0SolarPanelBatteryRequest(
device_id="battery1",
capacity_wh=5000,
initial_soc_percentage=80,
min_soc_percentage=10,
),
).to_parameters(),
prediction_hours = config_eos.prediction.hours,
)
akku.reset()
inverter = Genetic0Inverter(
Genetic0InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id),
Genetic0InverterRequest(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id).to_parameters(),
battery = akku,
)
# Household device (currently not used, set to None)
home_appliance = Genetic0HomeAppliance(
Genetic0HomeApplianceParameters(
Genetic0HomeApplianceRequest(
device_id="dishwasher1",
consumption_wh=2000,
duration_h=2,
time_windows=None,
),
).to_parameters(48),
optimization_hours = config_eos.optimization.genetic0.horizon_hours,
prediction_hours = config_eos.prediction.hours,
)
# Example initialization of electric car battery
eauto = Genetic0Battery(
Genetic0ElectricVehicleParameters(
Genetic0ElectricVehicleRequest(
device_id="ev1", capacity_wh=26400, initial_soc_percentage=10, min_soc_percentage=10
),
).to_parameters(),
prediction_hours = config_eos.prediction.hours,
)
eauto.set_charge_per_hour(np.full(config_eos.prediction.hours, 1))
@@ -241,13 +241,13 @@ def genetic0_simulation(config_eos) -> Genetic0Simulation:
# Initialize the energy management system with the respective parameters
genetic0_simulation = Genetic0Simulation()
genetic0_simulation.prepare(
Genetic0EnergyManagementParameters.model_validate(dict(
Genetic0EnergyManagementRequest.model_validate(dict(
pv_prognose_wh=pv_prognose_wh,
strompreis_euro_pro_wh=strompreis_euro_pro_wh,
einspeiseverguetung_euro_pro_wh=einspeiseverguetung_euro_pro_wh,
preis_euro_pro_wh_akku=preis_euro_pro_wh_akku,
gesamtlast=gesamtlast,
)),
)).to_parameters(),
optimization_hours = config_eos.optimization.genetic0.horizon_hours,
prediction_hours = config_eos.prediction.hours,
inverter=inverter,
@@ -287,38 +287,38 @@ def genetic0_simulation_2(config_eos) -> Genetic0Simulation:
# Initialize the battery and the inverter
akku = Genetic0Battery(
Genetic0SolarPanelBatteryParameters(
Genetic0SolarPanelBatteryRequest(
device_id="battery1",
capacity_wh=5000,
initial_soc_percentage=80,
min_soc_percentage=10,
),
).to_parameters(),
prediction_hours = config_eos.prediction.hours,
)
akku.reset()
inverter = Genetic0Inverter(
Genetic0InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id),
Genetic0InverterRequest(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id).to_parameters(),
battery = akku,
)
# Household device (currently not used, set to None)
home_appliance = Genetic0HomeAppliance(
Genetic0HomeApplianceParameters(
Genetic0HomeApplianceRequest(
device_id="dishwasher1",
consumption_wh=2000,
duration_h=2,
time_windows=None,
),
).to_parameters(48),
optimization_hours = config_eos.optimization.genetic0.horizon_hours,
prediction_hours = config_eos.prediction.hours,
)
# Example initialization of electric car battery
eauto = Genetic0Battery(
Genetic0ElectricVehicleParameters(
Genetic0ElectricVehicleRequest(
device_id="ev1", capacity_wh=26400, initial_soc_percentage=10, min_soc_percentage=10
),
).to_parameters(),
prediction_hours = config_eos.prediction.hours,
)
@@ -389,13 +389,13 @@ def genetic0_simulation_2(config_eos) -> Genetic0Simulation:
# Initialize the energy management system with the respective parameters
simulation = Genetic0Simulation()
simulation.prepare(
Genetic0EnergyManagementParameters.model_validate(dict(
Genetic0EnergyManagementRequest.model_validate(dict(
pv_prognose_wh=pv_prognose_wh,
strompreis_euro_pro_wh=strompreis_euro_pro_wh,
einspeiseverguetung_euro_pro_wh=einspeiseverguetung_euro_pro_wh,
preis_euro_pro_wh_akku=preis_euro_pro_wh_akku,
gesamtlast=gesamtlast,
)),
)).to_parameters(),
optimization_hours = config_eos.optimization.genetic0.horizon_hours,
prediction_hours = config_eos.prediction.hours,
inverter=inverter,
@@ -654,3 +654,25 @@ def test_reset(genetic0_simulation_2):
assert simulation.battery.current_soc_percentage() == simulation.battery.parameters.initial_soc_percentage, (
"Battery SOC should be reset to initial value"
)
def test_without_inverter_the_grid_supplies_the_whole_load():
"""Without an inverter the load is bought from the grid; PV is neither used nor fed in."""
hours = 4
simulation = Genetic0Simulation()
simulation.prepare(
Genetic0EnergyManagementRequest(
pv_forecast_wh=[2000.0] * hours,
electricity_price_per_wh=[0.0003] * hours,
feed_in_tariff_per_wh=[0.0001] * hours,
price_per_wh_battery=0.0,
total_load=[1000.0] * hours,
).to_parameters(),
optimization_hours=hours,
prediction_hours=hours,
)
result = simulation.simulate(0)
assert list(result["Netzbezug_Wh_pro_Stunde"]) == [1000.0] * hours
assert list(result["Netzeinspeisung_Wh_pro_Stunde"]) == [0.0] * hours
assert result["Gesamtkosten_Euro"] == pytest.approx(hours * 1000.0 * 0.0003)
assert result["Gesamteinnahmen_Euro"] == 0.0
+12 -10
View File
@@ -3,9 +3,11 @@
import json
from akkudoktoreos.optimization.genetic0.genetic0 import Genetic0SimulationResult
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0EnergyManagementParameters,
from akkudoktoreos.optimization.genetic0.genetic0api import (
Genetic0SimulationResult,
)
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0EnergyManagementRequest,
)
@@ -18,7 +20,7 @@ def test_genetic0_params_german_input():
"preis_euro_pro_wh_akku": 0.0001,
"gesamtlast": [500.0, 600.0],
}
params = Genetic0EnergyManagementParameters.model_validate(data_de)
params = Genetic0EnergyManagementRequest.model_validate(data_de)
assert params.pv_forecast_wh == [100.0, 200.0]
print("✅ German input accepted")
@@ -31,7 +33,7 @@ def test_genetic0_params_english_input():
"price_per_wh_battery": 0.0001,
"total_load": [500.0, 600.0],
}
params = Genetic0EnergyManagementParameters.model_validate(data_en)
params = Genetic0EnergyManagementRequest.model_validate(data_en)
assert params.pv_forecast_wh == [100.0, 200.0]
print("✅ English input accepted")
@@ -44,7 +46,7 @@ def test_genetic0_params_english_output():
"preis_euro_pro_wh_akku": 0.0001,
"gesamtlast": [500.0, 600.0],
}
params = Genetic0EnergyManagementParameters.model_validate(data_de)
params = Genetic0EnergyManagementRequest.model_validate(data_de)
json_output = json.loads(params.model_dump_json(by_alias=True))
# English names should be in output
@@ -129,8 +131,8 @@ if __name__ == "__main__":
def test_genetic0_optimization_parameters_device_translations():
"""Test that German device field names are accepted and re-emitted."""
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0OptimizationParameters,
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0Request,
)
ems_de = {
@@ -140,7 +142,7 @@ def test_genetic0_optimization_parameters_device_translations():
"preis_euro_pro_wh_akku": 0.0001,
"gesamtlast": [500.0, 600.0],
}
params = Genetic0OptimizationParameters.model_validate(dict(
params = Genetic0Request.model_validate(dict(
ems=ems_de,
pv_akku={"device_id": "battery1", "capacity_wh": 8000},
inverter=None,
@@ -153,7 +155,7 @@ def test_genetic0_optimization_parameters_device_translations():
assert params.ev.capacity_wh == 60000
# English input names work as well
params_en = Genetic0OptimizationParameters.model_validate(dict(
params_en = Genetic0Request.model_validate(dict(
ems=ems_de,
pv_battery={"device_id": "battery1", "capacity_wh": 8000},
inverter=None,
+54
View File
@@ -1,10 +1,18 @@
from pathlib import Path
from unittest.mock import AsyncMock, Mock, patch
import numpy as np
import pytest
from matplotlib.testing.compare import compare_images
from akkudoktoreos.core.coreabc import get_ems
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.optimization.genetic0.genetic0optimizer import Genetic0Optimizer
from akkudoktoreos.optimization.genetic0.genetic0visualize import (
genetic0_generate_example_report,
genetic0_prepare_visualize,
)
from akkudoktoreos.utils.datetimeutil import to_datetime
filename = "example_report.pdf"
@@ -35,3 +43,49 @@ def test_generate_pdf_example(config_eos):
reference_png_file.unlink()
output_file.unlink()
output_png_file.unlink()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"prediction_hours, start",
[
(6, "2026-08-01T00:00:00+00:00"), # fewer than 12 hours shown
(30, "2026-08-01T14:00:00+00:00"), # not the 48 hours the labels once assumed
],
)
async def test_report_of_a_run_that_is_not_48_hours_long(config_eos, prediction_hours, start):
"""The report shows a run of any length the run accepts."""
config_eos.merge_settings_from_dict(
{
"general": {"timezone_override": "UTC"},
"prediction": {"hours": prediction_hours},
"optimization": {"genetic0": {"individuals": 10, "generations": 10, "seed": 1}},
"elecfee": {"provider": None},
"devices": {
"max_batteries": 0,
"max_electric_vehicles": 0,
"max_inverters": 0,
"max_home_appliances": 0,
},
}
)
get_ems().set_start_datetime(to_datetime(start, in_timezone="UTC"))
async def read_array(*, start_datetime, end_datetime, interval, **kwargs):
slots = int((end_datetime - start_datetime).total_seconds() / interval.total_seconds())
return np.full(slots, 0.0003)
prediction = Mock(
update_data=AsyncMock(),
key_to_array=AsyncMock(side_effect=read_array),
key_to_raw_series=AsyncMock(side_effect=KeyError("no tariff")),
record_keys=[key for key, _ in genetic0prepare.PRESENTATION_PREDICTIONS],
)
optimizer = Genetic0Optimizer()
with patch.object(genetic0prepare, "get_prediction", return_value=prediction):
parameters = await optimizer.prepare(
get_ems().start_datetime, get_ems().observation_datetime, None
)
result = optimizer.run(parameters)
assert genetic0_prepare_visualize(parameters, result).startswith(b"%PDF-")
+2 -1
View File
@@ -11,6 +11,7 @@ from akkudoktoreos.devices.genetic.battery import (
SolarPanelBatteryParameters,
)
from akkudoktoreos.devices.settings.batterysettings import BatteryProfileAdjustment
from akkudoktoreos.optimization.genetic0 import genetic0prepare
@pytest.fixture
@@ -439,7 +440,7 @@ def test_equal_soc_limits_are_valid(target):
max_soc_percentage=target,
profile_adjustment=BatteryProfileAdjustment(nominal_capacity_wh=8000))
assert settings.to_genetic_ev_bat_param().min_soc_percentage == target
assert settings.to_genetic0_ev_bat_param().min_soc_percentage == target
assert genetic0prepare.electric_vehicle_request(settings).min_soc_percentage == target
@pytest.mark.parametrize("minimum,maximum", [(100, 99), (81, 80), (101, 100), (-1, 100)])
+4 -3
View File
@@ -20,6 +20,7 @@ from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettin
from akkudoktoreos.devices.settings.homeappliancesettings import (
HomeApplianceCommonSettings,
)
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.utils.datetimeutil import to_datetime
@@ -74,7 +75,7 @@ def test_profile_cannot_silently_override_explicit_flat_definition(fields: dict[
def test_settings_profile_roundtrip_and_legacy_defaults() -> None:
defaults = HomeApplianceCommonSettings(device_id="legacy")
assert defaults.to_genetic_param().consumption_wh == 3000
assert defaults.to_genetic0_param().duration_h == 3
assert genetic0prepare.home_appliance_request(defaults).duration_h == 3
settings = HomeApplianceCommonSettings.model_validate(
{
"device_id": "washer",
@@ -94,7 +95,7 @@ def test_settings_profile_roundtrip_and_legacy_defaults() -> None:
assert params.schedule_mode == ConsumerScheduleMode.DAILY
assert params.shared_time_windows is not None
with pytest.raises(ValueError, match="GENETIC"):
restored.to_genetic0_param()
genetic0prepare.home_appliance_request(restored)
def test_cycle_and_shared_windows_intersect_after_completed_cycle() -> None:
@@ -245,7 +246,7 @@ def test_ev_deadlines_roundtrip_without_changing_slot_physics() -> None:
charged, losses = battery.charge_energy(2000, hour=0)
assert charged == pytest.approx(1000 * params.charging_efficiency)
assert losses == pytest.approx(1000 * (1 - params.charging_efficiency))
assert "min_soc_deadline_datetime" not in settings.to_genetic0_ev_bat_param().model_dump()
assert "min_soc_deadline_datetime" not in genetic0prepare.electric_vehicle_request(settings).model_dump()
@pytest.mark.parametrize("duration", [0.0, -1.0, float("inf"), float("nan")])
@@ -422,6 +422,7 @@ async def test_real_ems_returns_coherent_quarter_hour_solution_and_plan(
)
assert solution is not None
assert solution is ems.genetic_solution()
assert solution is not None # run() returns Any; `is` narrowed to Optional
assert solution.start_solution_datetime == fake.start_datetime
assert len(solution.ac_charge) == 4
assert ems.optimization_solution() is not None
+8 -2
View File
@@ -9,6 +9,7 @@ from akkudoktoreos.devices.genetic.battery import (
)
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
from akkudoktoreos.optimization.genetic0 import genetic0prepare
@pytest.fixture
@@ -495,10 +496,15 @@ class TestInverterSettings:
def test_inverter_conversion_requires_nominal_power(self, config_eos, converter):
# The generic inverter profile provides no nominal power.
settings = InverterCommonSettings(device_id="inverter")
convert = (
(lambda: genetic0prepare.inverter_request(settings))
if converter == "to_genetic0_param"
else getattr(settings, converter)
)
with pytest.raises(ValueError, match="nominal_power_w"):
getattr(settings, converter)()
convert()
settings.profile_adjustment.nominal_power_w = 4200
assert getattr(settings, converter)().max_power_wh == 4200
assert convert().max_power_wh == 4200
def test_battery_discharge_limit_caps_load_and_grid_export():
+1 -3
View File
@@ -60,9 +60,7 @@ async def test_render_is_offloaded_and_uses_an_owned_copy(config_eos, monkeypatc
monkeypatch.setattr(
eos,
"get_ems",
lambda: SimpleNamespace(
genetic_solution=lambda: solution, genetic0_solution=lambda: solution
),
lambda: SimpleNamespace(genetic_solution=lambda: solution),
)
original_controls = list(solution.ac_charge)
+2 -1
View File
@@ -26,6 +26,7 @@ from akkudoktoreos.devices.settings.invertersettings import (
InverterCommonSettings,
InverterProfileAdjustment,
)
from akkudoktoreos.optimization.genetic0 import genetic0prepare
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
@@ -444,7 +445,7 @@ class TestSettings:
device_id="inverter1",
profile_adjustment=InverterProfileAdjustment(nominal_power_w=5000),
)
params = settings.to_genetic0_param()
params = genetic0prepare.inverter_request(settings)
assert not hasattr(params, "dc_to_ac_efficiency_curve")
+5 -3
View File
@@ -87,15 +87,17 @@ def test_genetic_interpolator_boundaries_are_finite_and_physical(load, pv):
def test_genetic0_inverter_keeps_its_independent_interpolator():
from akkudoktoreos.devices.genetic0.genetic0inverter import (
from akkudoktoreos.optimization.genetic0.devices.genetic0inverter import (
Genetic0Inverter,
Genetic0InverterParameters,
)
from akkudoktoreos.optimization.genetic0.genetic0loadinterpolator import (
get_genetic0_load_interpolator,
)
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0InverterRequest,
)
inverter = Genetic0Inverter(Genetic0InverterParameters(device_id="legacy", max_power_wh=10000))
inverter = Genetic0Inverter(Genetic0InverterRequest(device_id="legacy", max_power_wh=10000).to_parameters())
assert inverter.self_consumption_predictor is get_genetic0_load_interpolator()
assert inverter.self_consumption_predictor is not get_eos_load_interpolator()
+2 -1
View File
@@ -24,7 +24,8 @@ LAZY_MODULES = [
"lxml",
"scipy",
"tzfpy",
"akkudoktoreos.optimization.genetic0.genetic0",
"akkudoktoreos.optimization.genetic0.genetic0algorithm",
"akkudoktoreos.optimization.genetic0.genetic0simulation",
"akkudoktoreos.optimization.genetic0.genetic0visualize",
"akkudoktoreos.optimization.genetic.geneticvisualize",
]
+38 -15
View File
@@ -1,12 +1,13 @@
"""Contracts shared by the configuration, tariff and optimizer PRs."""
from types import SimpleNamespace
from typing import Any
from unittest.mock import Mock
import pytest
from akkudoktoreos.optimization.genetic0.genetic0params import (
Genetic0EnergyManagementParameters,
from akkudoktoreos.optimization.genetic0.genetic0request import (
Genetic0EnergyManagementRequest,
)
from akkudoktoreos.optimization.genetic.geneticparams import (
GeneticEnergyManagementParameters,
@@ -15,7 +16,7 @@ from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
@pytest.mark.parametrize(
"model", [GeneticEnergyManagementParameters, Genetic0EnergyManagementParameters]
"model", [GeneticEnergyManagementParameters, Genetic0EnergyManagementRequest]
)
@pytest.mark.parametrize("tariff", [0.00008, [0.00008, -0.00002]])
def test_energy_parameter_aliases_preserve_wh_prices(model, tariff):
@@ -45,12 +46,14 @@ def test_energy_parameter_aliases_preserve_wh_prices(model, tariff):
@pytest.mark.asyncio
@pytest.mark.parametrize("algorithm", list(OptimizationAlgorithm))
async def test_algorithm_result_endpoint_keeps_solution_types_separate(monkeypatch, algorithm):
"""GENETIC is served by the generic route, GENETIC0 by its own router (ADR 0005)."""
from httpx import ASGITransport, AsyncClient
from akkudoktoreos.server import eos
genetic, genetic0 = object(), object()
fake = SimpleNamespace(
genetic_solution=Mock(return_value=genetic),
genetic0_solution=Mock(return_value=genetic0),
genetic_solution=Mock(return_value=None),
optimizer_run=Mock(return_value=None),
)
monkeypatch.setattr(eos, "get_ems", lambda: fake)
monkeypatch.setattr(
@@ -58,14 +61,17 @@ async def test_algorithm_result_endpoint_keeps_solution_types_separate(monkeypat
"get_config",
lambda: SimpleNamespace(optimization=SimpleNamespace(algorithms=["GENETIC", "GENETIC0"])),
)
result = await eos.fastapi_energy_management_optimization_solution_algorithm_get(algorithm)
async with AsyncClient(
transport=ASGITransport(app=eos.app, raise_app_exceptions=False), base_url="http://test"
) as client:
response = await client.get(f"/v1/energy-management/optimization/solution/{algorithm}")
assert response.status_code == 404
assert response.json()["title"] == "Algorithm specific optimization solution retrieval failed"
if algorithm == OptimizationAlgorithm.GENETIC:
assert result is genetic
fake.genetic_solution.assert_called_once_with()
fake.genetic0_solution.assert_not_called()
fake.optimizer_run.assert_not_called()
else:
assert result is genetic0
fake.genetic0_solution.assert_called_once_with()
fake.optimizer_run.assert_called_once_with("GENETIC0")
fake.genetic_solution.assert_not_called()
@@ -95,10 +101,27 @@ def test_device_maps_feed_algorithm_specific_converters(algorithm):
assert settings.batteries is not None
assert settings.electric_vehicles is not None
assert settings.inverters is not None
battery = getattr(settings.batteries["storage"], "to_" + algorithm + "_pv_bat_param")()
ev = getattr(settings.electric_vehicles["car"], "to_" + algorithm + "_ev_bat_param")()
inverter = getattr(settings.inverters["inverter"], "to_" + algorithm + "_param")()
appliance = getattr(settings.home_appliances["washer"], "to_" + algorithm + "_param")()
storage = settings.batteries["storage"]
car = settings.electric_vehicles["car"]
hybrid = settings.inverters["inverter"]
washer = settings.home_appliances["washer"]
battery: Any
ev: Any
inverter: Any
appliance: Any
if algorithm == "genetic0":
# GENETIC0 converts the device settings in its parameter preparation (ADR 0004).
from akkudoktoreos.optimization.genetic0 import genetic0prepare
battery = genetic0prepare.battery_request(storage)
ev = genetic0prepare.electric_vehicle_request(car)
inverter = genetic0prepare.inverter_request(hybrid)
appliance = genetic0prepare.home_appliance_request(washer)
else:
battery = storage.to_genetic_pv_bat_param()
ev = car.to_genetic_ev_bat_param()
inverter = hybrid.to_genetic_param()
appliance = washer.to_genetic_param()
assert (battery.device_id, ev.device_id, inverter.device_id, appliance.device_id) == (
"storage",
"car",
+4 -174
View File
@@ -336,11 +336,6 @@ def collect_violations() -> frozenset[Violation]:
# the existing uses revealed by a new list entry (ADR 0007).
BASELINE: frozenset[Violation] = frozenset(
{
Violation(
"cross-optimizer",
"akkudoktoreos.optimization.genetic0.genetic0params",
"akkudoktoreos.optimization.genetic.forecast",
),
Violation(
"internals",
"akkudoktoreos.config.configmigrate",
@@ -366,31 +361,11 @@ BASELINE: frozenset[Violation] = frozenset(
"akkudoktoreos.core.ems",
"akkudoktoreos.optimization.genetic.geneticsolution",
),
Violation(
"internals",
"akkudoktoreos.core.ems",
"akkudoktoreos.optimization.genetic0.genetic0",
),
Violation(
"internals",
"akkudoktoreos.core.ems",
"akkudoktoreos.optimization.genetic0.genetic0params",
),
Violation(
"internals",
"akkudoktoreos.core.ems",
"akkudoktoreos.optimization.genetic0.genetic0solution",
),
Violation(
"internals",
"akkudoktoreos.optimization.optimization",
"akkudoktoreos.optimization.genetic.geneticsettings",
),
Violation(
"internals",
"akkudoktoreos.optimization.optimization",
"akkudoktoreos.optimization.genetic0.genetic0settings",
),
Violation(
"internals",
"akkudoktoreos.server.eos",
@@ -406,21 +381,6 @@ BASELINE: frozenset[Violation] = frozenset(
"akkudoktoreos.server.eos",
"akkudoktoreos.optimization.genetic.geneticvisualize",
),
Violation(
"internals",
"akkudoktoreos.server.eos",
"akkudoktoreos.optimization.genetic0.genetic0params",
),
Violation(
"internals",
"akkudoktoreos.server.eos",
"akkudoktoreos.optimization.genetic0.genetic0solution",
),
Violation(
"internals",
"akkudoktoreos.server.eos",
"akkudoktoreos.optimization.genetic0.genetic0visualize",
),
Violation(
"pydantic",
"akkudoktoreos.devices.genetic.battery",
@@ -436,21 +396,6 @@ BASELINE: frozenset[Violation] = frozenset(
"akkudoktoreos.devices.genetic.inverter",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.devices.genetic0.genetic0battery",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.devices.genetic0.genetic0homeappliance",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.devices.genetic0.genetic0inverter",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic.configrequest",
@@ -513,74 +458,24 @@ BASELINE: frozenset[Violation] = frozenset(
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic0.genetic0",
"akkudoktoreos.optimization.genetic0.genetic0convert",
"akkudoktoreos.core.pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic0.genetic0",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic0.genetic0abc",
"akkudoktoreos.core.pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic0.genetic0abc",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic0.genetic0devices",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic0.genetic0params",
"pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic0.genetic0solution",
"akkudoktoreos.core.pydantic",
),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic0.genetic0solution",
"pydantic",
),
Violation(
"shared-config",
"akkudoktoreos.devices.settings.batterysettings",
"akkudoktoreos.devices.genetic.battery",
),
Violation(
"shared-config",
"akkudoktoreos.devices.settings.batterysettings",
"akkudoktoreos.devices.genetic0.genetic0battery",
),
Violation(
"shared-config",
"akkudoktoreos.devices.settings.homeappliancesettings",
"akkudoktoreos.devices.genetic.homeappliance",
),
Violation(
"shared-config",
"akkudoktoreos.devices.settings.homeappliancesettings",
"akkudoktoreos.devices.genetic0.genetic0homeappliance",
),
Violation(
"shared-config",
"akkudoktoreos.devices.settings.invertersettings",
"akkudoktoreos.devices.genetic.inverter",
),
Violation(
"shared-config",
"akkudoktoreos.devices.settings.invertersettings",
"akkudoktoreos.devices.genetic0.genetic0inverter",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic.battery",
@@ -616,16 +511,6 @@ BASELINE: frozenset[Violation] = frozenset(
"akkudoktoreos.devices.genetic.inverter",
"akkudoktoreos.prediction.interpolator",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic0.genetic0battery",
"akkudoktoreos.devices.settings.batterysettings",
),
Violation(
"world-access",
"akkudoktoreos.devices.genetic0.genetic0homeappliance",
"akkudoktoreos.config.configabc",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic.configrequest",
@@ -713,68 +598,13 @@ BASELINE: frozenset[Violation] = frozenset(
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0",
"akkudoktoreos.optimization.optimizationabc:OptimizationBase",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0loadinterpolator",
"akkudoktoreos.core.cache",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0loadinterpolator",
"akkudoktoreos.utils.gridinterpolator:configured_grid_interpolator_backend",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0params",
"akkudoktoreos.core.coreabc:ConfigMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0params",
"akkudoktoreos.core.coreabc:MeasurementMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0params",
"akkudoktoreos.core.coreabc:PredictionMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0params",
"akkudoktoreos.core.coreabc:get_ems",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0solution",
"akkudoktoreos.core.coreabc:ConfigMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0solution",
"akkudoktoreos.core.coreabc:get_ems",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0solution",
"akkudoktoreos.core.coreabc:get_prediction",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0solution",
"akkudoktoreos.optimization.genetic0.genetic0convert",
"akkudoktoreos.devices.devicesabc",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0visualize",
"akkudoktoreos.core.coreabc:ConfigMixin",
),
Violation(
"world-access",
"akkudoktoreos.optimization.genetic0.genetic0visualize",
"akkudoktoreos.core.coreabc:get_ems",
"akkudoktoreos.optimization.genetic0.genetic0request",
"akkudoktoreos.config.configabc",
),
}
)
+25
View File
@@ -0,0 +1,25 @@
"""The optimizer registry (ADR 0005)."""
import pytest
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
from akkudoktoreos.optimization.optimizerregistry import get_optimizer
class TestOptimizerRegistry:
"""Finding optimizers by name."""
@pytest.mark.parametrize("name", ["GENETIC0"])
def test_registered_optimizer_carries_its_name(self, name: str) -> None:
optimizer = get_optimizer(name)
assert optimizer is not None
assert optimizer.name == name
# The registry name is the value of optimization.algorithm.
assert OptimizationAlgorithm(name) == name
def test_algorithm_enum_finds_the_same_optimizer(self) -> None:
assert get_optimizer(OptimizationAlgorithm.GENETIC0) is get_optimizer("GENETIC0")
@pytest.mark.parametrize("name", ["UNKNOWN", "", "genetic0"])
def test_unregistered_name_gives_none(self, name: str) -> None:
assert get_optimizer(name) is None
File diff suppressed because it is too large Load Diff
+329
View File
@@ -0,0 +1,329 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-01-14T10:00:00+01:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T01:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T06:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T07:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T08:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+289
View File
@@ -0,0 +1,289 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-01-14T10:00:00+01:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T02:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T03:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T04:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T06:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T07:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T08:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+579
View File
@@ -0,0 +1,579 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-01-14T10:00:00+01:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T19:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T21:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T00:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T00:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T01:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T01:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T02:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T02:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T03:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T03:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T04:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T04:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T06:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T06:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T07:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T07:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T08:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T08:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T09:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T09:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+599
View File
@@ -0,0 +1,599 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-03-28T10:00:00+01:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-03-28T10:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.23171229338842977,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-03-28T14:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.031712293388430055,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-03-28T16:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.031712293388430055,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.2205836776859505,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-28T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.25621900826446364,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-28T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-29T00:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.056219008264463924,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T01:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-29T03:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T03:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T04:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T05:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-29T07:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T07:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-29T08:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T08:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T09:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-29T11:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T11:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T12:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-29T13:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T14:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T15:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-29T16:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T16:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T17:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T18:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T19:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-29T20:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T20:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T21:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T22:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-29T23:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-03-29T23:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-03-30T00:00:00+02:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+449
View File
@@ -0,0 +1,449 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-01-14T10:00:00+01:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T14:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T16:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T00:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T01:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T02:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T03:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T05:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T06:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T07:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T08:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T09:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T09:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+599
View File
@@ -0,0 +1,599 @@
{
"id": "plan-genetic@<now>",
"generated_at": "<now>",
"valid_from": "2026-01-14T10:00:00+01:00",
"valid_until": null,
"instructions": [
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T10:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.23171229338842977,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T14:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "RUN",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.031712293388430055,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "homeappliance1@<uuid>",
"execution_time": "2026-01-14T16:00:00+01:00",
"abnormal_condition": false,
"type": "DDBCInstruction",
"actuator_id": "homeappliance1",
"operation_mode_id": "OFF",
"operation_mode_factor": 1.0,
"resource_id": "homeappliance1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.031712293388430055,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.2205836776859505,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-14T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.25621900826446364,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-14T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T00:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "FORCED_CHARGE",
"operation_mode_factor": 0.056219008264463924,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T01:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T02:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T02:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T03:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T04:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T06:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T06:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T07:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T07:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T08:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "NON_EXPORT",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T10:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T11:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.375,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T12:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T13:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T14:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T15:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T16:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T17:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T18:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.625,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "IDLE",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T19:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.75,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T20:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.875,
"resource_id": "ev1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T21:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 1.0,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "PEAK_SHAVING",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
},
{
"id": "ev1@<uuid>",
"execution_time": "2026-01-15T22:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "ev1",
"operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": 0.5,
"resource_id": "ev1"
},
{
"id": "battery1@<uuid>",
"execution_time": "2026-01-15T23:00:00+01:00",
"abnormal_condition": false,
"type": "FRBCInstruction",
"actuator_id": "battery1",
"operation_mode_id": "SELF_CONSUMPTION",
"operation_mode_factor": 1.0,
"resource_id": "battery1"
}
],
"comment": "Energy management plan derived from GeneticSolution."
}
File diff suppressed because it is too large Load Diff
+982
View File
@@ -0,0 +1,982 @@
{
"expected_result": "optimize_result_1.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": [
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05
],
"price_per_wh_battery": 0.0001,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": [
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05
],
"preis_euro_pro_wh_akku": 0.0001,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 15,
"max_soc_percentage": 100,
"charge_rates": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"max_ac_charge_power_w": null
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 54,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"dishwasher": null,
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": [
1.0,
1.0,
1.0,
1.0,
0.0,
1.0,
0.0,
0.0,
1.0,
1.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0
],
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 15,
"max_soc_percentage": 100,
"charge_rates": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 54,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
}
},
"start_hour": 10,
"settings": {
"prediction_hours": 48,
"horizon_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 0
},
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"battery_charge_rates": null,
"self_consumption_interpolator": "scipy",
"verbose": false
},
"presentation": {
"start_datetime": {
"datetime": "2026-01-14T10:00:00+01:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"battery_device_id": "battery1",
"ev_device_id": "ev1",
"home_appliance_device_id": "homeappliance1",
"home_appliance_enabled": true,
"prediction_series": {
"pvforecast_ac_power": [
170.5,
171.0,
171.5,
172.0,
172.5,
173.0,
173.5,
174.0,
174.5,
175.0,
175.5,
176.0,
176.5,
177.0,
177.5,
178.0,
178.5,
179.0,
179.5,
180.0,
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0
],
"pvforecast_dc_power": [
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0,
189.5,
190.0,
190.5,
191.0,
191.5,
192.0,
192.5,
193.0,
193.5,
194.0,
194.5,
195.0,
195.5,
196.0,
196.5,
197.0,
197.5,
198.0,
198.5,
199.0
],
"elecprice_marketprice_wh": [
1190.5,
1191.0,
1191.5,
1192.0,
1192.5,
1193.0,
1193.5,
1194.0,
1194.5,
1195.0,
1195.5,
1196.0,
1196.5,
1197.0,
1197.5,
1198.0,
1198.5,
1199.0,
1199.5,
1200.0,
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0
],
"feed_in_tariff_wh": [
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0,
1209.5,
1210.0,
1210.5,
1211.0,
1211.5,
1212.0,
1212.5,
1213.0,
1213.5,
1214.0,
1214.5,
1215.0,
1215.5,
1216.0,
1216.5,
1217.0,
1217.5,
1218.0,
1218.5,
1219.0
],
"weather_temp_air": [
210.5,
211.0,
211.5,
212.0,
212.5,
213.0,
213.5,
214.0,
214.5,
215.0,
215.5,
216.0,
216.5,
217.0,
217.5,
218.0,
218.5,
219.0,
219.5,
220.0,
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0
],
"loadforecast_power_w": [
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0,
229.5,
230.0,
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0
],
"loadakkudoktor_std_power_w": [
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0,
239.5,
240.0,
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0
],
"loadakkudoktor_mean_power_w": [
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0,
249.5,
250.0,
250.5,
251.0,
251.5,
252.0,
252.5,
253.0,
253.5,
254.0,
254.5,
255.0,
255.5,
256.0,
256.5,
257.0,
257.5,
258.0,
258.5,
259.0
]
}
}
}
}
+982
View File
@@ -0,0 +1,982 @@
{
"expected_result": "optimize_result_1_be.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": [
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05
],
"price_per_wh_battery": 0.0001,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": [
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05,
7e-05
],
"preis_euro_pro_wh_akku": 0.0001,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 15,
"max_soc_percentage": 100,
"charge_rates": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"max_ac_charge_power_w": null
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 54,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"dishwasher": null,
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": [
1.0,
1.0,
1.0,
1.0,
0.0,
1.0,
0.0,
0.0,
1.0,
1.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0
],
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 15,
"max_soc_percentage": 100,
"charge_rates": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 54,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
}
},
"start_hour": 10,
"settings": {
"prediction_hours": 48,
"horizon_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 1
},
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"battery_charge_rates": null,
"self_consumption_interpolator": "scipy",
"verbose": false
},
"presentation": {
"start_datetime": {
"datetime": "2026-01-14T10:00:00+01:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"battery_device_id": "battery1",
"ev_device_id": "ev1",
"home_appliance_device_id": "homeappliance1",
"home_appliance_enabled": true,
"prediction_series": {
"pvforecast_ac_power": [
170.5,
171.0,
171.5,
172.0,
172.5,
173.0,
173.5,
174.0,
174.5,
175.0,
175.5,
176.0,
176.5,
177.0,
177.5,
178.0,
178.5,
179.0,
179.5,
180.0,
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0
],
"pvforecast_dc_power": [
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0,
189.5,
190.0,
190.5,
191.0,
191.5,
192.0,
192.5,
193.0,
193.5,
194.0,
194.5,
195.0,
195.5,
196.0,
196.5,
197.0,
197.5,
198.0,
198.5,
199.0
],
"elecprice_marketprice_wh": [
1190.5,
1191.0,
1191.5,
1192.0,
1192.5,
1193.0,
1193.5,
1194.0,
1194.5,
1195.0,
1195.5,
1196.0,
1196.5,
1197.0,
1197.5,
1198.0,
1198.5,
1199.0,
1199.5,
1200.0,
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0
],
"feed_in_tariff_wh": [
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0,
1209.5,
1210.0,
1210.5,
1211.0,
1211.5,
1212.0,
1212.5,
1213.0,
1213.5,
1214.0,
1214.5,
1215.0,
1215.5,
1216.0,
1216.5,
1217.0,
1217.5,
1218.0,
1218.5,
1219.0
],
"weather_temp_air": [
210.5,
211.0,
211.5,
212.0,
212.5,
213.0,
213.5,
214.0,
214.5,
215.0,
215.5,
216.0,
216.5,
217.0,
217.5,
218.0,
218.5,
219.0,
219.5,
220.0,
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0
],
"loadforecast_power_w": [
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0,
229.5,
230.0,
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0
],
"loadakkudoktor_std_power_w": [
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0,
239.5,
240.0,
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0
],
"loadakkudoktor_mean_power_w": [
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0,
249.5,
250.0,
250.5,
251.0,
251.5,
252.0,
252.5,
253.0,
253.5,
254.0,
254.5,
255.0,
255.5,
256.0,
256.5,
257.0,
257.5,
258.0,
258.5,
259.0
]
}
}
}
}
+801
View File
@@ -0,0 +1,801 @@
{
"expected_result": "optimize_result_2.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": 7e-05,
"price_per_wh_battery": 0.0,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": 7e-05,
"preis_euro_pro_wh_akku": 0.0,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"max_ac_charge_power_w": null
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null
},
"dishwasher": {
"device_id": "dishwasher1",
"hours": null,
"consumption_wh": 5000,
"duration_h": 2,
"time_windows": {
"windows": [
{
"start_time": "00:00:00.000000",
"duration": "2 days",
"end_time": null,
"day_of_week": null,
"date": null,
"month": null,
"locale": null
}
]
}
},
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null
}
},
"start_hour": 10,
"settings": {
"prediction_hours": 48,
"horizon_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 0
},
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"battery_charge_rates": null,
"self_consumption_interpolator": "scipy",
"verbose": false
},
"presentation": {
"start_datetime": {
"datetime": "2026-01-14T10:00:00+01:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"battery_device_id": "battery1",
"ev_device_id": "ev1",
"home_appliance_device_id": "homeappliance1",
"home_appliance_enabled": true,
"prediction_series": {
"pvforecast_ac_power": [
170.5,
171.0,
171.5,
172.0,
172.5,
173.0,
173.5,
174.0,
174.5,
175.0,
175.5,
176.0,
176.5,
177.0,
177.5,
178.0,
178.5,
179.0,
179.5,
180.0,
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0
],
"pvforecast_dc_power": [
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0,
189.5,
190.0,
190.5,
191.0,
191.5,
192.0,
192.5,
193.0,
193.5,
194.0,
194.5,
195.0,
195.5,
196.0,
196.5,
197.0,
197.5,
198.0,
198.5,
199.0
],
"elecprice_marketprice_wh": [
1190.5,
1191.0,
1191.5,
1192.0,
1192.5,
1193.0,
1193.5,
1194.0,
1194.5,
1195.0,
1195.5,
1196.0,
1196.5,
1197.0,
1197.5,
1198.0,
1198.5,
1199.0,
1199.5,
1200.0,
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0
],
"feed_in_tariff_wh": [
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0,
1209.5,
1210.0,
1210.5,
1211.0,
1211.5,
1212.0,
1212.5,
1213.0,
1213.5,
1214.0,
1214.5,
1215.0,
1215.5,
1216.0,
1216.5,
1217.0,
1217.5,
1218.0,
1218.5,
1219.0
],
"weather_temp_air": [
210.5,
211.0,
211.5,
212.0,
212.5,
213.0,
213.5,
214.0,
214.5,
215.0,
215.5,
216.0,
216.5,
217.0,
217.5,
218.0,
218.5,
219.0,
219.5,
220.0,
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0
],
"loadforecast_power_w": [
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0,
229.5,
230.0,
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0
],
"loadakkudoktor_std_power_w": [
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0,
239.5,
240.0,
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0
],
"loadakkudoktor_mean_power_w": [
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0,
249.5,
250.0,
250.5,
251.0,
251.5,
252.0,
252.5,
253.0,
253.5,
254.0,
254.5,
255.0,
255.5,
256.0,
256.5,
257.0,
257.5,
258.0,
258.5,
259.0
]
}
}
}
}
+801
View File
@@ -0,0 +1,801 @@
{
"expected_result": "optimize_result_2_be.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": 7e-05,
"price_per_wh_battery": 0.0,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": 7e-05,
"preis_euro_pro_wh_akku": 0.0,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"max_ac_charge_power_w": null
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null
},
"dishwasher": {
"device_id": "dishwasher1",
"hours": null,
"consumption_wh": 5000,
"duration_h": 2,
"time_windows": {
"windows": [
{
"start_time": "00:00:00.000000",
"duration": "2 days",
"end_time": null,
"day_of_week": null,
"date": null,
"month": null,
"locale": null
}
]
}
},
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null
}
},
"start_hour": 10,
"settings": {
"prediction_hours": 48,
"horizon_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 1
},
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"battery_charge_rates": null,
"self_consumption_interpolator": "scipy",
"verbose": false
},
"presentation": {
"start_datetime": {
"datetime": "2026-01-14T10:00:00+01:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"battery_device_id": "battery1",
"ev_device_id": "ev1",
"home_appliance_device_id": "homeappliance1",
"home_appliance_enabled": true,
"prediction_series": {
"pvforecast_ac_power": [
170.5,
171.0,
171.5,
172.0,
172.5,
173.0,
173.5,
174.0,
174.5,
175.0,
175.5,
176.0,
176.5,
177.0,
177.5,
178.0,
178.5,
179.0,
179.5,
180.0,
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0
],
"pvforecast_dc_power": [
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0,
189.5,
190.0,
190.5,
191.0,
191.5,
192.0,
192.5,
193.0,
193.5,
194.0,
194.5,
195.0,
195.5,
196.0,
196.5,
197.0,
197.5,
198.0,
198.5,
199.0
],
"elecprice_marketprice_wh": [
1190.5,
1191.0,
1191.5,
1192.0,
1192.5,
1193.0,
1193.5,
1194.0,
1194.5,
1195.0,
1195.5,
1196.0,
1196.5,
1197.0,
1197.5,
1198.0,
1198.5,
1199.0,
1199.5,
1200.0,
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0
],
"feed_in_tariff_wh": [
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0,
1209.5,
1210.0,
1210.5,
1211.0,
1211.5,
1212.0,
1212.5,
1213.0,
1213.5,
1214.0,
1214.5,
1215.0,
1215.5,
1216.0,
1216.5,
1217.0,
1217.5,
1218.0,
1218.5,
1219.0
],
"weather_temp_air": [
210.5,
211.0,
211.5,
212.0,
212.5,
213.0,
213.5,
214.0,
214.5,
215.0,
215.5,
216.0,
216.5,
217.0,
217.5,
218.0,
218.5,
219.0,
219.5,
220.0,
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0
],
"loadforecast_power_w": [
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0,
229.5,
230.0,
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0
],
"loadakkudoktor_std_power_w": [
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0,
239.5,
240.0,
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0
],
"loadakkudoktor_mean_power_w": [
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0,
249.5,
250.0,
250.5,
251.0,
251.5,
252.0,
252.5,
253.0,
253.5,
254.0,
254.5,
255.0,
255.5,
256.0,
256.5,
257.0,
257.5,
258.0,
258.5,
259.0
]
}
}
}
}
@@ -0,0 +1,801 @@
{
"expected_result": "optimize_result_2.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": 7e-05,
"price_per_wh_battery": 0.0,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": 7e-05,
"preis_euro_pro_wh_akku": 0.0,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"max_ac_charge_power_w": null
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null
},
"dishwasher": {
"device_id": "dishwasher1",
"hours": null,
"consumption_wh": 5000,
"duration_h": 2,
"time_windows": {
"windows": [
{
"start_time": "00:00:00.000000",
"duration": "2 days",
"end_time": null,
"day_of_week": null,
"date": null,
"month": null,
"locale": null
}
]
}
},
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null
}
},
"start_hour": 10,
"settings": {
"prediction_hours": 48,
"horizon_hours": 48,
"individuals": 300,
"generations": 3,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 0
},
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"battery_charge_rates": null,
"self_consumption_interpolator": "scipy",
"verbose": false
},
"presentation": {
"start_datetime": {
"datetime": "2026-03-28T10:00:00+01:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"battery_device_id": "battery1",
"ev_device_id": "ev1",
"home_appliance_device_id": "homeappliance1",
"home_appliance_enabled": true,
"prediction_series": {
"pvforecast_ac_power": [
1046.5,
1047.0,
1047.5,
1048.0,
1048.5,
1049.0,
1049.5,
1050.0,
1050.5,
1051.0,
1051.5,
1052.0,
1052.5,
1053.0,
1053.5,
1054.0,
1054.5,
1055.0,
1055.5,
1056.0,
1056.5,
1057.0,
1057.5,
1058.0,
1058.5,
1059.0,
1059.5,
1060.0,
1060.5,
1061.0,
1061.5,
1062.0,
1062.5,
1063.0,
1063.5,
1064.0,
1064.5,
1065.0
],
"pvforecast_dc_power": [
1056.5,
1057.0,
1057.5,
1058.0,
1058.5,
1059.0,
1059.5,
1060.0,
1060.5,
1061.0,
1061.5,
1062.0,
1062.5,
1063.0,
1063.5,
1064.0,
1064.5,
1065.0,
1065.5,
1066.0,
1066.5,
1067.0,
1067.5,
1068.0,
1068.5,
1069.0,
1069.5,
1070.0,
1070.5,
1071.0,
1071.5,
1072.0,
1072.5,
1073.0,
1073.5,
1074.0,
1074.5,
1075.0
],
"elecprice_marketprice_wh": [
2066.5,
2067.0,
2067.5,
2068.0,
2068.5,
2069.0,
2069.5,
2070.0,
2070.5,
2071.0,
2071.5,
2072.0,
2072.5,
2073.0,
2073.5,
2074.0,
2074.5,
2075.0,
2075.5,
2076.0,
2076.5,
2077.0,
2077.5,
2078.0,
2078.5,
2079.0,
2079.5,
2080.0,
2080.5,
2081.0,
2081.5,
2082.0,
2082.5,
2083.0,
2083.5,
2084.0,
2084.5,
2085.0
],
"feed_in_tariff_wh": [
2076.5,
2077.0,
2077.5,
2078.0,
2078.5,
2079.0,
2079.5,
2080.0,
2080.5,
2081.0,
2081.5,
2082.0,
2082.5,
2083.0,
2083.5,
2084.0,
2084.5,
2085.0,
2085.5,
2086.0,
2086.5,
2087.0,
2087.5,
2088.0,
2088.5,
2089.0,
2089.5,
2090.0,
2090.5,
2091.0,
2091.5,
2092.0,
2092.5,
2093.0,
2093.5,
2094.0,
2094.5,
2095.0
],
"weather_temp_air": [
1086.5,
1087.0,
1087.5,
1088.0,
1088.5,
1089.0,
1089.5,
1090.0,
1090.5,
1091.0,
1091.5,
1092.0,
1092.5,
1093.0,
1093.5,
1094.0,
1094.5,
1095.0,
1095.5,
1096.0,
1096.5,
1097.0,
1097.5,
1098.0,
1098.5,
1099.0,
1099.5,
1100.0,
1100.5,
1101.0,
1101.5,
1102.0,
1102.5,
1103.0,
1103.5,
1104.0,
1104.5,
1105.0
],
"loadforecast_power_w": [
1096.5,
1097.0,
1097.5,
1098.0,
1098.5,
1099.0,
1099.5,
1100.0,
1100.5,
1101.0,
1101.5,
1102.0,
1102.5,
1103.0,
1103.5,
1104.0,
1104.5,
1105.0,
1105.5,
1106.0,
1106.5,
1107.0,
1107.5,
1108.0,
1108.5,
1109.0,
1109.5,
1110.0,
1110.5,
1111.0,
1111.5,
1112.0,
1112.5,
1113.0,
1113.5,
1114.0,
1114.5,
1115.0
],
"loadakkudoktor_std_power_w": [
1106.5,
1107.0,
1107.5,
1108.0,
1108.5,
1109.0,
1109.5,
1110.0,
1110.5,
1111.0,
1111.5,
1112.0,
1112.5,
1113.0,
1113.5,
1114.0,
1114.5,
1115.0,
1115.5,
1116.0,
1116.5,
1117.0,
1117.5,
1118.0,
1118.5,
1119.0,
1119.5,
1120.0,
1120.5,
1121.0,
1121.5,
1122.0,
1122.5,
1123.0,
1123.5,
1124.0,
1124.5,
1125.0
],
"loadakkudoktor_mean_power_w": [
1116.5,
1117.0,
1117.5,
1118.0,
1118.5,
1119.0,
1119.5,
1120.0,
1120.5,
1121.0,
1121.5,
1122.0,
1122.5,
1123.0,
1123.5,
1124.0,
1124.5,
1125.0,
1125.5,
1126.0,
1126.5,
1127.0,
1127.5,
1128.0,
1128.5,
1129.0,
1129.5,
1130.0,
1130.5,
1131.0,
1131.5,
1132.0,
1132.5,
1133.0,
1133.5,
1134.0,
1134.5,
1135.0
]
}
}
}
}
@@ -0,0 +1,801 @@
{
"expected_result": "optimize_result_2_full.json",
"parameters": {
"request": {
"ems": {
"pv_forecast_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"electricity_price_per_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"feed_in_tariff_per_wh": 7e-05,
"price_per_wh_battery": 0.0,
"total_load": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
],
"pv_prognose_wh": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
8.05,
352.91,
728.51,
930.28,
1043.25,
1106.74,
1161.69,
6018.82,
5519.07,
3969.88,
3017.96,
1943.07,
1007.17,
319.67,
7.88,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
5.04,
335.59,
705.32,
1121.12,
1604.79,
2157.38,
1433.25,
5718.49,
4553.96,
3027.55,
2574.46,
1720.4,
963.4,
383.3,
0.0,
0.0,
0.0
],
"strompreis_euro_pro_wh": [
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278,
0.0003384,
0.0003318,
0.0003284,
0.0003283,
0.0003289,
0.0003334,
0.000329,
0.0003302,
0.0003042,
0.000243,
0.000228,
0.0002212,
0.0002093,
0.0001879,
0.0001838,
0.0002004,
0.0002198,
0.000227,
0.0002997,
0.0003195,
0.0003081,
0.0002969,
0.0002921,
0.000278
],
"einspeiseverguetung_euro_pro_wh": 7e-05,
"preis_euro_pro_wh_akku": 0.0,
"gesamtlast": [
676.71,
876.19,
527.13,
468.88,
531.38,
517.95,
483.15,
472.28,
1011.68,
995.0,
1053.07,
1063.91,
1320.56,
1132.03,
1163.67,
1176.82,
1216.22,
1103.78,
1129.12,
1178.71,
1050.98,
988.56,
912.38,
704.61,
516.37,
868.05,
694.34,
608.79,
556.31,
488.89,
506.91,
804.89,
1141.98,
1056.97,
992.46,
1155.99,
827.01,
1257.98,
1232.67,
871.26,
860.88,
1158.03,
1222.72,
1221.04,
949.99,
987.01,
733.99,
592.97
]
},
"pv_battery": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"inverter": {
"device_id": "inverter1",
"hours": null,
"max_power_wh": 10000.0,
"battery_id": "battery1",
"ac_to_dc_efficiency": 1.0,
"dc_to_ac_efficiency": 1.0,
"max_ac_charge_power_w": null
},
"ev": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null
},
"dishwasher": {
"device_id": "dishwasher1",
"hours": null,
"consumption_wh": 5000,
"duration_h": 2,
"time_windows": {
"windows": [
{
"start_time": "00:00:00.000000",
"duration": "2 days",
"end_time": null,
"day_of_week": null,
"date": null,
"month": null,
"locale": null
}
]
}
},
"temperature_forecast": [
18.3,
17.8,
16.9,
16.2,
15.6,
15.1,
14.6,
14.2,
14.3,
14.8,
15.7,
16.7,
17.4,
18.0,
18.6,
19.2,
19.1,
18.7,
18.5,
17.7,
16.2,
14.6,
13.6,
13.0,
12.6,
12.2,
11.7,
11.6,
11.3,
11.0,
10.7,
10.2,
11.4,
14.4,
16.4,
18.3,
19.5,
20.7,
21.9,
22.7,
23.1,
23.1,
22.8,
21.8,
20.2,
19.1,
18.0,
17.4
],
"start_solution": null,
"pv_akku": {
"device_id": "battery1",
"hours": null,
"capacity_wh": 26400,
"charging_efficiency": 0.88,
"discharging_efficiency": 0.88,
"max_charge_power_w": 5000.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 80,
"min_soc_percentage": 0,
"max_soc_percentage": 100,
"charge_rates": null
},
"eauto": {
"device_id": "ev1",
"hours": null,
"capacity_wh": 60000,
"charging_efficiency": 0.95,
"discharging_efficiency": 1.0,
"max_charge_power_w": 11040.0,
"max_discharge_power_w": null,
"initial_soc_percentage": 5,
"min_soc_percentage": 80,
"max_soc_percentage": 100,
"charge_rates": null
}
},
"start_hour": 10,
"settings": {
"prediction_hours": 48,
"horizon_hours": 48,
"individuals": 300,
"generations": 400,
"seed": 42,
"penalties": {
"ev_soc_miss": 10,
"ac_charge_break_even": 0
},
"ev_charge_rates": [
0.0,
0.375,
0.5,
0.625,
0.75,
0.875,
1.0
],
"battery_charge_rates": null,
"self_consumption_interpolator": "scipy",
"verbose": false
},
"presentation": {
"start_datetime": {
"datetime": "2026-01-14T10:00:00+01:00",
"timezone": "Europe/Berlin"
},
"timezone": "Europe/Berlin",
"battery_device_id": "battery1",
"ev_device_id": "ev1",
"home_appliance_device_id": "homeappliance1",
"home_appliance_enabled": true,
"prediction_series": {
"pvforecast_ac_power": [
170.5,
171.0,
171.5,
172.0,
172.5,
173.0,
173.5,
174.0,
174.5,
175.0,
175.5,
176.0,
176.5,
177.0,
177.5,
178.0,
178.5,
179.0,
179.5,
180.0,
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0
],
"pvforecast_dc_power": [
180.5,
181.0,
181.5,
182.0,
182.5,
183.0,
183.5,
184.0,
184.5,
185.0,
185.5,
186.0,
186.5,
187.0,
187.5,
188.0,
188.5,
189.0,
189.5,
190.0,
190.5,
191.0,
191.5,
192.0,
192.5,
193.0,
193.5,
194.0,
194.5,
195.0,
195.5,
196.0,
196.5,
197.0,
197.5,
198.0,
198.5,
199.0
],
"elecprice_marketprice_wh": [
1190.5,
1191.0,
1191.5,
1192.0,
1192.5,
1193.0,
1193.5,
1194.0,
1194.5,
1195.0,
1195.5,
1196.0,
1196.5,
1197.0,
1197.5,
1198.0,
1198.5,
1199.0,
1199.5,
1200.0,
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0
],
"feed_in_tariff_wh": [
1200.5,
1201.0,
1201.5,
1202.0,
1202.5,
1203.0,
1203.5,
1204.0,
1204.5,
1205.0,
1205.5,
1206.0,
1206.5,
1207.0,
1207.5,
1208.0,
1208.5,
1209.0,
1209.5,
1210.0,
1210.5,
1211.0,
1211.5,
1212.0,
1212.5,
1213.0,
1213.5,
1214.0,
1214.5,
1215.0,
1215.5,
1216.0,
1216.5,
1217.0,
1217.5,
1218.0,
1218.5,
1219.0
],
"weather_temp_air": [
210.5,
211.0,
211.5,
212.0,
212.5,
213.0,
213.5,
214.0,
214.5,
215.0,
215.5,
216.0,
216.5,
217.0,
217.5,
218.0,
218.5,
219.0,
219.5,
220.0,
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0
],
"loadforecast_power_w": [
220.5,
221.0,
221.5,
222.0,
222.5,
223.0,
223.5,
224.0,
224.5,
225.0,
225.5,
226.0,
226.5,
227.0,
227.5,
228.0,
228.5,
229.0,
229.5,
230.0,
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0
],
"loadakkudoktor_std_power_w": [
230.5,
231.0,
231.5,
232.0,
232.5,
233.0,
233.5,
234.0,
234.5,
235.0,
235.5,
236.0,
236.5,
237.0,
237.5,
238.0,
238.5,
239.0,
239.5,
240.0,
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0
],
"loadakkudoktor_mean_power_w": [
240.5,
241.0,
241.5,
242.0,
242.5,
243.0,
243.5,
244.0,
244.5,
245.0,
245.5,
246.0,
246.5,
247.0,
247.5,
248.0,
248.5,
249.0,
249.5,
250.0,
250.5,
251.0,
251.5,
252.0,
252.5,
253.0,
253.5,
254.0,
254.5,
255.0,
255.5,
256.0,
256.5,
257.0,
257.5,
258.0,
258.5,
259.0
]
}
}
}
}