mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-12-02 18:36:28 +01:00
refactor(genetic): refactor GENETIC to the consolidated optimizer architecture
Pin result, conversion, plan and visualization of golden runs. Drive GENETIC through the optimizer interface and registry. Move GENETIC into one directory with role-named modules. Prepare every run input once, run from the parameters. Fall back instead of cancelling the optimization run. Simulate battery, EV and inverter from frozen dataclasses. Simulate the home appliance from frozen dataclasses. Convert and visualize from the parameters and result only. Serve GENETIC from its own router. Return a frozen result, build responses in the API. Echo the request as sent, not with an invented time window. Additional changes - Pin that the result does not depend on the number of evaluation workers. - Run the golden module in UTC: until the request date-times are held in UTC they render in the host time zone. - Add Optimizer.run_clock(), so the EMS gets slot length and time zone without GENETIC settings. - Rename ConfigOptimizationRequest, RuntimeForecasts and GeneticCommonSettings as ADR 0010 asks. - Correct the request example in ADR 0010. - Record the renamed OpenAPI schemas in CHANGELOG.md and the upgrade guide. - Add replay files that reproduce each golden result from its parameters. - Drop OptimizationBase from the algorithm. - Give the replay and worker tests own review files against xdist races. - Handle a failing preparation in the EMS like a failing run, no separate cancel path. - Record the fallbacks in CHANGELOG.md and the upgrade guide. - Without an inverter, buy the whole load from the grid instead of planning it at no cost. - Do not charge from the grid without any known price. - Treat an infinite value after the control horizon as a gap. - Correct the documentation that said missing forecasts cancel the run. - Copy the efficiency helpers and the self-consumption table evaluation into GENETIC. - Add CycleTimeWindowSequence, ConsumerScheduleMode and ConsumerDeadlinePolicy as contract names. - Hold the date-times of battery, EV and home appliance requests in UTC, so they render the same on every host. - Drop the UTC pin of the GENETIC golden module; the request date-times no longer depend on the host. - Copy the time window logic GENETIC needs into genetictimewindow.py. - Add ValueTimeWindow as a contract name. - Move the settings' to_genetic_*() converters into the preparation. - Drop the conversion's prediction reads and configuration fallbacks, which runs never reached. - Make the moved docstrings valid reST. - Remove the generic optimization solution route; each optimizer serves its own path. - Import the GENETIC settings from the package. - Record the removed route in CHANGELOG.md and the upgrade guide. - Make the terminal and tail value models frozen dataclasses. - Move the response models into geneticapi; remove geneticsolution and geneticabc. - Remove the legacy appliance start arrays and API, which read the wall clock. - Remove the time window helpers only they used. - Echo a start_solution without start_solution_datetime as sent. - Carry the previous solution's start in the run parameters. - Plan the home appliance cycles that fit, or leave the appliance out, instead of failing. - Move the appliance layout rules into geneticappliancelayout for the preparation. - Leave out a DAILY home appliance whose open windows leave no room for a run, with an error log, instead of silently. - Name the reason of the SoC fallback instead of Python's exception text. - Answer a solution request for an unknown algorithm with a 404 problem response. - Record the fixes in CHANGELOG.md and the upgrade guide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
b108335ee4
commit
b3d5334d3e
@@ -257,6 +257,9 @@ visualize_output_*.pdf
|
||||
|
||||
# Test files
|
||||
tests/testdata/new_optimize_result*
|
||||
tests/testdata/genetic/new_golden_*
|
||||
tests/testdata/genetic/new_replay_golden_*
|
||||
tests/testdata/genetic/new_workers*_golden_*
|
||||
tests/testdata/openapi-new.json
|
||||
tests/testdata/openapi-new.md
|
||||
tests/testdata/config-new.md
|
||||
|
||||
+32
-8
@@ -144,12 +144,17 @@ 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.
|
||||
- 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
|
||||
precedence, otherwise the latest fresh measurement is used, otherwise 0 % is assumed for that
|
||||
battery or EV and logged. The measurement age limit (`measurement_max_age_seconds`) defaults to
|
||||
five minutes.
|
||||
- GENETIC never cancels a run because of its inputs; each fallback is logged as an error naming the
|
||||
input. A forecast value that is missing, NaN or infinite within the control horizon gets a
|
||||
fallback: PV 0, an even load of 3000 kWh per year, a price or feed-in tariff carried forward
|
||||
(else the next known value, else 0); a negative PV or load value becomes 0. Surplus devices and a
|
||||
battery not linked to the inverter are left out; without a usable inverter the run buys the whole
|
||||
load from the grid, without PV and battery; without any known electricity price the run does not
|
||||
charge the battery from the grid. An infinite forecast value after the control horizon shortens
|
||||
the tail like a gap. A missing, future, invalid or stale state of charge no longer cancels the
|
||||
run: an explicit SoC in the request takes precedence, otherwise the latest fresh measurement is
|
||||
used, otherwise 0 % is assumed for that battery or EV and logged. The measurement age limit
|
||||
(`measurement_max_age_seconds`) defaults to five minutes.
|
||||
- Imported sale prices, including zero and negative prices, are preserved. Corrected
|
||||
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.
|
||||
@@ -198,8 +203,15 @@ test procedure. These changes are not yet a tagged release.
|
||||
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.
|
||||
models are `Genetic0<Thing>Request` and `Genetic0CommonSettings` is `Genetic0Settings`;
|
||||
GENETIC's `ConfigOptimizationRequest` is `GeneticRequest`, `RuntimeForecasts` is
|
||||
`GeneticForecastsRequest`, its device and forecast models are `Genetic<Thing>Request` (e.g.
|
||||
`SolarPanelBatteryParameters` is `GeneticBatteryRequest`) and `GeneticCommonSettings` is
|
||||
`GeneticSettings`. Clients generated from `openapi.json` must follow the new names.
|
||||
- Each optimizer serves its stored result on its own path,
|
||||
`GET /v1/energy-management/optimization/solution/GENETIC` and `.../solution/GENETIC0`,
|
||||
with unchanged responses. The generic `.../solution/{algorithm}` route is removed; any other
|
||||
algorithm name gets a 404 problem response instead of a 422.
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -211,6 +223,10 @@ test procedure. These changes are not yet a tagged release.
|
||||
no cost.
|
||||
- The GENETIC0 PDF report (`/visualization_results.pdf`) renders runs of any length, not only
|
||||
runs with `prediction.hours` 48.
|
||||
- The GENETIC result echoes the request as sent: a home appliance without time windows no longer
|
||||
shows an invented placeholder window in `parameters`, and a `start_solution` sent without
|
||||
`start_solution_datetime` is echoed without it, also when the run aligns it with the previous
|
||||
solution.
|
||||
- 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
|
||||
@@ -226,6 +242,11 @@ test procedure. These changes are not yet a tagged release.
|
||||
not exist ([#913](https://github.com/Akkudoktor-EOS/EOS/issues/913)).
|
||||
- Configuration migration keeps map entries with `/` in their keys; prediction providers are
|
||||
validated before the prediction exists.
|
||||
- A GENETIC home appliance that cannot be scheduled (a STRICT deadline already missed, a time
|
||||
window shorter than one run, more cycles than fit) no longer fails the optimization: the run
|
||||
plans as many cycles as fit or leaves the appliance out, logged as an error. A DAILY appliance
|
||||
whose open windows leave no room for a run is left out with that error too, instead of
|
||||
silently.
|
||||
- Planning: the AC setpoint caps the total charge where the inverter does; EVs can finish
|
||||
charging within the final slot; full SoC targets are accepted; energy below the minimum state
|
||||
of charge is preserved; GENETIC battery discharge is limited by the discharge power.
|
||||
@@ -259,6 +280,9 @@ test procedure. These changes are not yet a tagged release.
|
||||
follow their `tz`, or UTC without one, instead of the timezone of the EOS host. A series takes
|
||||
the timezone of its data. The keys name the same instants as before; only their UTC offsets
|
||||
can differ ([#1592](https://github.com/Akkudoktor-EOS/EOS/issues/1592)).
|
||||
- The date-times of a GENETIC request (battery full-charge deadline, EV minimum-SoC deadline,
|
||||
home appliance start window and run start) are held in UTC instead of the timezone of the EOS
|
||||
host. Echoed requests and replay files show them with `Z`; they name the same instants.
|
||||
|
||||
### Security
|
||||
|
||||
|
||||
@@ -35,7 +35,9 @@ and flag any conflict.
|
||||
`OptimizationSolution` may be imported. The other contract names of
|
||||
`CONTRACT_NAMES` (`PydanticDateTimeDataFrame` of the solution, the plan's
|
||||
`BatteryOperationMode` and `ApplianceOperationMode`, the request schema's
|
||||
`TimeWindow` and `TimeWindowSequence`) are allowed only in the request,
|
||||
time windows (`TimeWindow`, `TimeWindowSequence`, `ValueTimeWindow`,
|
||||
`CycleTimeWindowSequence`) and consumer enums (`ConsumerScheduleMode`,
|
||||
`ConsumerDeadlinePolicy`)) are allowed only in the request,
|
||||
conversion, visualization and API modules (`CONTRACT_ROLES`), never in the
|
||||
parameters or the simulation.
|
||||
- Parameter preparation runs once per run, never fails, never returns `None` and follows the
|
||||
@@ -57,6 +59,7 @@ This is the one maintained copy of the interface; ADR 0006 records the decision
|
||||
```python
|
||||
class Optimizer(Protocol[P, Q, R]):
|
||||
name: str
|
||||
def run_clock(self) -> RunClock # slot_seconds, timezone (None: server time)
|
||||
async def prepare(
|
||||
self, start_datetime: DateTime, observation_datetime: DateTime,
|
||||
warm_start: R | None, overrides: Mapping[str, Any] | None = None,
|
||||
@@ -77,6 +80,9 @@ optimizer through `akkudoktoreos.optimization.optimizerregistry.get_optimizer(na
|
||||
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_clock()` is how the energy management learns the optimizer's slot length and the time zone
|
||||
of a run without an explicit start; the optimizer reads them from its settings in its parameter
|
||||
preparation, and the energy management reads no optimizer's settings.
|
||||
|
||||
- `run()` is deterministic: the same optimization parameters give the same result. Generations,
|
||||
individuals, seed and penalties are part of the optimization parameters. A run-time override
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
| ---- | -------------------- | ---- | --------- | ------- | ----------- |
|
||||
| algorithm | `EOS_OPTIMIZATION__ALGORITHM` | `<enum 'OptimizationAlgorithm'>` | `rw` | `required` | Optimization algorithm [GENETIC | GENETIC0]. Defaults to GENETIC. |
|
||||
| algorithms | | `list[str]` | `ro` | `N/A` | Available optimization algorithms. |
|
||||
| genetic | `EOS_OPTIMIZATION__GENETIC` | `GeneticCommonSettings` | `rw` | `required` | GENETIC optimization algorithm configuration. |
|
||||
| genetic | `EOS_OPTIMIZATION__GENETIC` | `GeneticSettings` | `rw` | `required` | GENETIC optimization algorithm configuration. |
|
||||
| genetic0 | `EOS_OPTIMIZATION__GENETIC0` | `Genetic0Settings` | `rw` | `required` | GENETIC0 optimization algorithm configuration. |
|
||||
| keys | | `list[str]` | `ro` | `N/A` | The keys of the solution. |
|
||||
| self_consumption_interpolator | `EOS_OPTIMIZATION__SELF_CONSUMPTION_INTERPOLATOR` | `<enum 'GridInterpolatorBackend'>` | `rw` | `scipy` | How the inverter's self-consumption probability table is evaluated [scipy | numpy]. 'scipy' (default) uses scipy.interpolate. 'numpy' gives the same values without importing SciPy, which saves about 35 MB RSS after the first optimization run (useful on devices with little RAM); a run takes about 2.5 % longer. |
|
||||
|
||||
+24
-35
@@ -1,6 +1,6 @@
|
||||
# Akkudoktor-EOS
|
||||
|
||||
**Version**: `v0.3.0.dev2611151515912129`
|
||||
**Version**: `v0.3.0.dev2611261279306014`
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
**Description**: This project provides a comprehensive solution for simulating and optimizing an energy system based on renewable energy sources. With a focus on photovoltaic (PV) systems, battery storage (batteries), load management (consumer requirements), heat pumps, electric vehicles, and consideration of electricity price data, this system enables forecasting and optimization of energy flow and costs over a specified period.
|
||||
@@ -750,6 +750,28 @@ Get the latest solution of the optimization.
|
||||
|
||||
---
|
||||
|
||||
## GET /v1/energy-management/optimization/solution/GENETIC
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
**Links**: [local](http://localhost:8503/docs#/default/fastapi_energy_management_optimization_solution_genetic_get_v1_energy-management_optimization_solution_genetic_get), [eos](https://petstore3.swagger.io/?url=https://raw.githubusercontent.com/Akkudoktor-EOS/EOS/refs/heads/main/openapi.json#/default/fastapi_energy_management_optimization_solution_genetic_get_v1_energy-management_optimization_solution_genetic_get)
|
||||
<!-- pyml enable line-length -->
|
||||
|
||||
Fastapi Energy Management Optimization Solution Genetic Get
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
```python
|
||||
"""
|
||||
Get the latest GENETIC specific solution of the optimization.
|
||||
"""
|
||||
```
|
||||
<!-- pyml enable line-length -->
|
||||
|
||||
**Responses**:
|
||||
|
||||
- **200**: Successful Response
|
||||
|
||||
---
|
||||
|
||||
## GET /v1/energy-management/optimization/solution/GENETIC/pdf
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
@@ -798,39 +820,6 @@ Get the latest GENETIC0 specific solution of the optimization.
|
||||
|
||||
---
|
||||
|
||||
## GET /v1/energy-management/optimization/solution/{algorithm}
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
**Links**: [local](http://localhost:8503/docs#/default/fastapi_energy_management_optimization_solution_algorithm_get_v1_energy-management_optimization_solution__algorithm__get), [eos](https://petstore3.swagger.io/?url=https://raw.githubusercontent.com/Akkudoktor-EOS/EOS/refs/heads/main/openapi.json#/default/fastapi_energy_management_optimization_solution_algorithm_get_v1_energy-management_optimization_solution__algorithm__get)
|
||||
<!-- pyml enable line-length -->
|
||||
|
||||
Fastapi Energy Management Optimization Solution Algorithm Get
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
```python
|
||||
"""
|
||||
Get the latest algorithm specific solution of the optimization.
|
||||
|
||||
Optimizers of the registry serve their own solution path (e.g. ``.../solution/GENETIC0``).
|
||||
|
||||
Args:
|
||||
algorithm: Optimization algorithm
|
||||
"""
|
||||
```
|
||||
<!-- pyml enable line-length -->
|
||||
|
||||
**Parameters**:
|
||||
|
||||
- `algorithm` (path, required): No description provided.
|
||||
|
||||
**Responses**:
|
||||
|
||||
- **200**: Successful Response
|
||||
|
||||
- **422**: Validation Error
|
||||
|
||||
---
|
||||
|
||||
## GET /v1/energy-management/plan
|
||||
|
||||
<!-- pyml disable line-length -->
|
||||
@@ -1420,7 +1409,7 @@ The deprecated /optimize endpoint continues to run hourly GENETIC0.
|
||||
**Request Body**:
|
||||
|
||||
- `application/json`: {
|
||||
"$ref": "#/components/schemas/ConfigOptimizationRequest"
|
||||
"$ref": "#/components/schemas/GeneticRequest"
|
||||
}
|
||||
|
||||
**Responses**:
|
||||
|
||||
@@ -31,8 +31,9 @@ optimizer, not even its package.
|
||||
only the contract classes (`OptimizationSolution`) may be imported from there outside parameter
|
||||
preparation; the architecture test lists them. The same holds for the contract types that live
|
||||
in otherwise banned modules: the solution's `PydanticDateTimeDataFrame`, the operation-mode enums
|
||||
the plan's instructions name and the request schema's time windows (`TimeWindow`,
|
||||
`TimeWindowSequence`), but only in the modules that build the output or define the request; the
|
||||
the plan's instructions name and the request schema's time windows and consumer enums
|
||||
(`TimeWindow`, `TimeWindowSequence`, ...; the architecture test lists them), but only in the
|
||||
modules that build the output or define the request; the
|
||||
parameters and the simulation never see them.
|
||||
- The operation-mode enums and settings-side resolution stay shared because they describe the
|
||||
configuration, not an optimizer; an optimizer translates them into its own types during
|
||||
|
||||
@@ -3,14 +3,19 @@
|
||||
Every optimizer follows the same three-step interface (prepare, run, convert), so the energy management can drive any of
|
||||
them the same way and every run can be replayed from its optimization parameters. The interface is
|
||||
a `Protocol` generic in the optimizer's optimization parameters `P`, optimization request `Q` and
|
||||
optimization result `R`, with `prepare()` and `prepare_from_request()` (asynchronous, given the run
|
||||
start, the observation time, the warm start and run-time overrides), `run()`, `convert()`
|
||||
optimization result `R`, with `run_clock()` (the slot length and time zone of the next run),
|
||||
`prepare()` and `prepare_from_request()` (asynchronous, given the run start, the observation
|
||||
time, the warm start and run-time overrides), `run()`, `convert()`
|
||||
(asynchronous), which returns the optimization solution and the energy management plan, and
|
||||
`api()`, which hands out the optimizer's REST router
|
||||
([0011](0011-optimizer-api-visualization-and-wizard-get-no-exception.md)). Its current signature
|
||||
is kept in one place, the `optimizer-architecture` skill
|
||||
(`ai/skills/optimizer-architecture/SKILL.md`).
|
||||
|
||||
- `run_clock()` gives the energy management the optimizer's slot length and, for a run without
|
||||
an explicit start, the time zone to take the current time in; the energy management rounds the
|
||||
start down to a slot boundary before `prepare()`. The optimizer reads both from its settings
|
||||
through its parameter preparation; the energy management knows no optimizer's settings.
|
||||
- `prepare()` is the parameter preparation. It never fails and never returns `None` (see the
|
||||
`energy-domain` skill); the energy management never cancels a run because of it.
|
||||
- `run()` is CPU-bound and deterministic: the same optimization parameters give the same result.
|
||||
@@ -25,7 +30,7 @@ result (the warm start) to `prepare()` as arguments, so no part of an optimizer
|
||||
the warm start and its start datetime travel into `run()` inside the optimization parameters.
|
||||
|
||||
Optimization requests from clients (the parameters accepted by `POST /optimize` and the GENETIC0
|
||||
legacy endpoint, and `ConfigOptimizationRequest`) never go straight into `run()`. They keep their
|
||||
legacy endpoint, and `GeneticRequest`) never go straight into `run()`. They keep their
|
||||
public schema (`Q`) and go through the optimizer's parameter preparation,
|
||||
`prepare_from_request()`, which fills everything the
|
||||
request does not carry (time zone, device IDs, algorithm settings) from the configuration and
|
||||
@@ -36,7 +41,7 @@ preparation; a request that is valid but incomplete is completed, never rejected
|
||||
## Considered Options
|
||||
|
||||
- **Preparation reads the previous result from the energy management**: rejected. It keeps the
|
||||
optimizer coupled to EMS internals (today `get_ems().genetic_solution()`), and a run cannot be
|
||||
optimizer coupled to EMS internals (as GENETIC's `get_ems().genetic_solution()` did), and a run cannot be
|
||||
reproduced from its parameters alone.
|
||||
- **Algorithm settings passed beside the parameters**: rejected. A stored parameter set would not
|
||||
be enough to replay a run.
|
||||
|
||||
@@ -18,7 +18,7 @@ fit a role use the `<name>` prefix as well, also inside subdirectories such as `
|
||||
|
||||
## Consequences
|
||||
|
||||
- The public classes are renamed (e.g. `GeneticOptimizationParameters` → `GeneticRequest`,
|
||||
- The public classes are renamed (e.g. `ConfigOptimizationRequest` → `GeneticRequest`,
|
||||
`GeneticCommonSettings` → `GeneticSettings`). Field names and payloads stay unchanged; the
|
||||
schema names in OpenAPI and the configuration documentation change. Nested request models are
|
||||
renamed `<Name><Thing>Request` as well (e.g. `Genetic0InverterParameters` →
|
||||
|
||||
@@ -16,8 +16,8 @@ state today. None of them gets an exception from
|
||||
imports the server either. It reports errors as the generic `OptimizerProblem`, which the server
|
||||
renders like its own problem responses, and it holds the public response models, built from the
|
||||
optimization parameters and result. The server includes the optimizers' routers before its own
|
||||
routes, so an optimizer's specific path (`.../solution/GENETIC0`) wins over a generic one
|
||||
(`.../solution/{algorithm}`).
|
||||
routes, so an optimizer's specific path (e.g. `.../solution/GENETIC0`) wins over any generic
|
||||
one; each optimizer serves its own solution path.
|
||||
- Wizard steps are not code. They are metadata on the fields of `<name>settings.py` (which fields
|
||||
the wizard asks for, and in which order), which EOSdash reads; an optimizer contains no EOSdash
|
||||
code.
|
||||
|
||||
@@ -412,12 +412,11 @@ as `feed_in_tariff_wh` in EUR/Wh, converted from the API's EUR/MWh prices. These
|
||||
are raw market prices; no import charges or VAT are added.
|
||||
|
||||
Only published prices are stored. If the data does not cover the configured
|
||||
GENETIC control horizon, automatic optimization cancels with a missing tariff error
|
||||
instead of extending the final known price. GENETIC0 carries the last known tariff
|
||||
forward and logs the missing tariff as an error. Request, response, and storage
|
||||
GENETIC or GENETIC0 control horizon, automatic optimization carries the last known
|
||||
tariff forward and logs the missing tariff as an error. Request, response, and storage
|
||||
errors also fail the update, including when older prices are already stored.
|
||||
Set the control horizon within the published day-ahead window to use this
|
||||
provider for automatic optimization.
|
||||
Set the control horizon within the published day-ahead window to plan with the
|
||||
published tariffs.
|
||||
|
||||
Example configuration:
|
||||
|
||||
|
||||
@@ -35,7 +35,9 @@ automations and scripts do not. Check those paths and the saved configuration af
|
||||
migration. Battery wear cost is named `levelized_cost_of_storage_amt_kwh`.
|
||||
|
||||
The new GENETIC currently supports one inverter, one stationary battery, one EV and
|
||||
multiple household appliances. It rejects unsupported counts or inconsistent links.
|
||||
multiple household appliances. Surplus devices and a battery not linked to the inverter are
|
||||
left out of the run, and each is logged as an error; without a usable inverter the run plans
|
||||
grid energy only. Check the log after migrating your devices.
|
||||
|
||||
### 2. The two optimizer endpoints have different contracts
|
||||
|
||||
@@ -59,7 +61,7 @@ in the body and query-string overrides are rejected. Do not migrate by changing
|
||||
The legacy endpoint remains available, but the surrounding configuration has changed.
|
||||
That is not a promise that every old script works unchanged.
|
||||
|
||||
### 3. SoC measurements are optional; complete forecasts are required
|
||||
### 3. Missing SoC measurements and forecasts get logged fallbacks
|
||||
|
||||
Request SoC values are integer percentages from 0 to 100, keyed by device ID. Automatic
|
||||
measurement lookup instead reads a factor from 0 to 1 using the configured measurement
|
||||
@@ -76,10 +78,14 @@ The default measurement freshness limit is 300 seconds, controlled by
|
||||
`optimization.genetic.measurement_max_age_seconds`. This limit determines whether a
|
||||
measurement can be used; it does not require an update before every run.
|
||||
|
||||
Missing forecasts within the control period also stop the run. A shorter forecast
|
||||
continuation is allowed and reported. Failed calls return an error; they no longer look
|
||||
like a successful new run by returning an older result. Existing automations should
|
||||
handle errors and verify the timestamp of any separately retrieved stored plan.
|
||||
Missing or invalid forecasts within the control period do not stop the run either. A
|
||||
forecast value that is missing, NaN or infinite within the control horizon gets a fallback:
|
||||
PV 0, an even load of 3000 kWh per year, a price or feed-in tariff carried forward (else the
|
||||
next known value, else 0); a negative PV or load value becomes 0. Each fallback is logged as
|
||||
an error: check the log after setting up your forecasts. A shorter forecast continuation is
|
||||
allowed and reported. Failed calls return an error; they no longer look like a successful
|
||||
new run by returning an older result. Existing automations should handle errors and verify
|
||||
the timestamp of any separately retrieved stored plan.
|
||||
|
||||
A charging target may equal the configured maximum SoC. For example,
|
||||
`devices.electric_vehicles.car.min_soc_percentage = 100` is valid when
|
||||
@@ -110,12 +116,20 @@ time, charging power and supported charge rates.
|
||||
legacy GENETIC0 response format.
|
||||
- The OpenAPI schema names of the optimizers follow one scheme; fields and paths are unchanged:
|
||||
GENETIC0's `Genetic0OptimizationParameters` is `Genetic0Request`, its device and forecast
|
||||
models are `Genetic0<Thing>Request` and `Genetic0CommonSettings` is `Genetic0Settings`.
|
||||
Clients generated from `openapi.json` must follow the new names.
|
||||
models are `Genetic0<Thing>Request` and `Genetic0CommonSettings` is `Genetic0Settings`;
|
||||
GENETIC's `ConfigOptimizationRequest` is `GeneticRequest`, `RuntimeForecasts` is
|
||||
`GeneticForecastsRequest`, its device and forecast models are `Genetic<Thing>Request` (e.g.
|
||||
`SolarPanelBatteryParameters` is `GeneticBatteryRequest`) and `GeneticCommonSettings` is
|
||||
`GeneticSettings`. Clients generated from `openapi.json` must follow the new names.
|
||||
- The `parameters` echoed in a GENETIC result are the request as sent: a home appliance without
|
||||
time windows shows `time_windows: null`, no placeholder window.
|
||||
|
||||
The new report endpoint is
|
||||
`GET /v1/energy-management/optimization/solution/GENETIC/pdf`. It renders the stored
|
||||
GENETIC result and returns 404 if none exists. The legacy PDF endpoint remains separate.
|
||||
The stored GENETIC result itself is `GET /v1/energy-management/optimization/solution/GENETIC`
|
||||
(GENETIC0: `.../solution/GENETIC0`). The generic route `.../solution/{algorithm}` is gone; use
|
||||
the algorithm's own path. Any other algorithm name gets a 404 problem response (formerly 422).
|
||||
|
||||
### 5. Costs and schedules may change even with the same forecasts
|
||||
|
||||
@@ -154,8 +168,9 @@ storage interfaces: await those methods. HTTP clients continue to exchange JSON.
|
||||
compare units, timestamps, expected energy flows and costs before applying commands.
|
||||
4. Try an EV deadline and a household-appliance window if you use them. Check the stored
|
||||
result, execution plan and PDF agree. Test the legacy endpoint if you still rely on it.
|
||||
5. Test one missing-forecast or stale-measurement case. Confirm your automation handles
|
||||
the error and does not execute an old plan as a new one.
|
||||
5. Test one missing-forecast or stale-measurement case. Confirm the run reports its fallback
|
||||
in the log, and that your automation handles failed calls and does not execute an old plan
|
||||
as a new one.
|
||||
|
||||
Automated tests cover the model and API contracts. They do not replace checking your
|
||||
actual Home Assistant entities, Node-RED flows, forecast sources and connected devices.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
This package depends on the device-map and algorithm-converter configuration work
|
||||
from PR #1256 and the runtime settings foundation from PR #1305. Parameter classes
|
||||
remain in `devices/genetic`; settings remain in `devices/settings`.
|
||||
remain in `optimization/genetic/devices`; settings remain in `devices/settings`.
|
||||
|
||||
Battery and inverter models accept a slot duration, apply power limits as energy
|
||||
per slot, and preserve the total battery charge/discharge budget across multiple
|
||||
|
||||
@@ -46,8 +46,8 @@ the earlier `integration/eos-consolidation-20260916` is a historical checkpoint.
|
||||
- Automatic GENETIC runs use the site's timezone derived from its coordinates;
|
||||
explicit run starts and warmstart timestamps retain their timezone/instant.
|
||||
Configure device IDs and schedules against this timezone, including DST.
|
||||
- GET `/v1/energy-management/optimization/solution/{algorithm}` returns the stored
|
||||
algorithm-specific result. Native/generic results and execution plans publish
|
||||
- GET `/v1/energy-management/optimization/solution/GENETIC` (and `.../GENETIC0`) returns
|
||||
the stored algorithm-specific result. Native/generic results and execution plans publish
|
||||
atomically for the successful run. Failed Optimize calls return errors rather
|
||||
than a previous successful result.
|
||||
- GET `/v1/energy-management/optimization/solution/GENETIC/pdf` renders the stored
|
||||
|
||||
@@ -33,7 +33,8 @@ Use `interval_sec: 3600` for hourly operation. AUTO evaluates available forecast
|
||||
continuation; FIXED uses `terminal_value_euro_per_kwh`. Battery wear/LCOS remains a
|
||||
separate cost. The tail affects scoring, never the emitted control horizon.
|
||||
`prediction.hours` must cover the control horizon; shorter available tails are
|
||||
clipped with diagnostics. Missing control forecasts cancel the run.
|
||||
clipped with diagnostics. Missing control forecasts do not cancel the run: each
|
||||
gets a fallback for the run, logged as an error naming the forecast.
|
||||
|
||||
Old feature settings such as `optimization.interval` and flat terminal-value fields
|
||||
migrate into `optimization.genetic`; explicit nested settings win. Check the saved
|
||||
|
||||
+1612
-1632
File diff suppressed because it is too large
Load Diff
@@ -391,8 +391,9 @@ class SettingsEOSDefaults(SettingsEOS):
|
||||
prediction = self.prediction.hours
|
||||
if prediction is None or prediction < control:
|
||||
logger.warning(
|
||||
"Prediction horizon {} h is shorter than the {} h control horizon. Optimization "
|
||||
"runs will fail until prediction.hours covers the control horizon.",
|
||||
"Prediction horizon {} h is shorter than the {} h control horizon. GENETIC "
|
||||
"plans the control horizon with fallback forecasts until prediction.hours covers "
|
||||
"it.",
|
||||
prediction,
|
||||
control,
|
||||
)
|
||||
|
||||
@@ -504,9 +504,7 @@ def migrate_config_data(config_data: Dict[str, Any]) -> "SettingsEOSDefaults":
|
||||
# Normalize this provider before the generic field-by-field transfer. Validate
|
||||
# coupled bounds together so a transient intermediate default cannot lose them.
|
||||
config_data = dict(config_data)
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import (
|
||||
normalize_genetic_settings,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic import normalize_genetic_settings
|
||||
|
||||
if "optimization" in config_data:
|
||||
config_data["optimization"] = normalize_genetic_settings(config_data["optimization"])
|
||||
|
||||
+27
-142
@@ -6,7 +6,7 @@ from asyncio import Lock, get_running_loop
|
||||
from collections.abc import Mapping
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from enum import StrEnum
|
||||
from typing import Any, ClassVar, Optional, cast
|
||||
from typing import Any, ClassVar, Optional
|
||||
|
||||
from loguru import logger
|
||||
from pydantic import computed_field
|
||||
@@ -21,17 +21,11 @@ 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.genetic.configrequest import ConfigOptimizationRequest
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.optimization import (
|
||||
OptimizationAlgorithm,
|
||||
OptimizationSolution,
|
||||
)
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerRun
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerRun, RunClock
|
||||
from akkudoktoreos.optimization.optimizerregistry import get_optimizer
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
@@ -121,10 +115,6 @@ class EnergyManagement(
|
||||
# opimization solution of the latest energy management run
|
||||
_optimization_solution: ClassVar[Optional[OptimizationSolution]] = None
|
||||
|
||||
# Solution of the genetic algorithm of latest energy management run with optimization
|
||||
# For classic API
|
||||
_genetic_solution: ClassVar[Optional[GeneticSolution]] = 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]]] = {}
|
||||
@@ -165,7 +155,8 @@ class EnergyManagement(
|
||||
Args:
|
||||
start_datetime (Optional[DateTime]): The datetime to set as the start.
|
||||
If None, the current datetime is used.
|
||||
interval_seconds: Explicit slot duration; otherwise use the configured algorithm.
|
||||
interval_seconds: Explicit slot duration; otherwise the slot of the configured
|
||||
optimizer's run clock.
|
||||
|
||||
Returns:
|
||||
DateTime: The adjusted start datetime.
|
||||
@@ -174,11 +165,7 @@ class EnergyManagement(
|
||||
start_datetime = to_datetime()
|
||||
cls._observation_datetime = start_datetime
|
||||
if interval_seconds is None:
|
||||
interval_seconds = (
|
||||
cls.config.optimization.genetic.interval_sec
|
||||
if cls.config.optimization.algorithm == OptimizationAlgorithm.GENETIC
|
||||
else 3600
|
||||
)
|
||||
interval_seconds = cls._run_clock(cls.config.optimization.algorithm).slot_seconds
|
||||
if interval_seconds not in (900, 3600):
|
||||
raise ValueError("Optimization slots must be 900 or 3600 seconds.")
|
||||
midnight = start_datetime.start_of("day").int_timestamp
|
||||
@@ -189,6 +176,12 @@ class EnergyManagement(
|
||||
)
|
||||
return cls._start_datetime
|
||||
|
||||
@staticmethod
|
||||
def _run_clock(algorithm: str) -> RunClock:
|
||||
"""The run clock of the optimizer ``algorithm``; hourly local slots if unknown."""
|
||||
optimizer = get_optimizer(algorithm)
|
||||
return RunClock(slot_seconds=3600) if optimizer is None else optimizer.run_clock()
|
||||
|
||||
@classmethod
|
||||
def stage(cls) -> EnergyManagementStage:
|
||||
"""Get the the stage of the energy management.
|
||||
@@ -216,15 +209,6 @@ class EnergyManagement(
|
||||
"""
|
||||
return cls._optimization_solution
|
||||
|
||||
@classmethod
|
||||
def genetic_solution(cls) -> Optional[GeneticSolution]:
|
||||
"""Get the latest solution of the genetic algorithm.
|
||||
|
||||
Returns:
|
||||
Optional[GeneticSolution]: The latest solution of the genetic algorithm.
|
||||
"""
|
||||
return cls._genetic_solution
|
||||
|
||||
@classmethod
|
||||
def optimizer_run(cls, name: str) -> Optional[OptimizerRun[Any, Any]]:
|
||||
"""Get the parameters and result of the latest successful run of an optimizer.
|
||||
@@ -255,12 +239,6 @@ class EnergyManagement(
|
||||
start_datetime: Optional[DateTime] = None,
|
||||
mode: Optional[EnergyManagementMode] = None,
|
||||
algorithm: Optional[OptimizationAlgorithm] = None,
|
||||
genetic_parameters: Optional[
|
||||
GeneticOptimizationParameters | ConfigOptimizationRequest
|
||||
] = None,
|
||||
genetic_generations: Optional[int] = None,
|
||||
genetic_individuals: Optional[int] = None,
|
||||
genetic_seed: Optional[int] = None,
|
||||
request: Optional[Any] = None,
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
force_enable: Optional[bool] = False,
|
||||
@@ -286,20 +264,12 @@ class EnergyManagement(
|
||||
- "GENETIC0": Optimization uses the `GENETIC0` optimization algorithm.
|
||||
|
||||
Defaults to the algorithm defined in the current configuration.
|
||||
genetic_parameters (GeneticOptimizationParameters, optional): The
|
||||
parameter set for the `GENETIC` algorithm. If not provided, it will
|
||||
be constructed based on the current configuration and predictions.
|
||||
genetic_generations (int, optional): The number of generations for the
|
||||
`GENETIC` algorithm. Defaults to the algorithm's internal default (400)
|
||||
if not specified.
|
||||
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.
|
||||
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}``.
|
||||
request (optional): An optimization request for the optimizer (e.g. a
|
||||
`GeneticRequest` for `GENETIC`), 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 optimizer's settings,
|
||||
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.
|
||||
@@ -330,18 +300,12 @@ class EnergyManagement(
|
||||
# None leads to current time as start datetime
|
||||
if algorithm is None:
|
||||
algorithm = self.config.optimization.algorithm
|
||||
if start_datetime is None and algorithm == OptimizationAlgorithm.GENETIC:
|
||||
# Consumer windows and midnight-based forecasts use the site clock,
|
||||
run_clock = EnergyManagement._run_clock(algorithm)
|
||||
if start_datetime is None and run_clock.timezone is not None:
|
||||
# E.g. consumer windows and midnight-based forecasts use the site clock,
|
||||
# which can differ from the server's local timezone.
|
||||
start_datetime = to_datetime(in_timezone=self.config.general.timezone)
|
||||
self.set_start_datetime(
|
||||
start_datetime,
|
||||
interval_seconds=(
|
||||
self.config.optimization.genetic.interval_sec
|
||||
if algorithm == OptimizationAlgorithm.GENETIC
|
||||
else 3600
|
||||
),
|
||||
)
|
||||
start_datetime = to_datetime(in_timezone=run_clock.timezone)
|
||||
self.set_start_datetime(start_datetime, interval_seconds=run_clock.slot_seconds)
|
||||
|
||||
# Throw away any memory cached results of the last energy management run.
|
||||
CacheEnergyManagementStore().clear()
|
||||
@@ -386,82 +350,10 @@ class EnergyManagement(
|
||||
algorithm = self.config.optimization.algorithm
|
||||
|
||||
run_solution: Any
|
||||
optimizer = (
|
||||
None if algorithm == OptimizationAlgorithm.GENETIC else get_optimizer(algorithm)
|
||||
)
|
||||
|
||||
# --- GENETIC algorithm ---
|
||||
if algorithm == OptimizationAlgorithm.GENETIC:
|
||||
# Prepare optimization parameters
|
||||
# This also creates default configurations for missing values and updates the predictions
|
||||
logger.info(f"{algorithm}: Starting optimzation parameter preparation.")
|
||||
try:
|
||||
if isinstance(genetic_parameters, ConfigOptimizationRequest):
|
||||
genetic_parameters = await genetic_parameters.resolve()
|
||||
elif genetic_parameters is None:
|
||||
genetic_parameters = await GeneticOptimizationParameters.prepare()
|
||||
if genetic_parameters is None:
|
||||
logger.error("GENETIC: Parameter preparation failed; canceling run.")
|
||||
EnergyManagement._stage = EnergyManagementStage.IDLE
|
||||
return None
|
||||
except Exception:
|
||||
logger.exception("GENETIC: Parameter preparation failed.")
|
||||
EnergyManagement._stage = EnergyManagementStage.IDLE
|
||||
return None
|
||||
|
||||
# Take values from config if not given
|
||||
if genetic_generations is None:
|
||||
genetic_generations = self.config.optimization.genetic.generations
|
||||
if genetic_seed is None:
|
||||
genetic_seed = self.config.optimization.genetic.seed
|
||||
|
||||
if EnergyManagement._start_datetime is None: # Make mypy happy - already set by us
|
||||
raise RuntimeError(f"{algorithm}: Start datetime not set.")
|
||||
|
||||
# --- Optimization (CPU-bound → MUST offload) ---
|
||||
try:
|
||||
genetic_optimization = GeneticOptimization(
|
||||
verbose=bool(self.config.server.verbose),
|
||||
fixed_seed=genetic_seed,
|
||||
)
|
||||
|
||||
loop = get_running_loop()
|
||||
start_hour = EnergyManagement._start_datetime.hour
|
||||
genetic_solution = await loop.run_in_executor(
|
||||
None,
|
||||
lambda: genetic_optimization.optimize_ems(
|
||||
start_hour=start_hour,
|
||||
parameters=cast(
|
||||
GeneticOptimizationParameters, genetic_parameters
|
||||
), # cast for mypy
|
||||
ngen=genetic_generations,
|
||||
individuals=genetic_individuals,
|
||||
),
|
||||
)
|
||||
|
||||
# Build all representations before publishing any of them.
|
||||
optimization_solution = await genetic_solution.optimization_solution()
|
||||
plan = genetic_solution.energy_management_plan()
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"{algorithm}: Energy management optimization failed.")
|
||||
EnergyManagement._stage = EnergyManagementStage.IDLE
|
||||
return None
|
||||
|
||||
# Publish a consistent set without yielding to another coroutine.
|
||||
EnergyManagement._genetic_solution = genetic_solution
|
||||
EnergyManagement._optimization_solution = optimization_solution
|
||||
EnergyManagement._plan = plan
|
||||
run_solution = genetic_solution
|
||||
|
||||
logger.debug(
|
||||
"{}: Energy management genetic solution:\n{}",
|
||||
algorithm,
|
||||
EnergyManagement._genetic_solution,
|
||||
)
|
||||
optimizer = get_optimizer(algorithm)
|
||||
|
||||
# --- Optimizers of the registry ---
|
||||
elif optimizer is not None:
|
||||
if optimizer is not None:
|
||||
# Prepare optimization parameters
|
||||
logger.info(f"{algorithm}: Starting optimzation parameter preparation.")
|
||||
if EnergyManagement._start_datetime is None: # Make mypy happy - already set by us
|
||||
@@ -471,6 +363,8 @@ class EnergyManagement(
|
||||
previous = EnergyManagement._optimizer_runs.get(optimizer.name)
|
||||
warm_start = None if previous is None else previous.result
|
||||
try:
|
||||
# The preparation never fails: invalid inputs get fallbacks (ADR 0006). An
|
||||
# exception here is a bug, handled like one in the run or the conversion.
|
||||
if request is None:
|
||||
parameters = await optimizer.prepare(
|
||||
start, observation, warm_start, overrides
|
||||
@@ -479,17 +373,8 @@ class EnergyManagement(
|
||||
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:
|
||||
# --- Optimization (CPU-bound → MUST offload) ---
|
||||
loop = get_running_loop()
|
||||
result = await loop.run_in_executor(None, optimizer.run, parameters)
|
||||
|
||||
|
||||
@@ -370,9 +370,9 @@ class ConsumerDeadlinePolicy(StrEnum):
|
||||
automation.
|
||||
|
||||
- STRICT:
|
||||
Keep the deadline. A ONCE consumer without a feasible start makes the
|
||||
optimization fail; a DAILY consumer is simply not scheduled on days
|
||||
without a feasible start.
|
||||
Keep the deadline. A ONCE consumer without a feasible start is left out
|
||||
of the optimization run (error logged); a DAILY consumer is simply not
|
||||
scheduled on days without a feasible start.
|
||||
"""
|
||||
|
||||
BEST_EFFORT = "BEST_EFFORT"
|
||||
|
||||
@@ -120,10 +120,6 @@ from akkudoktoreos.measurement.batterycapacity import (
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
ElectricVehicleParameters,
|
||||
SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.profile.batteryprofileruntime import BatteryProfile
|
||||
|
||||
|
||||
@@ -396,7 +392,7 @@ class BatteriesCommonSettings(DevicesBaseSettings):
|
||||
except ValueError as exc:
|
||||
raise BatteryResolutionError(f"Battery '{self.device_id}': {exc}") from exc
|
||||
|
||||
def _genetic_snapshot(
|
||||
def snapshot_with_profile(
|
||||
self, operating_parameters: Optional[BatteryOperatingParameters], use_profile_tables: bool
|
||||
) -> tuple[BatteryOperatingParameters, Optional["BatteryProfile"]]:
|
||||
"""Return the snapshot to convert and the profile, loading the profile once.
|
||||
@@ -407,6 +403,14 @@ class BatteriesCommonSettings(DevicesBaseSettings):
|
||||
profile that was changed or deleted meanwhile, and the power tables
|
||||
belong to the same profile version as the snapshot.
|
||||
|
||||
Args:
|
||||
operating_parameters: Resolved snapshot; None resolves at the reference operating
|
||||
point.
|
||||
use_profile_tables: Whether the conversion adds the profile's tables.
|
||||
|
||||
Returns:
|
||||
The snapshot and the profile (None without tables).
|
||||
|
||||
Raises:
|
||||
BatteryResolutionError: See ``resolve_operating_parameters``; only
|
||||
if no snapshot is given.
|
||||
@@ -425,15 +429,23 @@ class BatteriesCommonSettings(DevicesBaseSettings):
|
||||
profile,
|
||||
)
|
||||
|
||||
def _genetic_power_parameters(
|
||||
def power_and_efficiency_fields(
|
||||
self, p: BatteryOperatingParameters, profile: Optional["BatteryProfile"]
|
||||
) -> dict[str, Any]:
|
||||
"""Return the power and efficiency fields of the GENETIC battery parameters.
|
||||
"""Return the power and efficiency fields of an optimizer's battery parameters.
|
||||
|
||||
With power curves from the profile, the rated powers are the highest
|
||||
powers over SoC; the per-SoC tables limit them in the simulation.
|
||||
Without (no profile, or the profile allows no charging at this
|
||||
temperature), the powers resolved at the operating point apply.
|
||||
|
||||
Args:
|
||||
p: The resolved operating parameters.
|
||||
profile: The battery profile, or None.
|
||||
|
||||
Returns:
|
||||
``max_charge_power_w``, ``max_discharge_power_w`` and, with power curves, the
|
||||
power limit tables and efficiency curves.
|
||||
"""
|
||||
curves = None
|
||||
if profile is not None:
|
||||
@@ -1009,78 +1021,6 @@ class BatteriesCommonSettings(DevicesBaseSettings):
|
||||
"""Measured SoC from which the battery counts as fully charged [%]."""
|
||||
return self._reference_resolution()[1].detect_percentage
|
||||
|
||||
def to_genetic_pv_bat_param(
|
||||
self,
|
||||
operating_parameters: Optional[BatteryOperatingParameters] = None,
|
||||
use_profile_tables: bool = True,
|
||||
) -> "SolarPanelBatteryParameters":
|
||||
"""Return SolarPanelBatteryParameters for the GENETIC optimizer.
|
||||
|
||||
Args:
|
||||
operating_parameters: Resolved snapshot to convert, e.g. from
|
||||
``resolve_current_operating_parameters``. None resolves at the
|
||||
reference operating point.
|
||||
use_profile_tables: Whether to add the SoC dependent power limits
|
||||
and efficiency curves of the profile. False for a snapshot
|
||||
resolved without profile (see
|
||||
``resolve_operating_parameters_or_defaults``); requires
|
||||
``operating_parameters``.
|
||||
|
||||
Raises:
|
||||
BatteryResolutionError: See ``resolve_operating_parameters``.
|
||||
"""
|
||||
from akkudoktoreos.devices.genetic.battery import SolarPanelBatteryParameters
|
||||
|
||||
p, profile = self._genetic_snapshot(operating_parameters, use_profile_tables)
|
||||
return SolarPanelBatteryParameters(
|
||||
device_id=self.device_id,
|
||||
capacity_wh=p.capacity_wh,
|
||||
charging_efficiency=p.charging_efficiency,
|
||||
discharging_efficiency=p.discharging_efficiency,
|
||||
min_soc_percentage=p.min_soc_percentage,
|
||||
max_soc_percentage=p.max_soc_percentage,
|
||||
charge_rates=self.charge_rates,
|
||||
grid_export_rates=self.grid_export_rates,
|
||||
**self._genetic_power_parameters(p, profile),
|
||||
levelized_cost_of_storage_kwh=self.levelized_cost_of_storage_amt_kwh,
|
||||
)
|
||||
|
||||
def to_genetic_ev_bat_param(
|
||||
self,
|
||||
operating_parameters: Optional[BatteryOperatingParameters] = None,
|
||||
use_profile_tables: bool = True,
|
||||
) -> "ElectricVehicleParameters":
|
||||
"""Return ElectricVehicleParameters for the GENETIC optimizer.
|
||||
|
||||
Args:
|
||||
operating_parameters: Resolved snapshot to convert, e.g. from
|
||||
``resolve_current_operating_parameters``. None resolves at the
|
||||
reference operating point.
|
||||
use_profile_tables: Whether to add the SoC dependent power limits
|
||||
and efficiency curves of the profile. False for a snapshot
|
||||
resolved without profile (see
|
||||
``resolve_operating_parameters_or_defaults``); requires
|
||||
``operating_parameters``.
|
||||
|
||||
Raises:
|
||||
BatteryResolutionError: See ``resolve_operating_parameters``.
|
||||
"""
|
||||
from akkudoktoreos.devices.genetic.battery import ElectricVehicleParameters
|
||||
|
||||
p, profile = self._genetic_snapshot(operating_parameters, use_profile_tables)
|
||||
return ElectricVehicleParameters(
|
||||
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,
|
||||
min_soc_percentage=p.min_soc_percentage,
|
||||
max_soc_percentage=p.max_soc_percentage,
|
||||
min_soc_deadline_datetime=self.min_soc_deadline_datetime,
|
||||
min_soc_max_duration_h=self.min_soc_max_duration_h,
|
||||
**self._genetic_power_parameters(p, profile),
|
||||
)
|
||||
|
||||
@field_validator("charge_rates", mode="before")
|
||||
def validate_and_sort_charge_rates(cls, v: Any) -> NDArray[Shape["*"], float]:
|
||||
# None means fallback to default values
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Note: Used for the GENETIC and GENETIC0 algorithm.
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Optional, Self
|
||||
from typing import Any, Optional, Self
|
||||
|
||||
from pydantic import Field, computed_field, field_validator, model_validator
|
||||
|
||||
@@ -20,9 +20,6 @@ from akkudoktoreos.devices.devicesabc import (
|
||||
from akkudoktoreos.devices.settings.devicebasesettings import DevicesBaseSettings
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, compare_datetimes, to_datetime
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
|
||||
|
||||
|
||||
class HomeApplianceCommonSettings(DevicesBaseSettings):
|
||||
"""Controllable home appliance device settings.
|
||||
@@ -309,7 +306,8 @@ class HomeApplianceCommonSettings(DevicesBaseSettings):
|
||||
"description": (
|
||||
"What to do when 'deadline_datetime' cannot be met: BEST_EFFORT "
|
||||
"runs as early as possible instead (warning logged), STRICT keeps "
|
||||
"the deadline (a ONCE consumer then fails the optimization)."
|
||||
"the deadline (an appliance that cannot meet it is left out of the "
|
||||
"run, error logged)."
|
||||
),
|
||||
"examples": ["BEST_EFFORT", "STRICT"],
|
||||
},
|
||||
@@ -368,30 +366,6 @@ class HomeApplianceCommonSettings(DevicesBaseSettings):
|
||||
return self.cycle_time_windows.num_cycles()
|
||||
return self.num_cycles
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# GENETIC domain conversion
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def to_genetic_param(self) -> "HomeApplianceParameters":
|
||||
"""Return HomeApplianceParameters for the GENETIC optimizer."""
|
||||
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
|
||||
|
||||
return HomeApplianceParameters(
|
||||
device_id=self.device_id,
|
||||
consumption_wh=self.consumption_wh,
|
||||
duration_h=self.duration_h,
|
||||
num_cycles=self.effective_num_cycles,
|
||||
min_cycle_gap_h=self.min_cycle_gap_h,
|
||||
time_windows=self.cycle_time_windows,
|
||||
shared_time_windows=self.time_windows,
|
||||
load_profile_power_w=self.load_profile_power_w,
|
||||
load_profile_interval_seconds=self.load_profile_interval_seconds,
|
||||
schedule_mode=self.schedule_mode,
|
||||
earliest_start_datetime=self.earliest_start_datetime,
|
||||
deadline_datetime=self.deadline_datetime,
|
||||
deadline_policy=self.deadline_policy,
|
||||
)
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def measurement_keys(self) -> Optional[list[str]]:
|
||||
|
||||
@@ -43,7 +43,6 @@ from akkudoktoreos.devices.settings.inverterresolution import (
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from akkudoktoreos.devices.genetic.inverter import InverterParameters
|
||||
from akkudoktoreos.devices.profile.inverterprofile import InverterProfile
|
||||
|
||||
|
||||
@@ -674,42 +673,6 @@ class InverterCommonSettings(DevicesBaseSettings):
|
||||
p = self._effective_parameters()
|
||||
return p.ac_to_dc_efficiency if p is not None else None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# GENETIC domain conversion
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def to_genetic_param(
|
||||
self, operating_parameters: Optional[InverterOperatingParameters] = None
|
||||
) -> "InverterParameters":
|
||||
"""Return InverterParameters for the GENETIC optimizer.
|
||||
|
||||
Args:
|
||||
operating_parameters: Resolved snapshot to convert, e.g. from
|
||||
``resolve_current_operating_parameters``. None resolves at the
|
||||
reference operating point.
|
||||
|
||||
Raises:
|
||||
InverterResolutionError: If the snapshot is resolved here and the
|
||||
inverter cannot be resolved.
|
||||
"""
|
||||
from akkudoktoreos.devices.genetic.inverter import InverterParameters
|
||||
|
||||
p = operating_parameters or self.resolve_operating_parameters()
|
||||
return InverterParameters(
|
||||
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,
|
||||
dc_to_ac_efficiency_curve=list(p.dc_to_ac_efficiency_curve),
|
||||
ac_to_dc_efficiency_curve=list(p.ac_to_dc_efficiency_curve),
|
||||
dc_to_ac_efficiency_reference_load_fraction=(
|
||||
self.dc_to_ac_efficiency_reference_load_fraction
|
||||
),
|
||||
max_ac_charge_power_w=p.max_ac_charge_power_w,
|
||||
ac_charge_limits_total_charge=p.ac_charge_limits_total_charge,
|
||||
)
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def measurement_key_temperature_degc(self) -> str:
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""GENETIC optimizer: the only module code outside the optimizer imports (ADR 0005).
|
||||
|
||||
``GeneticOptimizer``, ``GeneticSettings`` and ``normalize_genetic_settings`` 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.genetic.geneticoptimizer import GeneticOptimizer
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import (
|
||||
GeneticSettings,
|
||||
normalize_genetic_settings,
|
||||
)
|
||||
|
||||
__all__ = ["GeneticOptimizer", "GeneticSettings", "normalize_genetic_settings"]
|
||||
|
||||
|
||||
def __getattr__(name: str) -> Any:
|
||||
if name == "GeneticOptimizer":
|
||||
from akkudoktoreos.optimization.genetic.geneticoptimizer import (
|
||||
GeneticOptimizer,
|
||||
)
|
||||
|
||||
return GeneticOptimizer
|
||||
if name in ("GeneticSettings", "normalize_genetic_settings"):
|
||||
from akkudoktoreos.optimization.genetic import geneticsettings
|
||||
|
||||
return getattr(geneticsettings, name)
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
@@ -1,398 +0,0 @@
|
||||
"""Configuration-owned GENETIC requests with fresh runtime observations."""
|
||||
|
||||
import math
|
||||
from typing import Annotated, Any, Optional
|
||||
|
||||
import pandas as pd
|
||||
from loguru import logger
|
||||
from pydantic import AliasChoices, Field, field_validator
|
||||
|
||||
from akkudoktoreos.core.coreabc import (
|
||||
ConfigMixin,
|
||||
MeasurementMixin,
|
||||
PredictionMixin,
|
||||
get_ems,
|
||||
)
|
||||
from akkudoktoreos.devices.settings.batteryresolution import BatteryFullCharge
|
||||
from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettings
|
||||
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
|
||||
from akkudoktoreos.optimization.genetic.fullcharge import (
|
||||
enforced_full_charge_deadline,
|
||||
full_charge_deadline,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticabc import GeneticParametersBaseModel
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticEnergyManagementParameters,
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime, to_duration
|
||||
|
||||
# How far back the latest "run started" report of a home appliance is looked up.
|
||||
RUN_STARTED_LOOKBACK_HOURS = 48
|
||||
|
||||
|
||||
class RuntimeForecasts(GeneticParametersBaseModel):
|
||||
"""External series from local midnight, in slot Wh and currency per Wh.
|
||||
|
||||
The interval is configured in optimization.genetic.interval_sec. Omitted
|
||||
series are read from the configured providers, preserving their raw coverage.
|
||||
"""
|
||||
|
||||
pv_forecast_wh: Optional[list[float]] = Field(
|
||||
default=None, validation_alias=AliasChoices("pv_forecast_wh", "pv_prognose_wh")
|
||||
)
|
||||
total_load: Optional[list[float]] = Field(
|
||||
default=None, validation_alias=AliasChoices("total_load", "gesamtlast")
|
||||
)
|
||||
electricity_price_per_wh: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
validation_alias=AliasChoices("electricity_price_per_wh", "strompreis_euro_pro_wh"),
|
||||
)
|
||||
feed_in_tariff_per_wh: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
validation_alias=AliasChoices("feed_in_tariff_per_wh", "einspeiseverguetung_euro_pro_wh"),
|
||||
)
|
||||
temperature_forecast: Optional[list[Optional[float]]] = None
|
||||
|
||||
|
||||
class ConfigOptimizationRequest(
|
||||
ConfigMixin, MeasurementMixin, PredictionMixin, GeneticParametersBaseModel
|
||||
):
|
||||
"""Supply observations while hardware, tariffs and scheduling remain in config.
|
||||
|
||||
Explicit SoC values take precedence over fresh measurements. Without a usable
|
||||
measurement, assume 0% initial SoC for the affected device and continue.
|
||||
"""
|
||||
|
||||
soc: dict[str, Annotated[int, Field(ge=0, le=100)]] = Field(default_factory=dict)
|
||||
forecasts: RuntimeForecasts = Field(default_factory=RuntimeForecasts)
|
||||
start_solution: Optional[list[float]] = None
|
||||
start_solution_datetime: Optional[DateTime] = None
|
||||
|
||||
@field_validator("start_solution_datetime", mode="before")
|
||||
@classmethod
|
||||
def validate_start_solution_datetime(cls, value: Any) -> Optional[DateTime]:
|
||||
"""Parse a previous-plan timestamp while retaining its explicit timezone."""
|
||||
return GeneticOptimizationParameters.transform_start_solution_datetime(value)
|
||||
|
||||
async def _run_started(self, device: Any, observation_time: DateTime) -> Optional[DateTime]:
|
||||
"""Start of the appliance's run in progress from its measurement, or None.
|
||||
|
||||
The latest report at or before the observation time holds the run start
|
||||
as UNIX seconds, 0 when the device reported the run as finished. An
|
||||
invalid report is logged and treated as no run in progress, so the
|
||||
preparation never fails on it.
|
||||
|
||||
Args:
|
||||
device: Home appliance settings.
|
||||
observation_time: Moment of the optimization run.
|
||||
|
||||
Returns:
|
||||
The run start, or None when no run is in progress.
|
||||
"""
|
||||
key = device.run_started_measurement_key or f"{device.device_id}.run_started_at"
|
||||
try:
|
||||
dates, values = await self.measurement.key_to_lists(
|
||||
key=key,
|
||||
start_datetime=observation_time.subtract(hours=RUN_STARTED_LOOKBACK_HOURS),
|
||||
end_datetime=observation_time.add(seconds=1),
|
||||
dropna=False,
|
||||
)
|
||||
except KeyError:
|
||||
return None
|
||||
# Skip records without a value (e.g. an adapter's meter reading, #1447).
|
||||
samples = [
|
||||
(date, value)
|
||||
for date, value in zip(dates, values)
|
||||
if date.timestamp() <= observation_time.timestamp()
|
||||
and value is not None
|
||||
and value is not pd.NA
|
||||
]
|
||||
if not samples:
|
||||
return None
|
||||
value = max(samples, key=lambda sample: sample[0].timestamp())[1]
|
||||
try:
|
||||
seconds = float(value)
|
||||
except (TypeError, ValueError):
|
||||
seconds = math.nan
|
||||
if seconds == 0:
|
||||
return None
|
||||
if not math.isfinite(seconds) or seconds < 0 or seconds > observation_time.timestamp():
|
||||
logger.error(
|
||||
"Invalid run start {!r} in '{}' for home appliance '{}'; planned as not running.",
|
||||
value,
|
||||
key,
|
||||
device.device_id,
|
||||
)
|
||||
return None
|
||||
started = to_datetime(seconds)
|
||||
timezone = observation_time.timezone
|
||||
return started.in_timezone(timezone) if timezone is not None else started
|
||||
|
||||
async def resolve(self) -> GeneticOptimizationParameters:
|
||||
"""Resolve inside the EMS lock after its slot start has been established."""
|
||||
config = self.config
|
||||
settings = config.optimization.genetic
|
||||
config.validate_optimization_horizons()
|
||||
ems = get_ems()
|
||||
start = ems.start_datetime
|
||||
observation_time = ems.observation_datetime
|
||||
devices = config.devices
|
||||
groups: dict[str, list[Any]] = {}
|
||||
for name in ("batteries", "electric_vehicles", "inverters", "home_appliances"):
|
||||
entries = list((getattr(devices, name) or {}).values())
|
||||
maximum = getattr(devices, "max_" + name)
|
||||
if maximum is not None and len(entries) > maximum:
|
||||
raise ValueError(f"devices.{name} exceeds configured maximum {maximum}.")
|
||||
if name != "home_appliances" and len(entries) > 1:
|
||||
raise ValueError(f"GENETIC supports at most one device in devices.{name}.")
|
||||
groups[name] = entries
|
||||
ids = [device.device_id for entries in groups.values() for device in entries]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError("Configured device IDs must be unique across device groups.")
|
||||
storage = groups["batteries"] + groups["electric_vehicles"]
|
||||
unknown = set(self.soc) - {device.device_id for device in storage}
|
||||
if unknown:
|
||||
raise ValueError(f"SoC supplied for unconfigured devices: {sorted(unknown)}.")
|
||||
|
||||
async def state(device: BatteriesCommonSettings) -> int:
|
||||
if device.device_id in self.soc:
|
||||
return self.soc[device.device_id]
|
||||
try:
|
||||
dates, values = await self.measurement.key_to_lists(
|
||||
key=device.measurement_key_soc_factor,
|
||||
start_datetime=observation_time.subtract(
|
||||
seconds=settings.measurement_max_age_seconds
|
||||
),
|
||||
end_datetime=observation_time.add(seconds=1),
|
||||
dropna=False,
|
||||
)
|
||||
# Records without a SoC value (e.g. a meter reading stored by an
|
||||
# adapter, or pandas NA) must not hide an older SoC within the age
|
||||
# limit (#1447). An explicit NaN stays an invalid sample.
|
||||
samples = [
|
||||
(date, value)
|
||||
for date, value in zip(dates, values)
|
||||
if date.timestamp() <= observation_time.timestamp()
|
||||
and value is not None
|
||||
and value is not pd.NA
|
||||
]
|
||||
date, value = max(samples, key=lambda sample: sample[0].timestamp())
|
||||
if (
|
||||
observation_time.timestamp() - date.timestamp()
|
||||
> settings.measurement_max_age_seconds
|
||||
or not math.isfinite(value)
|
||||
or not 0 <= value <= 1
|
||||
):
|
||||
raise ValueError("Invalid or stale SoC factor")
|
||||
return int(value * 100)
|
||||
except (ValueError, KeyError) as exc:
|
||||
logger.warning(
|
||||
"No usable fresh SoC for {}; assuming 0% initial SoC for this "
|
||||
"optimization (not a measurement): {}",
|
||||
device.device_id,
|
||||
exc,
|
||||
)
|
||||
return 0
|
||||
|
||||
async def full_charge(
|
||||
device: BatteriesCommonSettings, policy: BatteryFullCharge
|
||||
) -> Optional[DateTime]:
|
||||
"""Deadline of the next periodic full charge, None if disabled or unknown."""
|
||||
interval_days = policy.interval_days
|
||||
if interval_days is None:
|
||||
return None
|
||||
try:
|
||||
dates, values = await self.measurement.key_to_lists(
|
||||
key=device.measurement_key_soc_factor,
|
||||
start_datetime=observation_time.subtract(days=math.ceil(interval_days)),
|
||||
end_datetime=observation_time.add(seconds=1),
|
||||
dropna=False,
|
||||
)
|
||||
except KeyError:
|
||||
dates, values = [], []
|
||||
deadline = full_charge_deadline(
|
||||
zip(dates, values),
|
||||
now=observation_time,
|
||||
interval_days=interval_days,
|
||||
detect_percentage=policy.detect_percentage,
|
||||
)
|
||||
if deadline is None:
|
||||
logger.warning(
|
||||
"No state of charge history for {}; cannot schedule its periodic full charge.",
|
||||
device.device_id,
|
||||
)
|
||||
return deadline
|
||||
|
||||
# A battery configuration error does not cancel the run: the battery gets
|
||||
# default values for what cannot be resolved, and an error is logged.
|
||||
battery = None
|
||||
if groups["batteries"]:
|
||||
device = groups["batteries"][0]
|
||||
(
|
||||
operating_parameters,
|
||||
use_profile_tables,
|
||||
) = await device.resolve_current_operating_parameters_or_defaults(observation_time)
|
||||
battery = device.to_genetic_pv_bat_param(operating_parameters, use_profile_tables)
|
||||
battery.initial_soc_percentage = await state(device)
|
||||
policy = device.resolve_full_charge()
|
||||
deadline = await full_charge(device, policy)
|
||||
horizon_end = start.add(seconds=settings.horizon * settings.interval_sec)
|
||||
if deadline is not None and deadline.timestamp() <= horizon_end.timestamp():
|
||||
# Due within the horizon: lift the upper limit so the battery may
|
||||
# reach the target, and enforce the target only if grid charging
|
||||
# is allowed for it. The target is within the technical SOC bounds.
|
||||
target = policy.soc_percentage
|
||||
battery.max_soc_percentage = max(battery.max_soc_percentage, target)
|
||||
if device.full_charge_allow_grid:
|
||||
enforced = enforced_full_charge_deadline(deadline, observation_time)
|
||||
battery.full_charge_soc_percentage = target
|
||||
battery.full_charge_deadline_datetime = enforced
|
||||
logger.info(
|
||||
"Periodic full charge of {} to {}% due by {}; enforced by {}.",
|
||||
device.device_id,
|
||||
target,
|
||||
deadline,
|
||||
enforced,
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"Periodic full charge of {} to {}% due by {}; PV surplus only.",
|
||||
device.device_id,
|
||||
target,
|
||||
deadline,
|
||||
)
|
||||
ev = None
|
||||
if groups["electric_vehicles"]:
|
||||
device = groups["electric_vehicles"][0]
|
||||
(
|
||||
operating_parameters,
|
||||
use_profile_tables,
|
||||
) = await device.resolve_current_operating_parameters_or_defaults(observation_time)
|
||||
ev = device.to_genetic_ev_bat_param(operating_parameters, use_profile_tables)
|
||||
ev.initial_soc_percentage = await state(device)
|
||||
inverter = None
|
||||
if groups["inverters"]:
|
||||
device = groups["inverters"][0]
|
||||
if device.battery_id != (battery.device_id if battery else None):
|
||||
raise ValueError("Inverter battery_id must match the configured battery.")
|
||||
# The derating of the inverter profile applies at the measured
|
||||
# ambient temperature, 45 degC without a measurement.
|
||||
inverter = device.to_genetic_param(
|
||||
await device.resolve_current_operating_parameters_or_defaults(observation_time)
|
||||
)
|
||||
if inverter is None:
|
||||
raise ValueError("Configure an inverter to model PV and grid energy flows.")
|
||||
appliances = [device.to_genetic_param() for device in groups["home_appliances"]]
|
||||
for device, appliance in zip(groups["home_appliances"], appliances):
|
||||
key = device.cycles_completed_measurement_key or f"{device.device_id}.cycles_completed"
|
||||
try:
|
||||
dates, counts = await self.measurement.key_to_lists(
|
||||
key=key,
|
||||
start_datetime=observation_time.start_of("day"),
|
||||
end_datetime=observation_time.add(seconds=1),
|
||||
dropna=False,
|
||||
)
|
||||
except KeyError:
|
||||
continue
|
||||
# Skip records without a count (e.g. an adapter's meter reading, #1447).
|
||||
samples = [
|
||||
(date, count)
|
||||
for date, count in zip(dates, counts)
|
||||
if date.timestamp() <= observation_time.timestamp()
|
||||
and count is not None
|
||||
and count is not pd.NA
|
||||
]
|
||||
if not samples:
|
||||
continue
|
||||
count = max(samples, key=lambda item: item[0].timestamp())[1]
|
||||
if (
|
||||
not math.isfinite(count)
|
||||
or int(count) != count
|
||||
or not 0 <= count <= appliance.num_cycles
|
||||
):
|
||||
raise ValueError(f"Invalid completed cycle count for {device.device_id}.")
|
||||
appliance.completed_cycles = int(count)
|
||||
for device, appliance in zip(groups["home_appliances"], appliances):
|
||||
appliance.run_started_datetime = await self._run_started(device, observation_time)
|
||||
|
||||
origin = start.start_of("day")
|
||||
if config.prediction.hours is None or config.prediction.hours <= 0:
|
||||
raise ValueError("Configure a positive prediction horizon.")
|
||||
end = start.add(hours=config.prediction.hours)
|
||||
interval = to_duration(settings.interval_sec)
|
||||
updated = False
|
||||
|
||||
async def forecast(
|
||||
supplied: Optional[list[float]], key: str, energy: bool = False
|
||||
) -> list[float]:
|
||||
nonlocal updated
|
||||
if supplied is not None:
|
||||
return list(supplied)
|
||||
if not updated:
|
||||
await self.prediction.update_data()
|
||||
updated = True
|
||||
values = await bounded_forecast_array(
|
||||
self.prediction, key=key, start_datetime=origin, end_datetime=end, interval=interval
|
||||
)
|
||||
if energy:
|
||||
values = values * (settings.interval_sec / 3600)
|
||||
return values.tolist()
|
||||
|
||||
supplied = self.forecasts
|
||||
pv = await forecast(supplied.pv_forecast_wh, "pvforecast_ac_power", energy=True)
|
||||
load = await forecast(supplied.total_load, "loadforecast_power_w", energy=True)
|
||||
prices = await forecast(supplied.electricity_price_per_wh, "elecprice_marketprice_wh")
|
||||
tariffs = await forecast(supplied.feed_in_tariff_per_wh, "feed_in_tariff_wh")
|
||||
length = min(len(pv), len(load), len(prices), len(tariffs))
|
||||
if not length:
|
||||
raise ValueError("Forecast series must be nonempty.")
|
||||
pv, load, prices, tariffs = (values[:length] for values in (pv, load, prices, tariffs))
|
||||
first = int((start - origin).total_seconds() / settings.interval_sec)
|
||||
last = first + settings.horizon
|
||||
if settings.horizon <= 0 or len(pv) < last:
|
||||
raise ValueError("Forecast does not cover the positive GENETIC control horizon.")
|
||||
for key, values in (
|
||||
("PV", pv),
|
||||
("load", load),
|
||||
("prices", prices),
|
||||
("feed-in tariff", tariffs),
|
||||
):
|
||||
missing = [index for index in range(first, last) if not math.isfinite(values[index])]
|
||||
if missing:
|
||||
left = origin.add(seconds=missing[0] * settings.interval_sec)
|
||||
right = left.add(seconds=settings.interval_sec)
|
||||
raise ValueError(
|
||||
f"Missing or invalid {key} within the control horizon. "
|
||||
f"First invalid interval: [{left.isoformat()}, {right.isoformat()}); "
|
||||
f"{len(missing)} invalid interval(s)."
|
||||
)
|
||||
if any(value < 0 for values in (pv, load) for value in values[first:last]):
|
||||
raise ValueError("PV and load energy must be nonnegative.")
|
||||
previous = ems.genetic_solution()
|
||||
warm_start = self.start_solution
|
||||
warm_start_time = self.start_solution_datetime
|
||||
if warm_start is None and previous is not None:
|
||||
warm_start = previous.start_solution
|
||||
warm_start_time = previous.start_solution_datetime
|
||||
return GeneticOptimizationParameters(
|
||||
forecast_interval_seconds=settings.interval_sec,
|
||||
ems=GeneticEnergyManagementParameters(
|
||||
pv_forecast_wh=pv,
|
||||
total_load=load,
|
||||
electricity_price_per_wh=prices,
|
||||
feed_in_tariff_per_wh=tariffs,
|
||||
price_per_wh_battery=settings.terminal_value_euro_per_kwh / 1000,
|
||||
),
|
||||
pv_battery=battery,
|
||||
ev=ev,
|
||||
inverter=inverter,
|
||||
home_appliances=appliances,
|
||||
temperature_forecast=(
|
||||
(supplied.temperature_forecast[:length] + [None] * length)[:length]
|
||||
if supplied.temperature_forecast is not None
|
||||
else None
|
||||
),
|
||||
start_solution=warm_start,
|
||||
start_solution_datetime=warm_start_time,
|
||||
)
|
||||
+60
-302
@@ -1,22 +1,65 @@
|
||||
import math
|
||||
"""Battery and electric vehicle of the GENETIC simulation."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Iterator, Optional
|
||||
|
||||
import numpy as np
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
|
||||
from akkudoktoreos.devices.devicesabc import validate_efficiency_curve
|
||||
from akkudoktoreos.devices.settings.batteryresolution import (
|
||||
BATTERY_SOC_TABLE_POINTS as SOC_TABLE_POINTS,
|
||||
)
|
||||
from akkudoktoreos.devices.settings.batterysettings import BATTERY_DEFAULT_CHARGE_RATES
|
||||
from akkudoktoreos.optimization.genetic.geneticdevices import DeviceParameters
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
# Values of a power limit table: one per SoC percent, 0 % ... 100 %.
|
||||
SOC_TABLE_POINTS = 101
|
||||
# Charge rates of a battery that has none of its own.
|
||||
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)
|
||||
|
||||
# Resolution of the dense efficiency tables: one value per power percent.
|
||||
_EFFICIENCY_TABLE_POINTS = 101
|
||||
|
||||
|
||||
def _dense_efficiency_table(curve: Optional[list[tuple[float, float]]]) -> Optional[list[float]]:
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticBatteryParameters:
|
||||
"""A battery or electric vehicle of the simulation, derived from its request.
|
||||
|
||||
Attributes:
|
||||
device_id: ID of the battery.
|
||||
capacity_wh: Capacity [Wh].
|
||||
charging_efficiency: Charging efficiency (0, 1].
|
||||
discharging_efficiency: Discharging efficiency (0, 1].
|
||||
max_charge_power_w: Maximum charging power [W]; ``None`` is the capacity per hour.
|
||||
max_discharge_power_w: Maximum discharging power [W]; ``None`` is the charging power.
|
||||
initial_soc_percentage: State of charge at the start of the run [%].
|
||||
min_soc_percentage: Lowest state of charge the simulation allows [%]; 0 for an
|
||||
electric vehicle, whose minimum is a charging target instead.
|
||||
max_soc_percentage: Highest state of charge [%].
|
||||
charge_rates: Selectable charge rates; ``None`` or empty uses ``DEFAULT_CHARGE_RATES``.
|
||||
charge_power_limit_w_by_soc: Charging power limit per SoC percent [W].
|
||||
discharge_power_limit_w_by_soc: Discharging power limit per SoC percent [W].
|
||||
charging_efficiency_curve: Charging efficiency by power fraction.
|
||||
discharging_efficiency_curve: Discharging efficiency by power fraction.
|
||||
levelized_cost_of_storage_kwh: Wear cost of stored energy [currency/kWh]; 0 for an
|
||||
electric vehicle.
|
||||
electric_vehicle: The vehicle's BMS ends charging when full, even within a slot.
|
||||
"""
|
||||
|
||||
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, ...]]
|
||||
charge_power_limit_w_by_soc: Optional[tuple[float, ...]]
|
||||
discharge_power_limit_w_by_soc: Optional[tuple[float, ...]]
|
||||
charging_efficiency_curve: Optional[tuple[tuple[float, float], ...]]
|
||||
discharging_efficiency_curve: Optional[tuple[tuple[float, float], ...]]
|
||||
levelized_cost_of_storage_kwh: float
|
||||
electric_vehicle: bool
|
||||
|
||||
|
||||
def _dense_efficiency_table(
|
||||
curve: Optional[tuple[tuple[float, float], ...]],
|
||||
) -> Optional[list[float]]:
|
||||
"""Interpolate an efficiency curve at every power percent 0 % ... 100 %."""
|
||||
if curve is None:
|
||||
return None
|
||||
@@ -25,282 +68,6 @@ def _dense_efficiency_table(curve: Optional[list[tuple[float, float]]]) -> Optio
|
||||
return [float(value) for value in np.interp(grid, fractions, efficiencies)]
|
||||
|
||||
|
||||
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})
|
||||
|
||||
|
||||
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 BaseBatteryParameters(DeviceParameters):
|
||||
"""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 means discharging is inhibited. "
|
||||
"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],
|
||||
},
|
||||
)
|
||||
grid_export_rates: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Battery-to-grid export rates as factor of maximum discharge "
|
||||
"power ]0.00 ... 1.00]. These levels are available to algorithms "
|
||||
"that explicitly enable battery-to-grid export. None leaves the "
|
||||
"choice of export levels to the caller."
|
||||
),
|
||||
"examples": [[0.25, 0.5, 0.75, 1.0], [1.0], None],
|
||||
},
|
||||
)
|
||||
charge_power_limit_w_by_soc: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Maximum charging power [W] per state of charge, e.g. from a battery "
|
||||
f"profile. {SOC_TABLE_POINTS} values, index i is the limit at SoC i %. "
|
||||
"Further limits max_charge_power_w. None means no SoC dependent limit."
|
||||
),
|
||||
"examples": [None],
|
||||
},
|
||||
)
|
||||
discharge_power_limit_w_by_soc: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Maximum discharging power [W] per state of charge, e.g. from a battery "
|
||||
f"profile. {SOC_TABLE_POINTS} values, index i is the limit at SoC i %. "
|
||||
"Further limits max_discharge_power_w. None means no SoC dependent limit."
|
||||
),
|
||||
"examples": [None],
|
||||
},
|
||||
)
|
||||
charging_efficiency_curve: Optional[list[tuple[float, float]]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Power dependent charging efficiency as a list of (power_fraction, "
|
||||
"efficiency) points. The power fraction is the charging power relative "
|
||||
"to max_charge_power_w [0.0 ... 1.0]; points must be strictly increasing "
|
||||
"in power fraction, efficiencies in (0, 1]. Values are interpolated "
|
||||
"linearly and clamped to the first/last point. When set, the curve "
|
||||
"replaces charging_efficiency in the simulation. None means constant "
|
||||
"charging_efficiency."
|
||||
),
|
||||
"examples": [None, [[0.0, 0.975], [0.5, 0.96], [1.0, 0.94]]],
|
||||
},
|
||||
)
|
||||
discharging_efficiency_curve: Optional[list[tuple[float, float]]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Power dependent discharging efficiency as a list of (power_fraction, "
|
||||
"efficiency) points. The power fraction is the discharging power "
|
||||
"relative to max_discharge_power_w [0.0 ... 1.0]; same rules as "
|
||||
"charging_efficiency_curve. When set, the curve replaces "
|
||||
"discharging_efficiency in the simulation. None means constant "
|
||||
"discharging_efficiency."
|
||||
),
|
||||
"examples": [None, [[0.0, 0.975], [1.0, 0.96]]],
|
||||
},
|
||||
)
|
||||
|
||||
@field_validator("charge_power_limit_w_by_soc", "discharge_power_limit_w_by_soc")
|
||||
@classmethod
|
||||
def _validate_power_limit_by_soc(cls, value: Optional[list[float]]) -> Optional[list[float]]:
|
||||
if value is None:
|
||||
return None
|
||||
if len(value) != SOC_TABLE_POINTS:
|
||||
raise ValueError(
|
||||
f"A power limit table needs {SOC_TABLE_POINTS} values (SoC 0 % ... 100 %), "
|
||||
f"got {len(value)}."
|
||||
)
|
||||
for power_w in value:
|
||||
if not math.isfinite(power_w) or power_w < 0:
|
||||
raise ValueError(f"Power limits must be finite and >= 0 W, got {power_w}.")
|
||||
return value
|
||||
|
||||
@field_validator("charging_efficiency_curve", "discharging_efficiency_curve")
|
||||
@classmethod
|
||||
def _validate_efficiency_curve(
|
||||
cls, value: Optional[list[tuple[float, float]]]
|
||||
) -> Optional[list[tuple[float, float]]]:
|
||||
return validate_efficiency_curve(value)
|
||||
|
||||
|
||||
class SolarPanelBatteryParameters(BaseBatteryParameters):
|
||||
"""PV battery device simulation configuration."""
|
||||
|
||||
levelized_cost_of_storage_kwh: float = Field(
|
||||
default=0.0,
|
||||
ge=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Levelized cost of storage applied once to each kWh delivered "
|
||||
"by the battery [EUR/kWh]."
|
||||
),
|
||||
"examples": [0.12],
|
||||
},
|
||||
)
|
||||
max_charge_power_w: Optional[float] = max_charging_power_field()
|
||||
full_charge_soc_percentage: Optional[int] = Field(
|
||||
default=None,
|
||||
ge=1,
|
||||
le=100,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"State of charge a due full charge has to reach at least once "
|
||||
"before 'full_charge_deadline_datetime' [%]. Must not exceed "
|
||||
"'max_soc_percentage'. None means no full charge is due."
|
||||
),
|
||||
"examples": [None, 100],
|
||||
},
|
||||
)
|
||||
full_charge_deadline_datetime: Optional[DateTime] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Moment by which 'full_charge_soc_percentage' has to be reached. "
|
||||
"A date time without timezone is read as local time. None means "
|
||||
"end of the optimization horizon."
|
||||
),
|
||||
"examples": [None, "2026-11-20T07:00:00+01:00"],
|
||||
},
|
||||
)
|
||||
|
||||
@field_validator("full_charge_deadline_datetime", mode="before")
|
||||
@classmethod
|
||||
def transform_full_charge_deadline(cls, value: Any) -> Optional[DateTime]:
|
||||
"""Accept the usual date time representations, naive input is local time."""
|
||||
if value is None:
|
||||
return None
|
||||
return to_datetime(value)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_full_charge_target(self) -> "SolarPanelBatteryParameters":
|
||||
"""A full charge target above the maximum SoC could never be reached."""
|
||||
if (
|
||||
self.full_charge_soc_percentage is not None
|
||||
and self.full_charge_soc_percentage > self.max_soc_percentage
|
||||
):
|
||||
raise ValueError("full_charge_soc_percentage must be <= max_soc_percentage")
|
||||
return self
|
||||
|
||||
|
||||
class ElectricVehicleParameters(BaseBatteryParameters):
|
||||
"""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."
|
||||
)
|
||||
|
||||
min_soc_deadline_datetime: Optional[DateTime] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Absolute moment by which 'min_soc_percentage' has to be "
|
||||
"reached (departure time). A date time without timezone is read "
|
||||
"as local time. None means end of the optimization horizon."
|
||||
),
|
||||
"examples": [None, "2026-07-16T07:00:00+02:00"],
|
||||
},
|
||||
)
|
||||
min_soc_max_duration_h: Optional[float] = Field(
|
||||
default=None,
|
||||
gt=0,
|
||||
allow_inf_nan=False,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Maximum time from the start of the optimization until "
|
||||
"'min_soc_percentage' has to be reached [h]. Combined with "
|
||||
"'min_soc_deadline_datetime' the earlier of the two applies."
|
||||
),
|
||||
"examples": [None, 6.0],
|
||||
},
|
||||
)
|
||||
|
||||
@field_validator("min_soc_deadline_datetime", mode="before")
|
||||
@classmethod
|
||||
def transform_deadline_to_datetime(cls, value: Any) -> Optional[DateTime]:
|
||||
"""Accept the usual date time representations, naive input is local time."""
|
||||
if value is None:
|
||||
return None
|
||||
return to_datetime(value)
|
||||
|
||||
|
||||
class _PowerCurves:
|
||||
"""Battery profile data of a simulated battery, prepared for fast access.
|
||||
|
||||
@@ -340,7 +107,7 @@ class _PowerCurves:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parameters: "BaseBatteryParameters",
|
||||
parameters: GeneticBatteryParameters,
|
||||
capacity_wh: float,
|
||||
max_charge_power_w: float,
|
||||
max_discharge_power_w: float,
|
||||
@@ -387,7 +154,7 @@ def _table_entry(table: list[float], index: int) -> float:
|
||||
return table[index]
|
||||
|
||||
|
||||
class Battery:
|
||||
class GeneticBattery:
|
||||
"""Represents a battery device with methods to simulate energy charging and discharging."""
|
||||
|
||||
# Battery profile data, set per instance only if the parameters provide it.
|
||||
@@ -403,7 +170,7 @@ class Battery:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parameters: BaseBatteryParameters,
|
||||
parameters: GeneticBatteryParameters,
|
||||
prediction_hours: int,
|
||||
slot_duration_h: float = 1.0,
|
||||
first_slot_fraction: float = 1.0,
|
||||
@@ -439,26 +206,17 @@ class Battery:
|
||||
self.initial_soc_percentage = self.parameters.initial_soc_percentage
|
||||
self.charging_efficiency = self.parameters.charging_efficiency
|
||||
self.discharging_efficiency = self.parameters.discharging_efficiency
|
||||
self.levelized_cost_of_storage_kwh = (
|
||||
self.parameters.levelized_cost_of_storage_kwh
|
||||
if isinstance(self.parameters, SolarPanelBatteryParameters)
|
||||
else 0.0
|
||||
)
|
||||
self.levelized_cost_of_storage_kwh = self.parameters.levelized_cost_of_storage_kwh
|
||||
|
||||
# Charge rates, in case of None use default
|
||||
self.charge_rates = np.array(BATTERY_DEFAULT_CHARGE_RATES, dtype=float)
|
||||
self.charge_rates = np.array(DEFAULT_CHARGE_RATES, dtype=float)
|
||||
if self.parameters.charge_rates:
|
||||
charge_rates = np.array(self.parameters.charge_rates, dtype=float)
|
||||
charge_rates = np.unique(charge_rates)
|
||||
charge_rates.sort()
|
||||
self.charge_rates = charge_rates
|
||||
|
||||
# Only assign for storage battery
|
||||
self.min_soc_percentage = (
|
||||
self.parameters.min_soc_percentage
|
||||
if isinstance(self.parameters, SolarPanelBatteryParameters)
|
||||
else 0
|
||||
)
|
||||
self.min_soc_percentage = self.parameters.min_soc_percentage
|
||||
self.max_soc_percentage = self.parameters.max_soc_percentage
|
||||
|
||||
# Initialize state of charge
|
||||
@@ -886,7 +644,7 @@ class Battery:
|
||||
elif wh is None and charge_factor > 0.0: # mode 2
|
||||
raw_request_wh = max_charge_per_slot_wh_fast * charge_factor
|
||||
raw_charge_wh = max(self.max_soc_wh - soc_wh_fast, 0.0) / charging_efficiency_fast
|
||||
if isinstance(self.parameters, ElectricVehicleParameters):
|
||||
if self.parameters.electric_vehicle:
|
||||
# The vehicle BMS ends charging when full, even within a slot.
|
||||
# Keep the feasible pilot/current setting; cap only the energy
|
||||
# below instead of inventing a current below the EV minimum.
|
||||
+2
-2
@@ -3,7 +3,7 @@ from typing import List, Sequence
|
||||
from loguru import logger
|
||||
|
||||
|
||||
class Heatpump:
|
||||
class GeneticHeatpump:
|
||||
MAX_HEAT_OUTPUT = 5000
|
||||
"""Maximum heating power in watts"""
|
||||
|
||||
@@ -135,7 +135,7 @@ if __name__ == "__main__":
|
||||
initial_indoor_temperature = 15 # Initial indoor temperature
|
||||
insulation_efficiency = 0.8 # Insulation efficiency
|
||||
desired_indoor_temperature = 20 # Desired indoor temperature
|
||||
hp = Heatpump(max_heating_power, 24) # Initialize heat pump with prediction hours
|
||||
hp = GeneticHeatpump(max_heating_power, 24) # Initialize heat pump with prediction hours
|
||||
|
||||
# Print COP for various outside temperatures
|
||||
print(hp.calculate_cop(-10), " ", hp.calculate_cop(0), " ", hp.calculate_cop(10))
|
||||
+124
-644
@@ -2,63 +2,93 @@
|
||||
|
||||
This module models household devices such as dishwashers or washing
|
||||
machines that must run for a fixed duration, possibly multiple times
|
||||
(cycles), within one or more allowed time windows. Given a set of
|
||||
requested start times, `HomeAppliance` repairs them into a
|
||||
feasible, chronologically ordered schedule and produces the resulting
|
||||
per-slot energy curve.
|
||||
(cycles), within one or more allowed time windows.
|
||||
|
||||
Time windows are always expressed as a `CycleTimeWindowSequence`
|
||||
(see ``akkudoktoreos.config.configabc``): each contained window's
|
||||
``value`` encodes the 0-based cycle index it applies to, so different
|
||||
cycles of the same appliance can be constrained to different windows.
|
||||
When no windows are configured, every cycle defaults to a single
|
||||
window spanning the full prediction horizon (i.e. unconstrained).
|
||||
Time windows are expressed as cycle windows (``GeneticTimeWindow``, see
|
||||
``genetictimewindow``): each window's ``value`` encodes the 0-based cycle
|
||||
index it applies to, so different cycles of the same appliance can be
|
||||
constrained to different windows. A cycle without a window of its own is
|
||||
unconstrained.
|
||||
|
||||
Cycle start times are repaired according to the following rules:
|
||||
|
||||
1. Round and clip the requested start to the simulation horizon.
|
||||
2. Snap each cycle's start to the nearest start allowed by that
|
||||
cycle's own time window.
|
||||
3. Sort all cycle starts chronologically, keeping each start paired
|
||||
with the cycle (and therefore the allowed-start mask) it belongs
|
||||
to.
|
||||
4. Walk the sorted starts and push any cycle that starts too soon
|
||||
after its predecessor to the next start allowed by its own
|
||||
window, enforcing the appliance duration plus the configured
|
||||
minimum idle gap.
|
||||
5. Generate the combined hourly load curve from the final starts.
|
||||
The optimizer asks ``allowed_start_slots()`` for the start slots at which a
|
||||
complete run is allowed (windows, earliest start, deadline and horizon, from
|
||||
the run start as slot 0), decodes the starts of its genome from them, and the
|
||||
appliance builds the per-slot energy curve of those starts
|
||||
(``build_load_curve()``).
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Sequence
|
||||
from typing import Any, Optional, Self
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import Any, Optional
|
||||
|
||||
import numpy as np
|
||||
from loguru import logger
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
|
||||
from akkudoktoreos.config.configabc import (
|
||||
CycleTimeWindowSequence,
|
||||
TimeWindow,
|
||||
TimeWindowSequence,
|
||||
ValueTimeWindow,
|
||||
from akkudoktoreos.optimization.genetic.devices.genetictimewindow import (
|
||||
GeneticTimeWindow,
|
||||
)
|
||||
from akkudoktoreos.devices.devicesabc import (
|
||||
ConsumerDeadlinePolicy,
|
||||
ConsumerScheduleMode,
|
||||
validate_home_appliance_load_definition,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticdevices import DeviceParameters
|
||||
from akkudoktoreos.utils.datetimeutil import (
|
||||
DateTime,
|
||||
Duration,
|
||||
compare_datetimes,
|
||||
to_datetime,
|
||||
to_duration,
|
||||
to_time,
|
||||
)
|
||||
|
||||
|
||||
class GeneticScheduleMode(StrEnum):
|
||||
"""How often an appliance's load profile is scheduled within the horizon."""
|
||||
|
||||
ONCE = "ONCE"
|
||||
DAILY = "DAILY"
|
||||
|
||||
|
||||
class GeneticDeadlinePolicy(StrEnum):
|
||||
"""Whether a deadline that cannot be kept may be dropped."""
|
||||
|
||||
BEST_EFFORT = "BEST_EFFORT"
|
||||
STRICT = "STRICT"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticHomeApplianceParameters:
|
||||
"""A home appliance of the simulation, derived from its request.
|
||||
|
||||
Attributes:
|
||||
device_id: ID of the appliance.
|
||||
consumption_wh: Energy of one run of the flat load [Wh]; with ``duration_h``.
|
||||
duration_h: Duration of one run of the flat load [h]; with ``consumption_wh``.
|
||||
num_cycles: Runs per schedule period.
|
||||
completed_cycles: Runs already completed.
|
||||
run_started_datetime: Start of a run in progress, if any.
|
||||
min_cycle_gap_h: Minimum idle time between two runs [h].
|
||||
time_windows: Cycle windows (``value`` is the cycle index); ``None`` unconstrained.
|
||||
shared_time_windows: Windows every run must lie within; ``None`` unconstrained.
|
||||
load_profile_power_w: Explicit power per profile step [W], instead of the flat load.
|
||||
load_profile_interval_seconds: Duration of one profile step [s].
|
||||
schedule_mode: How often the profile is scheduled.
|
||||
earliest_start_datetime: No run starts before this moment.
|
||||
deadline_datetime: Every run ends by this moment.
|
||||
deadline_policy: Whether a deadline that cannot be kept may be dropped.
|
||||
"""
|
||||
|
||||
device_id: str
|
||||
consumption_wh: Optional[int]
|
||||
duration_h: Optional[int]
|
||||
num_cycles: int
|
||||
completed_cycles: int
|
||||
run_started_datetime: Optional[DateTime]
|
||||
min_cycle_gap_h: int
|
||||
time_windows: Optional[tuple[GeneticTimeWindow, ...]]
|
||||
shared_time_windows: Optional[tuple[GeneticTimeWindow, ...]]
|
||||
load_profile_power_w: Optional[tuple[float, ...]]
|
||||
load_profile_interval_seconds: Optional[int]
|
||||
schedule_mode: GeneticScheduleMode
|
||||
earliest_start_datetime: Optional[DateTime]
|
||||
deadline_datetime: Optional[DateTime]
|
||||
deadline_policy: GeneticDeadlinePolicy
|
||||
|
||||
|
||||
def resample_power_to_slot_energy(
|
||||
power_w: list[float],
|
||||
input_interval_seconds: float,
|
||||
@@ -115,207 +145,12 @@ def resample_power_to_slot_energy(
|
||||
return out
|
||||
|
||||
|
||||
class HomeApplianceParameters(DeviceParameters):
|
||||
"""Configuration for a simulated home appliance device."""
|
||||
|
||||
device_id: str = Field(
|
||||
json_schema_extra={
|
||||
"description": "ID of home appliance",
|
||||
"examples": ["dishwasher"],
|
||||
}
|
||||
)
|
||||
consumption_wh: Optional[int] = Field(
|
||||
default=None,
|
||||
gt=0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"An integer representing the energy consumption "
|
||||
"of a household device in watt-hours."
|
||||
),
|
||||
"examples": [2000],
|
||||
},
|
||||
)
|
||||
duration_h: Optional[int] = Field(
|
||||
default=None,
|
||||
gt=0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"An integer representing the usage duration of a household device in hours."
|
||||
),
|
||||
"examples": [3],
|
||||
},
|
||||
)
|
||||
num_cycles: int = Field(
|
||||
default=1,
|
||||
gt=0,
|
||||
json_schema_extra={
|
||||
"description": "Number of cycles the appliance must run.",
|
||||
"examples": [2],
|
||||
},
|
||||
)
|
||||
completed_cycles: int = Field(
|
||||
default=0, ge=0, description="Cycles already completed on the first planning day."
|
||||
)
|
||||
run_started_datetime: Optional[DateTime] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Start of the run in progress, None when the appliance is not "
|
||||
"running. The run is kept until the device reports it as finished: "
|
||||
"its remaining load is fixed from now on, independent of windows, "
|
||||
"deadline and gene, and it is not counted in 'completed_cycles' yet."
|
||||
),
|
||||
"examples": [None, "2026-11-14T00:47:45+01:00"],
|
||||
},
|
||||
)
|
||||
|
||||
min_cycle_gap_h: int = Field(
|
||||
default=0,
|
||||
ge=0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Minimum idle time between the end of one cycle and the start of the next cycle."
|
||||
),
|
||||
"examples": [1],
|
||||
},
|
||||
)
|
||||
time_windows: Optional[CycleTimeWindowSequence] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Allowed per-cycle time windows. Each window's `value` "
|
||||
"encodes the 0-based cycle index it applies to; multiple "
|
||||
"windows may share a cycle index. When omitted, every "
|
||||
"cycle is unconstrained across the full prediction "
|
||||
"horizon."
|
||||
),
|
||||
"examples": [
|
||||
[
|
||||
{
|
||||
"start_time": "10:00",
|
||||
"duration": "3 hours",
|
||||
"value": 0,
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
shared_time_windows: Optional[TimeWindowSequence] = Field(
|
||||
default=None,
|
||||
description="Allowed recurring windows shared by every cycle; intersected with per-cycle windows.",
|
||||
)
|
||||
|
||||
load_profile_power_w: Optional[list[float]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Explicit load profile describing a single complete run as a "
|
||||
"sequence of non-negative power values in watts. Each value "
|
||||
"covers 'load_profile_interval_seconds'. Mutually exclusive with "
|
||||
"consumption_wh/duration_h."
|
||||
),
|
||||
"examples": [[200.0, 2000.0, 1800.0, 100.0]],
|
||||
},
|
||||
)
|
||||
load_profile_interval_seconds: Optional[int] = Field(
|
||||
default=None,
|
||||
gt=0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Duration of one 'load_profile_power_w' step in seconds. Defaults "
|
||||
"to the configured optimization interval when a profile is given."
|
||||
),
|
||||
"examples": [900, 3600],
|
||||
},
|
||||
)
|
||||
schedule_mode: ConsumerScheduleMode = Field(
|
||||
default=ConsumerScheduleMode.ONCE,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Scheduling mode: ONCE (a single run within the horizon) or DAILY "
|
||||
"(one run per local calendar day with a feasible full run)."
|
||||
),
|
||||
"examples": ["ONCE", "DAILY"],
|
||||
},
|
||||
)
|
||||
earliest_start_datetime: Optional[DateTime] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Absolute earliest moment the run may start. Starts before it are "
|
||||
"dropped, in addition to 'time_windows' and the horizon. A date "
|
||||
"time without timezone is read as local time. This bound is never "
|
||||
"relaxed."
|
||||
),
|
||||
"examples": [None, "2026-07-15T20:00:00+02:00"],
|
||||
},
|
||||
)
|
||||
deadline_datetime: Optional[DateTime] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Absolute deadline: the complete run must have *finished* at or "
|
||||
"before this moment (e.g. end of the day, or 03:00 tonight). A "
|
||||
"date time without timezone is read as local time. See "
|
||||
"'deadline_policy' for what happens when no start can meet it."
|
||||
),
|
||||
"examples": [None, "2026-07-16T03:00:00+02:00"],
|
||||
},
|
||||
)
|
||||
deadline_policy: ConsumerDeadlinePolicy = Field(
|
||||
default=ConsumerDeadlinePolicy.BEST_EFFORT,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"What to do when 'deadline_datetime' cannot be met: BEST_EFFORT "
|
||||
"runs as early as possible instead (warning logged), STRICT keeps "
|
||||
"the deadline (a ONCE consumer then fails the optimization)."
|
||||
),
|
||||
"examples": ["BEST_EFFORT", "STRICT"],
|
||||
},
|
||||
)
|
||||
|
||||
@field_validator(
|
||||
"earliest_start_datetime", "deadline_datetime", "run_started_datetime", mode="before"
|
||||
)
|
||||
@classmethod
|
||||
def transform_to_datetime(cls, value: Any) -> Optional[DateTime]:
|
||||
"""Accept the usual date time representations, naive input is local time."""
|
||||
if value is None:
|
||||
return None
|
||||
return to_datetime(value)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_load_definition(self) -> Self:
|
||||
"""Ensure a complete load definition and valid completed-cycle count."""
|
||||
if self.completed_cycles > self.num_cycles:
|
||||
raise ValueError("completed_cycles must not exceed num_cycles.")
|
||||
validate_home_appliance_load_definition(
|
||||
load_profile_power_w=self.load_profile_power_w,
|
||||
load_profile_interval_seconds=self.load_profile_interval_seconds,
|
||||
consumption_wh=self.consumption_wh,
|
||||
duration_h=self.duration_h,
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_schedule_bounds(self) -> Self:
|
||||
"""Reject an empty scheduling interval."""
|
||||
if self.earliest_start_datetime is not None and self.deadline_datetime is not None:
|
||||
if compare_datetimes(self.deadline_datetime, self.earliest_start_datetime).le:
|
||||
raise ValueError(
|
||||
f"deadline_datetime {self.deadline_datetime} must be after "
|
||||
f"earliest_start_datetime {self.earliest_start_datetime}."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class HomeAppliance:
|
||||
class GeneticHomeAppliance:
|
||||
"""Non-vectorized simulation of a multi-cycle home appliance.
|
||||
|
||||
A home appliance may execute multiple fixed-duration cycles during
|
||||
the simulation horizon. See the module docstring for the start-time
|
||||
repair algorithm.
|
||||
the simulation horizon. See the module docstring for how the optimizer
|
||||
schedules them.
|
||||
"""
|
||||
|
||||
# A run in progress whose start is more than this many run durations ago
|
||||
@@ -324,12 +159,12 @@ class HomeAppliance:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parameters: HomeApplianceParameters,
|
||||
parameters: GeneticHomeApplianceParameters,
|
||||
optimization_hours: int,
|
||||
prediction_hours: int,
|
||||
slot_duration_h: float = 1.0,
|
||||
) -> None:
|
||||
"""Initializes the appliance and builds its allowed-start masks.
|
||||
"""Initializes the appliance.
|
||||
|
||||
Args:
|
||||
parameters: The appliance's configuration.
|
||||
@@ -351,6 +186,8 @@ class HomeAppliance:
|
||||
self.device_id = parameters.device_id
|
||||
self.schedule_mode = parameters.schedule_mode
|
||||
self.time_windows = parameters.shared_time_windows
|
||||
# Cycle windows; a cycle without a window of its own is unconstrained.
|
||||
self.cycle_windows: tuple[GeneticTimeWindow, ...] = parameters.time_windows or ()
|
||||
self.earliest_start_datetime = parameters.earliest_start_datetime
|
||||
self.deadline_datetime = parameters.deadline_datetime
|
||||
self.deadline_policy = parameters.deadline_policy
|
||||
@@ -376,26 +213,6 @@ class HomeAppliance:
|
||||
# Start times for remaining cycles, in chronological order.
|
||||
self.start_hours: list[int] = []
|
||||
|
||||
# Absolute cycle index corresponding to each remaining cycle.
|
||||
#
|
||||
# Example:
|
||||
# num_cycles = 4
|
||||
# completed_cycles = 2
|
||||
#
|
||||
# remaining_cycle_indices = [2, 3]
|
||||
self.remaining_cycle_indices: list[int] = []
|
||||
|
||||
# start_allowed[k][hour]
|
||||
#
|
||||
# k is the index into remaining_cycle_indices (NOT into the
|
||||
# chronologically-sorted self.start_hours).
|
||||
self.start_allowed: list[np.ndarray] = []
|
||||
|
||||
self.start_earliest: list[int] = []
|
||||
self.start_latest: list[int] = []
|
||||
|
||||
self._setup()
|
||||
|
||||
def _build_run_profile(self) -> None:
|
||||
"""Build the per-slot energy [Wh] of a single complete run."""
|
||||
if self.parameters.load_profile_power_w is not None:
|
||||
@@ -520,7 +337,7 @@ class HomeAppliance:
|
||||
"""
|
||||
pinned = 0
|
||||
if self.run_in_progress and (
|
||||
self.schedule_mode == ConsumerScheduleMode.ONCE or self.pinned_run_date == first_date
|
||||
self.schedule_mode == GeneticScheduleMode.ONCE or self.pinned_run_date == first_date
|
||||
):
|
||||
pinned = 1
|
||||
return min(self.num_cycles, self.completed_cycles + pinned)
|
||||
@@ -596,7 +413,7 @@ class HomeAppliance:
|
||||
if (
|
||||
allowed
|
||||
or self.deadline_datetime is None
|
||||
or self.deadline_policy == ConsumerDeadlinePolicy.STRICT
|
||||
or self.deadline_policy == GeneticDeadlinePolicy.STRICT
|
||||
):
|
||||
return allowed
|
||||
|
||||
@@ -624,6 +441,39 @@ class HomeAppliance:
|
||||
)
|
||||
return earliest
|
||||
|
||||
def open_start_slots(
|
||||
self,
|
||||
*,
|
||||
slot0_datetime: DateTime,
|
||||
earliest_slot: int,
|
||||
horizon_end_slot: int,
|
||||
cycle_index: int,
|
||||
) -> list[int]:
|
||||
"""Return the start slots at which a run of one slot would be allowed.
|
||||
|
||||
Ignores the deadline; only starts that leave room for the full run before the horizon
|
||||
end count. Tells a horizon in which the windows and the earliest start allow no run at
|
||||
all (nothing to plan) from one in which they are open but leave no room for the
|
||||
appliance's full run (a configuration that cannot be scheduled).
|
||||
|
||||
Args:
|
||||
slot0_datetime: Local, timezone-aware datetime of slot index 0.
|
||||
earliest_slot: First slot the optimizer may schedule at ("now").
|
||||
horizon_end_slot: Exclusive upper bound; a run must end at or before.
|
||||
cycle_index: Global configured cycle index, independent of completed cycles.
|
||||
|
||||
Returns:
|
||||
Sorted list of absolute start slots (may be empty).
|
||||
"""
|
||||
return self._allowed_start_slots(
|
||||
slot0_datetime=slot0_datetime,
|
||||
earliest_slot=earliest_slot,
|
||||
horizon_end_slot=horizon_end_slot - self.run_slots + 1,
|
||||
cycle_index=cycle_index,
|
||||
apply_deadline=False,
|
||||
run_slots=1,
|
||||
)
|
||||
|
||||
def _allowed_start_slots(
|
||||
self,
|
||||
*,
|
||||
@@ -632,6 +482,7 @@ class HomeAppliance:
|
||||
horizon_end_slot: int,
|
||||
cycle_index: Optional[int] = None,
|
||||
apply_deadline: bool,
|
||||
run_slots: Optional[int] = None,
|
||||
) -> list[int]:
|
||||
"""Compute the allowed start slots for one set of constraints.
|
||||
|
||||
@@ -641,11 +492,13 @@ class HomeAppliance:
|
||||
horizon_end_slot: Exclusive upper bound; a run must end at or before.
|
||||
cycle_index: Global configured cycle index, independent of completed cycles.
|
||||
apply_deadline: Whether ``deadline_datetime`` restricts the run end.
|
||||
run_slots: Length of the run in slots; ``None`` is the appliance's run.
|
||||
|
||||
Returns:
|
||||
Sorted list of allowed absolute start slots (may be empty).
|
||||
"""
|
||||
run_slots = self.run_slots
|
||||
if run_slots is None:
|
||||
run_slots = self.run_slots
|
||||
if run_slots <= 0:
|
||||
return []
|
||||
|
||||
@@ -671,9 +524,7 @@ class HomeAppliance:
|
||||
raise ValueError("Cycle index is outside the configured cycle range.")
|
||||
cycle_windows = [
|
||||
window
|
||||
for window in (
|
||||
self.parameters.time_windows.windows if self.parameters.time_windows else []
|
||||
)
|
||||
for window in self.cycle_windows
|
||||
if window.value is not None and int(window.value) == cycle_index
|
||||
]
|
||||
|
||||
@@ -683,7 +534,7 @@ class HomeAppliance:
|
||||
start_dt = slot0_datetime.add(seconds=slot * self.slot_interval_seconds)
|
||||
if (
|
||||
self.time_windows is None
|
||||
or self._windows_allow_run(self.time_windows.windows, start_dt, run_duration)
|
||||
or self._windows_allow_run(self.time_windows, start_dt, run_duration)
|
||||
) and (
|
||||
not cycle_windows
|
||||
or self._windows_allow_run(cycle_windows, start_dt, run_duration, merge=True)
|
||||
@@ -693,7 +544,11 @@ class HomeAppliance:
|
||||
|
||||
@staticmethod
|
||||
def _windows_allow_run(
|
||||
windows: Sequence[TimeWindow], start: DateTime, duration: Duration, *, merge: bool = False
|
||||
windows: Sequence[GeneticTimeWindow],
|
||||
start: DateTime,
|
||||
duration: Duration,
|
||||
*,
|
||||
merge: bool = False,
|
||||
) -> bool:
|
||||
"""Check full coverage including windows anchored on previous local dates.
|
||||
|
||||
@@ -717,7 +572,7 @@ class HomeAppliance:
|
||||
continue
|
||||
if window.month is not None and anchor.month != window.month:
|
||||
continue
|
||||
opening, closing = window._window_start_end(anchor)
|
||||
opening, closing = window.start_end(anchor)
|
||||
opening_offset = (opening - start).total_seconds()
|
||||
closing_offset = (closing - start).total_seconds()
|
||||
if opening_offset <= 0 and run_seconds <= closing_offset:
|
||||
@@ -792,32 +647,6 @@ class HomeAppliance:
|
||||
# Setup
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _setup(self) -> None:
|
||||
"""Sets up appliance parameters and default time windows.
|
||||
|
||||
When no ``time_windows`` are configured, builds a single
|
||||
placeholder window spanning the full prediction horizon with
|
||||
``value`` left unset. ``CycleTimeWindowSequence.cycles_to_matrix``
|
||||
ignores windows whose ``value`` is ``None``, so this window never
|
||||
matches any cycle; every remaining cycle then falls through to
|
||||
the "no window for this cycle" branch in
|
||||
``_build_cycle_start_allowed``, which treats it as unconstrained.
|
||||
The net effect is the same as having no windows at all, without
|
||||
assigning cycles an explicit (and misleadingly meaningful)
|
||||
``value``.
|
||||
"""
|
||||
if self.parameters.time_windows is None:
|
||||
self.parameters.time_windows = CycleTimeWindowSequence(
|
||||
windows=[
|
||||
ValueTimeWindow(
|
||||
start_time=to_time("00:00"),
|
||||
duration=to_duration(f"{self.prediction_hours} hours"),
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
self._build_start_allowed()
|
||||
|
||||
@property
|
||||
def num_remaining_cycles(self) -> int:
|
||||
"""int: Number of cycles which still have to be scheduled."""
|
||||
@@ -826,9 +655,7 @@ class HomeAppliance:
|
||||
def set_completed_cycles(self, completed_cycles: int) -> None:
|
||||
"""Sets the number of cycles already completed.
|
||||
|
||||
Clears any previously scheduled start times and load curve,
|
||||
and rebuilds the allowed-start masks for the cycles that
|
||||
remain.
|
||||
Clears any previously scheduled start times and load curve.
|
||||
|
||||
Args:
|
||||
completed_cycles: Number of cycles completed so far.
|
||||
@@ -841,353 +668,6 @@ class HomeAppliance:
|
||||
|
||||
self.start_hours = []
|
||||
self.reset_load_curve()
|
||||
self._build_start_allowed()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Time-window handling
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _build_start_allowed(self) -> None:
|
||||
"""Builds allowed start positions for all remaining cycles."""
|
||||
if self.parameters.time_windows is None:
|
||||
raise ValueError("Expected time windows in parameters, got {self.parameters}.")
|
||||
self.start_allowed = []
|
||||
self.start_earliest = []
|
||||
self.start_latest = []
|
||||
|
||||
self.remaining_cycle_indices = list(
|
||||
range(
|
||||
self.completed_cycles,
|
||||
self.num_cycles,
|
||||
)
|
||||
)
|
||||
|
||||
if not self.remaining_cycle_indices:
|
||||
return
|
||||
|
||||
start_datetime = to_datetime().set(
|
||||
hour=0,
|
||||
minute=0,
|
||||
second=0,
|
||||
microsecond=0,
|
||||
)
|
||||
end_datetime = start_datetime.add(
|
||||
seconds=self.prediction_hours * self.slot_interval_seconds,
|
||||
)
|
||||
interval = to_duration(self.slot_interval_seconds)
|
||||
|
||||
self._build_cycle_start_allowed(
|
||||
self.parameters.time_windows,
|
||||
start_datetime,
|
||||
end_datetime,
|
||||
interval,
|
||||
)
|
||||
|
||||
def _build_cycle_start_allowed(
|
||||
self,
|
||||
time_windows: CycleTimeWindowSequence,
|
||||
start_datetime: DateTime,
|
||||
end_datetime: DateTime,
|
||||
interval: Duration,
|
||||
) -> None:
|
||||
"""Builds allowed starts from per-cycle windows.
|
||||
|
||||
Args:
|
||||
time_windows: Windows associated with individual cycles.
|
||||
start_datetime: Start of the simulation horizon.
|
||||
end_datetime: End of the simulation horizon.
|
||||
interval: Step size used to sample the cycle windows.
|
||||
"""
|
||||
cycle_indices, matrix = time_windows.cycles_to_matrix(
|
||||
start_datetime=start_datetime,
|
||||
end_datetime=end_datetime,
|
||||
interval=interval,
|
||||
)
|
||||
|
||||
cycle_to_row = {cycle: row for row, cycle in enumerate(cycle_indices)}
|
||||
|
||||
max_start = max(
|
||||
0,
|
||||
self.prediction_hours - self.run_slots,
|
||||
)
|
||||
|
||||
# The matrix tells us which individual *steps* are inside
|
||||
# the cycle window. We still have to check that the complete
|
||||
# appliance duration fits inside the window.
|
||||
for cycle in self.remaining_cycle_indices:
|
||||
row_index = cycle_to_row.get(cycle)
|
||||
|
||||
if row_index is None:
|
||||
# No window for this cycle -> unconstrained.
|
||||
allowed = np.zeros(
|
||||
self.prediction_hours,
|
||||
dtype=bool,
|
||||
)
|
||||
allowed[: max_start + 1] = True
|
||||
else:
|
||||
allowed = self._build_duration_feasibility(
|
||||
matrix[row_index],
|
||||
)
|
||||
|
||||
self.start_allowed.append(allowed)
|
||||
|
||||
allowed_indices = np.flatnonzero(allowed)
|
||||
|
||||
if len(allowed_indices):
|
||||
self.start_earliest.append(int(allowed_indices[0]))
|
||||
self.start_latest.append(int(allowed_indices[-1]))
|
||||
else:
|
||||
self.start_earliest.append(0)
|
||||
self.start_latest.append(max_start)
|
||||
|
||||
def _build_duration_feasibility(
|
||||
self,
|
||||
window_steps: np.ndarray,
|
||||
) -> np.ndarray:
|
||||
"""Returns starts where the complete appliance fits in a window.
|
||||
|
||||
A start ``s`` is feasible when every step in
|
||||
``window_steps[s : s + duration_h]`` lies inside the cycle's
|
||||
window (i.e. sums to ``duration_h``).
|
||||
|
||||
Args:
|
||||
window_steps: Per-hour membership of the cycle's window
|
||||
(1.0 inside the window, 0.0 outside), one value per
|
||||
hour of the prediction horizon.
|
||||
|
||||
Returns:
|
||||
Boolean mask, one entry per hour of the prediction
|
||||
horizon, ``True`` where a cycle of length ``duration_h``
|
||||
can start without leaving the window.
|
||||
"""
|
||||
horizon = len(window_steps)
|
||||
max_start = max(
|
||||
0,
|
||||
horizon - self.run_slots,
|
||||
)
|
||||
|
||||
allowed = np.zeros(
|
||||
horizon,
|
||||
dtype=bool,
|
||||
)
|
||||
|
||||
if self.run_slots > horizon:
|
||||
return allowed
|
||||
|
||||
# Rolling sum of `duration_h` consecutive steps, aligned so
|
||||
# that window_sums[s] == sum(window_steps[s : s + duration_h]).
|
||||
cumulative = np.concatenate(([0.0], np.cumsum(window_steps)))
|
||||
window_sums = cumulative[self.run_slots :] - cumulative[: -self.run_slots]
|
||||
|
||||
allowed[: max_start + 1] = window_sums[: max_start + 1] == float(self.run_slots)
|
||||
|
||||
return allowed
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Scheduling / repair
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def set_starting_times(
|
||||
self,
|
||||
start_hours: list[int],
|
||||
) -> list[int]:
|
||||
"""Sets and repairs the start times of all remaining cycles.
|
||||
|
||||
See the module docstring for the repair algorithm.
|
||||
|
||||
Args:
|
||||
start_hours: Requested start hour for each remaining
|
||||
cycle, in the same order as ``remaining_cycle_indices``
|
||||
(i.e. matching ``self.start_allowed``).
|
||||
|
||||
Returns:
|
||||
The repaired, chronologically ordered start hours.
|
||||
|
||||
Raises:
|
||||
ValueError: If ``start_hours`` does not have exactly
|
||||
``num_remaining_cycles`` entries.
|
||||
"""
|
||||
if len(start_hours) != self.num_remaining_cycles:
|
||||
raise ValueError(
|
||||
f"Expected {self.num_remaining_cycles} start times, got {len(start_hours)}."
|
||||
)
|
||||
|
||||
if self.num_remaining_cycles == 0:
|
||||
self.start_hours = []
|
||||
self._build_load_curve()
|
||||
return []
|
||||
|
||||
max_start = max(
|
||||
0,
|
||||
self.prediction_hours - self.run_slots,
|
||||
)
|
||||
|
||||
# 1. Round and clip.
|
||||
starts = [
|
||||
max(
|
||||
0,
|
||||
min(
|
||||
int(round(start)),
|
||||
max_start,
|
||||
),
|
||||
)
|
||||
for start in start_hours
|
||||
]
|
||||
|
||||
# 2. Snap each cycle to its nearest allowed start, keeping the
|
||||
# start paired with the cycle (start_allowed index) it
|
||||
# belongs to.
|
||||
repaired = [
|
||||
(
|
||||
self._repair_start(
|
||||
start,
|
||||
cycle_index,
|
||||
max_start,
|
||||
),
|
||||
cycle_index,
|
||||
)
|
||||
for cycle_index, start in enumerate(starts)
|
||||
]
|
||||
|
||||
# 3. Sort by start time, keeping each cycle's own index
|
||||
# attached so its allowed-start mask is still used
|
||||
# correctly in step 4.
|
||||
repaired.sort(key=lambda pair: pair[0])
|
||||
|
||||
# 4. Enforce duration + minimum idle gap. Each cycle is
|
||||
# pushed forward, if needed, to the next start allowed by
|
||||
# its *own* window.
|
||||
min_next_start = self.run_slots + math.ceil(self.min_cycle_gap_h / self.slot_duration_h)
|
||||
|
||||
final_starts = [repaired[0][0]]
|
||||
|
||||
for index in range(1, len(repaired)):
|
||||
_, cycle_index = repaired[index]
|
||||
earliest = final_starts[index - 1] + min_next_start
|
||||
|
||||
candidate = self._first_allowed_start_at_or_after(
|
||||
cycle_index=cycle_index,
|
||||
earliest=earliest,
|
||||
)
|
||||
|
||||
if candidate is None:
|
||||
# No valid start remains for this cycle.
|
||||
final_starts.append(max_start)
|
||||
else:
|
||||
final_starts.append(candidate)
|
||||
|
||||
# 5. Reconstruct load curve from the final schedule.
|
||||
self.start_hours = final_starts
|
||||
self._build_load_curve()
|
||||
|
||||
return list(self.start_hours)
|
||||
|
||||
def _repair_start(
|
||||
self,
|
||||
start: int,
|
||||
cycle_index: int,
|
||||
max_start: int,
|
||||
) -> int:
|
||||
"""Snaps a start to the nearest allowed start.
|
||||
|
||||
Args:
|
||||
start: Requested (already rounded and clipped) start
|
||||
hour.
|
||||
cycle_index: Index into ``self.start_allowed`` for the
|
||||
cycle being repaired.
|
||||
max_start: Latest hour at which any cycle may start
|
||||
without exceeding the prediction horizon, used as a
|
||||
fallback when the cycle has no allowed start at all.
|
||||
|
||||
Returns:
|
||||
The nearest hour allowed for this cycle, or ``max_start``
|
||||
if the cycle has no allowed start.
|
||||
"""
|
||||
allowed = self.start_allowed[cycle_index]
|
||||
|
||||
if not np.any(allowed):
|
||||
# Same fallback as the vectorized implementation.
|
||||
return max_start
|
||||
|
||||
if allowed[start]:
|
||||
return start
|
||||
|
||||
allowed_indices = np.flatnonzero(allowed)
|
||||
|
||||
distances = np.abs(allowed_indices - start)
|
||||
|
||||
return int(allowed_indices[np.argmin(distances)])
|
||||
|
||||
def _first_allowed_start_at_or_after(
|
||||
self,
|
||||
cycle_index: int,
|
||||
earliest: int,
|
||||
) -> int | None:
|
||||
"""Returns the first allowed start at or after ``earliest``.
|
||||
|
||||
Args:
|
||||
cycle_index: Index into ``self.start_allowed`` for the
|
||||
cycle being scheduled.
|
||||
earliest: Earliest acceptable start hour.
|
||||
|
||||
Returns:
|
||||
The first allowed hour ``>= earliest``, or ``None`` if no
|
||||
such hour exists.
|
||||
"""
|
||||
allowed = self.start_allowed[cycle_index]
|
||||
|
||||
allowed_indices = np.flatnonzero(allowed)
|
||||
|
||||
if len(allowed_indices) == 0:
|
||||
return None
|
||||
|
||||
position = np.searchsorted(
|
||||
allowed_indices,
|
||||
max(0, earliest),
|
||||
side="left",
|
||||
)
|
||||
|
||||
if position >= len(allowed_indices):
|
||||
return None
|
||||
|
||||
return int(allowed_indices[position])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Backwards-compatible single-cycle interface
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def set_starting_time(
|
||||
self,
|
||||
start_hour: int,
|
||||
global_start_hour: int = 0,
|
||||
) -> int:
|
||||
"""Sets the start time of the first remaining cycle.
|
||||
|
||||
Args:
|
||||
start_hour: Requested start hour for the first remaining
|
||||
cycle.
|
||||
global_start_hour: Retained for API compatibility with
|
||||
the old, single-cycle implementation. Unused.
|
||||
|
||||
Returns:
|
||||
The repaired start hour of the first remaining cycle, or
|
||||
``start_hour`` unchanged if there are no remaining
|
||||
cycles.
|
||||
"""
|
||||
if self.num_remaining_cycles == 0:
|
||||
self.reset_load_curve()
|
||||
return start_hour
|
||||
|
||||
if self.start_hours:
|
||||
starts = list(self.start_hours)
|
||||
else:
|
||||
starts = [self.start_earliest[index] for index in range(self.num_remaining_cycles)]
|
||||
|
||||
starts[0] = start_hour
|
||||
|
||||
repaired = self.set_starting_times(starts)
|
||||
|
||||
return repaired[0]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Load curve
|
||||
+49
-126
@@ -1,151 +1,72 @@
|
||||
"""Inverter of the GENETIC simulation."""
|
||||
|
||||
from bisect import bisect_left
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from loguru import logger
|
||||
from pydantic import Field, field_validator
|
||||
|
||||
from akkudoktoreos.devices.devicesabc import (
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import GeneticBattery
|
||||
from akkudoktoreos.optimization.genetic.geneticefficiency import (
|
||||
interpolate_efficiency_curve,
|
||||
solve_ac_for_charge_dc_energy,
|
||||
solve_ac_for_dc_energy,
|
||||
validate_efficiency_curve,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.battery import Battery
|
||||
from akkudoktoreos.optimization.genetic.geneticdevices import DeviceParameters
|
||||
from akkudoktoreos.prediction.interpolator import get_eos_load_interpolator
|
||||
from akkudoktoreos.optimization.genetic.geneticloadinterpolator import (
|
||||
get_genetic_load_interpolator,
|
||||
)
|
||||
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
|
||||
|
||||
|
||||
class InverterParameters(DeviceParameters):
|
||||
"""Inverter Device Simulation Configuration."""
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticInverterParameters:
|
||||
"""An inverter of the simulation, derived from its request.
|
||||
|
||||
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],
|
||||
},
|
||||
)
|
||||
dc_to_ac_efficiency_curve: Optional[list[tuple[float, float]]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Load-dependent efficiency of DC to AC conversion as a list of "
|
||||
"(load_fraction, efficiency) points. The load fraction is the AC power "
|
||||
"of the conversion relative to max_power_wh [0.0 ... 1.0]; points must be "
|
||||
"strictly increasing in load fraction, efficiencies in (0, 1]. Values are "
|
||||
"interpolated linearly and clamped to the first/last point. When set, the "
|
||||
"curve replaces dc_to_ac_efficiency. "
|
||||
"Default None (constant dc_to_ac_efficiency)."
|
||||
),
|
||||
"examples": [None, [[0.02, 0.8], [0.07, 0.93], [0.3, 0.96], [1.0, 0.95]]],
|
||||
},
|
||||
)
|
||||
dc_to_ac_efficiency_reference_load_fraction: float = Field(
|
||||
default=0.06,
|
||||
ge=0,
|
||||
le=1,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Load fraction at which dc_to_ac_efficiency_curve is evaluated where "
|
||||
"stored battery energy is valued without a specific conversion "
|
||||
"(e.g. remaining battery energy at the end of the horizon, AC charge "
|
||||
"break-even). Should represent the typical load the battery serves, "
|
||||
"e.g. the night-time base load. Only used with dc_to_ac_efficiency_curve. "
|
||||
"Default 0.06."
|
||||
),
|
||||
"examples": [0.06, 0.1],
|
||||
},
|
||||
)
|
||||
ac_to_dc_efficiency_curve: Optional[list[tuple[float, float]]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Load-dependent efficiency of AC to DC conversion (AC/grid charging of the "
|
||||
"battery) as a list of (load_fraction, efficiency) points. The load "
|
||||
"fraction is the AC power drawn relative to max_power_wh [0.0 ... 1.0]; "
|
||||
"same rules as dc_to_ac_efficiency_curve. When set, the curve replaces "
|
||||
"ac_to_dc_efficiency for the energy drawn from the grid; "
|
||||
"ac_to_dc_efficiency still converts the AC charge power limit and should "
|
||||
"be the efficiency at that limit. Default None (constant "
|
||||
"ac_to_dc_efficiency)."
|
||||
),
|
||||
"examples": [None, [[0.05, 0.86], [0.3, 0.96], [1.0, 0.96]]],
|
||||
},
|
||||
)
|
||||
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],
|
||||
},
|
||||
)
|
||||
ac_charge_limits_total_charge: bool = Field(
|
||||
default=False,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"True if the AC charge setpoint caps the battery's total charge power, "
|
||||
"PV included. PV surplus above it is exported, not stored. False keeps "
|
||||
"the default model: PV surplus charges first and the grid adds "
|
||||
"ac_charge x max_charge_power_w on top."
|
||||
),
|
||||
"examples": [False, True],
|
||||
},
|
||||
)
|
||||
Attributes:
|
||||
device_id: ID of the inverter.
|
||||
max_power_wh: Maximum power [W], the energy per hour it can convert.
|
||||
battery_id: ID of the battery behind the inverter, if any.
|
||||
ac_to_dc_efficiency: Efficiency of AC to DC conversion (grid charging).
|
||||
dc_to_ac_efficiency: Efficiency of DC to AC conversion.
|
||||
dc_to_ac_efficiency_curve: DC to AC efficiency by load fraction.
|
||||
dc_to_ac_efficiency_reference_load_fraction: Load fraction at which stored energy is
|
||||
valued with the DC to AC curve.
|
||||
ac_to_dc_efficiency_curve: AC to DC efficiency by load fraction.
|
||||
max_ac_charge_power_w: Maximum AC charging power [W]; ``None`` is no extra limit.
|
||||
ac_charge_limits_total_charge: The AC charge setpoint caps the total charge power.
|
||||
"""
|
||||
|
||||
@field_validator("dc_to_ac_efficiency_curve", "ac_to_dc_efficiency_curve")
|
||||
@classmethod
|
||||
def _validate_efficiency_curves(
|
||||
cls, value: Optional[list[tuple[float, float]]]
|
||||
) -> Optional[list[tuple[float, float]]]:
|
||||
return validate_efficiency_curve(value)
|
||||
device_id: str
|
||||
max_power_wh: float
|
||||
battery_id: Optional[str]
|
||||
ac_to_dc_efficiency: float
|
||||
dc_to_ac_efficiency: float
|
||||
dc_to_ac_efficiency_curve: Optional[tuple[tuple[float, float], ...]]
|
||||
dc_to_ac_efficiency_reference_load_fraction: float
|
||||
ac_to_dc_efficiency_curve: Optional[tuple[tuple[float, float], ...]]
|
||||
max_ac_charge_power_w: Optional[float]
|
||||
ac_charge_limits_total_charge: bool
|
||||
|
||||
|
||||
class Inverter:
|
||||
class GeneticInverter:
|
||||
"""Inverter of the simulation: converts PV, battery and grid energy within its power."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parameters: InverterParameters,
|
||||
battery: Optional[Battery] = None,
|
||||
parameters: GeneticInverterParameters,
|
||||
battery: Optional[GeneticBattery] = None,
|
||||
slot_duration_h: float = 1.0,
|
||||
first_slot_fraction: float = 1.0,
|
||||
self_consumption_backend: GridInterpolatorBackend = GridInterpolatorBackend.SCIPY,
|
||||
):
|
||||
# `first_slot_fraction` is the part of slot 0 still ahead when the
|
||||
# optimization runs within that slot; slot 0 then moves only that part
|
||||
# of the slot energy (see Battery).
|
||||
if not 0.0 < first_slot_fraction <= 1.0:
|
||||
raise ValueError(f"first_slot_fraction must be in (0, 1], got {first_slot_fraction}.")
|
||||
self.parameters: InverterParameters = parameters
|
||||
self.battery: Optional[Battery] = battery
|
||||
self.parameters: GeneticInverterParameters = parameters
|
||||
self.battery: Optional[GeneticBattery] = battery
|
||||
self.self_consumption_backend = self_consumption_backend
|
||||
self.slot_duration_h: float = slot_duration_h
|
||||
self.first_slot_fraction: float = first_slot_fraction
|
||||
self._setup()
|
||||
@@ -162,7 +83,9 @@ class Inverter:
|
||||
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_eos_load_interpolator()
|
||||
self.self_consumption_predictor = get_genetic_load_interpolator(
|
||||
self.self_consumption_backend
|
||||
)
|
||||
# max_power_wh is supplied as power [W] but used as the maximum energy
|
||||
# the inverter can move during one optimization slot.
|
||||
self.max_power_wh = self.parameters.max_power_wh * self.slot_duration_h
|
||||
@@ -196,7 +119,7 @@ class Inverter:
|
||||
"""
|
||||
if self.dc_to_ac_efficiency_curve is None:
|
||||
return self.dc_to_ac_efficiency
|
||||
curve: list[tuple[float, float]] = self.dc_to_ac_efficiency_curve
|
||||
curve: tuple[tuple[float, float], ...] = self.dc_to_ac_efficiency_curve
|
||||
slot_max_power_wh = self.max_power_wh * scale
|
||||
load_fraction = ac_wh / slot_max_power_wh if slot_max_power_wh > 0 else 0.0
|
||||
# This runs for every battery discharge of every candidate plan. Find
|
||||
@@ -320,7 +243,7 @@ class Inverter:
|
||||
if not battery or requested_ac_wh <= 0.0:
|
||||
return 0.0, 0.0
|
||||
scale = self.first_slot_fraction if hour == 0 else 1.0
|
||||
if type(battery) is not Battery:
|
||||
if type(battery) is not GeneticBattery:
|
||||
# Another battery implementation: ask it, step by step.
|
||||
if not battery.discharge_released(hour):
|
||||
return 0.0, 0.0
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Time windows of the GENETIC home appliance simulation.
|
||||
|
||||
GENETIC's own copy of the window logic it needs from ``config.configabc`` (ADR 0004: optimizers
|
||||
duplicate code instead of sharing it), on frozen dataclasses instead of settings models. The
|
||||
request's ``TimeWindow`` models derive them; the semantics are the same:
|
||||
|
||||
- ``start_time`` is a naive wall-clock time, interpreted in the timezone of the datetime it is
|
||||
compared with.
|
||||
- Date, weekday and month restrictions apply to the calendar date the window starts on.
|
||||
- The end is exclusive: ``end_time`` is the first occurrence of that clock time strictly after
|
||||
the start; the window ends at the later of ``end_time`` and ``start_time + duration``.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from akkudoktoreos.utils.datetimeutil import Date, DateTime, Duration, Time
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticTimeWindow:
|
||||
"""A time window of the simulation, derived from a request's time window.
|
||||
|
||||
Attributes:
|
||||
start_time: Naive local start time.
|
||||
duration: Length of the window.
|
||||
end_time: Naive local end time; ``None`` uses the duration only.
|
||||
day_of_week: Weekday the window starts on, 0 (Monday) to 6 (Sunday); ``None`` any day.
|
||||
date: Calendar date the window starts on; ``None`` any date.
|
||||
month: Month the window starts in, 1 to 12; ``None`` any month.
|
||||
value: Value of the window; for cycle windows the 0-based cycle index, ``None`` belongs
|
||||
to no cycle.
|
||||
"""
|
||||
|
||||
start_time: Time
|
||||
duration: Duration
|
||||
end_time: Optional[Time] = None
|
||||
day_of_week: Optional[int] = None
|
||||
date: Optional[Date] = None
|
||||
month: Optional[int] = None
|
||||
value: Optional[float] = None
|
||||
|
||||
def start_end(self, reference_date: DateTime) -> tuple[DateTime, DateTime]:
|
||||
"""Return the start and exclusive end of the window opening on a date.
|
||||
|
||||
Args:
|
||||
reference_date: Datetime identifying the calendar date the window starts on. Its
|
||||
time of day is ignored.
|
||||
|
||||
Returns:
|
||||
The start datetime and the exclusive end datetime.
|
||||
"""
|
||||
start_day = reference_date.start_of("day")
|
||||
|
||||
# Use Pendulum's default (second occurrence) for ambiguous boundaries,
|
||||
# independently of the fold carried by the reference datetime.
|
||||
start = start_day.replace(
|
||||
hour=self.start_time.hour,
|
||||
minute=self.start_time.minute,
|
||||
second=self.start_time.second,
|
||||
microsecond=self.start_time.microsecond,
|
||||
fold=1,
|
||||
)
|
||||
|
||||
duration_end = start + self.duration
|
||||
|
||||
if self.end_time is None:
|
||||
return start, duration_end
|
||||
|
||||
start_clock = (
|
||||
self.start_time.hour,
|
||||
self.start_time.minute,
|
||||
self.start_time.second,
|
||||
self.start_time.microsecond,
|
||||
)
|
||||
end_clock = (
|
||||
self.end_time.hour,
|
||||
self.end_time.minute,
|
||||
self.end_time.second,
|
||||
self.end_time.microsecond,
|
||||
)
|
||||
|
||||
# Choose the date before setting the time: a nonexistent clock time on
|
||||
# the start day must not be normalized and carried into the following day.
|
||||
end_day = start_day.add(days=1) if end_clock <= start_clock else start_day
|
||||
explicit_end = end_day.replace(
|
||||
hour=self.end_time.hour,
|
||||
minute=self.end_time.minute,
|
||||
second=self.end_time.second,
|
||||
microsecond=self.end_time.microsecond,
|
||||
fold=1,
|
||||
)
|
||||
|
||||
# Same-timezone datetime ordering ignores fold during the repeated DST
|
||||
# hour. Pendulum subtraction measures elapsed time between the instants.
|
||||
end = explicit_end if (explicit_end - duration_end).total_seconds() > 0 else duration_end
|
||||
return start, end
|
||||
@@ -1,11 +0,0 @@
|
||||
"""Genetic optimization algorithm abstract and base classes."""
|
||||
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
|
||||
|
||||
class GeneticParametersBaseModel(PydanticBaseModel):
|
||||
"""Pydantic base model for parameters for the GENETIC algorithm."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
+177
-1054
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,854 @@
|
||||
"""REST API of GENETIC (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 result of a run (``solution_response()``).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import dataclasses
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Request, Response
|
||||
from pydantic import AliasChoices, ConfigDict, Field, computed_field, field_validator
|
||||
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
from akkudoktoreos.optimization.genetic import geneticterminalvalue
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
GeneticParametersBaseModel,
|
||||
GeneticRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.optimization.optimizer import (
|
||||
OptimizerApi,
|
||||
OptimizerProblem,
|
||||
OptimizerRun,
|
||||
RunTrigger,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
from akkudoktoreos.utils.utils import NumpyEncoder
|
||||
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
# Response models
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TerminalValueCurve(PydanticBaseModel):
|
||||
"""Piecewise linear, concave value of battery energy left at the horizon.
|
||||
|
||||
``energy_wh`` and ``value_euro`` are the breakpoints of the cumulative
|
||||
value, ``marginal_euro_per_kwh`` the slope of each segment. Both arrays
|
||||
start at the origin; the curve is flat beyond its last breakpoint.
|
||||
"""
|
||||
|
||||
energy_wh: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Breakpoints of usable AC energy left in the battery [Wh]."
|
||||
},
|
||||
)
|
||||
value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={"description": "Cumulative credit at each breakpoint [EUR]."},
|
||||
)
|
||||
operating_value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Tail operating component at each breakpoint [EUR]; empty for a proxy curve."
|
||||
},
|
||||
)
|
||||
continuation_value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Continuation component at each breakpoint [EUR]; empty for a proxy curve."
|
||||
},
|
||||
)
|
||||
marginal_euro_per_kwh: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Marginal value of the segment that starts at each breakpoint "
|
||||
"[EUR/kWh]. May be negative or non-monotone in TAIL mode."
|
||||
)
|
||||
},
|
||||
)
|
||||
residual_energy_wh: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Energy up to which the curve is backed by residual load - the "
|
||||
"knee. Everything beyond it is only worth an export."
|
||||
)
|
||||
},
|
||||
)
|
||||
window_slots: int = Field(
|
||||
default=0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Number of trailing horizon slots the curve was derived from. "
|
||||
"Fewer slots than a full day mean a shorter proxy period."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class TailDiagnostics(PydanticBaseModel):
|
||||
"""Forecast summary used by the deterministic tail optimization."""
|
||||
|
||||
slots: int = 0
|
||||
slot_hours: float = 0.0
|
||||
soc_grid_points: int = 0
|
||||
min_import_price_euro_per_kwh: float = 0.0
|
||||
max_import_price_euro_per_kwh: float = 0.0
|
||||
min_feed_in_tariff_euro_per_kwh: float = 0.0
|
||||
max_feed_in_tariff_euro_per_kwh: float = 0.0
|
||||
negative_import_price_slots: int = 0
|
||||
positive_battery_export_slots: int = 0
|
||||
|
||||
|
||||
class TailPlanSlot(PydanticBaseModel):
|
||||
"""One diagnostic slot of the optimal tail path.
|
||||
|
||||
These values explain the lookahead used for fitness. They are diagnostics
|
||||
only and are never copied into the executable control arrays.
|
||||
"""
|
||||
|
||||
slot: int
|
||||
hour_from_start: float
|
||||
action: str
|
||||
alternative_action: str = ""
|
||||
decision_margin_euro: float = 0.0
|
||||
soc_start_percentage: float
|
||||
soc_end_percentage: float
|
||||
pv_wh: float
|
||||
load_wh: float
|
||||
grid_import_wh: float
|
||||
grid_export_wh: float
|
||||
battery_charge_wh: float
|
||||
battery_discharge_wh: float
|
||||
import_price_euro_per_kwh: float
|
||||
feed_in_tariff_euro_per_kwh: float
|
||||
slot_value_euro: float
|
||||
remaining_value_euro: float
|
||||
ac_charge_factor: float
|
||||
dc_charge_allowed: int
|
||||
discharge_allowed: int
|
||||
battery_grid_export_factor: float
|
||||
|
||||
|
||||
class TerminalValueResult(PydanticBaseModel):
|
||||
"""What the optimizer credited for the energy left in the battery."""
|
||||
|
||||
control_horizon_hours: float = 0
|
||||
requested_tail_hours: float = 0
|
||||
effective_tail_hours: float = 0
|
||||
tail_end_hour: float = 0
|
||||
continuation_mode: str = "FIXED"
|
||||
|
||||
mode: str = Field(
|
||||
json_schema_extra={
|
||||
"description": "Terminal value mode the run used: TAIL, AUTO or FIXED.",
|
||||
"examples": ["TAIL", "AUTO", "FIXED"],
|
||||
}
|
||||
)
|
||||
battery_energy_wh: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": "Usable AC energy left in the battery at the end of the horizon [Wh]."
|
||||
},
|
||||
)
|
||||
credited_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={"description": "Credit applied to the total balance [EUR]."},
|
||||
)
|
||||
tail_operating_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Optimal net cash flow within the effective tail for the selected "
|
||||
"control-end battery state [EUR]."
|
||||
)
|
||||
},
|
||||
)
|
||||
continuation_value_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Continuation credit remaining at the end of the optimal tail path [EUR]."
|
||||
)
|
||||
},
|
||||
)
|
||||
curve: Optional[TerminalValueCurve] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Combined tail value curve (tail operation plus continuation) read by fitness; "
|
||||
"None in FIXED mode."
|
||||
)
|
||||
},
|
||||
)
|
||||
continuation_curve: Optional[TerminalValueCurve] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "Conservative AUTO proxy constructed at the effective tail end."
|
||||
},
|
||||
)
|
||||
tail_diagnostics: Optional[TailDiagnostics] = None
|
||||
tail_plan: list[TailPlanSlot] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Diagnostic optimal battery path inside the tail. It explains the "
|
||||
"lookahead but is never an executable control plan."
|
||||
)
|
||||
},
|
||||
)
|
||||
reason: str = Field(
|
||||
default="",
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Why this mode applied. Empty in AUTO mode; in FIXED mode it "
|
||||
"says whether FIXED was configured or whether AUTO fell back "
|
||||
"because no curve could be derived."
|
||||
),
|
||||
"examples": ["", "terminal_value_mode is FIXED"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class DeviceOptimizeResult(GeneticParametersBaseModel):
|
||||
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 ElectricVehicleResult(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."}
|
||||
)
|
||||
max_discharge_power_w: Optional[float] = Field(
|
||||
default=None,
|
||||
json_schema_extra={"description": "Maximum discharging 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 GeneticSimulationResult(GeneticParametersBaseModel):
|
||||
"""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",
|
||||
"feed_in_tariff",
|
||||
mode="before",
|
||||
)
|
||||
def convert_numpy(cls, field: Any) -> Any:
|
||||
return NumpyEncoder.convert_numpy(field)[0]
|
||||
|
||||
home_appliance_energy_wh: dict[str, list[float]] = Field(
|
||||
default_factory=dict,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Per-device appliance energy in watt-hours per optimization slot, "
|
||||
"keyed by device_id."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
feed_in_tariff: list[float] = Field(
|
||||
validation_alias=AliasChoices("feed_in_tariff", "Feed_in_tariff"),
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Used feed-in tariff in €/Wh per hour, including predictions"
|
||||
},
|
||||
)
|
||||
|
||||
home_appliance_running: dict[str, list[bool]] = Field(
|
||||
default_factory=dict, description="Active run occupancy, including zero-power phases."
|
||||
)
|
||||
|
||||
@field_validator("home_appliance_energy_wh", mode="before")
|
||||
def convert_numpy_appliance_energy(cls, field: Any) -> Any:
|
||||
if isinstance(field, dict):
|
||||
return {
|
||||
device_id: NumpyEncoder.convert_numpy(values)[0]
|
||||
for device_id, values in field.items()
|
||||
}
|
||||
return field
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def Feed_in_tariff(self) -> Optional[list[float]]:
|
||||
"""Deprecated: use feed_in_tariff."""
|
||||
return self.feed_in_tariff
|
||||
|
||||
|
||||
class GeneticSolution(GeneticParametersBaseModel):
|
||||
"""**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: GeneticOptimizationParameters = 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: GeneticSimulationResult
|
||||
|
||||
ev_obj: Optional[ElectricVehicleResult] = 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, Any]] = 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_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[ElectricVehicleResult]:
|
||||
"""Deprecated: Use ev_obj instead."""
|
||||
return self.ev_obj
|
||||
|
||||
@field_validator(
|
||||
"ac_charge",
|
||||
"dc_charge",
|
||||
"discharge_allowed",
|
||||
"battery_grid_export_allowed",
|
||||
"battery_grid_export_factor",
|
||||
mode="before",
|
||||
)
|
||||
def convert_numpy(cls, field: Any) -> Any:
|
||||
return NumpyEncoder.convert_numpy(field)[0]
|
||||
|
||||
controls_start_at_now: bool = Field(
|
||||
default=False, description="Control arrays start at the run timestamp instead of midnight."
|
||||
)
|
||||
|
||||
battery_grid_export_allowed: list[int] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Array with battery-to-grid export values (1 for export discharge, 0 otherwise)."
|
||||
},
|
||||
)
|
||||
|
||||
terminal_value: Optional[TerminalValueResult] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"The terminal value applied to the energy left in the battery at "
|
||||
"the end of the horizon, including the curve it was read from. "
|
||||
"None when no battery is part of the optimization."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
battery_grid_export_factor: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Array with the battery-to-grid export level per slot as factor "
|
||||
"of the rated discharge power (0.0 for no export). Empty when "
|
||||
"direct marketing is disabled; a solution without this array "
|
||||
"exports at full power wherever "
|
||||
"'battery_grid_export_allowed' is 1."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
start_solution_datetime: Optional[DateTime] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Start of the slot that gene 0 of 'start_solution' controls. Send it "
|
||||
"back together with 'start_solution' so the next run can shift the "
|
||||
"warm start by the slots that have elapsed since."
|
||||
),
|
||||
"examples": [None, "2026-09-14T07:45:00+02:00"],
|
||||
},
|
||||
)
|
||||
|
||||
appliance_starts: dict[str, list[DateTime]] = Field(
|
||||
default_factory=dict,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Scheduled run start times per appliance device_id as absolute local datetimes. "
|
||||
"A run in progress is listed first with its actual (past) start."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
appliance_deadline_missed: dict[str, bool] = Field(
|
||||
default_factory=dict,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Per appliance device_id with a 'deadline_datetime': whether the "
|
||||
"scheduled run misses that deadline (or was not scheduled at "
|
||||
"all). Appliances without a deadline are not listed."
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
interval_seconds: int = Field(
|
||||
default=3600, description="Duration of one result/control slot in seconds."
|
||||
)
|
||||
|
||||
first_slot_fraction: float = Field(
|
||||
default=1.0,
|
||||
gt=0.0,
|
||||
le=1.0,
|
||||
description=(
|
||||
"Part of the first control slot that was still ahead when the "
|
||||
"optimization ran (0.25 for a run at 10:45 with hourly slots). The "
|
||||
"results of the first slot cover only that part, and its factors are "
|
||||
"chosen for it. 1.0 for a run on a slot boundary."
|
||||
),
|
||||
)
|
||||
|
||||
@field_validator("start_solution_datetime", mode="before")
|
||||
@classmethod
|
||||
def transform_start_solution_datetime(cls, value: Any) -> Optional[DateTime]:
|
||||
"""Accept the usual date time representations, naive input is local time."""
|
||||
return GeneticOptimizationParameters.transform_start_solution_datetime(value)
|
||||
|
||||
|
||||
def _curve_response(
|
||||
curve: Optional[geneticterminalvalue.TerminalValueCurve],
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""The fields of a terminal value curve, without the replay context of a tail curve."""
|
||||
if curve is None:
|
||||
return None
|
||||
return {name: getattr(curve, name) for name in TerminalValueCurve.model_fields}
|
||||
|
||||
|
||||
def terminal_value_response(
|
||||
terminal_value: Optional[geneticterminalvalue.TerminalValueResult],
|
||||
) -> Optional[TerminalValueResult]:
|
||||
"""The public terminal value of a run.
|
||||
|
||||
Args:
|
||||
terminal_value: The terminal value of the result.
|
||||
|
||||
Returns:
|
||||
The terminal value as the REST API returns it.
|
||||
"""
|
||||
if terminal_value is None:
|
||||
return None
|
||||
return TerminalValueResult.model_validate(
|
||||
{
|
||||
**{
|
||||
field.name: getattr(terminal_value, field.name)
|
||||
for field in dataclasses.fields(terminal_value)
|
||||
},
|
||||
"curve": _curve_response(terminal_value.curve),
|
||||
"continuation_curve": _curve_response(terminal_value.continuation_curve),
|
||||
"tail_diagnostics": None
|
||||
if terminal_value.tail_diagnostics is None
|
||||
else dataclasses.asdict(terminal_value.tail_diagnostics),
|
||||
"tail_plan": [dataclasses.asdict(slot) for slot in terminal_value.tail_plan],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def solution_response(result: GeneticResult) -> GeneticSolution:
|
||||
"""The public solution of a run.
|
||||
|
||||
Args:
|
||||
result: The result of the run; its request is echoed as ``parameters``.
|
||||
|
||||
Returns:
|
||||
The solution as the REST API returns it.
|
||||
"""
|
||||
return GeneticSolution.model_validate(
|
||||
{
|
||||
**{
|
||||
field.name: getattr(result, field.name)
|
||||
for field in dataclasses.fields(result)
|
||||
if field.name not in ("request", "result", "ev_obj", "terminal_value")
|
||||
},
|
||||
"parameters": result.request,
|
||||
"result": dataclasses.asdict(result.result),
|
||||
"ev_obj": None if result.ev_obj is None else dataclasses.asdict(result.ev_obj),
|
||||
"terminal_value": terminal_value_response(result.terminal_value),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
# Router
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def last_run() -> Optional[OptimizerRun[GeneticParameters, GeneticResult]]:
|
||||
"""Placeholder dependency: the latest GENETIC 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 GENETIC 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 GENETIC for the server.
|
||||
|
||||
Returns:
|
||||
The router and its placeholder dependencies.
|
||||
"""
|
||||
return OptimizerApi(router=router, last_run=last_run, run=run)
|
||||
|
||||
|
||||
@router.get("/v1/energy-management/optimization/solution/GENETIC", tags=["energy-management"])
|
||||
async def fastapi_energy_management_optimization_solution_genetic_get(
|
||||
latest: Optional[OptimizerRun[GeneticParameters, GeneticResult]] = Depends(last_run),
|
||||
) -> GeneticSolution:
|
||||
"""Get the latest GENETIC 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 'GENETIC' optimization solution.\n"
|
||||
"Did you configure automatic 'GENETIC' optimization?\n"
|
||||
"Did you run the optimization/ energy management?"
|
||||
),
|
||||
)
|
||||
return solution_response(latest.result)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/v1/energy-management/optimization/solution/GENETIC/pdf",
|
||||
tags=["energy-management"],
|
||||
response_class=Response,
|
||||
responses={200: {"content": {"application/pdf": {}}}},
|
||||
)
|
||||
async def fastapi_energy_management_optimization_solution_genetic_pdf_get(
|
||||
latest: Optional[OptimizerRun[GeneticParameters, GeneticResult]] = Depends(last_run),
|
||||
) -> Response:
|
||||
"""Render the retained GENETIC result without rerunning optimization.
|
||||
|
||||
Rendering runs outside the event loop. Copy the result before offloading;
|
||||
its recorded timestamp, interval and inputs own the report's time grid.
|
||||
The legacy /visualization_results.pdf route continues to serve GENETIC0.
|
||||
"""
|
||||
if latest is None:
|
||||
raise OptimizerProblem(
|
||||
status=404,
|
||||
title="Optimization solution report retrieval failed",
|
||||
detail="Can not get the 'GENETIC' optimization solution.",
|
||||
)
|
||||
snapshot = copy.deepcopy(latest.result)
|
||||
# matplotlib is only needed for the PDF report; import it on first use.
|
||||
from akkudoktoreos.optimization.genetic import geneticvisualize
|
||||
|
||||
pdf = await asyncio.to_thread(
|
||||
geneticvisualize.genetic_prepare_visualize, parameters=latest.parameters, result=snapshot
|
||||
)
|
||||
return Response(
|
||||
content=pdf,
|
||||
media_type="application/pdf",
|
||||
headers={"Content-Disposition": 'inline; filename="optimization-genetic.pdf"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/v1/optimize", tags=["optimize"])
|
||||
async def fastapi_optimize_config(
|
||||
request: Request,
|
||||
parameters: GeneticRequest = Body(default_factory=GeneticRequest),
|
||||
trigger: RunTrigger = Depends(run),
|
||||
) -> GeneticSolution:
|
||||
"""Optimize GENETIC using configured devices and optional fresh runtime inputs.
|
||||
|
||||
Static settings belong in configuration; query overrides are rejected.
|
||||
Forecast arrays start at local
|
||||
midnight and contain Wh per configured GENETIC slot; prices are currency/Wh.
|
||||
An empty body uses configured providers. Explicit SoC values take precedence over
|
||||
fresh measured states of charge; missing usable measurements default to an assumed
|
||||
initial SoC of 0% without blocking a plan.
|
||||
The deprecated /optimize endpoint continues to run hourly GENETIC0.
|
||||
"""
|
||||
if request.query_params:
|
||||
raise OptimizerProblem(
|
||||
status=422,
|
||||
title="HTTP Error",
|
||||
detail="Configure optimization settings; query overrides are not supported.",
|
||||
)
|
||||
result = await trigger(request=parameters)
|
||||
if result is None:
|
||||
raise OptimizerProblem(
|
||||
status=503,
|
||||
title="GENETIC optimization failed",
|
||||
detail="No new solution was produced. Check configured devices and forecast coverage.",
|
||||
)
|
||||
if not isinstance(result, GeneticResult):
|
||||
raise OptimizerProblem(
|
||||
status=500,
|
||||
title="Unexpected optimization algorithm result",
|
||||
detail="GENETIC did not return its native solution type.",
|
||||
)
|
||||
return solution_response(result)
|
||||
@@ -0,0 +1,324 @@
|
||||
"""Appliance part of the GENETIC genome: allowed starts, layout and decoding.
|
||||
|
||||
Pure functions of the appliances and the run's slot grid. The algorithm builds and decodes its
|
||||
genome with them; the parameter preparation checks with the same rules that every appliance of a
|
||||
run can be scheduled.
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from functools import lru_cache
|
||||
from typing import Any, Optional
|
||||
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
GeneticScheduleMode,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ApplianceGeneSlot:
|
||||
"""One appliance start gene in the genome.
|
||||
|
||||
The gene value is an **index into ``allowed_start_slots``**, not an absolute
|
||||
slot. This guarantees every gene value maps to a genuinely valid start and
|
||||
keeps all allowed starts equally reachable by mutation/crossover.
|
||||
"""
|
||||
|
||||
gene_index: int
|
||||
appliance_index: int
|
||||
device_id: str
|
||||
run_index: int
|
||||
# Local calendar date of the run for DAILY appliances; None for ONCE.
|
||||
run_date: Optional[Any]
|
||||
allowed_start_slots: list[int]
|
||||
cycle_index: int = 0
|
||||
deadline_relaxed: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ApplianceGeneLayout:
|
||||
"""Ordered descriptor of the appliance part of the genome.
|
||||
|
||||
Every genome-building step (create/split/merge/mutate/decode) consumes only
|
||||
this descriptor, so the appliance gene block can vary in length with the
|
||||
number of devices and DAILY run days without any hard-coded gene positions.
|
||||
"""
|
||||
|
||||
genes: list[ApplianceGeneSlot] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def n_genes(self) -> int:
|
||||
"""Number of appliance start genes."""
|
||||
return len(self.genes)
|
||||
|
||||
def signature(self) -> tuple:
|
||||
"""Stable identity of the layout for start-solution compatibility.
|
||||
|
||||
Two layouts with the same length can still describe different schedules;
|
||||
the signature captures device, run date and the allowed-start list so a
|
||||
cached start solution built for a different layout is not silently
|
||||
reused.
|
||||
"""
|
||||
return tuple(
|
||||
(gene.device_id, str(gene.run_date), gene.cycle_index, tuple(gene.allowed_start_slots))
|
||||
for gene in self.genes
|
||||
)
|
||||
|
||||
|
||||
def _run_date(appliance: GeneticHomeAppliance, slot0_datetime: Any, slot: int) -> Any:
|
||||
"""Local date of a run starting in ``slot``, the day a DAILY cycle counts for."""
|
||||
return slot0_datetime.add(seconds=slot * appliance.slot_interval_seconds).date()
|
||||
|
||||
|
||||
def build_appliance_layout(
|
||||
appliances: list[GeneticHomeAppliance],
|
||||
slot0_datetime: Any,
|
||||
*,
|
||||
start_slot: int,
|
||||
horizon_end_slot: int,
|
||||
control_end_slot: int,
|
||||
slot_duration_h: float,
|
||||
order_cache: dict[int, list[int]],
|
||||
) -> ApplianceGeneLayout:
|
||||
"""Keep each cycle's windows, completed cycles and local-day identity.
|
||||
|
||||
Args:
|
||||
appliances: The appliances of the run, with any run in progress pinned.
|
||||
slot0_datetime: Date-time of slot 0, the run start.
|
||||
start_slot: First slot an appliance may start in.
|
||||
horizon_end_slot: Exclusive end of the slots an appliance run must end in.
|
||||
control_end_slot: Exclusive control end of the run.
|
||||
slot_duration_h: Length of a slot in hours.
|
||||
order_cache: Feasible cycle order per appliance index; filled for the decoding.
|
||||
|
||||
Returns:
|
||||
The appliance genes of the genome.
|
||||
|
||||
Raises:
|
||||
ValueError: An appliance cannot be scheduled within its windows, deadline, minimum gaps
|
||||
and the control horizon.
|
||||
"""
|
||||
genes: list[ApplianceGeneSlot] = []
|
||||
first_date = slot0_datetime.date()
|
||||
for appliance_index, appliance in enumerate(appliances):
|
||||
cycles = range(appliance.num_cycles)
|
||||
# A run in progress counts as done for its day and delays the next
|
||||
# cycle until after its end and the minimum gap.
|
||||
completed_cycles = appliance.completed_cycles_on(first_date)
|
||||
earliest_slot = max(start_slot, appliance.next_cycle_earliest_slot())
|
||||
allowed_by_cycle: dict[int, list[int]] = {}
|
||||
relaxed_by_cycle: dict[int, bool] = {}
|
||||
for cycle in cycles:
|
||||
allowed_by_cycle[cycle] = appliance.allowed_start_slots(
|
||||
slot0_datetime=slot0_datetime,
|
||||
earliest_slot=earliest_slot,
|
||||
horizon_end_slot=horizon_end_slot,
|
||||
cycle_index=cycle,
|
||||
)
|
||||
relaxed_by_cycle[cycle] = appliance.deadline_relaxed
|
||||
if appliance.schedule_mode == GeneticScheduleMode.ONCE:
|
||||
groups = [
|
||||
(None, cycle, allowed_by_cycle[cycle])
|
||||
for cycle in cycles
|
||||
if cycle >= completed_cycles
|
||||
]
|
||||
else:
|
||||
by_date: dict[Any, dict[int, list[int]]] = {}
|
||||
for cycle, allowed in allowed_by_cycle.items():
|
||||
for slot in allowed:
|
||||
date = _run_date(appliance, slot0_datetime, slot)
|
||||
if date == first_date and cycle < completed_cycles:
|
||||
continue
|
||||
by_date.setdefault(date, {}).setdefault(cycle, []).append(slot)
|
||||
# Without any start the appliance cannot be scheduled if its windows and earliest
|
||||
# start are open for a cycle it still owes, but too short for the full run. A
|
||||
# horizon in which they are not open at all has nothing to plan.
|
||||
if not by_date and any(
|
||||
not (
|
||||
_run_date(appliance, slot0_datetime, slot) == first_date
|
||||
and cycle < completed_cycles
|
||||
)
|
||||
for cycle in cycles
|
||||
for slot in appliance.open_start_slots(
|
||||
slot0_datetime=slot0_datetime,
|
||||
earliest_slot=earliest_slot,
|
||||
horizon_end_slot=horizon_end_slot,
|
||||
cycle_index=cycle,
|
||||
)
|
||||
):
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' has no valid start within its windows, deadline and control horizon."
|
||||
)
|
||||
groups = [
|
||||
(date, cycle, allowed)
|
||||
for date, cycle_slots in sorted(by_date.items())
|
||||
for cycle, allowed in sorted(cycle_slots.items())
|
||||
]
|
||||
# A partially elapsed first day may have no feasible remaining run;
|
||||
# later complete planning days must retain all configured cycles.
|
||||
for date, cycle_slots in by_date.items():
|
||||
expected = {
|
||||
cycle for cycle in cycles if date != first_date or cycle >= completed_cycles
|
||||
}
|
||||
if set(cycle_slots) != expected:
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' has no complete cycle schedule on {date}."
|
||||
)
|
||||
for run_index, (date, cycle, allowed) in enumerate(groups):
|
||||
if not allowed:
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' cycle {cycle} has no valid start within its windows, deadline and control horizon."
|
||||
)
|
||||
genes.append(
|
||||
ApplianceGeneSlot(
|
||||
gene_index=len(genes),
|
||||
appliance_index=appliance_index,
|
||||
device_id=appliance.device_id,
|
||||
run_index=run_index,
|
||||
run_date=date,
|
||||
allowed_start_slots=allowed,
|
||||
cycle_index=cycle,
|
||||
deadline_relaxed=relaxed_by_cycle[cycle],
|
||||
)
|
||||
)
|
||||
layout = ApplianceGeneLayout(genes)
|
||||
# Detect impossible cross-cycle gaps before running a population search.
|
||||
decode_appliance_starts(
|
||||
layout,
|
||||
appliances,
|
||||
[0] * layout.n_genes,
|
||||
start_slot=start_slot,
|
||||
control_end_slot=control_end_slot,
|
||||
slot_duration_h=slot_duration_h,
|
||||
order_cache=order_cache,
|
||||
)
|
||||
return layout
|
||||
|
||||
|
||||
def decode_appliance_starts(
|
||||
layout: ApplianceGeneLayout,
|
||||
appliances: list[GeneticHomeAppliance],
|
||||
appliance_gene_values: list[int],
|
||||
*,
|
||||
start_slot: int,
|
||||
control_end_slot: int,
|
||||
slot_duration_h: float,
|
||||
order_cache: dict[int, list[int]],
|
||||
) -> dict[int, list[int]]:
|
||||
"""Repair requested starts jointly, preserving cycle windows and minimum gaps.
|
||||
|
||||
Backward latest-feasible bounds and a forward nearest-choice pass prevent
|
||||
an unlucky late first gene from making otherwise feasible cycles invalid.
|
||||
The canonical gene values are updated to describe the executed schedule.
|
||||
|
||||
Args:
|
||||
layout: The appliance genes of the genome.
|
||||
appliances: The appliances the genes refer to by index.
|
||||
appliance_gene_values: The appliance genes; updated to the executed schedule.
|
||||
start_slot: First slot an appliance may start in.
|
||||
control_end_slot: Exclusive control end of the run.
|
||||
slot_duration_h: Length of a slot in hours.
|
||||
order_cache: Feasible cycle order per appliance index, found once per run.
|
||||
|
||||
Returns:
|
||||
The start slots of each appliance, by appliance index.
|
||||
|
||||
Raises:
|
||||
ValueError: An appliance has no feasible schedule.
|
||||
"""
|
||||
starts_per_appliance: dict[int, list[int]] = defaultdict(list)
|
||||
grouped: dict[int, list[tuple[int, ApplianceGeneSlot]]] = defaultdict(list)
|
||||
for position, gene in enumerate(layout.genes):
|
||||
grouped[gene.appliance_index].append((position, gene))
|
||||
for appliance_index, entries in grouped.items():
|
||||
appliance = appliances[appliance_index]
|
||||
separation = appliance.run_slots + math.ceil(appliance.min_cycle_gap_h / slot_duration_h)
|
||||
by_position = dict(entries)
|
||||
|
||||
def requested_start(entry: tuple[int, ApplianceGeneSlot]) -> int:
|
||||
position, gene = entry
|
||||
index = min(
|
||||
max(int(appliance_gene_values[position]), 0), len(gene.allowed_start_slots) - 1
|
||||
)
|
||||
return gene.allowed_start_slots[0 if gene.deadline_relaxed else index]
|
||||
|
||||
def latest_bounds(order: list[tuple[int, ApplianceGeneSlot]]) -> Optional[list[int]]:
|
||||
bounds: list[int] = []
|
||||
limit = control_end_slot
|
||||
for _, gene in reversed(order):
|
||||
candidates = [slot for slot in gene.allowed_start_slots if slot <= limit]
|
||||
if not candidates:
|
||||
return None
|
||||
last = candidates[-1]
|
||||
bounds.append(last)
|
||||
limit = last - separation
|
||||
return list(reversed(bounds))
|
||||
|
||||
# Cycle numbers identify masks; they do not impose temporal order.
|
||||
# Keep every feasible order represented by a candidate genome.
|
||||
entries.sort(key=lambda entry: (requested_start(entry), entry[0]))
|
||||
latest = latest_bounds(entries)
|
||||
if latest is None:
|
||||
if appliance_index not in order_cache:
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def feasible_order(
|
||||
remaining: tuple[int, ...], earliest: int
|
||||
) -> Optional[tuple[int, ...]]:
|
||||
if not remaining:
|
||||
return ()
|
||||
choices = []
|
||||
for position in remaining:
|
||||
allowed = [
|
||||
slot
|
||||
for slot in by_position[position].allowed_start_slots
|
||||
if slot >= earliest
|
||||
]
|
||||
if not allowed:
|
||||
return None
|
||||
choices.append((allowed[0], allowed[-1], position))
|
||||
# For a fixed order the earliest start dominates all later
|
||||
# starts for feasibility. Search permutations only once
|
||||
# per run, memoizing impossible remaining-cycle states.
|
||||
for first, _, position in sorted(choices):
|
||||
rest = feasible_order(
|
||||
tuple(index for index in remaining if index != position),
|
||||
first + separation,
|
||||
)
|
||||
if rest is not None:
|
||||
return (position, *rest)
|
||||
return None
|
||||
|
||||
order = feasible_order(tuple(sorted(by_position)), start_slot)
|
||||
if order is None:
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' cycles cannot fit their windows and minimum gaps."
|
||||
)
|
||||
order_cache[appliance_index] = list(order)
|
||||
entries = [
|
||||
(position, by_position[position]) for position in order_cache[appliance_index]
|
||||
]
|
||||
latest = latest_bounds(entries)
|
||||
if latest is None:
|
||||
raise ValueError(
|
||||
f"Home appliance '{appliance.device_id}' has no feasible cycle schedule."
|
||||
)
|
||||
earliest = start_slot
|
||||
for (position, gene), last in zip(entries, latest):
|
||||
allowed = gene.allowed_start_slots
|
||||
requested_index = min(max(int(appliance_gene_values[position]), 0), len(allowed) - 1)
|
||||
requested = allowed[requested_index]
|
||||
candidates = [slot for slot in allowed if earliest <= slot <= last]
|
||||
if not candidates:
|
||||
raise ValueError(f"Home appliance '{gene.device_id}' has no feasible cycle start.")
|
||||
chosen = (
|
||||
candidates[0]
|
||||
if gene.deadline_relaxed
|
||||
else min(candidates, key=lambda slot: (abs(slot - requested), slot))
|
||||
)
|
||||
starts_per_appliance[appliance_index].append(chosen)
|
||||
appliance_gene_values[position] = allowed.index(chosen)
|
||||
earliest = chosen + separation
|
||||
return starts_per_appliance
|
||||
@@ -0,0 +1,710 @@
|
||||
"""Solution conversion of GENETIC (ADR 0003, 0006).
|
||||
|
||||
Turns the result of a run into the optimization solution and the energy management plan, from
|
||||
the optimization parameters (run start, time zone) and the result (genes, simulation result and
|
||||
the forecast and device parameters it echoes) only.
|
||||
"""
|
||||
|
||||
from typing import Optional, cast
|
||||
|
||||
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.devices.devicesabc import (
|
||||
ApplianceOperationMode,
|
||||
BatteryOperationMode,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticInverterRequest,
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
|
||||
async def convert(
|
||||
parameters: GeneticParameters, result: GeneticResult
|
||||
) -> 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_device_id(result: GeneticResult) -> str:
|
||||
"""Device ID of the run's battery."""
|
||||
parameters = result.request
|
||||
if parameters is not None and parameters.pv_battery is not None:
|
||||
return parameters.pv_battery.device_id
|
||||
return "battery1"
|
||||
|
||||
|
||||
def _ev_device_id(result: GeneticResult) -> str:
|
||||
"""Device ID of the run's electric vehicle."""
|
||||
parameters = result.request
|
||||
if parameters is not None and parameters.ev is not None:
|
||||
return parameters.ev.device_id
|
||||
return "ev1"
|
||||
|
||||
|
||||
def _battery_operation_from_solution(
|
||||
ac_charge: float,
|
||||
dc_charge: float,
|
||||
discharge_allowed: bool,
|
||||
battery_grid_export_allowed: bool = False,
|
||||
battery_grid_export_factor: float = 1.0,
|
||||
) -> 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 to local load is permitted.
|
||||
battery_grid_export_allowed (bool): Whether discharge into the grid is permitted.
|
||||
battery_grid_export_factor (float): Export level as factor of the rated
|
||||
discharge power ]0.0 ... 1.0]. Becomes the operation factor of
|
||||
GRID_SUPPORT_EXPORT.
|
||||
|
||||
Returns:
|
||||
tuple[BatteryOperationMode, float]: A tuple containing
|
||||
- `BatteryOperationMode`: the representative high-level operation mode.
|
||||
- `float`: the operation factor corresponding to the active signal.
|
||||
|
||||
Notes:
|
||||
- Explicit grid export is separate from local-load discharge.
|
||||
- The mapping prioritizes export > 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
|
||||
and not battery_grid_export_allowed
|
||||
):
|
||||
return BatteryOperationMode.IDLE, 1.0
|
||||
|
||||
if battery_grid_export_allowed:
|
||||
if ac_charge > 0.0 or dc_charge > 0.0:
|
||||
raise ValueError(
|
||||
"Illegal state: battery_grid_export_allowed cannot be combined with charging"
|
||||
)
|
||||
return BatteryOperationMode.GRID_SUPPORT_EXPORT, min(
|
||||
max(float(battery_grid_export_factor), 0.0), 1.0
|
||||
)
|
||||
|
||||
# (0,0,1) -> Discharge for local load only: serve local demand, no grid
|
||||
# charging and no export.
|
||||
if ac_charge <= 0.0 and dc_charge <= 0.0 and discharge_allowed:
|
||||
return BatteryOperationMode.SELF_CONSUMPTION, 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_list(
|
||||
parameters: Optional[GeneticOptimizationParameters],
|
||||
) -> list[GeneticInverterRequest]:
|
||||
"""Return the inverter parameters the solution was computed with, as a list.
|
||||
|
||||
Args:
|
||||
parameters: The forecast and device parameters the result echoes.
|
||||
|
||||
Returns:
|
||||
The inverter, or no inverter.
|
||||
"""
|
||||
if parameters is not None and parameters.inverter is not None:
|
||||
return [parameters.inverter]
|
||||
return []
|
||||
|
||||
|
||||
def _soc_clamped_operation_factors(
|
||||
result: GeneticResult,
|
||||
ac_charge: float,
|
||||
dc_charge: float,
|
||||
discharge_allowed: bool,
|
||||
soc_pct: float,
|
||||
battery_grid_export_allowed: bool = False,
|
||||
slot_fraction: float = 1.0,
|
||||
) -> tuple[float, float, bool, 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 optimization slot. 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.
|
||||
- Battery grid export: blocked when SOC is at or below min SOC.
|
||||
|
||||
``slot_fraction`` is the part of the slot the factors apply to:
|
||||
``first_slot_fraction`` for the running first slot, else 1.0. The
|
||||
headroom check of the AC charge factor uses only that part of the slot.
|
||||
"""
|
||||
parameters = result.request
|
||||
bat_list = []
|
||||
if parameters is not None and parameters.pv_battery is not None:
|
||||
bat_list = [parameters.pv_battery]
|
||||
if not bat_list:
|
||||
return ac_charge, dc_charge, discharge_allowed, battery_grid_export_allowed
|
||||
|
||||
bat = bat_list[0]
|
||||
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)
|
||||
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_list = _inverter_parameters_list(parameters)
|
||||
ac_to_dc_eff = float(inv_list[0].ac_to_dc_efficiency) if inv_list else 1.0
|
||||
max_ac_cp_w = (
|
||||
float(inv_list[0].max_ac_charge_power_w)
|
||||
if inv_list and inv_list[0].max_ac_charge_power_w is not None
|
||||
else float(cast(float, bat.max_charge_power_w))
|
||||
)
|
||||
# Energy storable in one optimization slot, not per hour: scale the
|
||||
# power [W] by the slot duration (1.0 hourly, 0.25 at 15 min).
|
||||
slot_duration_h = float(result.interval_seconds) / 3600.0 * slot_fraction
|
||||
max_dc_per_slot_wh = (
|
||||
effective_ac * max_ac_cp_w * slot_duration_h * ac_to_dc_eff * ch_eff
|
||||
)
|
||||
if max_dc_per_slot_wh > headroom_wh:
|
||||
effective_ac = effective_ac * (headroom_wh / max_dc_per_slot_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)
|
||||
effective_grid_export = battery_grid_export_allowed and (soc_pct > min_soc)
|
||||
|
||||
return effective_ac, effective_dc, effective_dis, effective_grid_export
|
||||
|
||||
|
||||
async def optimization_solution(
|
||||
parameters: GeneticParameters, result: GeneticResult
|
||||
) -> OptimizationSolution:
|
||||
"""Provide the result of a run as a general optimization solution.
|
||||
|
||||
The battery modes are controlled by the grid control triggers:
|
||||
|
||||
- ac_charge: charge from grid
|
||||
- discharge_allowed: discharge to local load
|
||||
- battery_grid_export_allowed: discharge to grid
|
||||
|
||||
The following battery modes are supported:
|
||||
|
||||
- SELF_CONSUMPTION: discharge_allowed == 1 and ac_charge == 0 (with or without dc_charge)
|
||||
- GRID_SUPPORT_EXPORT: battery_grid_export_allowed == 1
|
||||
- GRID_SUPPORT_IMPORT: ac_charge > 0 and discharge_allowed == 0 or 1
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run (run start, time zone).
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The optimization solution.
|
||||
"""
|
||||
start_datetime = result.start_solution_datetime or parameters.settings.start_datetime
|
||||
# New controls use the run-relative control horizon; old payloads retain a midnight prefix.
|
||||
# entries indexed by slot (slot 0 == 00:00 local). Index this serializer
|
||||
# by slot too. At the default interval of 3600 s slots_per_hour == 1 and
|
||||
# this is the established hourly behaviour.
|
||||
interval_s = result.interval_seconds
|
||||
start_local = start_datetime.in_timezone(cast(str, parameters.settings.timezone))
|
||||
start_day_slot = (
|
||||
0
|
||||
if result.controls_start_at_now
|
||||
else int((start_local - start_local.start_of("day")).total_seconds() // interval_s)
|
||||
)
|
||||
# power [W] -> energy per slot [Wh]: multiply by the slot duration in hours.
|
||||
|
||||
# --- 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_slot)
|
||||
time_index = pd.date_range(
|
||||
start=start_datetime,
|
||||
periods=periods,
|
||||
freq=f"{interval_s}s",
|
||||
)
|
||||
n_points = len(time_index)
|
||||
end_datetime = start_datetime.add(seconds=interval_s * n_points)
|
||||
|
||||
# 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_slot
|
||||
"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,
|
||||
)
|
||||
|
||||
if result.request.pv_battery is not None:
|
||||
# Add battery data
|
||||
battery_device_id = _battery_device_id(result)
|
||||
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_slot
|
||||
]
|
||||
operation: dict[str, list[float]] = {
|
||||
"genetic_ac_charge_factor": [],
|
||||
"genetic_dc_charge_factor": [],
|
||||
"genetic_discharge_allowed_factor": [],
|
||||
"genetic_battery_grid_export_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_slot:
|
||||
continue
|
||||
if hour_idx >= start_day_slot + 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])
|
||||
battery_grid_export_allowed_hour = (
|
||||
bool(result.battery_grid_export_allowed[hour_idx])
|
||||
if hour_idx < len(result.battery_grid_export_allowed)
|
||||
else False
|
||||
)
|
||||
# Solutions written before graded export carry no factor array; they
|
||||
# exported at full power wherever the signal was set.
|
||||
battery_grid_export_factor_hour = (
|
||||
float(result.battery_grid_export_factor[hour_idx])
|
||||
if hour_idx < len(result.battery_grid_export_factor)
|
||||
else (1.0 if battery_grid_export_allowed_hour else 0.0)
|
||||
)
|
||||
|
||||
# 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))
|
||||
operation["genetic_battery_grid_export_allowed_factor"].append(
|
||||
battery_grid_export_factor_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_slot
|
||||
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, eff_grid_export = _soc_clamped_operation_factors(
|
||||
result,
|
||||
ac_charge_hour,
|
||||
dc_charge_hour,
|
||||
discharge_allowed_hour,
|
||||
soc_h_pct,
|
||||
battery_grid_export_allowed_hour,
|
||||
result.first_slot_fraction if result_idx == 0 else 1.0,
|
||||
)
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
eff_ac, eff_dc, eff_dis, eff_grid_export, battery_grid_export_factor_hour
|
||||
)
|
||||
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
|
||||
# eautocharge_hours_float start at hour 0 of start day
|
||||
# result.EAuto_SoC_pro_Stunde start at start_datetime.hour
|
||||
if result.ev_obj:
|
||||
ev_device_id = _ev_device_id(result)
|
||||
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_slot:
|
||||
continue
|
||||
if hour_idx >= start_day_slot + n_points:
|
||||
break
|
||||
operation["genetic_ev_charge_factor"].append(rate)
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
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, one block of columns per device. Per-device
|
||||
# energy arrays start at start_day_slot, like the other result arrays.
|
||||
for device_id, energy_wh in result.result.home_appliance_energy_wh.items():
|
||||
solution[f"{device_id}_energy_wh"] = energy_wh[:n_points]
|
||||
operation = {
|
||||
f"{device_id}_run_op_mode": [],
|
||||
f"{device_id}_run_op_factor": [],
|
||||
f"{device_id}_off_op_mode": [],
|
||||
f"{device_id}_off_op_factor": [],
|
||||
}
|
||||
running_slots = result.result.home_appliance_running.get(device_id, [])
|
||||
for hour_idx, energy in enumerate(solution[f"{device_id}_energy_wh"]):
|
||||
running = (
|
||||
running_slots[hour_idx]
|
||||
if hour_idx < len(running_slots)
|
||||
else bool(energy and energy > 0.0)
|
||||
)
|
||||
if running:
|
||||
operation[f"{device_id}_run_op_mode"].append(1.0)
|
||||
operation[f"{device_id}_run_op_factor"].append(1.0)
|
||||
operation[f"{device_id}_off_op_mode"].append(0.0)
|
||||
operation[f"{device_id}_off_op_factor"].append(0.0)
|
||||
else:
|
||||
operation[f"{device_id}_run_op_mode"].append(0.0)
|
||||
operation[f"{device_id}_run_op_factor"].append(0.0)
|
||||
operation[f"{device_id}_off_op_mode"].append(1.0)
|
||||
operation[f"{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,
|
||||
)
|
||||
if result.controls_start_at_now:
|
||||
snapshot = result.request.ems
|
||||
prediction["pvforecast_ac_energy_wh"] = snapshot.pv_forecast_wh[:n_points]
|
||||
prediction["loadforecast_energy_wh"] = snapshot.total_load[:n_points]
|
||||
prediction["elec_price_amt_kwh"] = (
|
||||
np.asarray(snapshot.electricity_price_per_wh[:n_points]) * 1000
|
||||
)
|
||||
tariffs = snapshot.feed_in_tariff_per_wh
|
||||
prediction["feed_in_tariff_amt_kwh"] = (
|
||||
np.asarray(tariffs[:n_points]) * 1000 if isinstance(tariffs, list) else tariffs * 1000
|
||||
)
|
||||
if result.controls_start_at_now and result.request.temperature_forecast is not None:
|
||||
prediction["weather_air_temp_celcius"] = result.request.temperature_forecast[:n_points]
|
||||
|
||||
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=end_datetime,
|
||||
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: GeneticParameters, result: GeneticResult
|
||||
) -> EnergyManagementPlan:
|
||||
"""Provide the result of a run as an energy management plan.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run (run start, time zone).
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The energy management plan.
|
||||
"""
|
||||
start_datetime = result.start_solution_datetime or parameters.settings.start_datetime
|
||||
# Index by slot, not hour (mirrors optimization_solution). At the default
|
||||
# interval of 3600 s this reduces to the start hour-of-day.
|
||||
interval_s = result.interval_seconds
|
||||
start_local = start_datetime.in_timezone(cast(str, parameters.settings.timezone))
|
||||
start_day_slot = (
|
||||
0
|
||||
if result.controls_start_at_now
|
||||
else int((start_local - start_local.start_of("day")).total_seconds() // interval_s)
|
||||
)
|
||||
plan = EnergyManagementPlan(
|
||||
id=f"plan-genetic@{to_datetime(as_string=True)}",
|
||||
generated_at=to_datetime(),
|
||||
instructions=[],
|
||||
comment="Energy management plan derived from GeneticSolution.",
|
||||
)
|
||||
|
||||
if result.request.pv_battery is not None:
|
||||
# Add battery instructions (fill rate based control)
|
||||
last_operation_mode: Optional[str] = None
|
||||
last_operation_mode_factor: Optional[float] = None
|
||||
resource_id = _battery_device_id(result)
|
||||
# ac_charge, dc_charge, discharge_allowed start at hour 0 of start day
|
||||
logger.debug("BAT: {} - {}", resource_id, result.ac_charge[start_day_slot:])
|
||||
for hour_idx, rate in enumerate(result.ac_charge):
|
||||
if hour_idx < start_day_slot:
|
||||
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_slot
|
||||
soc_h_pct = (
|
||||
result.result.battery_soc_per_hour[result_idx]
|
||||
if result_idx < len(result.result.battery_soc_per_hour)
|
||||
else 0.0
|
||||
)
|
||||
battery_grid_export_allowed_hour = (
|
||||
bool(result.battery_grid_export_allowed[hour_idx])
|
||||
if hour_idx < len(result.battery_grid_export_allowed)
|
||||
else False
|
||||
)
|
||||
eff_ac, eff_dc, eff_dis, eff_grid_export = _soc_clamped_operation_factors(
|
||||
result,
|
||||
result.ac_charge[hour_idx],
|
||||
result.dc_charge[hour_idx],
|
||||
bool(result.discharge_allowed[hour_idx]),
|
||||
soc_h_pct,
|
||||
battery_grid_export_allowed_hour,
|
||||
result.first_slot_fraction if result_idx == 0 else 1.0,
|
||||
)
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
eff_ac,
|
||||
eff_dc,
|
||||
eff_dis,
|
||||
eff_grid_export,
|
||||
result.battery_grid_export_factor[hour_idx]
|
||||
if hour_idx < len(result.battery_grid_export_factor)
|
||||
else 1.0,
|
||||
)
|
||||
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(seconds=interval_s * (hour_idx - start_day_slot))
|
||||
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)
|
||||
# eautocharge_hours_float start at hour 0 of start day
|
||||
if result.ev_obj:
|
||||
resource_id = _ev_device_id(result)
|
||||
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_slot:])
|
||||
for hour_idx, rate in enumerate(result.ev_charge_hours_float):
|
||||
if hour_idx < start_day_slot:
|
||||
continue
|
||||
operation_mode, operation_mode_factor = _battery_operation_from_solution(
|
||||
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(
|
||||
seconds=interval_s * (hour_idx - start_day_slot)
|
||||
)
|
||||
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), one
|
||||
# stream of instructions per device. A new instruction is only emitted on
|
||||
# a transition between OFF (energy == 0) and RUN (energy > 0); a mere
|
||||
# power change within a running profile does not add an instruction.
|
||||
for resource_id, energy_wh in result.result.home_appliance_energy_wh.items():
|
||||
last_state: Optional[bool] = None
|
||||
for hours, energy in enumerate(energy_wh):
|
||||
# hours starts at start_datetime with 0
|
||||
if energy is None:
|
||||
raise ValueError(
|
||||
f"Unexpected value {energy} in home_appliance_energy_wh[{resource_id}]"
|
||||
)
|
||||
running_slots = result.result.home_appliance_running.get(resource_id, [])
|
||||
running = running_slots[hours] if hours < len(running_slots) else energy > 0.0
|
||||
if last_state is None or running != last_state:
|
||||
appliance_mode = (
|
||||
ApplianceOperationMode.RUN if running else ApplianceOperationMode.OFF
|
||||
)
|
||||
execution_time = start_datetime.add(seconds=interval_s * hours)
|
||||
plan.add_instruction(
|
||||
DDBCInstruction(
|
||||
resource_id=resource_id,
|
||||
execution_time=execution_time,
|
||||
actuator_id=resource_id,
|
||||
operation_mode_id=appliance_mode,
|
||||
operation_mode_factor=1.0,
|
||||
)
|
||||
)
|
||||
last_state = running
|
||||
|
||||
if not plan.instructions:
|
||||
plan.valid_from = start_datetime
|
||||
return plan
|
||||
@@ -1,19 +0,0 @@
|
||||
"""Genetic optimization algorithm device interfaces/ parameters."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from akkudoktoreos.optimization.genetic.geneticabc import GeneticParametersBaseModel
|
||||
|
||||
|
||||
class DeviceParameters(GeneticParametersBaseModel):
|
||||
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,208 @@
|
||||
"""Load-dependent conversion efficiency of the GENETIC simulation devices.
|
||||
|
||||
GENETIC's own copy of the efficiency curve helpers (ADR 0004: optimizers duplicate code instead
|
||||
of sharing it), so its simulation does not import the shared device configuration.
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Sequence
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def validate_efficiency_curve(
|
||||
curve: Optional[list[tuple[float, float]]],
|
||||
) -> Optional[list[tuple[float, float]]]:
|
||||
"""Validate a load-dependent conversion efficiency curve.
|
||||
|
||||
A curve is a list of ``(load_fraction, efficiency)`` points. The load
|
||||
fraction is the converted power relative to the rated power of the device
|
||||
(0.0 = idle, 1.0 = rated power), the efficiency is the conversion
|
||||
efficiency at that load.
|
||||
|
||||
Rules:
|
||||
- At least two points.
|
||||
- Load fractions are finite, within [0, 1] and strictly increasing
|
||||
(sorted, no duplicates).
|
||||
- Efficiencies are finite and within (0, 1].
|
||||
|
||||
Args:
|
||||
curve: The curve points, or None for no curve.
|
||||
|
||||
Returns:
|
||||
The unchanged curve, or None.
|
||||
|
||||
Raises:
|
||||
ValueError: If the curve violates one of the rules.
|
||||
"""
|
||||
if curve is None:
|
||||
return None
|
||||
if len(curve) < 2:
|
||||
raise ValueError("An efficiency curve needs at least two points.")
|
||||
previous_fraction: Optional[float] = None
|
||||
for fraction, efficiency in curve:
|
||||
if not math.isfinite(fraction) or not 0.0 <= fraction <= 1.0:
|
||||
raise ValueError(f"Efficiency curve load fraction {fraction} is outside of [0, 1].")
|
||||
if not math.isfinite(efficiency) or not 0.0 < efficiency <= 1.0:
|
||||
raise ValueError(f"Efficiency curve efficiency {efficiency} is outside of (0, 1].")
|
||||
if previous_fraction is not None and fraction <= previous_fraction:
|
||||
raise ValueError(
|
||||
"Efficiency curve load fractions must be strictly increasing "
|
||||
f"(sorted, no duplicates); got {fraction} after {previous_fraction}."
|
||||
)
|
||||
previous_fraction = fraction
|
||||
return curve
|
||||
|
||||
|
||||
def interpolate_efficiency_curve(
|
||||
curve: Sequence[tuple[float, float]], load_fraction: float
|
||||
) -> float:
|
||||
"""Return the efficiency of a curve at a load fraction.
|
||||
|
||||
Interpolates linearly between the curve points. Load fractions below the
|
||||
first or above the last point are clamped to the efficiency of that point.
|
||||
|
||||
Args:
|
||||
curve: Points as validated by ``validate_efficiency_curve``.
|
||||
load_fraction: Converted power relative to the rated power.
|
||||
|
||||
Returns:
|
||||
The efficiency at ``load_fraction``.
|
||||
"""
|
||||
first_fraction, first_efficiency = curve[0]
|
||||
if load_fraction <= first_fraction:
|
||||
return first_efficiency
|
||||
for fraction, efficiency in curve[1:]:
|
||||
if load_fraction <= fraction:
|
||||
return first_efficiency + (load_fraction - first_fraction) / (
|
||||
fraction - first_fraction
|
||||
) * (efficiency - first_efficiency)
|
||||
first_fraction, first_efficiency = fraction, efficiency
|
||||
return first_efficiency
|
||||
|
||||
|
||||
def solve_ac_for_dc_energy(
|
||||
curve: Sequence[tuple[float, float]],
|
||||
dc_wh: float,
|
||||
rated_wh: float,
|
||||
upper_ac_wh: float,
|
||||
) -> float:
|
||||
"""Return the AC energy a DC energy yields through a load-dependent conversion.
|
||||
|
||||
The efficiency of a curve depends on the AC load actually delivered, so for a
|
||||
given DC energy the delivered AC energy ``a`` is the solution of
|
||||
``a = dc_wh * efficiency(a / rated_wh)``. The curve is piecewise linear and
|
||||
clamped at both ends, so the equation is solved exactly on each piece.
|
||||
|
||||
Args:
|
||||
curve: Points as validated by ``validate_efficiency_curve``.
|
||||
dc_wh: DC energy available to the conversion in one slot.
|
||||
rated_wh: AC energy at rated power in one slot (load fraction 1.0).
|
||||
upper_ac_wh: Upper bound of the result, e.g. the requested AC energy.
|
||||
|
||||
Returns:
|
||||
The largest consistent AC energy that does not exceed ``upper_ac_wh``.
|
||||
"""
|
||||
if dc_wh <= 0.0 or rated_wh <= 0.0 or upper_ac_wh <= 0.0:
|
||||
return 0.0
|
||||
tolerance = 1e-9
|
||||
best = -1.0
|
||||
|
||||
def consider(ac_wh: float, low: float, high: float) -> None:
|
||||
nonlocal best
|
||||
fraction = ac_wh / rated_wh
|
||||
if (
|
||||
low - tolerance <= fraction <= high + tolerance
|
||||
and 0.0 < ac_wh <= upper_ac_wh * (1.0 + tolerance)
|
||||
and ac_wh > best
|
||||
):
|
||||
best = ac_wh
|
||||
|
||||
first_fraction, first_efficiency = curve[0]
|
||||
last_fraction, last_efficiency = curve[-1]
|
||||
# Clamped ends: constant efficiency below the first and above the last point.
|
||||
consider(dc_wh * first_efficiency, float("-inf"), first_fraction)
|
||||
consider(dc_wh * last_efficiency, last_fraction, float("inf"))
|
||||
for (x0, e0), (x1, e1) in zip(curve, curve[1:]):
|
||||
slope = (e1 - e0) / (x1 - x0)
|
||||
# a = dc * (e0 + slope * (a / rated - x0)) => a * (1 - dc*slope/rated) = dc * (e0 - slope*x0)
|
||||
denominator = 1.0 - dc_wh * slope / rated_wh
|
||||
if abs(denominator) < 1e-12:
|
||||
continue
|
||||
consider(dc_wh * (e0 - slope * x0) / denominator, x0, x1)
|
||||
if best >= 0.0:
|
||||
return min(best, upper_ac_wh)
|
||||
# No piece holds a solution within the bound (only possible numerically at a
|
||||
# kink): converge on it from the bound.
|
||||
ac_wh = min(upper_ac_wh, dc_wh)
|
||||
for _ in range(50):
|
||||
next_ac_wh = min(dc_wh * interpolate_efficiency_curve(curve, ac_wh / rated_wh), upper_ac_wh)
|
||||
if abs(next_ac_wh - ac_wh) <= tolerance:
|
||||
break
|
||||
ac_wh = next_ac_wh
|
||||
return ac_wh
|
||||
|
||||
|
||||
def solve_ac_for_charge_dc_energy(
|
||||
curve: Sequence[tuple[float, float]],
|
||||
dc_wh: float,
|
||||
rated_wh: float,
|
||||
) -> float:
|
||||
"""Return the AC energy an AC→DC conversion draws to deliver a DC energy.
|
||||
|
||||
The efficiency of a curve depends on the AC load drawn, so the AC energy
|
||||
``a`` that delivers ``dc_wh`` is the solution of
|
||||
``a * efficiency(a / rated_wh) = dc_wh``. The curve is piecewise linear and
|
||||
clamped at both ends; on each piece the equation is quadratic and solved
|
||||
exactly.
|
||||
|
||||
Args:
|
||||
curve: Points as validated by ``validate_efficiency_curve``.
|
||||
dc_wh: DC energy delivered by the conversion in one slot.
|
||||
rated_wh: AC energy at rated power in one slot (load fraction 1.0).
|
||||
|
||||
Returns:
|
||||
The smallest consistent AC energy, 0.0 for no DC energy.
|
||||
"""
|
||||
if dc_wh <= 0.0:
|
||||
return 0.0
|
||||
if rated_wh <= 0.0:
|
||||
return dc_wh / curve[-1][1]
|
||||
tolerance = 1e-9
|
||||
best = float("inf")
|
||||
|
||||
def consider(ac_wh: float, low: float, high: float) -> None:
|
||||
nonlocal best
|
||||
fraction = ac_wh / rated_wh
|
||||
if low - tolerance <= fraction <= high + tolerance and 0.0 < ac_wh < best:
|
||||
best = ac_wh
|
||||
|
||||
first_fraction, first_efficiency = curve[0]
|
||||
last_fraction, last_efficiency = curve[-1]
|
||||
# Clamped ends: constant efficiency below the first and above the last point.
|
||||
consider(dc_wh / first_efficiency, float("-inf"), first_fraction)
|
||||
consider(dc_wh / last_efficiency, last_fraction, float("inf"))
|
||||
for (x0, e0), (x1, e1) in zip(curve, curve[1:]):
|
||||
slope = (e1 - e0) / (x1 - x0)
|
||||
# a * (c + k * a) = dc with c = e0 - slope * x0 and k = slope / rated.
|
||||
c = e0 - slope * x0
|
||||
k = slope / rated_wh
|
||||
if abs(k) < 1e-15:
|
||||
if c > 0.0:
|
||||
consider(dc_wh / c, x0, x1)
|
||||
continue
|
||||
discriminant = c * c + 4.0 * k * dc_wh
|
||||
if discriminant < 0.0:
|
||||
continue
|
||||
root = math.sqrt(discriminant)
|
||||
consider((-c + root) / (2.0 * k), x0, x1)
|
||||
consider((-c - root) / (2.0 * k), x0, x1)
|
||||
if best < float("inf"):
|
||||
return best
|
||||
# Only possible numerically at a kink: converge on it.
|
||||
ac_wh = dc_wh / interpolate_efficiency_curve(curve, 1.0)
|
||||
for _ in range(50):
|
||||
next_ac_wh = dc_wh / interpolate_efficiency_curve(curve, ac_wh / rated_wh)
|
||||
if abs(next_ac_wh - ac_wh) <= tolerance:
|
||||
break
|
||||
ac_wh = next_ac_wh
|
||||
return ac_wh
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Forecasts and prices of the GENETIC simulation."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticEnergyManagementParameters:
|
||||
"""Forecasts and prices per slot of a run, derived from the request.
|
||||
|
||||
Attributes:
|
||||
pv_forecast_wh: PV energy per slot [Wh].
|
||||
electricity_price_per_wh: Electricity price per slot [currency/Wh].
|
||||
feed_in_tariff_per_wh: Feed-in tariff per slot, or one value for all slots
|
||||
[currency/Wh].
|
||||
price_per_wh_battery: Value of energy left in the battery [currency/Wh].
|
||||
total_load: Load energy per slot [Wh].
|
||||
"""
|
||||
|
||||
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, ...]
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Expected direct PV-to-load power of the GENETIC inverter simulation.
|
||||
|
||||
GENETIC's own copy of the self-consumption probability table evaluation (ADR 0004). The backend
|
||||
comes from the run settings (``optimization.self_consumption_interpolator``, read by the
|
||||
parameter preparation), never from the configuration directly (ADR 0003).
|
||||
"""
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from akkudoktoreos.utils.gridinterpolator import (
|
||||
GridInterpolatorBackend,
|
||||
SwitchableGridInterpolator,
|
||||
load_grid_interpolator,
|
||||
)
|
||||
|
||||
# The table shipped with EOS: minute-load probabilities per one-hour mean load.
|
||||
_TABLE_FILE = (
|
||||
Path(__file__).parent.parent.parent.resolve() / "data" / "regular_grid_interpolator.pkl"
|
||||
)
|
||||
|
||||
|
||||
def fixed_order_dot(a: np.ndarray, b: np.ndarray) -> float:
|
||||
"""Return the dot product of two vectors, summed from the first element to the last.
|
||||
|
||||
``np.dot`` calls BLAS, whose kernel is chosen per CPU at run time, so the last bit of the
|
||||
result depends on the machine. The optimizer compares fitness values exactly; here every
|
||||
product is rounded and added in index order, with Python floats: the same result on every
|
||||
CPU.
|
||||
|
||||
Args:
|
||||
a: First vector.
|
||||
b: Second vector, same length as ``a``.
|
||||
|
||||
Returns:
|
||||
``sum(a[i] * b[i])`` in index order.
|
||||
"""
|
||||
total = 0.0
|
||||
for x, y in zip(a.tolist(), b.tolist(), strict=True):
|
||||
total += x * y
|
||||
return total
|
||||
|
||||
|
||||
class GeneticLoadInterpolator:
|
||||
"""Expected direct consumption from the self-consumption probability table."""
|
||||
|
||||
LOAD_DISTRIBUTION_CACHE_SIZE = 4096
|
||||
DIRECT_CONSUMPTION_CACHE_SIZE = 8192
|
||||
|
||||
def __init__(self, backend: GridInterpolatorBackend) -> None:
|
||||
"""Load the table.
|
||||
|
||||
Args:
|
||||
backend: How the table is evaluated.
|
||||
"""
|
||||
self.interpolator = SwitchableGridInterpolator(
|
||||
load_grid_interpolator(_TABLE_FILE), lambda: backend
|
||||
)
|
||||
self.load_power_min_w = float(self.interpolator.grid[0][0])
|
||||
self.load_power_max_w = float(self.interpolator.grid[0][-1])
|
||||
self.minute_load_levels_w = np.asarray(self.interpolator.grid[1], dtype=float)
|
||||
# The table is static and the backend fixed, so a cached value never goes stale; the
|
||||
# caches are only bounded in size.
|
||||
self._load_distributions: dict[float, tuple[np.ndarray, np.ndarray]] = {}
|
||||
self._direct_consumption: dict[tuple[float, float], float] = {}
|
||||
|
||||
def _load_distribution(self, mean_load_power_w: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Return the conditional minute-load distribution for a mean load.
|
||||
|
||||
Negative masses from the linear interpolation between mean-load rows are removed and
|
||||
the result is normalized. Callers must not modify the returned arrays.
|
||||
"""
|
||||
bounded_mean_load_w = min(
|
||||
max(float(mean_load_power_w), self.load_power_min_w), self.load_power_max_w
|
||||
)
|
||||
cached = self._load_distributions.get(bounded_mean_load_w)
|
||||
if cached is not None:
|
||||
return cached
|
||||
points = np.column_stack(
|
||||
(
|
||||
np.full(self.minute_load_levels_w.shape, bounded_mean_load_w),
|
||||
self.minute_load_levels_w,
|
||||
)
|
||||
)
|
||||
probabilities = np.maximum(np.asarray(self.interpolator(points), dtype=float), 0.0)
|
||||
probability_sum = float(probabilities.sum())
|
||||
if probability_sum <= 0.0:
|
||||
distribution = (self.minute_load_levels_w, probabilities)
|
||||
else:
|
||||
distribution = (self.minute_load_levels_w, probabilities / probability_sum)
|
||||
if bounded_mean_load_w == bounded_mean_load_w: # not NaN: NaN never matches a key
|
||||
if len(self._load_distributions) >= self.LOAD_DISTRIBUTION_CACHE_SIZE:
|
||||
self._load_distributions.clear()
|
||||
self._load_distributions[bounded_mean_load_w] = distribution
|
||||
return distribution
|
||||
|
||||
def calculate_expected_direct_consumption(
|
||||
self, mean_load_power_w: float, pv_power_w: float
|
||||
) -> float:
|
||||
"""Calculate expected direct PV-to-load power in watts.
|
||||
|
||||
For conditional minute-load probabilities ``p_i`` and load-bin powers ``L_i``, the
|
||||
expected direct consumption is ``sum(p_i * min(L_i, pv_power_w))``. The load-bin powers
|
||||
are rescaled to preserve the supplied forecast mean exactly.
|
||||
|
||||
Args:
|
||||
mean_load_power_w: Mean load power of the forecast interval [W].
|
||||
pv_power_w: Mean PV power of the forecast interval [W].
|
||||
|
||||
Returns:
|
||||
Expected direct PV-to-load power [W].
|
||||
"""
|
||||
cache = self._direct_consumption
|
||||
key = (mean_load_power_w, pv_power_w)
|
||||
cached = cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
result = self._expected_direct_consumption(mean_load_power_w, pv_power_w)
|
||||
if len(cache) >= self.DIRECT_CONSUMPTION_CACHE_SIZE:
|
||||
cache.clear()
|
||||
cache[key] = result
|
||||
return result
|
||||
|
||||
def _expected_direct_consumption(self, mean_load_power_w: float, pv_power_w: float) -> float:
|
||||
"""Calculate the expected direct PV-to-load power in watts, uncached."""
|
||||
mean_load_power_w = max(float(mean_load_power_w), 0.0)
|
||||
pv_power_w = max(float(pv_power_w), 0.0)
|
||||
if mean_load_power_w == 0.0 or pv_power_w == 0.0:
|
||||
return 0.0
|
||||
|
||||
load_levels_w, probabilities = self._load_distribution(mean_load_power_w)
|
||||
modeled_mean_load_w = fixed_order_dot(probabilities, load_levels_w)
|
||||
if modeled_mean_load_w <= 0.0:
|
||||
return 0.0
|
||||
|
||||
normalized_load_levels_w = load_levels_w * (mean_load_power_w / modeled_mean_load_w)
|
||||
expected_direct_power_w = fixed_order_dot(
|
||||
probabilities, np.minimum(normalized_load_levels_w, pv_power_w)
|
||||
)
|
||||
return min(max(expected_direct_power_w, 0.0), min(mean_load_power_w, pv_power_w))
|
||||
|
||||
|
||||
# One interpolator per backend, created on first use.
|
||||
_interpolators: dict[GridInterpolatorBackend, GeneticLoadInterpolator] = {}
|
||||
_interpolators_lock = threading.Lock()
|
||||
|
||||
|
||||
def get_genetic_load_interpolator(backend: GridInterpolatorBackend) -> GeneticLoadInterpolator:
|
||||
"""Return the shared interpolator for ``backend``.
|
||||
|
||||
Args:
|
||||
backend: How the table is evaluated.
|
||||
|
||||
Returns:
|
||||
The interpolator, loaded on first use.
|
||||
"""
|
||||
interpolator = _interpolators.get(backend)
|
||||
if interpolator is None:
|
||||
with _interpolators_lock:
|
||||
interpolator = _interpolators.get(backend)
|
||||
if interpolator is None:
|
||||
interpolator = GeneticLoadInterpolator(backend)
|
||||
_interpolators[backend] = interpolator
|
||||
return interpolator
|
||||
@@ -0,0 +1,77 @@
|
||||
"""GENETIC behind the optimizer interface (ADR 0006)."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Optional
|
||||
|
||||
from akkudoktoreos.core.emplan import EnergyManagementPlan
|
||||
from akkudoktoreos.optimization.genetic import geneticconvert, geneticprepare
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import GeneticRequest
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerApi, RunClock
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
|
||||
|
||||
class GeneticOptimizer:
|
||||
"""The GENETIC optimizer."""
|
||||
|
||||
name = "GENETIC"
|
||||
|
||||
def run_clock(self) -> RunClock:
|
||||
"""See ``Optimizer.run_clock()``."""
|
||||
return geneticprepare.run_clock()
|
||||
|
||||
async def prepare(
|
||||
self,
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[GeneticResult],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> GeneticParameters:
|
||||
"""See ``Optimizer.prepare()``."""
|
||||
return await geneticprepare.prepare(
|
||||
start_datetime, observation_datetime, warm_start, overrides
|
||||
)
|
||||
|
||||
async def prepare_from_request(
|
||||
self,
|
||||
request: GeneticRequest,
|
||||
start_datetime: DateTime,
|
||||
observation_datetime: DateTime,
|
||||
warm_start: Optional[GeneticResult],
|
||||
overrides: Optional[Mapping[str, Any]] = None,
|
||||
) -> GeneticParameters:
|
||||
"""See ``Optimizer.prepare_from_request()``."""
|
||||
return await geneticprepare.prepare_from_request(
|
||||
request, start_datetime, observation_datetime, warm_start, overrides
|
||||
)
|
||||
|
||||
def run(self, parameters: GeneticParameters) -> GeneticResult:
|
||||
"""See ``Optimizer.run()``."""
|
||||
# Imported on first use: the simulation is only needed for a run.
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
|
||||
optimization = GeneticOptimization(parameters.settings)
|
||||
return optimization.optimize_ems(
|
||||
start_hour=parameters.start_hour,
|
||||
parameters=parameters.request,
|
||||
ngen=parameters.settings.generations,
|
||||
individuals=parameters.settings.individuals,
|
||||
start_solution_datetime=parameters.start_solution_datetime,
|
||||
)
|
||||
|
||||
def api(self) -> OptimizerApi:
|
||||
"""See ``Optimizer.api()``."""
|
||||
# Imported on first use: the router is only needed by the server.
|
||||
from akkudoktoreos.optimization.genetic import geneticapi
|
||||
|
||||
return geneticapi.api()
|
||||
|
||||
async def convert(
|
||||
self, parameters: GeneticParameters, result: GeneticResult
|
||||
) -> tuple[OptimizationSolution, EnergyManagementPlan]:
|
||||
"""See ``Optimizer.convert()``."""
|
||||
return await geneticconvert.convert(parameters, result)
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Optimization parameters of GENETIC: the complete input of one run (ADR 0003, 0006, 0009).
|
||||
|
||||
A run reads nothing but these parameters: the run settings and the forecast and device
|
||||
parameters. They are prepared once before the run by ``geneticprepare``.
|
||||
|
||||
The simulation reads the forecast and device dataclasses, which the request
|
||||
(``GeneticOptimizationParameters``) derives. The request itself is kept for the conversion, the
|
||||
visualization and the public responses.
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import TerminalValueMode
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticRunSettings:
|
||||
"""Algorithm settings and run clock of one run, resolved from configuration and overrides.
|
||||
|
||||
Attributes:
|
||||
interval_sec: Length of one optimization slot in seconds (900 or 3600).
|
||||
horizon_hours: Control horizon in hours.
|
||||
tail_horizon_hours: Requested forecast tail beyond the control horizon in hours.
|
||||
prediction_hours: Forecast budget 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``).
|
||||
workers: Number of evaluation processes; ``None`` chooses automatically.
|
||||
pin_workers: Pin the evaluation processes to fixed CPU cores.
|
||||
fitness_cache_max_entries: Size limit of the fitness cache; ``None`` is unbounded.
|
||||
terminal_value_mode: How energy left at the end of the horizon is valued.
|
||||
terminal_value_window_hours: Price window of the terminal value.
|
||||
direct_marketing_enabled: Optimize DC charging and battery export for direct marketing.
|
||||
battery_charge_rates: Charge rates of the first configured battery, used when the
|
||||
request has none.
|
||||
battery_grid_export_rates: Grid export rates of the first configured battery, used when
|
||||
the request has none.
|
||||
ev_charge_rates: Charge rates of the first configured electric vehicle, used when the
|
||||
request has none.
|
||||
start_datetime: Start of the run's first slot.
|
||||
observation_datetime: Unrounded moment of the run that measurements refer to.
|
||||
timezone: Site time zone of the appliance start times; ``None`` is the local time zone.
|
||||
self_consumption_interpolator: How the inverter's self-consumption table is evaluated.
|
||||
verbose: Log the progress of the run.
|
||||
"""
|
||||
|
||||
interval_sec: int
|
||||
horizon_hours: int
|
||||
tail_horizon_hours: int
|
||||
prediction_hours: int
|
||||
individuals: Optional[int]
|
||||
generations: Optional[int]
|
||||
seed: Optional[int]
|
||||
penalties: Mapping[str, Union[float, int, str]]
|
||||
workers: Optional[int]
|
||||
pin_workers: bool
|
||||
fitness_cache_max_entries: Optional[int]
|
||||
terminal_value_mode: TerminalValueMode
|
||||
terminal_value_window_hours: int
|
||||
direct_marketing_enabled: bool
|
||||
battery_charge_rates: Optional[tuple[float, ...]]
|
||||
battery_grid_export_rates: Optional[tuple[float, ...]]
|
||||
ev_charge_rates: Optional[tuple[float, ...]]
|
||||
start_datetime: DateTime
|
||||
observation_datetime: DateTime
|
||||
timezone: Optional[str]
|
||||
self_consumption_interpolator: GridInterpolatorBackend
|
||||
verbose: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticParameters:
|
||||
"""Everything a GENETIC run needs.
|
||||
|
||||
Attributes:
|
||||
request: Forecast and device parameters of the run, including the warm start.
|
||||
start_hour: Hour of the day the run starts at.
|
||||
settings: Algorithm settings and run clock of the run.
|
||||
start_solution_datetime: Start of slot 0 of the start solution of ``request``. It is the
|
||||
request's own one, or that of the previous run when the request echoes the previous
|
||||
run's genome without it; the request stays as the client sent it.
|
||||
"""
|
||||
|
||||
request: GeneticOptimizationParameters
|
||||
start_hour: int
|
||||
settings: GeneticRunSettings
|
||||
start_solution_datetime: Optional[DateTime] = None
|
||||
|
||||
|
||||
def parameters_to_dict(parameters: GeneticParameters) -> dict[str, Any]:
|
||||
"""Serialize the parameters into plain JSON values, e.g. for a replay file.
|
||||
|
||||
NaN in the forecast series (a gap the preparation keeps) becomes ``None``; the series
|
||||
carry no other ``None``.
|
||||
|
||||
Args:
|
||||
parameters: The parameters to serialize.
|
||||
|
||||
Returns:
|
||||
A dictionary that ``parameters_from_dict()`` turns back into equal parameters.
|
||||
"""
|
||||
settings = parameters.settings
|
||||
request = parameters.request.model_dump(mode="json")
|
||||
for key, values in request["ems"].items():
|
||||
if isinstance(values, list):
|
||||
request["ems"][key] = [None if math.isnan(value) else value for value in values]
|
||||
return {
|
||||
"request": request,
|
||||
"start_hour": parameters.start_hour,
|
||||
"settings": {
|
||||
"interval_sec": settings.interval_sec,
|
||||
"horizon_hours": settings.horizon_hours,
|
||||
"tail_horizon_hours": settings.tail_horizon_hours,
|
||||
"prediction_hours": settings.prediction_hours,
|
||||
"individuals": settings.individuals,
|
||||
"generations": settings.generations,
|
||||
"seed": settings.seed,
|
||||
"penalties": dict(settings.penalties),
|
||||
"workers": settings.workers,
|
||||
"pin_workers": settings.pin_workers,
|
||||
"fitness_cache_max_entries": settings.fitness_cache_max_entries,
|
||||
"terminal_value_mode": settings.terminal_value_mode.value,
|
||||
"terminal_value_window_hours": settings.terminal_value_window_hours,
|
||||
"direct_marketing_enabled": settings.direct_marketing_enabled,
|
||||
"battery_charge_rates": _list_or_none(settings.battery_charge_rates),
|
||||
"battery_grid_export_rates": _list_or_none(settings.battery_grid_export_rates),
|
||||
"ev_charge_rates": _list_or_none(settings.ev_charge_rates),
|
||||
"start_datetime": _datetime_to_dict(settings.start_datetime),
|
||||
"observation_datetime": _datetime_to_dict(settings.observation_datetime),
|
||||
"timezone": settings.timezone,
|
||||
"self_consumption_interpolator": settings.self_consumption_interpolator.value,
|
||||
"verbose": settings.verbose,
|
||||
},
|
||||
"start_solution_datetime": (
|
||||
None
|
||||
if parameters.start_solution_datetime is None
|
||||
else _datetime_to_dict(parameters.start_solution_datetime)
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def parameters_from_dict(data: Mapping[str, Any]) -> GeneticParameters:
|
||||
"""Deserialize parameters written by ``parameters_to_dict()``.
|
||||
|
||||
Args:
|
||||
data: The serialized parameters.
|
||||
|
||||
Returns:
|
||||
The parameters.
|
||||
"""
|
||||
settings = data["settings"]
|
||||
request = dict(data["request"])
|
||||
request["ems"] = dict(request["ems"])
|
||||
for key, values in request["ems"].items():
|
||||
if isinstance(values, list):
|
||||
request["ems"][key] = [math.nan if value is None else value for value in values]
|
||||
return GeneticParameters(
|
||||
request=GeneticOptimizationParameters.model_validate(request),
|
||||
start_hour=data["start_hour"],
|
||||
settings=GeneticRunSettings(
|
||||
interval_sec=settings["interval_sec"],
|
||||
horizon_hours=settings["horizon_hours"],
|
||||
tail_horizon_hours=settings["tail_horizon_hours"],
|
||||
prediction_hours=settings["prediction_hours"],
|
||||
individuals=settings["individuals"],
|
||||
generations=settings["generations"],
|
||||
seed=settings["seed"],
|
||||
penalties=dict(settings["penalties"]),
|
||||
workers=settings["workers"],
|
||||
pin_workers=settings["pin_workers"],
|
||||
fitness_cache_max_entries=settings["fitness_cache_max_entries"],
|
||||
terminal_value_mode=TerminalValueMode(settings["terminal_value_mode"]),
|
||||
terminal_value_window_hours=settings["terminal_value_window_hours"],
|
||||
direct_marketing_enabled=settings["direct_marketing_enabled"],
|
||||
battery_charge_rates=_tuple_or_none(settings["battery_charge_rates"]),
|
||||
battery_grid_export_rates=_tuple_or_none(settings["battery_grid_export_rates"]),
|
||||
ev_charge_rates=_tuple_or_none(settings["ev_charge_rates"]),
|
||||
start_datetime=_datetime_from_dict(settings["start_datetime"]),
|
||||
observation_datetime=_datetime_from_dict(settings["observation_datetime"]),
|
||||
timezone=settings["timezone"],
|
||||
self_consumption_interpolator=GridInterpolatorBackend(
|
||||
settings["self_consumption_interpolator"]
|
||||
),
|
||||
verbose=settings["verbose"],
|
||||
),
|
||||
start_solution_datetime=(
|
||||
None
|
||||
if data["start_solution_datetime"] is None
|
||||
else _datetime_from_dict(data["start_solution_datetime"])
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _datetime_to_dict(value: DateTime) -> dict[str, Optional[str]]:
|
||||
# The offset alone would lose daylight saving time; keep the named zone as well.
|
||||
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"])
|
||||
|
||||
|
||||
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)
|
||||
@@ -1,303 +0,0 @@
|
||||
"""GENETIC 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.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
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,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
ElectricVehicleParameters,
|
||||
SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
|
||||
from akkudoktoreos.devices.genetic.inverter import InverterParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticabc import GeneticParametersBaseModel
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
# Do not import directly from akkudoktoreos.core.coreabc
|
||||
# EnergyManagementSystemMixin - Creates circular dependency with ems.py
|
||||
# StartMixin - Creates circular dependency with ems.py
|
||||
|
||||
|
||||
class GeneticEnergyManagementParameters(GeneticParametersBaseModel):
|
||||
"""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 energy in watt-hours per slot 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 watt-hours per slot 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_forecast_arrays(self) -> Self:
|
||||
"""Require forecasts; the optimizer validates control coverage and clips the tail."""
|
||||
arrays = [self.pv_forecast_wh, self.electricity_price_per_wh, self.total_load]
|
||||
if isinstance(self.feed_in_tariff_per_wh, list):
|
||||
arrays.append(self.feed_in_tariff_per_wh)
|
||||
if any(not values for values in arrays):
|
||||
raise ValueError("Forecast arrays must not be empty.")
|
||||
return self
|
||||
|
||||
|
||||
class GeneticOptimizationParameters(
|
||||
ConfigMixin,
|
||||
MeasurementMixin,
|
||||
PredictionMixin,
|
||||
# EnergyManagementSystemMixin, # Creates circular dependency with ems.py
|
||||
# StartMixin, # Creates circular dependency with ems.py
|
||||
GeneticParametersBaseModel,
|
||||
):
|
||||
"""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: GeneticEnergyManagementParameters
|
||||
pv_battery: Optional[SolarPanelBatteryParameters] = Field(
|
||||
validation_alias=AliasChoices("pv_battery", "pv_akku"),
|
||||
json_schema_extra={"description": "PV battery parameters."},
|
||||
)
|
||||
inverter: Optional[InverterParameters]
|
||||
ev: Optional[ElectricVehicleParameters] = Field(
|
||||
validation_alias=AliasChoices("ev", "eauto"),
|
||||
json_schema_extra={"description": "Electric vehicle parameters."},
|
||||
)
|
||||
dishwasher: Optional[HomeApplianceParameters] = 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)."
|
||||
},
|
||||
)
|
||||
|
||||
forecast_interval_seconds: Optional[int] = Field(
|
||||
default=None,
|
||||
description="Input interval: 3600 for hourly, or optimization interval for native slots.",
|
||||
)
|
||||
|
||||
home_appliances: Optional[list[HomeApplianceParameters]] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "List of flexible consumers (home appliances) to schedule."
|
||||
},
|
||||
)
|
||||
|
||||
start_solution_datetime: Optional[DateTime] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Start of the slot that gene 0 of 'start_solution' controls, as "
|
||||
"returned with the previous solution. The warm start is shifted by "
|
||||
"the slots that have elapsed until this run. Without it, a "
|
||||
"'start_solution' identical to the last solution of this server "
|
||||
"uses that solution's start; any other one is used unshifted."
|
||||
),
|
||||
"examples": [None, "2026-09-14T07:45:00+02:00"],
|
||||
},
|
||||
)
|
||||
|
||||
@field_validator("forecast_interval_seconds")
|
||||
@classmethod
|
||||
def validate_forecast_interval(cls, value: Optional[int]) -> Optional[int]:
|
||||
if value not in (None, 900, 3600):
|
||||
raise ValueError("forecast_interval_seconds must be 900 or 3600")
|
||||
return value
|
||||
|
||||
@field_validator("start_solution_datetime", mode="before")
|
||||
@classmethod
|
||||
def transform_start_solution_datetime(cls, value: Any) -> Optional[DateTime]:
|
||||
"""Accept the usual date time representations, naive input is local time."""
|
||||
if value is None:
|
||||
return None
|
||||
# A stored run must retain its timezone/fold even when the server host
|
||||
# uses another local timezone. ISO offsets survive JSON round trips.
|
||||
aware = value
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
aware = datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
pass
|
||||
if isinstance(aware, datetime) and aware.tzinfo is not None:
|
||||
return DateTime.instance(aware)
|
||||
return to_datetime(value)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_home_appliances(self) -> Self:
|
||||
"""Reject conflicting home appliance definitions.
|
||||
|
||||
The deprecated ``dishwasher`` field and the new ``home_appliances`` list
|
||||
must not be set at the same time; nothing is silently overwritten.
|
||||
Device ids within ``home_appliances`` must be unique.
|
||||
"""
|
||||
# Read the deprecated field via __dict__ to avoid emitting a deprecation
|
||||
# warning on every internal validation.
|
||||
dishwasher = self.__dict__.get("dishwasher")
|
||||
if dishwasher is not None and self.home_appliances is not None:
|
||||
raise ValueError(
|
||||
"Provide either 'home_appliances' or the deprecated 'dishwasher', not both."
|
||||
)
|
||||
appliances = self.home_appliances or []
|
||||
device_ids = [appliance.device_id for appliance in appliances]
|
||||
if len(device_ids) != len(set(device_ids)):
|
||||
raise ValueError("home_appliances device_id values must be unique.")
|
||||
return self
|
||||
|
||||
def resolved_home_appliances(self) -> list[HomeApplianceParameters]:
|
||||
"""Return the effective home appliance list.
|
||||
|
||||
Maps the deprecated single ``dishwasher`` onto a one-element list so the
|
||||
optimizer only ever deals with the list form.
|
||||
"""
|
||||
if self.home_appliances is not None:
|
||||
return list(self.home_appliances)
|
||||
dishwasher = self.__dict__.get("dishwasher")
|
||||
if dishwasher is not None:
|
||||
return [dishwasher]
|
||||
return []
|
||||
|
||||
# Computed fields for backward compatibility (deprecated German names)
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def pv_akku(self) -> Optional[SolarPanelBatteryParameters]:
|
||||
"""Deprecated: Use pv_battery instead."""
|
||||
return self.pv_battery
|
||||
|
||||
@computed_field(json_schema_extra={"deprecated": True})
|
||||
def eauto(self) -> Optional[ElectricVehicleParameters]:
|
||||
"""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 prepare(cls) -> "Optional[GeneticOptimizationParameters]":
|
||||
"""Resolve configured devices and fresh forecasts for automatic optimization.
|
||||
|
||||
Missing inputs cancel the run without changing providers or inventing devices.
|
||||
The same resolver serves the configuration-owned HTTP request.
|
||||
"""
|
||||
from akkudoktoreos.optimization.genetic.configrequest import (
|
||||
ConfigOptimizationRequest,
|
||||
)
|
||||
|
||||
try:
|
||||
return await ConfigOptimizationRequest().resolve()
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"Cannot prepare GENETIC parameters; canceling optimization with provider {}: {}",
|
||||
cls.config.feedintariff.provider,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,245 @@
|
||||
"""Optimization result of GENETIC: the output of one run (ADR 0006, 0009, 0010).
|
||||
|
||||
Plain frozen dataclasses. Their values are normalised as the public response models validate them
|
||||
(``geneticapi``): NumPy arrays become lists, NaN in NumPy arrays becomes ``None`` and values get the
|
||||
field's number type, so that the conversion, the visualization and a response built from a result
|
||||
see the same values as before the result became a dataclass (ADR 0008).
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticterminalvalue import TerminalValueResult
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
from akkudoktoreos.utils.utils import NumpyEncoder
|
||||
|
||||
# Keys of the simulation output (German and current) 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",
|
||||
"Feed_in_tariff": "feed_in_tariff",
|
||||
"home_appliance_energy_wh": "home_appliance_energy_wh",
|
||||
"home_appliance_running": "home_appliance_running",
|
||||
}
|
||||
|
||||
|
||||
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 GeneticSimulationOutput:
|
||||
"""Values of the simulated best solution, per slot from the run start, and totals.
|
||||
|
||||
Attributes:
|
||||
home_appliance_energy_wh: Energy of each home appliance per slot [Wh], by device id.
|
||||
feed_in_tariff: Feed-in tariff per slot.
|
||||
home_appliance_running: Active run occupancy of each home appliance per slot, including
|
||||
zero-power phases, by device id.
|
||||
"""
|
||||
|
||||
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]
|
||||
home_appliance_energy_wh: dict[str, list[float]] = field(default_factory=dict)
|
||||
feed_in_tariff: list[float] = field(default_factory=list)
|
||||
home_appliance_running: dict[str, list[bool]] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def from_simulation(cls, output: Mapping[str, Any]) -> "GeneticSimulationOutput":
|
||||
"""Build the output from the simulation's dictionary (German keys).
|
||||
|
||||
Args:
|
||||
output: The dictionary ``GeneticSimulation.simulate()`` returns, with the home
|
||||
appliance energy and occupancy added.
|
||||
|
||||
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)
|
||||
elif key == "home_appliance_energy_wh":
|
||||
fields[key] = {device_id: float_list(energy) for device_id, energy in value.items()}
|
||||
elif key == "home_appliance_running":
|
||||
fields[key] = {device_id: list(running) for device_id, running in value.items()}
|
||||
else:
|
||||
fields[key] = float_list(value)
|
||||
return cls(**fields)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeneticElectricVehicleState:
|
||||
"""The electric vehicle at the end of the simulated best solution.
|
||||
|
||||
Attributes:
|
||||
device_id: ID of the electric vehicle.
|
||||
hours: Number of slots of the simulation.
|
||||
charge_array: Charging factor per slot.
|
||||
discharge_array: 1 where discharging is allowed, per slot.
|
||||
discharging_efficiency: Discharging efficiency (0 to 1).
|
||||
capacity_wh: Battery capacity [Wh].
|
||||
charging_efficiency: Charging efficiency (0 to 1).
|
||||
max_charge_power_w: Maximum charging power [W].
|
||||
max_discharge_power_w: Maximum discharging power [W], if limited.
|
||||
soc_wh: State of charge at the end of the simulation [Wh].
|
||||
initial_soc_percentage: State of charge at the start [%].
|
||||
"""
|
||||
|
||||
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
|
||||
max_discharge_power_w: Optional[float]
|
||||
soc_wh: float
|
||||
initial_soc_percentage: int
|
||||
|
||||
@classmethod
|
||||
def from_battery(cls, state: Mapping[str, Any]) -> "GeneticElectricVehicleState":
|
||||
"""Build the state from ``GeneticBattery.to_dict()``.
|
||||
|
||||
Args:
|
||||
state: The battery's dictionary.
|
||||
|
||||
Returns:
|
||||
The normalised electric vehicle state.
|
||||
"""
|
||||
max_discharge_power_w = state.get("max_discharge_power_w")
|
||||
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"]),
|
||||
max_discharge_power_w=(
|
||||
None if max_discharge_power_w is None else _float(max_discharge_power_w)
|
||||
),
|
||||
soc_wh=_float(state["soc_wh"]),
|
||||
initial_soc_percentage=_int(state["initial_soc_percentage"]),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class GeneticResult:
|
||||
"""Output of one GENETIC run.
|
||||
|
||||
The control arrays and per-slot values start at the run start (``controls_start_at_now``).
|
||||
|
||||
Attributes:
|
||||
request: The request the run optimized, after its adaptation to the configuration and
|
||||
the slot grid; the response echoes it as ``parameters``.
|
||||
ac_charge: AC charging factor per slot.
|
||||
dc_charge: DC charging factor per slot.
|
||||
discharge_allowed: 1 where discharging is allowed, per slot.
|
||||
ev_charge_hours_float: EV charging factor per slot, 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: Deprecated start hour of a single hourly home appliance, if any.
|
||||
extra_data: Extra data of the run.
|
||||
fitness_history: Fitness per generation.
|
||||
fixed_seed: Seed of the run.
|
||||
controls_start_at_now: The control arrays start at the run timestamp, not midnight.
|
||||
battery_grid_export_allowed: 1 where battery export to the grid is allowed, per slot.
|
||||
terminal_value: What the run credited for the energy left in the battery.
|
||||
battery_grid_export_factor: Battery grid export factor per slot.
|
||||
start_solution_datetime: Start of slot 0 of ``start_solution``.
|
||||
appliance_starts: Planned run starts of each home appliance, by device id.
|
||||
appliance_deadline_missed: Whether a home appliance misses its deadline, by device id.
|
||||
interval_seconds: Duration of one slot [s].
|
||||
first_slot_fraction: Fraction of the first slot that is still ahead at the run start.
|
||||
"""
|
||||
|
||||
request: GeneticOptimizationParameters
|
||||
ac_charge: list[float]
|
||||
dc_charge: list[float]
|
||||
discharge_allowed: list[int]
|
||||
ev_charge_hours_float: Optional[list[float]]
|
||||
result: GeneticSimulationOutput
|
||||
ev_obj: Optional[GeneticElectricVehicleState]
|
||||
start_hour: int = 0
|
||||
start_solution: Optional[list[float]] = None
|
||||
washingstart: Optional[int] = None
|
||||
extra_data: Optional[dict[str, Union[list[int], list[float]]]] = None
|
||||
fitness_history: Optional[dict[str, Any]] = None
|
||||
fixed_seed: Optional[int] = None
|
||||
controls_start_at_now: bool = False
|
||||
battery_grid_export_allowed: list[int] = field(default_factory=list)
|
||||
terminal_value: Optional[TerminalValueResult] = None
|
||||
battery_grid_export_factor: list[float] = field(default_factory=list)
|
||||
start_solution_datetime: Optional[DateTime] = None
|
||||
appliance_starts: dict[str, list[DateTime]] = field(default_factory=dict)
|
||||
appliance_deadline_missed: dict[str, bool] = field(default_factory=dict)
|
||||
interval_seconds: int = 3600
|
||||
first_slot_fraction: float = 1.0
|
||||
@@ -61,7 +61,7 @@ class TerminalValueMode(StrEnum):
|
||||
FIXED = "FIXED"
|
||||
|
||||
|
||||
class GeneticCommonSettings(SettingsBaseModel):
|
||||
class GeneticSettings(SettingsBaseModel):
|
||||
"""GENETIC Optimization Algorithm Configuration."""
|
||||
|
||||
interval_sec: Literal[900, 3600] = Field(
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
"""Simulation of GENETIC: the energy flows of one genome over the slots of a run."""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
import numpy as np
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import GeneticBattery
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import GeneticInverter
|
||||
from akkudoktoreos.optimization.genetic.geneticenergymanagement import (
|
||||
GeneticEnergyManagementParameters,
|
||||
)
|
||||
|
||||
|
||||
def _slot_values(values: Any) -> Any:
|
||||
"""Return per-slot values as plain Python numbers for the simulation loop.
|
||||
|
||||
Reading single elements of a NumPy array yields NumPy scalars, whose
|
||||
arithmetic is several times slower than that of Python numbers. The values
|
||||
are the same IEEE doubles (or integers), so the results do not change.
|
||||
Other element types are left as they are.
|
||||
"""
|
||||
if isinstance(values, np.ndarray) and (values.dtype == np.float64 or values.dtype.kind in "iu"):
|
||||
return values.tolist()
|
||||
return values
|
||||
|
||||
|
||||
class GeneticSimulation:
|
||||
"""Device simulation for GENETIC optimization algorithm.
|
||||
|
||||
``prepare()`` sets the forecasts, prices and devices of a run; ``simulate()`` evaluates one
|
||||
candidate plan.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Create an empty simulation; ``prepare()`` fills it."""
|
||||
# Starting slot of the latest simulate() call.
|
||||
self.start_hour: int = 0
|
||||
self.optimization_hours: Optional[int] = 24
|
||||
self.prediction_hours: Optional[int] = 48
|
||||
# Per-slot forecasts and prices [Wh, currency/Wh].
|
||||
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
|
||||
# Use direct marketing behavior for feed-in/export decisions.
|
||||
self.direct_marketing_enabled: bool = False
|
||||
self.battery: Optional[GeneticBattery] = None
|
||||
self.ev: Optional[GeneticBattery] = None
|
||||
# Flexible consumers scheduled by the optimizer.
|
||||
self.home_appliances: list[GeneticHomeAppliance] = []
|
||||
self.inverter: Optional[GeneticInverter] = None
|
||||
# Per-slot actions of the candidate plan.
|
||||
self.ac_charge_hours: Optional[np.ndarray] = None
|
||||
self.dc_charge_hours: Optional[np.ndarray] = None
|
||||
self.bat_discharge_hours: Optional[np.ndarray] = None
|
||||
# Per-slot permission for battery discharge into the grid.
|
||||
self.bat_grid_export_hours: Optional[np.ndarray] = None
|
||||
self.ev_charge_hours: Optional[np.ndarray] = None
|
||||
self.ev_discharge_hours: Optional[np.ndarray] = None
|
||||
|
||||
@property
|
||||
def home_appliance(self) -> Optional[GeneticHomeAppliance]:
|
||||
"""Deprecated singular device accessor."""
|
||||
return self.home_appliances[0] if self.home_appliances else None
|
||||
|
||||
@home_appliance.setter
|
||||
def home_appliance(self, appliance: Optional[GeneticHomeAppliance]) -> None:
|
||||
self.home_appliances = [appliance] if appliance is not None else []
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
parameters: GeneticEnergyManagementParameters,
|
||||
optimization_hours: int,
|
||||
prediction_hours: int,
|
||||
ev: Optional[GeneticBattery] = None,
|
||||
home_appliance: Optional[GeneticHomeAppliance] = None,
|
||||
inverter: Optional[GeneticInverter] = None,
|
||||
direct_marketing_enabled: bool = False,
|
||||
home_appliances: Optional[list[GeneticHomeAppliance]] = None,
|
||||
) -> None:
|
||||
"""Prepare simulation runs.
|
||||
|
||||
Populate internal arrays and device references used during simulation.
|
||||
"""
|
||||
self.optimization_hours = optimization_hours
|
||||
self.prediction_hours = prediction_hours
|
||||
self.direct_marketing_enabled = direct_marketing_enabled
|
||||
|
||||
# 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.array(parameters.feed_in_tariff_per_wh, float)
|
||||
if isinstance(parameters.feed_in_tariff_per_wh, (list, 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
|
||||
if home_appliance is not None and home_appliances is not None:
|
||||
raise ValueError("Use home_appliance or home_appliances, not both.")
|
||||
self.home_appliances = home_appliances or (
|
||||
[home_appliance] if home_appliance is not None else []
|
||||
)
|
||||
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.bat_grid_export_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)
|
||||
|
||||
def reset(self) -> None:
|
||||
if self.ev:
|
||||
self.ev.reset()
|
||||
if self.battery:
|
||||
self.battery.reset()
|
||||
|
||||
def simulate(self, start_hour: int) -> dict[str, Any]:
|
||||
"""Simulate energy usage and costs for the given start hour.
|
||||
|
||||
akku_soc_pro_stunde begin of the hour, initial hour state!
|
||||
last_wh_pro_stunde 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
|
||||
bat_grid_export_hours_fast = self.bat_grid_export_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_appliances_fast = self.home_appliances
|
||||
inverter_fast = self.inverter
|
||||
direct_marketing_enabled_fast = self.direct_marketing_enabled
|
||||
|
||||
# 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 bat_grid_export_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("Battery Discharge Hours")
|
||||
if bat_grid_export_hours_fast is None:
|
||||
missing.append("Battery Grid Export 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 = min(
|
||||
len(load_energy_array_fast), self.prediction_hours or len(load_energy_array_fast)
|
||||
)
|
||||
total_hours = end_hour - start_hour
|
||||
if total_hours < 0:
|
||||
raise ValueError("negative dimensions are not allowed")
|
||||
|
||||
# Per-slot results are collected in plain lists (element writes into
|
||||
# NumPy arrays are slow) and turned into arrays after the loop.
|
||||
nan = float("nan")
|
||||
loads_energy_per_hour: Any = [nan] * total_hours
|
||||
feedin_energy_per_hour: Any = [nan] * total_hours
|
||||
consumption_energy_per_hour: Any = [nan] * total_hours
|
||||
costs_per_hour: Any = [nan] * total_hours
|
||||
revenue_per_hour: Any = [nan] * total_hours
|
||||
losses_wh_per_hour: Any = [nan] * total_hours
|
||||
electricity_price_per_hour: Any = [nan] * total_hours
|
||||
feed_in_tariff_per_hour: Any = [nan] * total_hours
|
||||
soc_per_hour: Any
|
||||
soc_ev_per_hour: Any
|
||||
home_appliance_wh_per_hour: Any
|
||||
|
||||
# Set initial state
|
||||
if battery_fast:
|
||||
soc_per_hour = [nan] * total_hours
|
||||
|
||||
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.
|
||||
# In place, not by rebinding: the reported plan is read back from
|
||||
# this very array, so a rebind would leave AC charge values in the
|
||||
# solution that the simulation never executed - and a controller
|
||||
# acting on them would grid-charge the battery unplanned.
|
||||
if not ac_charging_possible:
|
||||
ac_charge_hours_fast[:] = 0.0
|
||||
|
||||
# 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
|
||||
bat_grid_export_hours_fast[0:start_hour] = 0
|
||||
bat_grid_export_hours_fast[end_hour:] = 0
|
||||
battery_fast.discharge_array = np.where(
|
||||
(bat_discharge_hours_fast > 0)
|
||||
| (
|
||||
direct_marketing_enabled_fast
|
||||
& (bat_grid_export_hours_fast > 0)
|
||||
& (elect_revenue_per_hour_arr_fast[: len(bat_grid_export_hours_fast)] > 0.0)
|
||||
),
|
||||
1,
|
||||
0,
|
||||
)
|
||||
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:
|
||||
soc_ev_per_hour = [nan] * total_hours
|
||||
|
||||
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_appliances_fast:
|
||||
home_appliance_enabled = True
|
||||
# The aggregate appliance load (sum over all devices). Each
|
||||
# appliance already carries its own resampled load curve, built
|
||||
# from the decoded start(s) before this call.
|
||||
home_appliance_wh_per_hour = [nan] * total_hours
|
||||
appliance_loads_fast = [
|
||||
appliance.get_load_for_hour for appliance in home_appliances_fast
|
||||
]
|
||||
else:
|
||||
home_appliance_enabled = False
|
||||
# Default return if no home appliance is available
|
||||
home_appliance_wh_per_hour = np.full((total_hours), 0)
|
||||
appliance_loads_fast = []
|
||||
|
||||
# The per-slot inputs as plain numbers. They are final here: the loop
|
||||
# itself changes only the charge arrays of the devices, and those after
|
||||
# the slot value was read.
|
||||
load_energy_array_fast = _slot_values(load_energy_array_fast)
|
||||
pv_prediction_wh_fast = _slot_values(pv_prediction_wh_fast)
|
||||
elect_price_hourly_fast = _slot_values(elect_price_hourly_fast)
|
||||
elect_revenue_per_hour_arr_fast = _slot_values(elect_revenue_per_hour_arr_fast)
|
||||
bat_grid_export_hours_fast = _slot_values(bat_grid_export_hours_fast)
|
||||
ac_charge_hours_fast = _slot_values(ac_charge_hours_fast)
|
||||
ev_charge_hours_fast = _slot_values(ev_charge_hours_fast)
|
||||
if battery_fast:
|
||||
battery_lcos_per_wh_factor = battery_fast.levelized_cost_of_storage_kwh
|
||||
|
||||
# Aggregate appliance load per slot, summed once per candidate in the
|
||||
# order the loop used to add the appliances (0.0 + first + second ...).
|
||||
# Anything unusual (another appliance class, a curve that does not
|
||||
# cover the simulated slots) keeps the per-slot lookups and their
|
||||
# range check.
|
||||
appliance_load_fast: Optional[list[float]] = None
|
||||
if home_appliance_enabled and start_hour >= 0:
|
||||
appliance_load_fast = [0.0] * end_hour
|
||||
for appliance in home_appliances_fast:
|
||||
curve = getattr(appliance, "load_curve", None)
|
||||
if (
|
||||
type(appliance).get_load_for_hour is not GeneticHomeAppliance.get_load_for_hour
|
||||
or not isinstance(curve, np.ndarray)
|
||||
or curve.dtype != np.float64
|
||||
or curve.ndim != 1
|
||||
or len(curve) < end_hour
|
||||
or appliance.prediction_hours < end_hour
|
||||
):
|
||||
appliance_load_fast = None
|
||||
break
|
||||
appliance_load_fast = [
|
||||
total + load for total, load in zip(appliance_load_fast, curve.tolist())
|
||||
]
|
||||
|
||||
# State of charge in percent, read directly where the device uses the
|
||||
# plain Battery formula (two method calls per slot otherwise).
|
||||
battery_soc_direct = bool(
|
||||
battery_fast
|
||||
and type(battery_fast).current_soc_percentage is GeneticBattery.current_soc_percentage
|
||||
)
|
||||
ev_soc_direct = bool(
|
||||
ev_fast
|
||||
and type(ev_fast).current_soc_percentage is GeneticBattery.current_soc_percentage
|
||||
)
|
||||
battery_lcos_direct = False
|
||||
if battery_fast is not None and type(battery_fast) is GeneticBattery:
|
||||
battery_lcos_direct = True
|
||||
if battery_fast._curves is None:
|
||||
battery_discharged_raw_fast = battery_fast._discharged_raw_wh_per_slot
|
||||
battery_discharging_efficiency_fast = battery_fast.discharging_efficiency
|
||||
else:
|
||||
# With power dependent efficiencies the delivered energy is kept
|
||||
# per slot (see Battery.discharged_energy_wh()).
|
||||
battery_discharged_raw_fast = battery_fast._curves.discharged_dc_wh_per_slot
|
||||
battery_discharging_efficiency_fast = 1.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]
|
||||
slot_losses = 0.0
|
||||
|
||||
# Home appliances (sum the per-slot load of all flexible consumers)
|
||||
if home_appliance_enabled:
|
||||
if appliance_load_fast is not None:
|
||||
ha_load = appliance_load_fast[hour]
|
||||
else:
|
||||
ha_load = 0.0
|
||||
for appliance_load in appliance_loads_fast:
|
||||
ha_load += appliance_load(hour)
|
||||
consumption += ha_load
|
||||
home_appliance_wh_per_hour[hour_idx] = ha_load
|
||||
|
||||
# E-Auto handling
|
||||
if ev_fast:
|
||||
# save begin state
|
||||
if ev_soc_direct:
|
||||
soc_ev_per_hour[hour_idx] = (ev_fast.soc_wh / ev_fast.capacity_wh) * 100
|
||||
else:
|
||||
soc_ev_per_hour[hour_idx] = ev_fast.current_soc_percentage()
|
||||
ev_charge_factor = ev_charge_hours_fast[hour]
|
||||
if ev_charge_factor > 0:
|
||||
stored_energy_ev, verluste_eauto = ev_fast.charge_energy(
|
||||
wh=None, hour=hour, charge_factor=ev_charge_factor
|
||||
)
|
||||
# The inverter/grid must supply the EV charger's raw input,
|
||||
# not only the energy stored after charging losses.
|
||||
consumption += stored_energy_ev + verluste_eauto
|
||||
slot_losses += verluste_eauto
|
||||
|
||||
# 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:
|
||||
if battery_soc_direct:
|
||||
soc_per_hour[hour_idx] = (battery_fast.soc_wh / battery_fast.capacity_wh) * 100
|
||||
else:
|
||||
soc_per_hour[hour_idx] = battery_fast.current_soc_percentage()
|
||||
|
||||
# Process inverter logic
|
||||
energy_feedin_grid_actual = energy_consumption_grid_actual = losses = eigenverbrauch = (
|
||||
0.0
|
||||
)
|
||||
|
||||
# AC charge factor of this slot, capped by max_ac_charge_power_w
|
||||
ac_charge_factor = 0.0
|
||||
if battery_fast and ac_charging_possible:
|
||||
ac_charge_factor = ac_charge_hours_fast[hour]
|
||||
# No AC charging in this slot (the usual case): nothing to cap.
|
||||
if inverter_fast and ac_charge_factor != 0:
|
||||
ac_charge_factor = inverter_fast.ac_charge_factor(ac_charge_factor)
|
||||
|
||||
if inverter_fast:
|
||||
# Some inverters cap the total charge power with the AC setpoint;
|
||||
# that cap has to be in place before PV charges the battery.
|
||||
if ac_charge_factor > 0.0:
|
||||
inverter_fast.begin_ac_charge_slot(hour, ac_charge_factor)
|
||||
energy_produced = pv_prediction_wh_fast[hour]
|
||||
hourly_feed_in_tariff = elect_revenue_per_hour_arr_fast[hour]
|
||||
# bat_grid_export_hours carries the export level per slot:
|
||||
# 0.0 = no export, otherwise the factor of the rated discharge
|
||||
# power the optimizer selected.
|
||||
battery_grid_export_factor = float(bat_grid_export_hours_fast[hour])
|
||||
battery_grid_export_allowed = (
|
||||
direct_marketing_enabled_fast
|
||||
and hourly_feed_in_tariff > 0.0
|
||||
and battery_grid_export_factor > 0.0
|
||||
)
|
||||
(
|
||||
energy_feedin_grid_actual,
|
||||
energy_consumption_grid_actual,
|
||||
losses,
|
||||
eigenverbrauch,
|
||||
) = inverter_fast.process_energy(
|
||||
energy_produced,
|
||||
consumption,
|
||||
hour,
|
||||
battery_grid_export_allowed,
|
||||
battery_grid_export_factor,
|
||||
)
|
||||
else:
|
||||
hourly_feed_in_tariff = elect_revenue_per_hour_arr_fast[hour]
|
||||
# Without an inverter the grid supplies the whole load; PV is not converted.
|
||||
energy_consumption_grid_actual = consumption
|
||||
|
||||
# AC PV Battery Charge
|
||||
if ac_charge_factor > 0.0 and battery_fast:
|
||||
if inverter_fast:
|
||||
ac_energy, ac_charge_losses = inverter_fast.charge_battery_from_grid(
|
||||
hour, ac_charge_factor
|
||||
)
|
||||
else:
|
||||
# Without an inverter the grid charges the battery losslessly
|
||||
# (AC-to-DC efficiency 1.0).
|
||||
stored, ac_charge_losses = battery_fast.charge_energy(
|
||||
None, hour, charge_factor=ac_charge_factor
|
||||
)
|
||||
ac_energy = stored + ac_charge_losses
|
||||
consumption += ac_energy
|
||||
energy_consumption_grid_actual += ac_energy
|
||||
slot_losses += ac_charge_losses
|
||||
|
||||
# Update hourly arrays
|
||||
if (
|
||||
direct_marketing_enabled_fast
|
||||
and hourly_feed_in_tariff < 0.0
|
||||
and energy_feedin_grid_actual > 0.0
|
||||
):
|
||||
slot_losses += energy_feedin_grid_actual
|
||||
energy_feedin_grid_actual = 0.0
|
||||
|
||||
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] = slot_losses + 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
|
||||
feed_in_tariff_per_hour[hour_idx] = hourly_feed_in_tariff
|
||||
|
||||
# Financial calculations
|
||||
grid_cost = energy_consumption_grid_actual * hourly_electricity_price
|
||||
# LCOS is charged exactly once on battery-delivered DC energy. It is
|
||||
# not charged on input energy, internal discharge losses, or the
|
||||
# downstream DC-to-AC inverter loss.
|
||||
battery_lcos_cost = 0.0
|
||||
if battery_lcos_direct:
|
||||
# Battery.discharged_energy_wh(), without the call per slot.
|
||||
battery_lcos_cost = (
|
||||
battery_discharged_raw_fast[hour]
|
||||
* battery_discharging_efficiency_fast
|
||||
* battery_lcos_per_wh_factor
|
||||
/ 1000.0
|
||||
)
|
||||
elif battery_fast:
|
||||
battery_lcos_cost = (
|
||||
battery_fast.discharged_energy_wh(hour) * battery_lcos_per_wh_factor / 1000.0
|
||||
)
|
||||
costs_per_hour[hour_idx] = grid_cost + battery_lcos_cost
|
||||
revenue_per_hour[hour_idx] = energy_feedin_grid_actual * hourly_feed_in_tariff
|
||||
|
||||
loads_energy_per_hour = np.array(loads_energy_per_hour, dtype=float)
|
||||
feedin_energy_per_hour = np.array(feedin_energy_per_hour, dtype=float)
|
||||
consumption_energy_per_hour = np.array(consumption_energy_per_hour, dtype=float)
|
||||
costs_per_hour = np.array(costs_per_hour, dtype=float)
|
||||
revenue_per_hour = np.array(revenue_per_hour, dtype=float)
|
||||
losses_wh_per_hour = np.array(losses_wh_per_hour, dtype=float)
|
||||
electricity_price_per_hour = np.array(electricity_price_per_hour, dtype=float)
|
||||
feed_in_tariff_per_hour = np.array(feed_in_tariff_per_hour, dtype=float)
|
||||
if battery_fast:
|
||||
soc_per_hour = np.array(soc_per_hour, dtype=float)
|
||||
if ev_fast:
|
||||
soc_ev_per_hour = np.array(soc_ev_per_hour, dtype=float)
|
||||
if home_appliance_enabled:
|
||||
home_appliance_wh_per_hour = np.array(home_appliance_wh_per_hour, dtype=float)
|
||||
|
||||
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,
|
||||
"Feed_in_tariff": feed_in_tariff_per_hour,
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+45
-28
@@ -5,12 +5,15 @@ Tail actions never enter the executable control arrays. The selected path may
|
||||
be returned separately as diagnostics so users can inspect the lookahead.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from pydantic import PrivateAttr
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from akkudoktoreos.devices.genetic.battery import Battery
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter
|
||||
from akkudoktoreos.optimization.genetic.terminalvalue import (
|
||||
import numpy as np
|
||||
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import GeneticBattery
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import GeneticInverter
|
||||
from akkudoktoreos.optimization.genetic.geneticterminalvalue import (
|
||||
TailPlanSlot,
|
||||
TerminalValueCurve,
|
||||
)
|
||||
@@ -35,8 +38,8 @@ def _action_name(action: TailAction) -> str:
|
||||
|
||||
def _simulate_action(
|
||||
*,
|
||||
bat: Battery,
|
||||
inv: Inverter,
|
||||
bat: GeneticBattery,
|
||||
inv: GeneticInverter,
|
||||
energy_wh: float,
|
||||
action: TailAction,
|
||||
price: float,
|
||||
@@ -93,14 +96,19 @@ def _simulate_action(
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TailValueCurve(TerminalValueCurve):
|
||||
"""Value of usable AC battery energy, including the value of empty capacity.
|
||||
|
||||
Neither values nor marginal values are constrained to be monotone. The empty
|
||||
state can earn money by charging at negative prices and selling later.
|
||||
|
||||
Attributes:
|
||||
trace_context: What ``diagnostic_plan()`` needs to replay the optimal tail path; not
|
||||
part of the curve's value.
|
||||
"""
|
||||
|
||||
_trace_context: dict = PrivateAttr(default_factory=dict)
|
||||
trace_context: Mapping[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
||||
|
||||
def value(self, energy_wh: float) -> float:
|
||||
return (
|
||||
@@ -117,18 +125,19 @@ class TailValueCurve(TerminalValueCurve):
|
||||
|
||||
def diagnostic_plan(self, energy_wh: float, control_horizon_hours: float) -> list[TailPlanSlot]:
|
||||
"""Replay the optimal tail path for one control-end battery state."""
|
||||
context = self._trace_context
|
||||
context = self.trace_context
|
||||
if not context:
|
||||
return []
|
||||
bat = Battery(
|
||||
bat = GeneticBattery(
|
||||
context["battery_parameters"],
|
||||
prediction_hours=1,
|
||||
slot_duration_h=context["slot_duration_h"],
|
||||
)
|
||||
inv = Inverter(
|
||||
inv = GeneticInverter(
|
||||
context["inverter_parameters"],
|
||||
battery=bat,
|
||||
slot_duration_h=context["slot_duration_h"],
|
||||
self_consumption_backend=context["self_consumption_backend"],
|
||||
)
|
||||
conversion = bat.discharging_efficiency * inv.reference_dc_to_ac_efficiency
|
||||
state_wh = bat.min_soc_wh + (energy_wh / conversion if conversion > 0 else 0.0)
|
||||
@@ -205,8 +214,8 @@ class TailValueCurve(TerminalValueCurve):
|
||||
|
||||
def build_tail_value_curve(
|
||||
*,
|
||||
battery: Battery,
|
||||
inverter: Inverter,
|
||||
battery: GeneticBattery,
|
||||
inverter: GeneticInverter,
|
||||
prices_euro_per_wh: np.ndarray,
|
||||
load_wh: np.ndarray,
|
||||
pv_wh: np.ndarray,
|
||||
@@ -229,9 +238,16 @@ def build_tail_value_curve(
|
||||
]
|
||||
if len({len(a) for a in arrays}) != 1 or any(not np.isfinite(a).all() for a in arrays):
|
||||
raise ValueError("Tail forecasts must have equal lengths and contain only finite values")
|
||||
bat = Battery(battery.parameters, prediction_hours=1, slot_duration_h=battery.slot_duration_h)
|
||||
bat = GeneticBattery(
|
||||
battery.parameters, prediction_hours=1, slot_duration_h=battery.slot_duration_h
|
||||
)
|
||||
bat.charge_array = np.zeros(1, dtype=float)
|
||||
inv = Inverter(inverter.parameters, battery=bat, slot_duration_h=battery.slot_duration_h)
|
||||
inv = GeneticInverter(
|
||||
inverter.parameters,
|
||||
battery=bat,
|
||||
slot_duration_h=battery.slot_duration_h,
|
||||
self_consumption_backend=inverter.self_consumption_backend,
|
||||
)
|
||||
states = np.linspace(bat.min_soc_wh, bat.max_soc_wh, grid_points)
|
||||
usable = (
|
||||
(states - bat.min_soc_wh) * bat.discharging_efficiency * inv.reference_dc_to_ac_efficiency
|
||||
@@ -289,18 +305,19 @@ def build_tail_value_curve(
|
||||
continuation_value_euro=continuation_values.tolist(),
|
||||
marginal_euro_per_kwh=(np.diff(values) / np.maximum(np.diff(usable), 1e-9) * 1000).tolist(),
|
||||
window_slots=len(arrays[0]),
|
||||
trace_context={
|
||||
"battery_parameters": battery.parameters,
|
||||
"inverter_parameters": inverter.parameters,
|
||||
"self_consumption_backend": inverter.self_consumption_backend,
|
||||
"slot_duration_h": battery.slot_duration_h,
|
||||
"states": states,
|
||||
"future_values": future_values,
|
||||
"actions": actions,
|
||||
"prices": arrays[0],
|
||||
"load": arrays[1],
|
||||
"pv": arrays[2],
|
||||
"tariffs": arrays[3],
|
||||
"direct_marketing": direct_marketing,
|
||||
},
|
||||
)
|
||||
result._trace_context = {
|
||||
"battery_parameters": battery.parameters,
|
||||
"inverter_parameters": inverter.parameters,
|
||||
"slot_duration_h": battery.slot_duration_h,
|
||||
"states": states,
|
||||
"future_values": future_values,
|
||||
"actions": actions,
|
||||
"prices": arrays[0],
|
||||
"load": arrays[1],
|
||||
"pv": arrays[2],
|
||||
"tariffs": arrays[3],
|
||||
"direct_marketing": direct_marketing,
|
||||
}
|
||||
return result
|
||||
+57
-126
@@ -23,72 +23,43 @@ aid, not a prediction - which is also why the marginal values are deliberately
|
||||
conservative wherever a choice exists.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
from loguru import logger
|
||||
from pydantic import Field
|
||||
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
|
||||
|
||||
class TerminalValueCurve(PydanticBaseModel):
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TerminalValueCurve:
|
||||
"""Piecewise linear, concave value of battery energy left at the horizon.
|
||||
|
||||
``energy_wh`` and ``value_euro`` are the breakpoints of the cumulative
|
||||
value, ``marginal_euro_per_kwh`` the slope of each segment. Both arrays
|
||||
start at the origin; the curve is flat beyond its last breakpoint.
|
||||
|
||||
Attributes:
|
||||
energy_wh: Breakpoints of usable AC energy left in the battery [Wh].
|
||||
value_euro: Cumulative credit at each breakpoint [EUR].
|
||||
operating_value_euro: Tail operating component at each breakpoint [EUR]; empty for a
|
||||
proxy curve.
|
||||
continuation_value_euro: Continuation component at each breakpoint [EUR]; empty for a
|
||||
proxy curve.
|
||||
marginal_euro_per_kwh: Marginal value of the segment that starts at each breakpoint
|
||||
[EUR/kWh]. May be negative or non-monotone in TAIL mode.
|
||||
residual_energy_wh: Energy up to which the curve is backed by residual load - the knee.
|
||||
Everything beyond it is only worth an export.
|
||||
window_slots: Number of trailing horizon slots the curve was derived from. Fewer slots
|
||||
than a full day mean a shorter proxy period.
|
||||
"""
|
||||
|
||||
energy_wh: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Breakpoints of usable AC energy left in the battery [Wh]."
|
||||
},
|
||||
)
|
||||
value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={"description": "Cumulative credit at each breakpoint [EUR]."},
|
||||
)
|
||||
operating_value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Tail operating component at each breakpoint [EUR]; empty for a proxy curve."
|
||||
},
|
||||
)
|
||||
continuation_value_euro: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": "Continuation component at each breakpoint [EUR]; empty for a proxy curve."
|
||||
},
|
||||
)
|
||||
marginal_euro_per_kwh: list[float] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Marginal value of the segment that starts at each breakpoint "
|
||||
"[EUR/kWh]. May be negative or non-monotone in TAIL mode."
|
||||
)
|
||||
},
|
||||
)
|
||||
residual_energy_wh: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Energy up to which the curve is backed by residual load - the "
|
||||
"knee. Everything beyond it is only worth an export."
|
||||
)
|
||||
},
|
||||
)
|
||||
window_slots: int = Field(
|
||||
default=0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Number of trailing horizon slots the curve was derived from. "
|
||||
"Fewer slots than a full day mean a shorter proxy period."
|
||||
)
|
||||
},
|
||||
)
|
||||
energy_wh: list[float] = field(default_factory=list)
|
||||
value_euro: list[float] = field(default_factory=list)
|
||||
operating_value_euro: list[float] = field(default_factory=list)
|
||||
continuation_value_euro: list[float] = field(default_factory=list)
|
||||
marginal_euro_per_kwh: list[float] = field(default_factory=list)
|
||||
residual_energy_wh: float = 0.0
|
||||
window_slots: int = 0
|
||||
|
||||
def value(self, energy_wh: float) -> float:
|
||||
"""Return the credit for ``energy_wh`` of usable AC energy [EUR].
|
||||
@@ -104,7 +75,8 @@ class TerminalValueCurve(PydanticBaseModel):
|
||||
return float(np.interp(energy_wh, self.energy_wh, self.value_euro))
|
||||
|
||||
|
||||
class TailDiagnostics(PydanticBaseModel):
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TailDiagnostics:
|
||||
"""Forecast summary used by the deterministic tail optimization."""
|
||||
|
||||
slots: int = 0
|
||||
@@ -118,7 +90,8 @@ class TailDiagnostics(PydanticBaseModel):
|
||||
positive_battery_export_slots: int = 0
|
||||
|
||||
|
||||
class TailPlanSlot(PydanticBaseModel):
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TailPlanSlot:
|
||||
"""One diagnostic slot of the optimal tail path.
|
||||
|
||||
These values explain the lookahead used for fitness. They are diagnostics
|
||||
@@ -148,84 +121,42 @@ class TailPlanSlot(PydanticBaseModel):
|
||||
battery_grid_export_factor: float
|
||||
|
||||
|
||||
class TerminalValueResult(PydanticBaseModel):
|
||||
"""What the optimizer credited for the energy left in the battery."""
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TerminalValueResult:
|
||||
"""What the optimizer credited for the energy left in the battery.
|
||||
|
||||
Attributes:
|
||||
mode: Terminal value mode the run used: TAIL, AUTO or FIXED.
|
||||
battery_energy_wh: Usable AC energy left in the battery at the end of the horizon [Wh].
|
||||
credited_euro: Credit applied to the total balance [EUR].
|
||||
tail_operating_euro: Optimal net cash flow within the effective tail for the selected
|
||||
control-end battery state [EUR].
|
||||
continuation_value_euro: Continuation credit remaining at the end of the optimal tail
|
||||
path [EUR].
|
||||
curve: Combined tail value curve (tail operation plus continuation) read by fitness;
|
||||
None in FIXED mode.
|
||||
continuation_curve: Conservative AUTO proxy constructed at the effective tail end.
|
||||
tail_plan: Diagnostic optimal battery path inside the tail. It explains the lookahead
|
||||
but is never an executable control plan.
|
||||
reason: Why this mode applied. Empty in AUTO mode; in FIXED mode it says whether FIXED
|
||||
was configured or whether AUTO fell back because no curve could be derived.
|
||||
"""
|
||||
|
||||
control_horizon_hours: float = 0
|
||||
requested_tail_hours: float = 0
|
||||
effective_tail_hours: float = 0
|
||||
tail_end_hour: float = 0
|
||||
continuation_mode: str = "FIXED"
|
||||
|
||||
mode: str = Field(
|
||||
json_schema_extra={
|
||||
"description": "Terminal value mode the run used: TAIL, AUTO or FIXED.",
|
||||
"examples": ["TAIL", "AUTO", "FIXED"],
|
||||
}
|
||||
)
|
||||
battery_energy_wh: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": "Usable AC energy left in the battery at the end of the horizon [Wh]."
|
||||
},
|
||||
)
|
||||
credited_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={"description": "Credit applied to the total balance [EUR]."},
|
||||
)
|
||||
tail_operating_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Optimal net cash flow within the effective tail for the selected "
|
||||
"control-end battery state [EUR]."
|
||||
)
|
||||
},
|
||||
)
|
||||
continuation_value_euro: float = Field(
|
||||
default=0.0,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Continuation credit remaining at the end of the optimal tail path [EUR]."
|
||||
)
|
||||
},
|
||||
)
|
||||
curve: Optional[TerminalValueCurve] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Combined tail value curve (tail operation plus continuation) read by fitness; "
|
||||
"None in FIXED mode."
|
||||
)
|
||||
},
|
||||
)
|
||||
continuation_curve: Optional[TerminalValueCurve] = Field(
|
||||
default=None,
|
||||
json_schema_extra={
|
||||
"description": "Conservative AUTO proxy constructed at the effective tail end."
|
||||
},
|
||||
)
|
||||
mode: str
|
||||
battery_energy_wh: float = 0.0
|
||||
credited_euro: float = 0.0
|
||||
tail_operating_euro: float = 0.0
|
||||
continuation_value_euro: float = 0.0
|
||||
curve: Optional[TerminalValueCurve] = None
|
||||
continuation_curve: Optional[TerminalValueCurve] = None
|
||||
tail_diagnostics: Optional[TailDiagnostics] = None
|
||||
tail_plan: list[TailPlanSlot] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Diagnostic optimal battery path inside the tail. It explains the "
|
||||
"lookahead but is never an executable control plan."
|
||||
)
|
||||
},
|
||||
)
|
||||
reason: str = Field(
|
||||
default="",
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"Why this mode applied. Empty in AUTO mode; in FIXED mode it "
|
||||
"says whether FIXED was configured or whether AUTO fell back "
|
||||
"because no curve could be derived."
|
||||
),
|
||||
"examples": ["", "terminal_value_mode is FIXED"],
|
||||
},
|
||||
)
|
||||
tail_plan: list[TailPlanSlot] = field(default_factory=list)
|
||||
reason: str = ""
|
||||
|
||||
|
||||
def build_terminal_value_curve(
|
||||
@@ -1,3 +1,4 @@
|
||||
import dataclasses
|
||||
import json
|
||||
import textwrap
|
||||
from collections.abc import Sequence
|
||||
@@ -11,8 +12,8 @@ import numpy as np
|
||||
import pendulum
|
||||
from matplotlib.backends.backend_pdf import PdfPages
|
||||
|
||||
from akkudoktoreos.core.coreabc import ConfigMixin, get_ems
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
matplotlib.use(
|
||||
@@ -23,15 +24,26 @@ matplotlib.use(
|
||||
debug_visualize: bool = False
|
||||
|
||||
|
||||
class GeneticVisualizationReport(ConfigMixin):
|
||||
class GeneticVisualizationReport:
|
||||
"""PDF report of a GENETIC run: groups of charts, rendered page by page."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
version: str = "0.0.1",
|
||||
interval_seconds: int = 3600,
|
||||
timezone: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Create an empty report.
|
||||
|
||||
Args:
|
||||
version: Version shown in the report.
|
||||
interval_seconds: Length of one slot of the charts.
|
||||
timezone: Time zone of the charts' hours; ``None`` is the local time zone.
|
||||
"""
|
||||
if interval_seconds <= 0:
|
||||
raise ValueError("Report interval must be positive")
|
||||
self.interval_seconds = interval_seconds
|
||||
self.timezone = timezone
|
||||
# Initialize the report with empty groups
|
||||
self.groups: list[list[Callable[[], None]]] = [] # Store groups of charts
|
||||
self.current_group: list[
|
||||
@@ -43,9 +55,7 @@ class GeneticVisualizationReport(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."""
|
||||
@@ -184,7 +194,7 @@ class GeneticVisualizationReport(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(
|
||||
@@ -457,13 +467,26 @@ class GeneticVisualizationReport(ConfigMixin):
|
||||
|
||||
|
||||
def genetic_prepare_visualize(
|
||||
solution: GeneticSolution,
|
||||
parameters: GeneticParameters,
|
||||
result: GeneticResult,
|
||||
) -> bytes:
|
||||
"""Render the PDF report of a run.
|
||||
|
||||
Args:
|
||||
parameters: The optimization parameters of the run (run start, time zone).
|
||||
result: The result of the run.
|
||||
|
||||
Returns:
|
||||
The PDF document.
|
||||
"""
|
||||
global debug_visualize
|
||||
|
||||
report = GeneticVisualizationReport(interval_seconds=solution.interval_seconds)
|
||||
# New solutions own their timeline. The fallback supports historical hourly solutions.
|
||||
start_datetime = solution.start_solution_datetime or get_ems().start_datetime
|
||||
solution = result
|
||||
report = GeneticVisualizationReport(
|
||||
interval_seconds=solution.interval_seconds, timezone=parameters.settings.timezone
|
||||
)
|
||||
# New solutions own their timeline; the run start is the fallback.
|
||||
start_datetime = solution.start_solution_datetime or parameters.settings.start_datetime
|
||||
start_offset = 0 if solution.controls_start_at_now else solution.start_hour
|
||||
control_slots = len(solution.result.load_wh_per_hour)
|
||||
end_offset = start_offset + control_slots
|
||||
@@ -472,7 +495,7 @@ def genetic_prepare_visualize(
|
||||
report.create_line_chart_date(
|
||||
start_datetime,
|
||||
[
|
||||
solution.parameters.ems.total_load[start_offset:end_offset],
|
||||
solution.request.ems.total_load[start_offset:end_offset],
|
||||
],
|
||||
title="Load Profile",
|
||||
# xlabel="Hours", # not enough space
|
||||
@@ -482,7 +505,7 @@ def genetic_prepare_visualize(
|
||||
report.create_line_chart_date(
|
||||
start_datetime,
|
||||
[
|
||||
solution.parameters.ems.pv_forecast_wh[start_offset:end_offset],
|
||||
solution.request.ems.pv_forecast_wh[start_offset:end_offset],
|
||||
],
|
||||
title="PV Forecast",
|
||||
# xlabel="Hours", # not enough space
|
||||
@@ -492,20 +515,20 @@ def genetic_prepare_visualize(
|
||||
report.create_line_chart_date(
|
||||
start_datetime,
|
||||
[
|
||||
np.asarray(solution.parameters.ems.feed_in_tariff_per_wh[start_offset:end_offset])
|
||||
if isinstance(solution.parameters.ems.feed_in_tariff_per_wh, list)
|
||||
else np.full(control_slots, solution.parameters.ems.feed_in_tariff_per_wh)
|
||||
np.asarray(solution.request.ems.feed_in_tariff_per_wh[start_offset:end_offset])
|
||||
if isinstance(solution.request.ems.feed_in_tariff_per_wh, list)
|
||||
else np.full(control_slots, solution.request.ems.feed_in_tariff_per_wh)
|
||||
],
|
||||
title="Remuneration",
|
||||
# xlabel="Hours", # not enough space
|
||||
ylabel="amount/Wh",
|
||||
x2label=None, # not enough space
|
||||
)
|
||||
if solution.parameters.temperature_forecast:
|
||||
if solution.request.temperature_forecast:
|
||||
report.create_line_chart_date(
|
||||
start_datetime,
|
||||
[
|
||||
solution.parameters.temperature_forecast[start_offset:end_offset],
|
||||
solution.request.temperature_forecast[start_offset:end_offset],
|
||||
],
|
||||
title="Temperature Forecast",
|
||||
# xlabel="Hours", # not enough space
|
||||
@@ -554,7 +577,7 @@ def genetic_prepare_visualize(
|
||||
)
|
||||
report.create_line_chart_date(
|
||||
start_date=start_datetime, # start_date
|
||||
y_list=[solution.parameters.ems.electricity_price_per_wh[start_offset:end_offset]],
|
||||
y_list=[solution.request.ems.electricity_price_per_wh[start_offset:end_offset]],
|
||||
# title="Electricity Price", # not enough space
|
||||
# xlabel="Date", # not enough space
|
||||
ylabel="Electricity Price (amount/Wh)",
|
||||
@@ -706,7 +729,7 @@ def genetic_prepare_visualize(
|
||||
|
||||
|
||||
def _add_solution_diagnostics(
|
||||
report: GeneticVisualizationReport, solution: GeneticSolution, start: DateTime
|
||||
report: GeneticVisualizationReport, solution: GeneticResult, start: DateTime
|
||||
) -> None:
|
||||
"""Render the retained run diagnostics; tail actions are never executable controls."""
|
||||
report.add_text_page(
|
||||
@@ -761,7 +784,9 @@ def _add_solution_diagnostics(
|
||||
report.finalize_group()
|
||||
if terminal.tail_diagnostics is not None:
|
||||
report.add_json_page(
|
||||
terminal.tail_diagnostics.model_dump(), title="Tail Forecast Summary", fontsize=10
|
||||
dataclasses.asdict(terminal.tail_diagnostics),
|
||||
title="Tail Forecast Summary",
|
||||
fontsize=10,
|
||||
)
|
||||
report.finalize_group()
|
||||
curve = terminal.curve
|
||||
|
||||
@@ -14,7 +14,7 @@ from akkudoktoreos.optimization.genetic0.genetic0request import (
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0.genetic0result import Genetic0Result
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerApi
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerApi, RunClock
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
|
||||
|
||||
@@ -23,6 +23,10 @@ class Genetic0Optimizer:
|
||||
|
||||
name = "GENETIC0"
|
||||
|
||||
def run_clock(self) -> RunClock:
|
||||
"""See ``Optimizer.run_clock()``: hourly slots in the server's local time."""
|
||||
return RunClock(slot_seconds=3600)
|
||||
|
||||
async def prepare(
|
||||
self,
|
||||
start_datetime: DateTime,
|
||||
|
||||
@@ -828,7 +828,7 @@ def inverter_request(
|
||||
The inverter parameters of the request.
|
||||
|
||||
Raises:
|
||||
InverterResolutionError: See ``InverterCommonSettings.to_genetic_param``.
|
||||
InverterResolutionError: See ``InverterCommonSettings.resolve_operating_parameters``.
|
||||
"""
|
||||
p = operating_parameters or settings.resolve_operating_parameters()
|
||||
return Genetic0InverterRequest(
|
||||
|
||||
@@ -9,11 +9,11 @@ from akkudoktoreos.core.pydantic import (
|
||||
PydanticBaseModel,
|
||||
PydanticDateTimeDataFrame,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0 import Genetic0Settings
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import (
|
||||
GeneticCommonSettings,
|
||||
from akkudoktoreos.optimization.genetic import (
|
||||
GeneticSettings,
|
||||
normalize_genetic_settings,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic0 import Genetic0Settings
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime
|
||||
from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
|
||||
|
||||
@@ -51,8 +51,8 @@ class OptimizationCommonSettings(SettingsBaseModel):
|
||||
},
|
||||
)
|
||||
|
||||
genetic: GeneticCommonSettings = Field(
|
||||
default_factory=GeneticCommonSettings,
|
||||
genetic: GeneticSettings = Field(
|
||||
default_factory=GeneticSettings,
|
||||
json_schema_extra={
|
||||
"description": "GENETIC optimization algorithm configuration.",
|
||||
"examples": [{"individuals": 400, "seed": None, "penalties": {"ev_soc_miss": 10}}],
|
||||
|
||||
@@ -20,6 +20,21 @@ RequestT_contra = TypeVar("RequestT_contra", contravariant=True)
|
||||
ResultT = TypeVar("ResultT")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RunClock:
|
||||
"""The clock an optimizer's runs follow (ADR 0006).
|
||||
|
||||
Attributes:
|
||||
slot_seconds: Length of the optimizer's slots; the run start is rounded down to a slot
|
||||
boundary. 900 or 3600.
|
||||
timezone: Time zone a run without an explicit start starts in, e.g. the site's time zone
|
||||
for slots that follow the local day; ``None`` uses the server's local time.
|
||||
"""
|
||||
|
||||
slot_seconds: int
|
||||
timezone: Optional[str] = None
|
||||
|
||||
|
||||
class Optimizer(Protocol[ParametersT, RequestT_contra, ResultT]):
|
||||
"""An optimizer, driven by the energy management.
|
||||
|
||||
@@ -29,6 +44,17 @@ class Optimizer(Protocol[ParametersT, RequestT_contra, ResultT]):
|
||||
|
||||
name: str
|
||||
|
||||
def run_clock(self) -> RunClock:
|
||||
"""The slot length and time zone the energy management starts the next run in.
|
||||
|
||||
Read from the optimizer's settings by its parameter preparation, before the run start is
|
||||
fixed; never fails.
|
||||
|
||||
Returns:
|
||||
The clock of the next run.
|
||||
"""
|
||||
...
|
||||
|
||||
async def prepare(
|
||||
self,
|
||||
start_datetime: DateTime,
|
||||
|
||||
@@ -11,14 +11,21 @@ from typing import Any, Optional
|
||||
from akkudoktoreos.optimization.optimizer import Optimizer
|
||||
|
||||
|
||||
def _genetic() -> Optimizer[Any, Any, Any]:
|
||||
from akkudoktoreos.optimization.genetic import GeneticOptimizer
|
||||
|
||||
return GeneticOptimizer()
|
||||
|
||||
|
||||
def _genetic0() -> Optimizer[Any, Any, Any]:
|
||||
from akkudoktoreos.optimization.genetic0 import Genetic0Optimizer
|
||||
|
||||
return Genetic0Optimizer()
|
||||
|
||||
|
||||
# Optimizer name -> factory. GENETIC joins when it is migrated.
|
||||
# Optimizer name -> factory.
|
||||
_FACTORIES: dict[str, Callable[[], Optimizer[Any, Any, Any]]] = {
|
||||
"GENETIC": _genetic,
|
||||
"GENETIC0": _genetic0,
|
||||
}
|
||||
|
||||
@@ -48,6 +55,6 @@ def optimizer_names() -> list[str]:
|
||||
"""Names of all registered optimizers.
|
||||
|
||||
Returns:
|
||||
The names, e.g. ``["GENETIC0"]``.
|
||||
The names, e.g. ``["GENETIC", "GENETIC0"]``.
|
||||
"""
|
||||
return list(_FACTORIES)
|
||||
|
||||
+22
-107
@@ -10,7 +10,7 @@ import sys
|
||||
import traceback
|
||||
from contextlib import asynccontextmanager
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, AsyncGenerator, Dict, List, Optional, Union
|
||||
from typing import Annotated, Any, AsyncGenerator, Dict, List, NoReturn, Optional, Union
|
||||
from urllib.parse import urljoin, urlsplit
|
||||
|
||||
import psutil
|
||||
@@ -57,8 +57,6 @@ from akkudoktoreos.core.types import (
|
||||
)
|
||||
from akkudoktoreos.core.version import __version__
|
||||
from akkudoktoreos.devices.devices import ResourceKey
|
||||
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.optimization import (
|
||||
OptimizationAlgorithm,
|
||||
OptimizationSolution,
|
||||
@@ -1869,74 +1867,31 @@ def fastapi_energy_management_optimization_solution_get() -> OptimizationSolutio
|
||||
return solution
|
||||
|
||||
|
||||
@app.get("/v1/energy-management/optimization/solution/{algorithm}", tags=["energy-management"])
|
||||
async def fastapi_energy_management_optimization_solution_algorithm_get(
|
||||
algorithm: OptimizationAlgorithm,
|
||||
) -> GeneticSolution:
|
||||
"""Get the latest algorithm specific solution of the optimization.
|
||||
@app.get(
|
||||
"/v1/energy-management/optimization/solution/{algorithm}",
|
||||
tags=["energy-management"],
|
||||
include_in_schema=False,
|
||||
response_model=None,
|
||||
)
|
||||
def fastapi_energy_management_optimization_solution_unknown_get(algorithm: str) -> NoReturn:
|
||||
"""Answer a solution request for an algorithm without its own solution endpoint.
|
||||
|
||||
Optimizers of the registry serve their own solution path (e.g. ``.../solution/GENETIC0``).
|
||||
The registered optimizers serve their solutions from their own routers, which take
|
||||
precedence; any other algorithm name is unknown.
|
||||
|
||||
Args:
|
||||
algorithm: Optimization algorithm
|
||||
algorithm: Name of the requested optimization algorithm.
|
||||
|
||||
Raises:
|
||||
EOSProblem: Always, with status 404.
|
||||
"""
|
||||
solution: Optional[GeneticSolution] = None
|
||||
|
||||
if algorithm not in get_config().optimization.algorithms:
|
||||
raise EOSProblem(
|
||||
status=404,
|
||||
title="Algorithm specific optimization solution retrieval failed",
|
||||
detail=f"Optimization algorithm '{algorithm}' unknown.",
|
||||
)
|
||||
|
||||
if algorithm == OptimizationAlgorithm.GENETIC:
|
||||
solution = get_ems().genetic_solution()
|
||||
|
||||
if solution is None:
|
||||
raise EOSProblem(
|
||||
status=404,
|
||||
title="Algorithm specific optimization solution retrieval failed",
|
||||
detail=(
|
||||
f"Can not get the '{algorithm}' optimization solution.\n"
|
||||
f"Did you configure automatic '{algorithm}' optimization?\n"
|
||||
"Did you run the optimization/ energy management?"
|
||||
),
|
||||
)
|
||||
|
||||
return solution
|
||||
|
||||
|
||||
@app.get(
|
||||
"/v1/energy-management/optimization/solution/GENETIC/pdf",
|
||||
tags=["energy-management"],
|
||||
response_class=Response,
|
||||
responses={200: {"content": {"application/pdf": {}}}},
|
||||
)
|
||||
async def fastapi_energy_management_optimization_solution_genetic_pdf_get() -> Response:
|
||||
"""Render the retained GENETIC result without rerunning optimization.
|
||||
|
||||
Rendering runs outside the event loop. Copy the result before offloading;
|
||||
its recorded timestamp, interval and inputs own the report's time grid.
|
||||
The legacy /visualization_results.pdf route continues to serve GENETIC0.
|
||||
"""
|
||||
retained = get_ems().genetic_solution()
|
||||
if retained is None:
|
||||
raise EOSProblem(
|
||||
status=404,
|
||||
title="Optimization solution report retrieval failed",
|
||||
detail="Can not get the 'GENETIC' optimization solution.",
|
||||
)
|
||||
snapshot = retained.model_copy(deep=True)
|
||||
# matplotlib is only needed for the PDF report; import it on first use.
|
||||
from akkudoktoreos.optimization.genetic.geneticvisualize import (
|
||||
genetic_prepare_visualize,
|
||||
)
|
||||
|
||||
pdf = await asyncio.to_thread(genetic_prepare_visualize, solution=snapshot)
|
||||
return Response(
|
||||
content=pdf,
|
||||
media_type="application/pdf",
|
||||
headers={"Content-Disposition": 'inline; filename="optimization-genetic.pdf"'},
|
||||
raise EOSProblem(
|
||||
status=404,
|
||||
title="Unknown optimization algorithm",
|
||||
detail=(
|
||||
f"Optimization algorithm '{algorithm}' unknown; "
|
||||
f"known algorithms: {', '.join(optimizer_names())}."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -2247,46 +2202,6 @@ async def fastapi_pvforecast() -> ForecastResponse:
|
||||
return ForecastResponse(temperature=temp_air_list, pvpower=ac_power_list)
|
||||
|
||||
|
||||
@app.post("/v1/optimize", tags=["optimize"])
|
||||
async def fastapi_optimize_config(
|
||||
request: Request,
|
||||
parameters: ConfigOptimizationRequest = Body(default_factory=ConfigOptimizationRequest),
|
||||
) -> GeneticSolution:
|
||||
"""Optimize GENETIC using configured devices and optional fresh runtime inputs.
|
||||
|
||||
Static settings belong in configuration; query overrides are rejected.
|
||||
Forecast arrays start at local
|
||||
midnight and contain Wh per configured GENETIC slot; prices are currency/Wh.
|
||||
An empty body uses configured providers. Explicit SoC values take precedence over
|
||||
fresh measured states of charge; missing usable measurements default to an assumed
|
||||
initial SoC of 0% without blocking a plan.
|
||||
The deprecated /optimize endpoint continues to run hourly GENETIC0.
|
||||
"""
|
||||
if request.query_params:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="Configure optimization settings; query overrides are not supported.",
|
||||
)
|
||||
solution = await get_ems().run(
|
||||
mode=EnergyManagementMode.OPTIMIZATION,
|
||||
algorithm=OptimizationAlgorithm.GENETIC,
|
||||
genetic_parameters=parameters,
|
||||
)
|
||||
if solution is None:
|
||||
raise EOSProblem(
|
||||
status=503,
|
||||
title="GENETIC optimization failed",
|
||||
detail="No new solution was produced. Check configured devices and forecast coverage.",
|
||||
)
|
||||
if not isinstance(solution, GeneticSolution):
|
||||
raise EOSProblem(
|
||||
status=500,
|
||||
title="Unexpected optimization algorithm result",
|
||||
detail="GENETIC did not return its native solution type.",
|
||||
)
|
||||
return solution
|
||||
|
||||
|
||||
@app.get("/site-map", include_in_schema=False)
|
||||
def site_map() -> RedirectResponse:
|
||||
return RedirectResponse(url="/docs")
|
||||
|
||||
@@ -16,6 +16,7 @@ from http import HTTPStatus
|
||||
from pathlib import Path
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Callable,
|
||||
Generator,
|
||||
Iterator,
|
||||
@@ -43,6 +44,8 @@ from akkudoktoreos.server.server import get_default_host
|
||||
if TYPE_CHECKING:
|
||||
from playwright.sync_api import Browser
|
||||
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import GeneticOptimization
|
||||
|
||||
# -----------------------------------------------
|
||||
# Adapt pytest logging handling to Loguru logging
|
||||
# -----------------------------------------------
|
||||
@@ -926,3 +929,123 @@ def set_other_timezone():
|
||||
# Restore the original timezone
|
||||
cast(Callable[[pendulum.Timezone | pendulum.FixedTimezone], None], pendulum.set_local_timezone)(original_timezone)
|
||||
assert pendulum.local_timezone() == original_timezone
|
||||
|
||||
|
||||
def genetic_optimization(seed: Optional[int] = None) -> "GeneticOptimization":
|
||||
"""GENETIC algorithm with the run settings of the configuration and EMS run start.
|
||||
|
||||
Before migration step 3 the algorithm read the configuration and the run start of the
|
||||
energy management itself; tests that build it directly get the same settings here.
|
||||
|
||||
Args:
|
||||
seed: Random seed of the run; ``None`` gives a random seed.
|
||||
|
||||
Returns:
|
||||
A ``GeneticOptimization`` for the current configuration and run start.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticprepare import run_settings
|
||||
|
||||
ems = get_ems()
|
||||
settings = run_settings(ems.start_datetime, ems.observation_datetime)
|
||||
return GeneticOptimization(replace(settings, seed=seed, verbose=False))
|
||||
|
||||
|
||||
def genetic_run_parameters(request: Any, optimization: Any = None) -> Any:
|
||||
"""GENETIC optimization parameters for the conversion and visualization tests.
|
||||
|
||||
Args:
|
||||
request: The forecast and device parameters (``GeneticOptimizationParameters``), e.g. the
|
||||
ones a result echoes.
|
||||
optimization: The ``GeneticOptimization`` of the run, whose settings are used; without it,
|
||||
the settings of the configuration and EMS run start.
|
||||
|
||||
Returns:
|
||||
A ``GeneticParameters``.
|
||||
"""
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticprepare import run_settings
|
||||
|
||||
if optimization is not None:
|
||||
settings = optimization.settings
|
||||
else:
|
||||
ems = get_ems()
|
||||
settings = run_settings(ems.start_datetime, ems.observation_datetime)
|
||||
return GeneticParameters(
|
||||
request=request, start_hour=settings.start_datetime.hour, settings=settings
|
||||
)
|
||||
|
||||
|
||||
def genetic_result_of(solution: Any) -> Any:
|
||||
"""The GENETIC result a public solution was built from.
|
||||
|
||||
Tests keep stored solutions (``GeneticSolution`` JSON); the conversion and the visualization
|
||||
take the result of a run (``GeneticResult``).
|
||||
|
||||
Args:
|
||||
solution: A ``GeneticSolution`` response.
|
||||
|
||||
Returns:
|
||||
A ``GeneticResult`` with the solution's values; its request is the echoed ``parameters``.
|
||||
"""
|
||||
import dataclasses
|
||||
|
||||
from akkudoktoreos.optimization.genetic import geneticterminalvalue
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import (
|
||||
GeneticElectricVehicleState,
|
||||
GeneticResult,
|
||||
GeneticSimulationOutput,
|
||||
)
|
||||
|
||||
def curve(value: Any) -> Any:
|
||||
if value is None:
|
||||
return None
|
||||
return geneticterminalvalue.TerminalValueCurve(**value.model_dump())
|
||||
|
||||
terminal_value = None
|
||||
if solution.terminal_value is not None:
|
||||
tv = solution.terminal_value
|
||||
terminal_value = geneticterminalvalue.TerminalValueResult(
|
||||
**{
|
||||
name: getattr(tv, name)
|
||||
for name in type(tv).model_fields
|
||||
if name not in ("curve", "continuation_curve", "tail_diagnostics", "tail_plan")
|
||||
},
|
||||
curve=curve(tv.curve),
|
||||
continuation_curve=curve(tv.continuation_curve),
|
||||
tail_diagnostics=None
|
||||
if tv.tail_diagnostics is None
|
||||
else geneticterminalvalue.TailDiagnostics(**tv.tail_diagnostics.model_dump()),
|
||||
tail_plan=[
|
||||
geneticterminalvalue.TailPlanSlot(**slot.model_dump()) for slot in tv.tail_plan
|
||||
],
|
||||
)
|
||||
simulation = GeneticSimulationOutput(
|
||||
**{
|
||||
field.name: getattr(solution.result, field.name)
|
||||
for field in dataclasses.fields(GeneticSimulationOutput)
|
||||
}
|
||||
)
|
||||
ev = None
|
||||
if solution.ev_obj is not None:
|
||||
ev = GeneticElectricVehicleState(
|
||||
**{
|
||||
field.name: getattr(solution.ev_obj, field.name)
|
||||
for field in dataclasses.fields(GeneticElectricVehicleState)
|
||||
}
|
||||
)
|
||||
return GeneticResult(
|
||||
**{
|
||||
field.name: getattr(solution, field.name)
|
||||
for field in dataclasses.fields(GeneticResult)
|
||||
if field.name not in ("request", "result", "ev_obj", "terminal_value")
|
||||
},
|
||||
request=solution.parameters,
|
||||
result=simulation,
|
||||
ev_obj=ev,
|
||||
terminal_value=terminal_value,
|
||||
)
|
||||
|
||||
@@ -7,17 +7,19 @@ import json
|
||||
import pstats
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.core.coreabc import get_config, get_ems, get_prediction
|
||||
from akkudoktoreos.core.emsettings import EnergyManagementMode
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.optimization.genetic import GeneticOptimizer, geneticapi
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import GeneticParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticprepare import run_settings
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
config_eos = get_config()
|
||||
@@ -425,21 +427,17 @@ def run_optimization(
|
||||
else:
|
||||
start_datetime = to_datetime().set(hour=start_hour)
|
||||
|
||||
asyncio.run(
|
||||
ems_eos.run(
|
||||
start_datetime=start_datetime,
|
||||
mode=EnergyManagementMode.OPTIMIZATION,
|
||||
algorithm=OptimizationAlgorithm.GENETIC,
|
||||
genetic_parameters=parameters,
|
||||
genetic_generations=ngen,
|
||||
genetic_seed=seed,
|
||||
# The parameters are complete already: add the run settings, then run the optimizer.
|
||||
start = ems_eos.set_start_datetime(start_datetime)
|
||||
settings = run_settings(start, ems_eos.observation_datetime, {"generations": ngen, "seed": seed})
|
||||
solution = GeneticOptimizer().run(
|
||||
GeneticParameters(
|
||||
request=parameters,
|
||||
start_hour=start.hour,
|
||||
settings=replace(settings, verbose=verbose),
|
||||
)
|
||||
)
|
||||
|
||||
solution = ems_eos.genetic_solution()
|
||||
if solution is None:
|
||||
return None
|
||||
return solution.model_dump_json()
|
||||
return geneticapi.solution_response(solution).model_dump_json()
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
+11
-14
@@ -30,9 +30,11 @@ from akkudoktoreos.config.configabc import (
|
||||
ValueTimeWindow,
|
||||
ValueTimeWindowSequence,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.homeappliance import (
|
||||
HomeAppliance,
|
||||
HomeApplianceParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticHomeApplianceRequest,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import Time, to_datetime, to_duration
|
||||
|
||||
@@ -2412,27 +2414,22 @@ class TestTimeWindowBoundaries:
|
||||
)
|
||||
# Exercise the serialized settings used by the dashboard/API as well.
|
||||
sequence = CycleTimeWindowSequence.model_validate_json(sequence.model_dump_json())
|
||||
appliance = HomeAppliance(
|
||||
parameters=HomeApplianceParameters(
|
||||
appliance = GeneticHomeAppliance(
|
||||
parameters=GeneticHomeApplianceRequest(
|
||||
device_id="dishwasher",
|
||||
duration_h=2,
|
||||
consumption_wh=2000,
|
||||
num_cycles=1,
|
||||
time_windows=sequence,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=24,
|
||||
optimization_hours=24,
|
||||
)
|
||||
start = pendulum.datetime(2026, 10, 26)
|
||||
appliance.start_allowed = []
|
||||
appliance.start_earliest = []
|
||||
appliance.start_latest = []
|
||||
|
||||
appliance._build_cycle_start_allowed(
|
||||
sequence, start, start.add(days=1), pendulum.duration(hours=1)
|
||||
)
|
||||
|
||||
np.testing.assert_array_equal(np.flatnonzero(appliance.start_allowed[0]), [8, 9, 10])
|
||||
assert appliance.allowed_start_slots(
|
||||
slot0_datetime=start, earliest_slot=0, horizon_end_slot=24, cycle_index=0
|
||||
) == [8, 9, 10]
|
||||
|
||||
|
||||
class TestTimeWindowDST:
|
||||
|
||||
@@ -1015,7 +1015,9 @@ class TestDataSequence:
|
||||
assert pd.isna(values_keep[1])
|
||||
|
||||
async def test_raw_none_record_keeps_forecast_gap_and_true_interval_length(self, sequence):
|
||||
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
|
||||
from akkudoktoreos.optimization.genetic.geneticforecast import (
|
||||
bounded_forecast_array,
|
||||
)
|
||||
|
||||
start = to_datetime("2026-09-16T10:00:00Z", in_timezone="UTC")
|
||||
for minute, value in [(0, 100.0), (15, None), (30, 100.0)]:
|
||||
|
||||
@@ -43,6 +43,7 @@ from akkudoktoreos.devices.settings.batterysettings import (
|
||||
BatteryProfileAdjustment,
|
||||
BatteryResolutionError,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
|
||||
# The real measurement accessor, captured before any fixture replaces it.
|
||||
REAL_GET_MEASURED_VALUE = batterymeasurement.get_measured_value
|
||||
@@ -77,7 +78,12 @@ PARAMETER_METHODS = [
|
||||
]
|
||||
|
||||
|
||||
# GENETIC0's conversions live in its parameter preparation (ADR 0004), not in the settings.
|
||||
# The optimizers' conversions live in their parameter preparation (ADR 0004), not in the
|
||||
# settings.
|
||||
GENETIC_CONVERSIONS = {
|
||||
"to_genetic_pv_bat_param": "battery_request",
|
||||
"to_genetic_ev_bat_param": "electric_vehicle_request",
|
||||
}
|
||||
GENETIC0_CONVERSIONS = {
|
||||
"to_genetic0_pv_bat_param": "battery_request",
|
||||
"to_genetic0_ev_bat_param": "electric_vehicle_request",
|
||||
@@ -85,13 +91,14 @@ GENETIC0_CONVERSIONS = {
|
||||
|
||||
|
||||
def converter(settings, method):
|
||||
"""The conversion ``method`` of the settings, or GENETIC0's function for them."""
|
||||
"""The conversion function named ``method`` of GENETIC or GENETIC0, bound to the settings."""
|
||||
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)
|
||||
else:
|
||||
function = getattr(geneticprepare, GENETIC_CONVERSIONS[method])
|
||||
return lambda *args, **kwargs: function(settings, *args, **kwargs)
|
||||
|
||||
|
||||
COMPUTED_FIELDS = [
|
||||
@@ -816,7 +823,7 @@ class TestGetBatteryProfile:
|
||||
settings.resolve_operating_parameters()
|
||||
_ = settings.effective_nominal_capacity_wh
|
||||
_ = settings.effective_max_charge_power_w
|
||||
settings.to_genetic_pv_bat_param()
|
||||
geneticprepare.battery_request(settings)
|
||||
assert calls == ["generic-lfp"] * 5
|
||||
|
||||
def test_dump_resolves_the_battery_once(self, install_profile, monkeypatch):
|
||||
@@ -968,7 +975,7 @@ class TestMaxChargePower:
|
||||
measurements["battery1-temperature-degc"] = -12.0
|
||||
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 geneticprepare.battery_request(settings, 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):
|
||||
@@ -1037,7 +1044,7 @@ class TestMaxDischargePower:
|
||||
def test_inhibited_discharging_does_not_block_conversions(self, make_profiled_settings):
|
||||
profile = make_profile(hard_cutoffs=discharge_inhibited_below_30())
|
||||
settings = make_profiled_settings(profile, capacity_wh=10000)
|
||||
assert settings.to_genetic_pv_bat_param().max_charge_power_w == pytest.approx(5000.0)
|
||||
assert geneticprepare.battery_request(settings).max_charge_power_w == pytest.approx(5000.0)
|
||||
|
||||
|
||||
# --- Efficiencies ----------------------------------------------------------------
|
||||
@@ -1429,11 +1436,11 @@ class TestOptimizationParameters:
|
||||
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()
|
||||
params = geneticprepare.battery_request(make_settings(levelized_cost_of_storage_amt_kwh=0.12))
|
||||
assert params.levelized_cost_of_storage_kwh == pytest.approx(0.12)
|
||||
|
||||
def test_genetic_ev_receives_soc_deadline_settings(self):
|
||||
params = make_settings(min_soc_max_duration_h=6.0).to_genetic_ev_bat_param()
|
||||
params = geneticprepare.electric_vehicle_request(make_settings(min_soc_max_duration_h=6.0))
|
||||
assert params.min_soc_max_duration_h == pytest.approx(6.0)
|
||||
assert params.min_soc_deadline_datetime is None
|
||||
|
||||
@@ -1536,11 +1543,11 @@ class TestGeneticPowerCurves:
|
||||
max_soc_percentage=100,
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("converter", ["to_genetic_pv_bat_param", "to_genetic_ev_bat_param"])
|
||||
def test_tables_follow_soc(self, make_profiled_settings, converter):
|
||||
@pytest.mark.parametrize("method", ["to_genetic_pv_bat_param", "to_genetic_ev_bat_param"])
|
||||
def test_tables_follow_soc(self, make_profiled_settings, method):
|
||||
profile = make_profile(charge=[list(self.TAPER) for _ in range(10)], discharge=0.4)
|
||||
settings = make_profiled_settings(profile, capacity_wh=10000)
|
||||
parameters = getattr(settings, converter)()
|
||||
parameters = converter(settings, method)()
|
||||
|
||||
charge = parameters.charge_power_limit_w_by_soc
|
||||
discharge = parameters.discharge_power_limit_w_by_soc
|
||||
@@ -1564,8 +1571,9 @@ class TestGeneticPowerCurves:
|
||||
snapshot = await current(settings)
|
||||
assert snapshot.max_charge_power_w == pytest.approx(5000.0)
|
||||
|
||||
parameters = settings.to_genetic_pv_bat_param(snapshot)
|
||||
parameters = geneticprepare.battery_request(settings, snapshot)
|
||||
assert parameters.max_charge_power_w == pytest.approx(10000.0)
|
||||
assert parameters.charge_power_limit_w_by_soc is not None
|
||||
assert parameters.charge_power_limit_w_by_soc[100] == pytest.approx(5000.0)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1583,7 +1591,7 @@ class TestGeneticPowerCurves:
|
||||
if temperature is not None:
|
||||
measurements["battery1-temperature-degc"] = temperature
|
||||
|
||||
parameters = settings.to_genetic_pv_bat_param(await current(settings))
|
||||
parameters = geneticprepare.battery_request(settings, await current(settings))
|
||||
assert parameters.charge_power_limit_w_by_soc == pytest.approx([expected_w] * 101)
|
||||
assert parameters.discharge_power_limit_w_by_soc == pytest.approx([expected_w] * 101)
|
||||
|
||||
@@ -1595,7 +1603,8 @@ class TestGeneticPowerCurves:
|
||||
charge_limit_w=6000,
|
||||
discharge_limit_w=1000,
|
||||
)
|
||||
parameters = settings.to_genetic_pv_bat_param()
|
||||
parameters = geneticprepare.battery_request(settings)
|
||||
assert parameters.charge_power_limit_w_by_soc is not None
|
||||
assert max(parameters.charge_power_limit_w_by_soc) == pytest.approx(6000.0)
|
||||
assert parameters.charge_power_limit_w_by_soc[100] == pytest.approx(5000.0)
|
||||
assert parameters.discharge_power_limit_w_by_soc == pytest.approx([1000.0] * 101)
|
||||
@@ -1604,7 +1613,7 @@ class TestGeneticPowerCurves:
|
||||
|
||||
def test_efficiency_curves_over_power_fraction(self, make_profiled_settings, full_profile):
|
||||
settings = make_profiled_settings(full_profile, capacity_wh=10000)
|
||||
parameters = settings.to_genetic_pv_bat_param()
|
||||
parameters = geneticprepare.battery_request(settings)
|
||||
|
||||
charging = parameters.charging_efficiency_curve
|
||||
discharging = parameters.discharging_efficiency_curve
|
||||
@@ -1617,7 +1626,7 @@ class TestGeneticPowerCurves:
|
||||
assert discharging[-1][1] == pytest.approx(0.9375)
|
||||
|
||||
def test_efficiency_curves_come_from_the_profile(self):
|
||||
parameters = make_settings(capacity_wh=10000).to_genetic_pv_bat_param()
|
||||
parameters = geneticprepare.battery_request(make_settings(capacity_wh=10000))
|
||||
assert parameters.charge_power_limit_w_by_soc is not None
|
||||
assert parameters.charging_efficiency_curve is not None
|
||||
assert parameters.discharging_efficiency_curve is not None
|
||||
@@ -1629,7 +1638,7 @@ class TestGeneticPowerCurves:
|
||||
snapshot = self.snapshot(temperature_degC=20.0)
|
||||
assert settings.resolve_power_curves(snapshot) is None
|
||||
|
||||
parameters = settings.to_genetic_pv_bat_param(snapshot)
|
||||
parameters = geneticprepare.battery_request(settings, snapshot)
|
||||
assert parameters.charge_power_limit_w_by_soc is None
|
||||
assert parameters.max_charge_power_w == pytest.approx(snapshot.max_charge_power_w)
|
||||
|
||||
@@ -1637,7 +1646,7 @@ class TestGeneticPowerCurves:
|
||||
"""A snapshot resolved without profile is converted as is: no load, no abort."""
|
||||
snapshot = self.snapshot()
|
||||
settings = make_settings(battery_profile="does-not-exist")
|
||||
converted = settings.to_genetic_pv_bat_param(snapshot)
|
||||
converted = geneticprepare.battery_request(settings, snapshot)
|
||||
assert converted.max_charge_power_w == snapshot.max_charge_power_w
|
||||
assert converted.max_discharge_power_w == snapshot.max_discharge_power_w
|
||||
assert converted.charge_power_limit_w_by_soc is None
|
||||
|
||||
@@ -23,6 +23,7 @@ from akkudoktoreos.devices.settings.invertersettings import (
|
||||
InverterCommonSettings,
|
||||
InverterProfileAdjustment,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic0 import genetic0prepare
|
||||
|
||||
|
||||
@@ -141,7 +142,7 @@ class TestResolution:
|
||||
curve = settings.resolve_operating_parameters().dc_to_ac_efficiency_curve
|
||||
assert [x for x, _ in curve] == [0.0, 1.0]
|
||||
assert [y for _, y in curve] == pytest.approx([0.88, 0.88])
|
||||
settings.to_genetic_param()
|
||||
geneticprepare.inverter_request(settings)
|
||||
|
||||
def test_no_power_at_the_operating_point(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000)
|
||||
@@ -166,7 +167,7 @@ class TestResolution:
|
||||
parameters = settings.resolve_operating_parameters()
|
||||
assert parameters.max_ac_charge_power_w == 0
|
||||
assert math.isfinite(parameters.ac_to_dc_efficiency)
|
||||
assert settings.to_genetic_param().max_ac_charge_power_w == 0
|
||||
assert geneticprepare.inverter_request(settings).max_ac_charge_power_w == 0
|
||||
|
||||
def test_model_ac_charge_limit_is_derated(self, generic, use_profile):
|
||||
use_profile(dataclasses.replace(generic, nominal_power_w=10000, max_ac_charge_power_w=5000))
|
||||
@@ -232,7 +233,7 @@ class TestConversion:
|
||||
def test_genetic_parameters(self, generic):
|
||||
settings = make_settings(nominal_power_w=10000, max_ac_charge_power_w=4000)
|
||||
parameters = settings.resolve_operating_parameters(InverterOperatingPoint(60.0))
|
||||
genetic = settings.to_genetic_param(parameters)
|
||||
genetic = geneticprepare.inverter_request(settings, parameters)
|
||||
assert genetic.device_id == "inverter1"
|
||||
assert genetic.battery_id == "battery1"
|
||||
assert genetic.max_power_wh == pytest.approx(6000)
|
||||
@@ -279,7 +280,7 @@ class TestOptimizationDefaults:
|
||||
assert len(logged_errors) == 1
|
||||
assert "allows no power at 70.0 degC" in logged_errors[0]
|
||||
# The conversion gets valid parameters.
|
||||
assert settings.to_genetic_param(parameters).max_power_wh == pytest.approx(10000)
|
||||
assert geneticprepare.inverter_request(settings, parameters).max_power_wh == pytest.approx(10000)
|
||||
|
||||
def test_missing_nominal_power_gives_the_fallback(self, generic, logged_errors):
|
||||
parameters = make_settings().resolve_operating_parameters_or_defaults()
|
||||
|
||||
@@ -3,17 +3,20 @@
|
||||
from asyncio import Lock
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
from unittest.mock import ANY, AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.core import ems as ems_module
|
||||
from akkudoktoreos.core.emsettings import EnergyManagementMode
|
||||
from akkudoktoreos.optimization.genetic import geneticalgorithm as genetic_module
|
||||
from akkudoktoreos.optimization.genetic import geneticconvert, geneticprepare
|
||||
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.genetic.geneticrequest import GeneticRequest
|
||||
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerRun
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
@@ -21,20 +24,24 @@ from akkudoktoreos.utils.gridinterpolator import GridInterpolatorBackend
|
||||
|
||||
|
||||
def _patch_optimizer(monkeypatch, prefix: str, constructor: Any) -> None:
|
||||
"""Replace the optimizer class that EnergyManagement.run() instantiates.
|
||||
"""Replace the optimizer class that the optimizer's ``run()`` instantiates.
|
||||
|
||||
GENETIC0 is imported on first use inside its optimizer, so it is patched at its source.
|
||||
Both are imported on first use inside their optimizer, so they are patched at their source.
|
||||
"""
|
||||
module = genetic0_module if prefix == "Genetic0" else ems_module
|
||||
module = genetic0_module if prefix == "Genetic0" else genetic_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."""
|
||||
"""Replace the forecast and device preparation of GENETIC or GENETIC0.
|
||||
|
||||
GENETIC resolves every request, the configured default one included, through
|
||||
``resolve_request()``; GENETIC0's legacy preparation serves runs without a request only.
|
||||
"""
|
||||
if prefix == "Genetic0":
|
||||
monkeypatch.setattr(genetic0prepare, "prepare_request", prepare)
|
||||
else:
|
||||
monkeypatch.setattr(ems_module.GeneticOptimizationParameters, "prepare", prepare)
|
||||
monkeypatch.setattr(geneticprepare, "resolve_request", prepare)
|
||||
|
||||
|
||||
def _warm_start_of(call: Any) -> Any:
|
||||
@@ -44,12 +51,14 @@ def _warm_start_of(call: Any) -> Any:
|
||||
|
||||
|
||||
def _assert_prepared_without_request(prefix: str, prepare: Any) -> None:
|
||||
"""GENETIC0 passes start, observation time and warm start (none here) into its preparation."""
|
||||
"""Both pass the warm start (none here) into their preparation; GENETIC a default request."""
|
||||
prepare.assert_awaited_once()
|
||||
if prefix == "Genetic0":
|
||||
prepare.assert_awaited_once()
|
||||
assert _warm_start_of(prepare.await_args) is None
|
||||
else:
|
||||
prepare.assert_awaited_once_with()
|
||||
request, start, observation, warm_start = prepare.await_args.args
|
||||
assert request.model_dump() == GeneticRequest().model_dump()
|
||||
assert warm_start is None
|
||||
|
||||
|
||||
def _conversion_arguments(prefix: str) -> dict[str, Any]:
|
||||
@@ -59,31 +68,32 @@ def _conversion_arguments(prefix: str) -> dict[str, Any]:
|
||||
|
||||
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
|
||||
return ems_module.EnergyManagement.optimizer_result(prefix.upper())
|
||||
|
||||
|
||||
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)
|
||||
runs = {prefix.upper(): OptimizerRun(parameters=object(), result=solution)}
|
||||
monkeypatch.setattr(ems_module.EnergyManagement, "_optimizer_runs", runs)
|
||||
|
||||
|
||||
def _supplied(prefix: str, parameters: Any, generations: int, seed: int) -> dict[str, Any]:
|
||||
def _stand_in_request() -> SimpleNamespace:
|
||||
"""A request both preparations accept.
|
||||
|
||||
GENETIC0's preparation looks at its home appliance, GENETIC's at its start solution and its
|
||||
home appliances.
|
||||
"""
|
||||
return SimpleNamespace(
|
||||
dishwasher=None,
|
||||
start_solution=None,
|
||||
start_solution_datetime=None,
|
||||
resolved_home_appliances=lambda: [],
|
||||
)
|
||||
|
||||
|
||||
def _supplied(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,
|
||||
}
|
||||
return {"request": parameters, "overrides": {"generations": generations, "seed": seed}}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -96,7 +106,6 @@ def offline_ems(monkeypatch):
|
||||
"_last_run_datetime",
|
||||
"_plan",
|
||||
"_optimization_solution",
|
||||
"_genetic_solution",
|
||||
):
|
||||
monkeypatch.setattr(cls, name, None)
|
||||
monkeypatch.setattr(cls, "_optimizer_runs", {})
|
||||
@@ -109,12 +118,27 @@ def offline_ems(monkeypatch):
|
||||
ems=SimpleNamespace(mode=EnergyManagementMode.OPTIMIZATION),
|
||||
optimization=SimpleNamespace(
|
||||
algorithm=OptimizationAlgorithm.GENETIC,
|
||||
genetic=SimpleNamespace(generations=3, seed=17, interval_sec=3600, individuals=31),
|
||||
self_consumption_interpolator="scipy",
|
||||
genetic=SimpleNamespace(
|
||||
generations=3,
|
||||
seed=17,
|
||||
interval_sec=3600,
|
||||
individuals=31,
|
||||
horizon_hours=24,
|
||||
tail_horizon_hours=0,
|
||||
penalties={},
|
||||
workers=None,
|
||||
pin_workers=True,
|
||||
fitness_cache_max_entries=None,
|
||||
terminal_value_mode="AUTO",
|
||||
terminal_value_window_hours=24,
|
||||
),
|
||||
genetic0=SimpleNamespace(
|
||||
generations=5, seed=29, horizon_hours=24, individuals=13, penalties={}
|
||||
),
|
||||
),
|
||||
prediction=SimpleNamespace(hours=48),
|
||||
feedintariff=SimpleNamespace(provider=None, direct_marketing_enabled=False),
|
||||
devices=SimpleNamespace(
|
||||
batteries=None, electric_vehicles=None, max_home_appliances=0
|
||||
),
|
||||
@@ -124,7 +148,12 @@ 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.
|
||||
# The parameter preparations read the settings (and GENETIC0's the predictions) themselves.
|
||||
monkeypatch.setattr(geneticprepare, "get_config", lambda: ems.config)
|
||||
# Stand-in requests are already resolved.
|
||||
monkeypatch.setattr(
|
||||
geneticprepare, "resolve_request", AsyncMock(side_effect=lambda request, *args: request)
|
||||
)
|
||||
monkeypatch.setattr(genetic0prepare, "get_config", lambda: ems.config)
|
||||
monkeypatch.setattr(
|
||||
genetic0prepare, "get_prediction", lambda: SimpleNamespace(record_keys=[])
|
||||
@@ -139,6 +168,12 @@ def offline_ems(monkeypatch):
|
||||
return await result.optimization_solution()
|
||||
|
||||
monkeypatch.setattr(genetic0convert, "optimization_solution", optimization_solution)
|
||||
monkeypatch.setattr(geneticconvert, "optimization_solution", optimization_solution)
|
||||
monkeypatch.setattr(
|
||||
geneticconvert,
|
||||
"energy_management_plan",
|
||||
lambda parameters, result: result.energy_management_plan(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
genetic0convert,
|
||||
"energy_management_plan",
|
||||
@@ -202,8 +237,7 @@ async def test_optimization_routes_only_selected_algorithm(
|
||||
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"
|
||||
# GENETIC0's preparation looks at the request's home appliance.
|
||||
sentinel_parameters = SimpleNamespace(dishwasher=None)
|
||||
sentinel_parameters = _stand_in_request()
|
||||
sentinel_result, sentinel_plan = object(), object()
|
||||
solution = SimpleNamespace(
|
||||
optimization_solution=AsyncMock(return_value=sentinel_result),
|
||||
@@ -228,9 +262,9 @@ async def test_optimization_routes_only_selected_algorithm(
|
||||
offline_ems.config.optimization.algorithm = OptimizationAlgorithm(other_suffix.upper())
|
||||
kwargs["algorithm"] = algorithm
|
||||
if supplied:
|
||||
kwargs.update(_supplied(selected_name, sentinel_parameters, 7, 43))
|
||||
kwargs.update(_supplied(sentinel_parameters, 7, 43))
|
||||
if algorithm == OptimizationAlgorithm.GENETIC:
|
||||
kwargs["genetic_individuals"] = 11
|
||||
kwargs["overrides"]["individuals"] = 11
|
||||
run_result = await ems_module.EnergyManagement.run(offline_ems, **kwargs)
|
||||
assert run_result is solution
|
||||
selected = constructors[selected_name]
|
||||
@@ -241,19 +275,18 @@ async def test_optimization_routes_only_selected_algorithm(
|
||||
"start_hour": expected_hour,
|
||||
"parameters": sentinel_parameters,
|
||||
}
|
||||
# Both get their 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:
|
||||
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
|
||||
expected_arguments["individuals"] = 11 if supplied else expected_config.individuals
|
||||
# The start of the start solution comes from the parameters, not their request.
|
||||
expected_arguments["start_solution_datetime"] = None
|
||||
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.
|
||||
@@ -262,7 +295,12 @@ async def test_optimization_routes_only_selected_algorithm(
|
||||
assert parameters.start_hour == expected_hour
|
||||
constructors[other_name].assert_not_called()
|
||||
preparers[other_name].assert_not_awaited()
|
||||
if supplied:
|
||||
if supplied and algorithm == OptimizationAlgorithm.GENETIC:
|
||||
# GENETIC completes the supplied request.
|
||||
preparers[selected_name].assert_awaited_once_with(
|
||||
sentinel_parameters, ANY, ANY, None
|
||||
)
|
||||
elif supplied:
|
||||
preparers[selected_name].assert_not_awaited()
|
||||
else:
|
||||
_assert_prepared_without_request(selected_name, preparers[selected_name])
|
||||
@@ -298,24 +336,6 @@ async def test_non_optimization_modes_never_optimize(monkeypatch, offline_ems, m
|
||||
assert ems_module.EnergyManagement.plan() is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@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)
|
||||
_patch_prepare(monkeypatch, prefix, prepare)
|
||||
await ems_module.EnergyManagement.run(
|
||||
offline_ems, algorithm=OptimizationAlgorithm(prefix.upper())
|
||||
)
|
||||
_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
|
||||
assert ems_module.EnergyManagement.stage() == ems_module.EnergyManagementStage.IDLE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("start_hour", [None, 11])
|
||||
async def test_legacy_optimize_explicitly_uses_genetic0(monkeypatch, start_hour):
|
||||
@@ -434,7 +454,7 @@ 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 = _supplied(prefix, SimpleNamespace(dishwasher=None), 3, 17)
|
||||
supplied_parameters = _supplied(_stand_in_request(), 3, 17)
|
||||
result = await cls.run(
|
||||
offline_ems,
|
||||
algorithm=OptimizationAlgorithm(prefix.upper()),
|
||||
|
||||
@@ -13,21 +13,30 @@ from unittest.mock import Mock, patch
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
from akkudoktoreos.devices.profile.inverterprofile import InverterProfileSettings
|
||||
from akkudoktoreos.devices.profile.profilestore import get_profile_store
|
||||
from akkudoktoreos.devices.settings.invertersettings import (
|
||||
InverterCommonSettings,
|
||||
InverterProfileAdjustment,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticInverterRequest,
|
||||
)
|
||||
|
||||
MAX_CHARGE_W = 5000
|
||||
|
||||
|
||||
def _build(limits_total: bool, max_ac_charge_power_w=None) -> tuple[Inverter, Battery]:
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
def _build(limits_total: bool, max_ac_charge_power_w=None) -> tuple[GeneticInverter, GeneticBattery]:
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=20000,
|
||||
initial_soc_percentage=20,
|
||||
@@ -36,7 +45,7 @@ def _build(limits_total: bool, max_ac_charge_power_w=None) -> tuple[Inverter, Ba
|
||||
min_soc_percentage=0,
|
||||
max_soc_percentage=100,
|
||||
max_charge_power_w=MAX_CHARGE_W,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=4,
|
||||
)
|
||||
battery.reset()
|
||||
@@ -45,24 +54,24 @@ def _build(limits_total: bool, max_ac_charge_power_w=None) -> tuple[Inverter, Ba
|
||||
predictor = Mock()
|
||||
predictor.calculate_expected_direct_consumption.side_effect = min
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
|
||||
return_value=predictor,
|
||||
):
|
||||
inverter = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=10000,
|
||||
battery_id="battery1",
|
||||
ac_to_dc_efficiency=1.0,
|
||||
max_ac_charge_power_w=max_ac_charge_power_w,
|
||||
ac_charge_limits_total_charge=limits_total,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
)
|
||||
return inverter, battery
|
||||
|
||||
|
||||
def _run_ac_slot(inverter: Inverter, battery: Battery, pv_wh: float, factor: float):
|
||||
def _run_ac_slot(inverter: GeneticInverter, battery: GeneticBattery, pv_wh: float, factor: float):
|
||||
"""Run one AC slot the way GeneticSimulation.simulate() does."""
|
||||
battery.charge_array[0] = factor
|
||||
battery.discharge_array[0] = 0
|
||||
@@ -150,9 +159,11 @@ class TestGeneticSimulation:
|
||||
|
||||
@pytest.fixture
|
||||
def simulate(self, config_eos):
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticEnergyManagementParameters,
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticEnergyManagementRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsimulation import (
|
||||
GeneticSimulation,
|
||||
)
|
||||
|
||||
config_eos.merge_settings_from_dict(
|
||||
@@ -161,8 +172,8 @@ class TestGeneticSimulation:
|
||||
hours = config_eos.prediction.hours
|
||||
|
||||
def _simulate(limits_total: bool, ac_factor: float, dc_factor: float):
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=30000,
|
||||
initial_soc_percentage=20,
|
||||
@@ -171,22 +182,22 @@ class TestGeneticSimulation:
|
||||
min_soc_percentage=0,
|
||||
max_soc_percentage=100,
|
||||
max_charge_power_w=MAX_CHARGE_W,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=hours,
|
||||
)
|
||||
battery.reset()
|
||||
inverter = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=10000,
|
||||
battery_id="battery1",
|
||||
ac_charge_limits_total_charge=limits_total,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
)
|
||||
sim = GeneticSimulation()
|
||||
sim.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(
|
||||
GeneticEnergyManagementRequest.model_validate(
|
||||
dict(
|
||||
pv_prognose_wh=[8000.0] * hours,
|
||||
strompreis_euro_pro_wh=[0.0003] * hours,
|
||||
@@ -194,7 +205,7 @@ class TestGeneticSimulation:
|
||||
preis_euro_pro_wh_akku=0.0001,
|
||||
gesamtlast=[0.0] * hours,
|
||||
)
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=config_eos.optimization.genetic.horizon_hours,
|
||||
prediction_hours=hours,
|
||||
inverter=inverter,
|
||||
@@ -244,11 +255,11 @@ class TestConfigOption:
|
||||
battery_id="battery1",
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=10000),
|
||||
)
|
||||
assert settings.to_genetic_param().ac_charge_limits_total_charge is enabled
|
||||
assert geneticprepare.inverter_request(settings).ac_charge_limits_total_charge is enabled
|
||||
|
||||
def test_default_profile_keeps_the_existing_model(self, config_eos):
|
||||
settings = InverterCommonSettings(
|
||||
device_id="inverter",
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=10000),
|
||||
)
|
||||
assert settings.to_genetic_param().ac_charge_limits_total_charge is False
|
||||
assert geneticprepare.inverter_request(settings).ac_charge_limits_total_charge is False
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Tests for the appliance gene layout of the GENETIC optimizer."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticappliancelayout import (
|
||||
ApplianceGeneLayout,
|
||||
build_appliance_layout,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticHomeApplianceRequest,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
|
||||
def _layout(
|
||||
slot0_datetime: DateTime, horizon_slots: int, **fields: Any
|
||||
) -> ApplianceGeneLayout:
|
||||
"""Lay out one DAILY appliance on an hourly grid starting at ``slot0_datetime``."""
|
||||
request = GeneticHomeApplianceRequest(
|
||||
**{
|
||||
"device_id": "dishwasher",
|
||||
"consumption_wh": 1000,
|
||||
"duration_h": 1,
|
||||
"num_cycles": 1,
|
||||
"schedule_mode": "DAILY",
|
||||
**fields,
|
||||
}
|
||||
)
|
||||
appliance = GeneticHomeAppliance(
|
||||
parameters=request.to_parameters(),
|
||||
optimization_hours=horizon_slots,
|
||||
prediction_hours=horizon_slots,
|
||||
)
|
||||
return build_appliance_layout(
|
||||
[appliance],
|
||||
slot0_datetime,
|
||||
start_slot=0,
|
||||
horizon_end_slot=horizon_slots,
|
||||
control_end_slot=horizon_slots,
|
||||
slot_duration_h=1.0,
|
||||
order_cache={},
|
||||
)
|
||||
|
||||
|
||||
class TestBuildApplianceLayout:
|
||||
"""A DAILY appliance whose open windows leave no room for a cycle it owes is unschedulable."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fields",
|
||||
[
|
||||
{
|
||||
"duration_h": 5,
|
||||
"shared_time_windows": {"windows": [{"start_time": "10:00", "end_time": "13:00"}]},
|
||||
},
|
||||
# The first hourly start in the window is 11:00; the run would end after 12:30.
|
||||
{
|
||||
"duration_h": 2,
|
||||
"shared_time_windows": {"windows": [{"start_time": "10:30", "end_time": "12:30"}]},
|
||||
},
|
||||
{"deadline_datetime": "2026-09-11T12:00:00Z", "deadline_policy": "STRICT"},
|
||||
],
|
||||
ids=["run-longer-than-window", "window-off-the-slot-grid", "past-strict-deadline"],
|
||||
)
|
||||
def test_daily_appliance_without_any_start_is_rejected(self, fields: dict[str, Any]) -> None:
|
||||
with pytest.raises(ValueError, match="has no valid start"):
|
||||
_layout(to_datetime("2026-09-12T00:00:00+00:00", in_timezone="UTC"), 48, **fields)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"start, horizon_slots, fields",
|
||||
[
|
||||
# 2026-09-14 is a Monday; the only window opens on Saturdays.
|
||||
(
|
||||
"2026-09-14T00:00:00+00:00",
|
||||
48,
|
||||
{
|
||||
"shared_time_windows": {
|
||||
"windows": [{"start_time": "10:00", "end_time": "13:00", "day_of_week": 5}]
|
||||
}
|
||||
},
|
||||
),
|
||||
("2026-09-14T00:00:00+00:00", 48, {"earliest_start_datetime": "2026-09-20T10:00:00Z"}),
|
||||
# Today's cycle is done; the horizon ends at 11:00, inside tomorrow's window.
|
||||
(
|
||||
"2026-09-12T11:00:00+00:00",
|
||||
24,
|
||||
{
|
||||
"duration_h": 2,
|
||||
"completed_cycles": 1,
|
||||
"shared_time_windows": {
|
||||
"windows": [{"start_time": "10:00", "end_time": "13:00"}]
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
ids=[
|
||||
"window-on-another-weekday",
|
||||
"earliest-start-after-the-horizon",
|
||||
"horizon-ends-in-the-window",
|
||||
],
|
||||
)
|
||||
def test_daily_appliance_without_an_open_window_is_kept_without_runs(
|
||||
self, start: str, horizon_slots: int, fields: dict[str, Any]
|
||||
) -> None:
|
||||
"""Nothing to plan in this horizon is not an unschedulable appliance."""
|
||||
layout = _layout(to_datetime(start, in_timezone="UTC"), horizon_slots, **fields)
|
||||
assert layout.n_genes == 0
|
||||
|
||||
def test_daily_appliance_done_for_a_horizon_within_the_day_is_kept_without_runs(self) -> None:
|
||||
layout = _layout(
|
||||
to_datetime("2026-09-12T00:00:00+00:00", in_timezone="UTC"),
|
||||
24,
|
||||
completed_cycles=1,
|
||||
shared_time_windows={"windows": [{"start_time": "10:00", "end_time": "13:00"}]},
|
||||
)
|
||||
assert layout.n_genes == 0
|
||||
|
||||
def test_daily_appliance_past_todays_window_runs_tomorrow(self) -> None:
|
||||
layout = _layout(
|
||||
to_datetime("2026-09-12T14:00:00+00:00", in_timezone="UTC"),
|
||||
24,
|
||||
shared_time_windows={"windows": [{"start_time": "10:00", "end_time": "13:00"}]},
|
||||
)
|
||||
assert [str(gene.run_date) for gene in layout.genes] == ["2026-09-13"]
|
||||
@@ -5,13 +5,22 @@ import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from akkudoktoreos.devices.devices import BatteriesCommonSettings
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
Battery,
|
||||
ElectricVehicleParameters,
|
||||
SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.settings.batterysettings import BatteryProfileAdjustment
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic0 import genetic0prepare
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticElectricVehicleRequest,
|
||||
)
|
||||
|
||||
# GENETIC's conversions of the battery settings, in its parameter preparation.
|
||||
CONVERSIONS = {
|
||||
"to_genetic_pv_bat_param": "battery_request",
|
||||
"to_genetic_ev_bat_param": "electric_vehicle_request",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -26,7 +35,7 @@ def setup_pv_battery():
|
||||
max_charge_power_w=8000
|
||||
hours=24
|
||||
|
||||
params = SolarPanelBatteryParameters(
|
||||
params = GeneticBatteryRequest(
|
||||
device_id=device_id,
|
||||
capacity_wh=capacity_wh,
|
||||
initial_soc_percentage=initial_soc_percentage,
|
||||
@@ -37,8 +46,8 @@ def setup_pv_battery():
|
||||
max_charge_power_w=max_charge_power_w,
|
||||
hours=hours,
|
||||
)
|
||||
battery = Battery(
|
||||
params,
|
||||
battery = GeneticBattery(
|
||||
params.to_parameters(),
|
||||
prediction_hours=48,
|
||||
)
|
||||
battery.reset()
|
||||
@@ -122,13 +131,13 @@ def test_battery_discharge_when_empty(setup_pv_battery):
|
||||
def test_discharge_preserves_energy_at_or_below_min_soc(
|
||||
slot_duration_h, initial_soc, requested_wh
|
||||
):
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=26_400,
|
||||
initial_soc_percentage=initial_soc,
|
||||
min_soc_percentage=6,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=2,
|
||||
slot_duration_h=slot_duration_h,
|
||||
)
|
||||
@@ -278,11 +287,11 @@ def test_charge_energy_with_charge_factor(setup_pv_battery, wh, charge_factor, e
|
||||
|
||||
@pytest.fixture
|
||||
def setup_car_battery():
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
ElectricVehicleParameters,
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticElectricVehicleRequest,
|
||||
)
|
||||
|
||||
params = ElectricVehicleParameters(
|
||||
params = GeneticElectricVehicleRequest(
|
||||
device_id="ev1",
|
||||
capacity_wh=40000,
|
||||
initial_soc_percentage=60,
|
||||
@@ -291,8 +300,8 @@ def setup_car_battery():
|
||||
max_charge_power_w=7000,
|
||||
hours=24,
|
||||
)
|
||||
battery = Battery(
|
||||
params,
|
||||
battery = GeneticBattery(
|
||||
params.to_parameters(),
|
||||
prediction_hours=48,
|
||||
)
|
||||
battery.reset()
|
||||
@@ -332,7 +341,7 @@ def test_car_and_pv_battery_discharge_and_max_charge_power(setup_pv_battery, set
|
||||
|
||||
|
||||
def test_quarter_hour_charge_calls_share_one_power_budget():
|
||||
params = SolarPanelBatteryParameters(
|
||||
params = GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=10_000,
|
||||
initial_soc_percentage=0,
|
||||
@@ -342,7 +351,7 @@ def test_quarter_hour_charge_calls_share_one_power_budget():
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=1.0,
|
||||
)
|
||||
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
|
||||
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
|
||||
battery.set_charge_per_hour(np.ones(4))
|
||||
|
||||
first_stored, _ = battery.charge_energy(200.0, 0)
|
||||
@@ -354,7 +363,7 @@ def test_quarter_hour_charge_calls_share_one_power_budget():
|
||||
|
||||
|
||||
def test_quarter_hour_discharge_calls_share_one_power_budget():
|
||||
params = SolarPanelBatteryParameters(
|
||||
params = GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=10_000,
|
||||
initial_soc_percentage=100,
|
||||
@@ -364,7 +373,7 @@ def test_quarter_hour_discharge_calls_share_one_power_budget():
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=1.0,
|
||||
)
|
||||
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
|
||||
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
|
||||
battery.set_discharge_per_hour(np.ones(4))
|
||||
|
||||
first_delivered, _ = battery.discharge_energy(200.0, 0)
|
||||
@@ -425,12 +434,12 @@ def test_pv_converter_preserves_id_lcos_charge_and_export_rates():
|
||||
levelized_cost_of_storage_amt_kwh=0.123,
|
||||
)
|
||||
assert isinstance(BatteriesCommonSettings.validate_and_sort_charge_rates(None), np.ndarray)
|
||||
parameters = settings.to_genetic_pv_bat_param()
|
||||
parameters = geneticprepare.battery_request(settings)
|
||||
assert parameters.device_id == "house"
|
||||
assert parameters.charge_rates == [0.0, 0.5, 1.0]
|
||||
assert parameters.grid_export_rates == [0.25, 1.0]
|
||||
assert parameters.levelized_cost_of_storage_kwh == pytest.approx(0.123)
|
||||
battery = Battery(parameters, prediction_hours=4, slot_duration_h=0.25)
|
||||
battery = GeneticBattery(parameters.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
|
||||
assert battery.levelized_cost_of_storage_kwh == pytest.approx(0.123)
|
||||
|
||||
|
||||
@@ -439,7 +448,7 @@ def test_equal_soc_limits_are_valid(target):
|
||||
settings = BatteriesCommonSettings(device_id="ev", min_soc_percentage=target,
|
||||
max_soc_percentage=target,
|
||||
profile_adjustment=BatteryProfileAdjustment(nominal_capacity_wh=8000))
|
||||
assert settings.to_genetic_ev_bat_param().min_soc_percentage == target
|
||||
assert geneticprepare.electric_vehicle_request(settings).min_soc_percentage == target
|
||||
assert genetic0prepare.electric_vehicle_request(settings).min_soc_percentage == target
|
||||
|
||||
|
||||
@@ -456,9 +465,9 @@ def test_full_target_charges_to_capacity_without_overcharge():
|
||||
nominal_capacity_wh=1000, max_charge_power_w=1000
|
||||
),
|
||||
min_soc_percentage=100, max_soc_percentage=100)
|
||||
params = settings.to_genetic_ev_bat_param()
|
||||
params = geneticprepare.electric_vehicle_request(settings)
|
||||
params.initial_soc_percentage = 70
|
||||
battery = Battery(params, prediction_hours=4, slot_duration_h=0.25)
|
||||
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
|
||||
battery.charge_array = np.ones(4)
|
||||
for slot in range(4):
|
||||
battery.charge_energy(wh=1000, hour=slot)
|
||||
@@ -470,14 +479,14 @@ def test_full_target_charges_to_capacity_without_overcharge():
|
||||
_EV_CHARGE_RATES = [0.0] + [amps / 16 for amps in range(6, 17)]
|
||||
|
||||
|
||||
def _minimum_current_battery(kind=ElectricVehicleParameters, soc=99, maximum=100):
|
||||
def _minimum_current_battery(kind=GeneticElectricVehicleRequest, soc=99, maximum=100):
|
||||
parameters = kind(
|
||||
device_id="ev-test", capacity_wh=60000,
|
||||
initial_soc_percentage=int(soc), charging_efficiency=0.95,
|
||||
discharging_efficiency=1.0, max_charge_power_w=11040,
|
||||
max_soc_percentage=maximum, charge_rates=_EV_CHARGE_RATES,
|
||||
)
|
||||
value = Battery(parameters, prediction_hours=4, slot_duration_h=0.25)
|
||||
value = GeneticBattery(parameters.to_parameters(), prediction_hours=4, slot_duration_h=0.25)
|
||||
value.reset()
|
||||
value.soc_wh = soc / 100 * value.capacity_wh
|
||||
value.charge_array = np.full(4, 0.375)
|
||||
@@ -514,7 +523,7 @@ class TestEVMinimumCurrent(unittest.TestCase):
|
||||
self.assertAlmostEqual(value.soc_wh, 60000 * 0.96)
|
||||
|
||||
def test_stationary_battery_keeps_discrete_rate_behavior(self):
|
||||
value = _minimum_current_battery(SolarPanelBatteryParameters, soc=99)
|
||||
value = _minimum_current_battery(GeneticBatteryRequest, soc=99)
|
||||
self.assertEqual(value.charge_energy(None, 0, charge_factor=0.375), (0.0, 0.0))
|
||||
self.assertEqual(value.soc_wh, 59400)
|
||||
self.assertEqual(value.charge_array[0], 0)
|
||||
@@ -538,7 +547,7 @@ class TestMaxDischargePower:
|
||||
|
||||
@staticmethod
|
||||
def _battery(max_discharge_power_w=None, slot_duration_h=1.0):
|
||||
params = SolarPanelBatteryParameters(
|
||||
params = GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=10_000,
|
||||
initial_soc_percentage=100,
|
||||
@@ -548,7 +557,7 @@ class TestMaxDischargePower:
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=1.0,
|
||||
)
|
||||
battery = Battery(params, prediction_hours=4, slot_duration_h=slot_duration_h)
|
||||
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=slot_duration_h)
|
||||
battery.set_discharge_per_hour(np.ones(4))
|
||||
return battery
|
||||
|
||||
@@ -584,7 +593,7 @@ class TestMaxDischargePower:
|
||||
|
||||
def test_negative_is_rejected(self):
|
||||
with pytest.raises(ValidationError):
|
||||
SolarPanelBatteryParameters(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1", capacity_wh=10_000, max_discharge_power_w=-1
|
||||
)
|
||||
|
||||
@@ -598,7 +607,7 @@ class TestMaxDischargePower:
|
||||
settings = BatteriesCommonSettings(
|
||||
device_id="battery1", profile_adjustment=BatteryProfileAdjustment(nominal_capacity_wh=8_000)
|
||||
)
|
||||
parameters = getattr(settings, converter)()
|
||||
parameters = getattr(geneticprepare, CONVERSIONS[converter])(settings)
|
||||
assert parameters.max_charge_power_w == pytest.approx(5_000.0)
|
||||
assert parameters.max_discharge_power_w == pytest.approx(4_000.0)
|
||||
|
||||
@@ -611,7 +620,7 @@ class TestMaxDischargePower:
|
||||
nominal_capacity_wh=8_000, max_charge_power_w=10_000, max_discharge_power_w=10_000
|
||||
),
|
||||
)
|
||||
parameters = getattr(settings, converter)()
|
||||
parameters = getattr(geneticprepare, CONVERSIONS[converter])(settings)
|
||||
assert parameters.max_charge_power_w == pytest.approx(8_000.0)
|
||||
assert parameters.max_discharge_power_w == pytest.approx(4_000.0)
|
||||
|
||||
@@ -621,7 +630,7 @@ class TestPowerCurves:
|
||||
|
||||
@staticmethod
|
||||
def _battery(soc_percentage=50, slot_duration_h=1.0, **curves):
|
||||
params = SolarPanelBatteryParameters(
|
||||
params = GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=10_000,
|
||||
initial_soc_percentage=soc_percentage,
|
||||
@@ -633,7 +642,7 @@ class TestPowerCurves:
|
||||
discharging_efficiency=1.0,
|
||||
**curves,
|
||||
)
|
||||
battery = Battery(params, prediction_hours=4, slot_duration_h=slot_duration_h)
|
||||
battery = GeneticBattery(params.to_parameters(), prediction_hours=4, slot_duration_h=slot_duration_h)
|
||||
battery.set_charge_per_hour(np.ones(4))
|
||||
battery.set_discharge_per_hour(np.ones(4))
|
||||
return battery
|
||||
@@ -760,7 +769,7 @@ class TestPowerCurves:
|
||||
)
|
||||
def test_invalid_curves_are_rejected(self, field, value):
|
||||
with pytest.raises(ValidationError):
|
||||
SolarPanelBatteryParameters(device_id="battery1", capacity_wh=10_000, **{field: value})
|
||||
GeneticBatteryRequest(device_id="battery1", capacity_wh=10_000, **{field: value})
|
||||
|
||||
|
||||
class TestFirstSlotFraction:
|
||||
@@ -768,7 +777,7 @@ class TestFirstSlotFraction:
|
||||
|
||||
@staticmethod
|
||||
def _battery(first_slot_fraction=1.0, soc=50, **curves):
|
||||
params = SolarPanelBatteryParameters(
|
||||
params = GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=40_000,
|
||||
initial_soc_percentage=soc,
|
||||
@@ -780,8 +789,8 @@ class TestFirstSlotFraction:
|
||||
discharging_efficiency=1.0,
|
||||
**curves,
|
||||
)
|
||||
battery = Battery(
|
||||
params, prediction_hours=4, slot_duration_h=1.0, first_slot_fraction=first_slot_fraction
|
||||
battery = GeneticBattery(
|
||||
params.to_parameters(), prediction_hours=4, slot_duration_h=1.0, first_slot_fraction=first_slot_fraction
|
||||
)
|
||||
battery.set_charge_per_hour(np.ones(4))
|
||||
battery.set_discharge_per_hour(np.ones(4))
|
||||
@@ -810,7 +819,7 @@ class TestFirstSlotFraction:
|
||||
|
||||
def test_full_fraction_is_the_plain_slot(self):
|
||||
partial = self._battery(first_slot_fraction=1.0)
|
||||
plain = Battery(partial.parameters, prediction_hours=4, slot_duration_h=1.0)
|
||||
plain = GeneticBattery(partial.parameters, prediction_hours=4, slot_duration_h=1.0)
|
||||
plain.set_charge_per_hour(np.ones(4))
|
||||
assert partial.charge_energy(None, 0, charge_factor=1.0) == plain.charge_energy(
|
||||
None, 0, charge_factor=1.0
|
||||
|
||||
@@ -8,12 +8,12 @@ from unittest.mock import AsyncMock, MagicMock, Mock
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from conftest import genetic_optimization
|
||||
from pydantic import ValidationError
|
||||
|
||||
from akkudoktoreos.config.config import ConfigEOS
|
||||
from akkudoktoreos.core.cache import CacheEnergyManagementStore
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
|
||||
from akkudoktoreos.devices.profile.batteryprofile import BatteryProfileSettings
|
||||
from akkudoktoreos.devices.profile.batteryprofileruntime import BatteryProfile
|
||||
from akkudoktoreos.devices.profile.profilestore import get_profile_store
|
||||
@@ -26,19 +26,35 @@ from akkudoktoreos.devices.settings.batterysettings import (
|
||||
BatteriesCommonSettings,
|
||||
BatteryProfileAdjustment,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic import configrequest
|
||||
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
|
||||
from akkudoktoreos.optimization.genetic.fullcharge import (
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticfullcharge import (
|
||||
FULL_CHARGE_MIN_LEAD_HOURS,
|
||||
enforced_full_charge_deadline,
|
||||
full_charge_deadline,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticOptimizationParameters,
|
||||
GeneticRequest,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
# Run start and observation time of the run the tests prepare; the fixture sets them.
|
||||
RUN = SimpleNamespace(ems=None)
|
||||
|
||||
|
||||
async def resolve(request: GeneticRequest, warm_start: Any = None) -> GeneticOptimizationParameters:
|
||||
"""Prepare ``request`` at the run start and observation time of ``RUN.ems``."""
|
||||
return await geneticprepare.resolve_request(
|
||||
request, RUN.ems.start_datetime, RUN.ems.observation_datetime, warm_start
|
||||
)
|
||||
|
||||
ems_eos = get_ems(init=True) # init once
|
||||
|
||||
NOW = to_datetime("2026-11-20T12:00:00+01:00")
|
||||
@@ -206,7 +222,7 @@ def test_resolve_full_charge_caps_target_and_threshold(config_eos):
|
||||
|
||||
def test_parameters_reject_target_above_max_soc():
|
||||
with pytest.raises(ValidationError):
|
||||
SolarPanelBatteryParameters(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=10000,
|
||||
max_soc_percentage=90,
|
||||
@@ -215,7 +231,7 @@ def test_parameters_reject_target_above_max_soc():
|
||||
|
||||
|
||||
def test_parameters_parse_naive_deadline_as_local_time():
|
||||
parameters = SolarPanelBatteryParameters.model_validate(
|
||||
parameters = GeneticBatteryRequest.model_validate(
|
||||
{
|
||||
"device_id": "battery1",
|
||||
"capacity_wh": 10000,
|
||||
@@ -226,6 +242,26 @@ def test_parameters_parse_naive_deadline_as_local_time():
|
||||
assert parameters.full_charge_deadline_datetime == to_datetime("2026-11-21T07:00:00")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host_timezone", ["UTC", "Europe/Berlin", "America/New_York"])
|
||||
@pytest.mark.parametrize("deadline_timezone", ["UTC", "Asia/Tokyo"])
|
||||
def test_parameters_hold_the_deadline_in_utc(
|
||||
set_other_timezone, host_timezone, deadline_timezone
|
||||
):
|
||||
set_other_timezone(host_timezone)
|
||||
deadline = to_datetime("2026-11-21T07:00:00", in_timezone=deadline_timezone)
|
||||
parameters = GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=10000,
|
||||
full_charge_soc_percentage=100,
|
||||
full_charge_deadline_datetime=deadline,
|
||||
)
|
||||
assert parameters.full_charge_deadline_datetime == deadline
|
||||
assert parameters.full_charge_deadline_datetime.timezone_name == "UTC"
|
||||
# The serialized deadline reads back the same.
|
||||
dumped = parameters.model_dump(mode="json")
|
||||
assert GeneticBatteryRequest.model_validate(dumped).model_dump(mode="json") == dumped
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Resolving the configuration
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -272,12 +308,10 @@ def full_charge_request(config_eos, monkeypatch):
|
||||
}
|
||||
)
|
||||
start = to_datetime("2026-09-12T10:15:00Z", in_timezone="UTC")
|
||||
ems = SimpleNamespace(
|
||||
start_datetime=start, observation_datetime=start, genetic_solution=lambda: None
|
||||
)
|
||||
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
|
||||
ems = SimpleNamespace(start_datetime=start, observation_datetime=start)
|
||||
monkeypatch.setattr(RUN, "ems", ems)
|
||||
measurement = Mock(key_to_lists=AsyncMock(return_value=([], [])))
|
||||
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", measurement)
|
||||
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=measurement))
|
||||
data = {
|
||||
"soc": {"storage": 40},
|
||||
"forecasts": {
|
||||
@@ -302,7 +336,7 @@ async def test_cold_battery_does_not_cancel_the_request(full_charge_request, mon
|
||||
|
||||
monkeypatch.setattr(BatteriesCommonSettings, "measure_operating_point", cold)
|
||||
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.max_charge_power_w == 0.0
|
||||
@@ -324,7 +358,7 @@ async def test_hot_inverter_does_not_cancel_the_request(full_charge_request, mon
|
||||
|
||||
monkeypatch.setattr(InverterCommonSettings, "measure_operating_point", hot)
|
||||
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
|
||||
assert parameters.inverter is not None
|
||||
assert parameters.inverter.max_power_wh > 0.0
|
||||
@@ -343,7 +377,7 @@ def _history(start: DateTime, full_days_ago: Optional[float]) -> tuple[list[Date
|
||||
async def test_feature_disabled_reads_no_history(full_charge_request):
|
||||
config, _, measurement, data = full_charge_request
|
||||
config.devices.batteries["storage"].profile_adjustment.full_charge_interval_days = None
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.max_soc_percentage == 90
|
||||
assert parameters.pv_battery.full_charge_soc_percentage is None
|
||||
@@ -354,7 +388,7 @@ async def test_feature_disabled_reads_no_history(full_charge_request):
|
||||
async def test_not_due_within_horizon_leaves_battery_unchanged(full_charge_request):
|
||||
_, start, measurement, data = full_charge_request
|
||||
measurement.key_to_lists.return_value = _history(start, full_days_ago=5)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.max_soc_percentage == 90
|
||||
assert parameters.pv_battery.full_charge_soc_percentage is None
|
||||
@@ -369,7 +403,7 @@ async def test_not_due_within_horizon_leaves_battery_unchanged(full_charge_reque
|
||||
async def test_due_without_grid_only_raises_the_maximum(full_charge_request):
|
||||
_, start, measurement, data = full_charge_request
|
||||
measurement.key_to_lists.return_value = _history(start, full_days_ago=20.5)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.max_soc_percentage == 100
|
||||
assert parameters.pv_battery.full_charge_soc_percentage is None
|
||||
@@ -381,7 +415,7 @@ async def test_due_with_grid_enforces_target_and_deadline(full_charge_request):
|
||||
config, start, measurement, data = full_charge_request
|
||||
config.devices.batteries["storage"].full_charge_allow_grid = True
|
||||
measurement.key_to_lists.return_value = _history(start, full_days_ago=None)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.max_soc_percentage == 100
|
||||
assert parameters.pv_battery.full_charge_soc_percentage == 100
|
||||
@@ -400,7 +434,7 @@ async def test_overdue_full_charge_is_due_with_a_horizon_shorter_than_the_lead_t
|
||||
config.merge_settings_from_dict({"optimization": {"genetic": {"horizon_hours": 12}}})
|
||||
config.devices.batteries["storage"].full_charge_allow_grid = True
|
||||
measurement.key_to_lists.return_value = _history(start, full_days_ago=None)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.max_soc_percentage == 100
|
||||
assert parameters.pv_battery.full_charge_soc_percentage == 100
|
||||
@@ -414,7 +448,7 @@ async def test_missing_history_does_not_schedule_a_full_charge(full_charge_reque
|
||||
config, _, measurement, data = full_charge_request
|
||||
config.devices.batteries["storage"].full_charge_allow_grid = True
|
||||
measurement.key_to_lists.side_effect = KeyError("storage-soc-factor")
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.max_soc_percentage == 90
|
||||
assert parameters.pv_battery.full_charge_soc_percentage is None
|
||||
@@ -430,7 +464,7 @@ async def test_profile_interval_schedules_the_full_charge(full_charge_request, m
|
||||
profile = _profile(full_charge_interval_days=21.0)
|
||||
monkeypatch.setattr(BatteriesCommonSettings, "get_battery_profile", lambda self: profile)
|
||||
measurement.key_to_lists.return_value = _history(start, full_days_ago=None)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.max_soc_percentage == 100
|
||||
assert parameters.pv_battery.full_charge_soc_percentage == 100
|
||||
@@ -443,7 +477,7 @@ async def test_full_charge_target_stays_within_technical_bounds(full_charge_requ
|
||||
profile = _profile(technical_max_soc_percent=95.0)
|
||||
monkeypatch.setattr(BatteriesCommonSettings, "get_battery_profile", lambda self: profile)
|
||||
measurement.key_to_lists.return_value = _history(start, full_days_ago=None)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.max_soc_percentage == 95
|
||||
assert parameters.pv_battery.full_charge_soc_percentage == 95
|
||||
@@ -511,8 +545,8 @@ def _full_charge_parameters(hours: int, **battery_extra) -> GeneticOptimizationP
|
||||
def test_full_charge_slot_resolution(config_eos: ConfigEOS):
|
||||
_optimizer_config(config_eos, 24)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
|
||||
optimization = GeneticOptimization(fixed_seed=1)
|
||||
optimization._slot0_datetime = optimization.ems.start_datetime
|
||||
optimization = genetic_optimization(seed=1)
|
||||
optimization._slot0_datetime = optimization.settings.start_datetime
|
||||
slot0 = optimization._slot0_datetime
|
||||
|
||||
assert optimization._full_charge_slot(_full_charge_parameters(24)) is None
|
||||
@@ -531,8 +565,8 @@ def test_full_charge_slot_resolution(config_eos: ConfigEOS):
|
||||
def test_maximum_soc_before_deadline_counts(config_eos: ConfigEOS):
|
||||
_optimizer_config(config_eos, 24)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
|
||||
optimization = GeneticOptimization(fixed_seed=1)
|
||||
optimization.simulation.battery = MagicMock(spec=Battery)
|
||||
optimization = genetic_optimization(seed=1)
|
||||
optimization.simulation.battery = MagicMock(spec=GeneticBattery)
|
||||
optimization.simulation.battery.current_soc_percentage.return_value = 40.0
|
||||
result = {"akku_soc_pro_stunde": [30.0, 100.0, 60.0, 50.0]}
|
||||
|
||||
@@ -557,7 +591,7 @@ def _run(config_eos: ConfigEOS, **battery_extra) -> list[float]:
|
||||
_optimizer_config(config_eos, hours)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=0, minute=0, second=0, microsecond=0))
|
||||
CacheEnergyManagementStore().clear()
|
||||
solution = GeneticOptimization(fixed_seed=42).optimize_ems(
|
||||
solution = genetic_optimization(seed=42).optimize_ems(
|
||||
parameters=_full_charge_parameters(hours, **battery_extra), start_hour=0, ngen=40
|
||||
)
|
||||
return list(solution.result.battery_soc_per_hour)
|
||||
|
||||
@@ -10,30 +10,37 @@ from akkudoktoreos.devices.devicesabc import (
|
||||
ConsumerDeadlinePolicy,
|
||||
ConsumerScheduleMode,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.battery import Battery, ElectricVehicleParameters
|
||||
from akkudoktoreos.devices.genetic.homeappliance import (
|
||||
HomeAppliance,
|
||||
HomeApplianceParameters,
|
||||
resample_power_to_slot_energy,
|
||||
)
|
||||
from akkudoktoreos.devices.settings.batterysettings import BatteriesCommonSettings
|
||||
from akkudoktoreos.devices.settings.homeappliancesettings import (
|
||||
HomeApplianceCommonSettings,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic0 import genetic0prepare
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticDeadlinePolicy,
|
||||
GeneticHomeAppliance,
|
||||
resample_power_to_slot_energy,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticElectricVehicleRequest,
|
||||
GeneticHomeApplianceRequest,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
|
||||
def appliance(*, slots: int = 192, slot_h: float = 0.25, **kwargs: Any) -> HomeAppliance:
|
||||
return HomeAppliance(
|
||||
HomeApplianceParameters.model_validate(
|
||||
def appliance(*, slots: int = 192, slot_h: float = 0.25, **kwargs: Any) -> GeneticHomeAppliance:
|
||||
return GeneticHomeAppliance(
|
||||
GeneticHomeApplianceRequest.model_validate(
|
||||
{
|
||||
"device_id": "washer",
|
||||
"load_profile_power_w": [1200.0, 600.0, 300.0],
|
||||
"load_profile_interval_seconds": 600,
|
||||
**kwargs,
|
||||
}
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=48,
|
||||
prediction_hours=slots,
|
||||
slot_duration_h=slot_h,
|
||||
@@ -58,7 +65,7 @@ def test_profile_energy_independent_of_slot_grid(input_s: int, slot_s: int) -> N
|
||||
|
||||
@pytest.mark.parametrize("profile", [[], [-1], [float("nan")], [float("inf")]])
|
||||
def test_invalid_profiles_rejected_in_parameters_and_settings(profile: list[float]) -> None:
|
||||
for model in (HomeApplianceParameters, HomeApplianceCommonSettings):
|
||||
for model in (GeneticHomeApplianceRequest, HomeApplianceCommonSettings):
|
||||
with pytest.raises(ValidationError):
|
||||
model.model_validate({"device_id": "bad", "load_profile_power_w": profile})
|
||||
|
||||
@@ -67,14 +74,14 @@ def test_invalid_profiles_rejected_in_parameters_and_settings(profile: list[floa
|
||||
"fields", [{"duration_h": 2}, {"consumption_wh": 500}, {"duration_h": 2, "consumption_wh": 500}]
|
||||
)
|
||||
def test_profile_cannot_silently_override_explicit_flat_definition(fields: dict[str, int]) -> None:
|
||||
for model in (HomeApplianceParameters, HomeApplianceCommonSettings):
|
||||
for model in (GeneticHomeApplianceRequest, HomeApplianceCommonSettings):
|
||||
with pytest.raises(ValidationError, match="Conflicting"):
|
||||
model.model_validate({"device_id": "bad", "load_profile_power_w": [100.0], **fields})
|
||||
|
||||
|
||||
def test_settings_profile_roundtrip_and_legacy_defaults() -> None:
|
||||
defaults = HomeApplianceCommonSettings(device_id="legacy")
|
||||
assert defaults.to_genetic_param().consumption_wh == 3000
|
||||
assert geneticprepare.home_appliance_request(defaults).consumption_wh == 3000
|
||||
assert genetic0prepare.home_appliance_request(defaults).duration_h == 3
|
||||
settings = HomeApplianceCommonSettings.model_validate(
|
||||
{
|
||||
@@ -88,7 +95,7 @@ def test_settings_profile_roundtrip_and_legacy_defaults() -> None:
|
||||
}
|
||||
)
|
||||
restored = HomeApplianceCommonSettings.model_validate_json(settings.model_dump_json())
|
||||
params = restored.to_genetic_param()
|
||||
params = geneticprepare.home_appliance_request(restored)
|
||||
assert params.load_profile_power_w == [1200.0, 600.0]
|
||||
assert params.consumption_wh is None and params.duration_h is None
|
||||
assert params.num_cycles == 2 and params.min_cycle_gap_h == 1
|
||||
@@ -114,10 +121,10 @@ def test_cycle_and_shared_windows_intersect_after_completed_cycle() -> None:
|
||||
"time_windows": {"windows": [{"start_time": "18:30", "duration": "1 hour"}]},
|
||||
}
|
||||
)
|
||||
device = HomeAppliance(settings.to_genetic_param(), 48, 192, 0.25)
|
||||
device = GeneticHomeAppliance(geneticprepare.home_appliance_request(settings).to_parameters(), 48, 192, 0.25)
|
||||
device.set_completed_cycles(1)
|
||||
zero = to_datetime("2026-09-16T00:00:00+02:00", in_timezone="Europe/Berlin")
|
||||
assert device.remaining_cycle_indices == [1]
|
||||
assert device.num_remaining_cycles == 1
|
||||
assert device.allowed_start_slots(
|
||||
slot0_datetime=zero, earliest_slot=0, horizon_end_slot=96, cycle_index=1
|
||||
) == [74, 75, 76]
|
||||
@@ -133,12 +140,6 @@ def test_cycle_and_shared_windows_intersect_after_completed_cycle() -> None:
|
||||
) == [170, 171, 172]
|
||||
|
||||
|
||||
def test_legacy_multiple_cycles_use_slots_and_physical_idle_gap() -> None:
|
||||
device = appliance(slots=96, num_cycles=2, min_cycle_gap_h=1)
|
||||
assert device.set_starting_times([4, 4]) == [4, 10]
|
||||
assert device.get_load_curve().sum() == pytest.approx(700)
|
||||
|
||||
|
||||
def test_touching_cycle_windows_preserve_union() -> None:
|
||||
device = appliance(
|
||||
time_windows={
|
||||
@@ -180,7 +181,7 @@ def test_best_effort_relaxes_only_deadline_not_window_or_earliest() -> None:
|
||||
slot0_datetime=zero, earliest_slot=0, horizon_end_slot=96
|
||||
) == [36]
|
||||
assert device.deadline_relaxed and device.deadline_missed([36], zero)
|
||||
device.deadline_policy = ConsumerDeadlinePolicy.STRICT
|
||||
device.deadline_policy = GeneticDeadlinePolicy.STRICT
|
||||
assert (
|
||||
device.allowed_start_slots(slot0_datetime=zero, earliest_slot=0, horizon_end_slot=96) == []
|
||||
)
|
||||
@@ -233,13 +234,13 @@ def test_ev_deadlines_roundtrip_without_changing_slot_physics() -> None:
|
||||
"min_soc_max_duration_h": 2.5,
|
||||
}
|
||||
)
|
||||
params = settings.to_genetic_ev_bat_param()
|
||||
params = geneticprepare.electric_vehicle_request(settings)
|
||||
assert params.min_soc_max_duration_h == 2.5
|
||||
assert params.min_soc_deadline_datetime is not None
|
||||
assert params.min_soc_deadline_datetime.in_timezone("Europe/Berlin").hour == 7
|
||||
assert params.capacity_wh == 10000
|
||||
assert params.max_charge_power_w == pytest.approx(4000)
|
||||
battery = Battery(params, prediction_hours=16, slot_duration_h=0.25)
|
||||
battery = GeneticBattery(params.to_parameters(), prediction_hours=16, slot_duration_h=0.25)
|
||||
battery.charge_array[0] = 1
|
||||
# 4000 W for a 0.25 h slot caps the 2000 Wh request at 1000 Wh; the charging
|
||||
# efficiency comes from the battery profile.
|
||||
@@ -253,20 +254,19 @@ def test_ev_deadlines_roundtrip_without_changing_slot_physics() -> None:
|
||||
def test_ev_invalid_departure_durations_rejected(duration: float) -> None:
|
||||
# Optimizer parameters take "capacity_wh", settings a profile adjustment.
|
||||
for model, capacity in (
|
||||
(ElectricVehicleParameters, {"capacity_wh": 10000}),
|
||||
(GeneticElectricVehicleRequest, {"capacity_wh": 10000}),
|
||||
(BatteriesCommonSettings, {"profile_adjustment": {"nominal_capacity_wh": 10000}}),
|
||||
):
|
||||
with pytest.raises(ValidationError):
|
||||
model.model_validate({"device_id": "car", **capacity, "min_soc_max_duration_h": duration})
|
||||
|
||||
|
||||
def test_completed_cycles_parameter_initializes_remaining_global_ids() -> None:
|
||||
def test_completed_cycles_parameter_initializes_remaining_cycles() -> None:
|
||||
device = appliance(num_cycles=3, completed_cycles=2)
|
||||
assert device.completed_cycles == 2
|
||||
assert device.remaining_cycle_indices == [2]
|
||||
assert device.num_remaining_cycles == 1
|
||||
done = appliance(num_cycles=3, completed_cycles=3)
|
||||
assert done.remaining_cycle_indices == []
|
||||
assert done.num_remaining_cycles == 0
|
||||
with pytest.raises(ValidationError, match="completed_cycles"):
|
||||
appliance(num_cycles=2, completed_cycles=3)
|
||||
|
||||
@@ -296,3 +296,35 @@ def test_absolute_deadline_offsets_describe_same_instant(deadline: str) -> None:
|
||||
) == [0, 1, 2]
|
||||
assert not device.deadline_missed([2], zero)
|
||||
assert device.deadline_missed([3], zero)
|
||||
|
||||
|
||||
APPLIANCE_REQUEST: dict[str, Any] = {
|
||||
"device_id": "dishwasher",
|
||||
"consumption_wh": 2000,
|
||||
"duration_h": 2,
|
||||
"num_cycles": 1,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host_timezone", ["Europe/Berlin", "America/New_York"])
|
||||
@pytest.mark.parametrize(
|
||||
"model, field, request_data",
|
||||
[
|
||||
(GeneticElectricVehicleRequest, "min_soc_deadline_datetime", {"device_id": "car", "capacity_wh": 10000}),
|
||||
(GeneticHomeApplianceRequest, "earliest_start_datetime", APPLIANCE_REQUEST),
|
||||
(GeneticHomeApplianceRequest, "deadline_datetime", APPLIANCE_REQUEST),
|
||||
(GeneticHomeApplianceRequest, "run_started_datetime", APPLIANCE_REQUEST),
|
||||
],
|
||||
)
|
||||
def test_request_date_times_are_held_in_utc(
|
||||
set_other_timezone, host_timezone, model, field, request_data
|
||||
) -> None:
|
||||
"""Request date-times render the same on every host and read back the same."""
|
||||
set_other_timezone(host_timezone)
|
||||
moment = to_datetime("2026-09-16T09:30:00", in_timezone="Asia/Tokyo")
|
||||
request = model.model_validate({**request_data, field: moment})
|
||||
assert getattr(request, field) == moment
|
||||
assert getattr(request, field).timezone_name == "UTC"
|
||||
dumped = request.model_dump(mode="json")
|
||||
assert dumped[field] == "2026-09-16T00:30:00Z"
|
||||
assert model.model_validate(dumped).model_dump(mode="json") == dumped
|
||||
|
||||
@@ -3,16 +3,19 @@ from typing import Optional
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from conftest import genetic_optimization
|
||||
|
||||
from akkudoktoreos.config.config import ConfigEOS
|
||||
from akkudoktoreos.core.cache import CacheEnergyManagementStore
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.devices.genetic.battery import Battery
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import GeneticBattery
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
ems_eos = get_ems(init=True) # init once
|
||||
@@ -39,7 +42,7 @@ def test_direct_marketing_preserves_constant_supplied_feed_in_tariff(config_eos:
|
||||
)
|
||||
)
|
||||
|
||||
adjusted = GeneticOptimization()._parameters_for_config(parameters)
|
||||
adjusted = genetic_optimization()._parameters_for_config(parameters)
|
||||
|
||||
assert adjusted.ems.einspeiseverguetung_euro_pro_wh == [0.00007, 0.00007]
|
||||
assert parameters.ems.einspeiseverguetung_euro_pro_wh == [0.00007, 0.00007]
|
||||
@@ -62,7 +65,7 @@ def test_direct_marketing_keeps_variable_feed_in_tariff(config_eos: ConfigEOS):
|
||||
)
|
||||
)
|
||||
|
||||
adjusted = GeneticOptimization()._parameters_for_config(parameters)
|
||||
adjusted = genetic_optimization()._parameters_for_config(parameters)
|
||||
|
||||
assert adjusted.ems.einspeiseverguetung_euro_pro_wh == [0.0001, -0.00005]
|
||||
|
||||
@@ -120,7 +123,7 @@ def test_grid_export_rates_reach_the_solution(config_eos: ConfigEOS):
|
||||
)
|
||||
)
|
||||
|
||||
optimization = GeneticOptimization(fixed_seed=42)
|
||||
optimization = genetic_optimization(seed=42)
|
||||
solution = optimization.optimize_ems(parameters=parameters, start_hour=0, ngen=3)
|
||||
|
||||
# Full power first, so the full-power state keeps the lowest export index.
|
||||
@@ -173,8 +176,8 @@ def test_ev_deadline_slot_resolution(config_eos: ConfigEOS):
|
||||
}
|
||||
)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0, second=0, microsecond=0))
|
||||
optimization = GeneticOptimization(fixed_seed=1)
|
||||
optimization._slot0_datetime = optimization.ems.start_datetime
|
||||
optimization = genetic_optimization(seed=1)
|
||||
optimization._slot0_datetime = optimization.settings.start_datetime
|
||||
slot0 = optimization._slot0_datetime
|
||||
|
||||
# Duration only: 6 h after the start hour 10.
|
||||
@@ -214,10 +217,10 @@ def test_ev_soc_penalty_reads_the_deadline_slot(config_eos: ConfigEOS):
|
||||
}
|
||||
)
|
||||
ems_eos.set_start_datetime(to_datetime().set(hour=10, minute=0, second=0, microsecond=0))
|
||||
optimization = GeneticOptimization(fixed_seed=1)
|
||||
optimization = genetic_optimization(seed=1)
|
||||
simulation_result = {"EAuto_SoC_pro_Stunde": [20.0, 35.0, 50.0, 80.0]}
|
||||
|
||||
optimization.simulation.ev = MagicMock(spec=Battery)
|
||||
optimization.simulation.ev = MagicMock(spec=GeneticBattery)
|
||||
optimization.simulation.ev.current_soc_percentage.return_value = 80.0
|
||||
|
||||
# Without a deadline the final SoC counts.
|
||||
@@ -254,7 +257,7 @@ def test_ev_deadline_charges_before_departure(config_eos: ConfigEOS):
|
||||
CacheEnergyManagementStore().clear()
|
||||
|
||||
parameters = _ev_deadline_parameters(hours, min_soc_max_duration_h=6)
|
||||
solution = GeneticOptimization(fixed_seed=42).optimize_ems(
|
||||
solution = genetic_optimization(seed=42).optimize_ems(
|
||||
parameters=parameters, start_hour=0, ngen=40
|
||||
)
|
||||
|
||||
@@ -266,7 +269,7 @@ def test_ev_deadline_charges_before_departure(config_eos: ConfigEOS):
|
||||
|
||||
def _terminal_value_run(
|
||||
config_eos: ConfigEOS, mode: str, prices: Optional[list[float]] = None
|
||||
) -> GeneticSolution:
|
||||
) -> GeneticResult:
|
||||
"""48 h with expensive energy and two dirt-cheap slots at the very end.
|
||||
|
||||
Charging in those last slots only pays off when the stored energy keeps a
|
||||
@@ -324,7 +327,7 @@ def _terminal_value_run(
|
||||
ev=None,
|
||||
)
|
||||
)
|
||||
return GeneticOptimization(fixed_seed=7).optimize_ems(
|
||||
return genetic_optimization(seed=7).optimize_ems(
|
||||
parameters=parameters, start_hour=0, ngen=20
|
||||
)
|
||||
|
||||
|
||||
@@ -3,19 +3,24 @@ from unittest.mock import Mock
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
Battery,
|
||||
ElectricVehicleParameters,
|
||||
SolarPanelBatteryParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.homeappliance import (
|
||||
HomeAppliance,
|
||||
HomeApplianceParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticEnergyManagementParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticElectricVehicleRequest,
|
||||
GeneticEnergyManagementRequest,
|
||||
GeneticHomeApplianceRequest,
|
||||
GeneticInverterRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsimulation import (
|
||||
GeneticSimulation,
|
||||
)
|
||||
|
||||
start_hour = 1
|
||||
@@ -36,42 +41,42 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
|
||||
assert config_eos.optimization.genetic.horizon_hours == 24
|
||||
|
||||
# Initialize the battery and the inverter
|
||||
akku = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
akku = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
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 = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=akku,
|
||||
)
|
||||
|
||||
# Flexible consumer (fixed start at slot 2 for this deterministic test)
|
||||
home_appliance = HomeAppliance(
|
||||
HomeApplianceParameters(
|
||||
home_appliance = GeneticHomeAppliance(
|
||||
GeneticHomeApplianceRequest(
|
||||
device_id="dishwasher1",
|
||||
consumption_wh=2000,
|
||||
duration_h=2,
|
||||
time_windows=None,
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=config_eos.optimization.genetic.horizon_hours,
|
||||
prediction_hours=config_eos.prediction.hours,
|
||||
)
|
||||
home_appliance.build_load_curve([2])
|
||||
|
||||
# Example initialization of electric car battery
|
||||
eauto = Battery(
|
||||
ElectricVehicleParameters(
|
||||
eauto = GeneticBattery(
|
||||
GeneticElectricVehicleRequest(
|
||||
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))
|
||||
@@ -236,7 +241,7 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
|
||||
# Initialize the energy management system with the respective parameters
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(
|
||||
GeneticEnergyManagementRequest.model_validate(
|
||||
dict(
|
||||
pv_prognose_wh=pv_prognose_wh,
|
||||
strompreis_euro_pro_wh=strompreis_euro_pro_wh,
|
||||
@@ -244,7 +249,7 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
|
||||
preis_euro_pro_wh_akku=preis_euro_pro_wh_akku,
|
||||
gesamtlast=gesamtlast,
|
||||
)
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=config_eos.optimization.genetic.horizon_hours,
|
||||
prediction_hours=config_eos.prediction.hours,
|
||||
inverter=inverter,
|
||||
@@ -273,21 +278,21 @@ def test_ev_charging_uses_raw_input_energy_for_load_and_grid(config_eos):
|
||||
"optimization": {"genetic": {"tail_horizon_hours": 0, "horizon_hours": 1}},
|
||||
}
|
||||
)
|
||||
ev = Battery(
|
||||
ElectricVehicleParameters(
|
||||
ev = GeneticBattery(
|
||||
GeneticElectricVehicleRequest(
|
||||
device_id="ev1",
|
||||
capacity_wh=1000,
|
||||
charging_efficiency=0.8,
|
||||
max_charge_power_w=100,
|
||||
initial_soc_percentage=0,
|
||||
min_soc_percentage=0,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=1,
|
||||
)
|
||||
inverter = Inverter(InverterParameters(device_id="inverter1", max_power_wh=1000.0))
|
||||
inverter = GeneticInverter(GeneticInverterRequest(device_id="inverter1", max_power_wh=1000.0).to_parameters())
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(
|
||||
GeneticEnergyManagementRequest.model_validate(
|
||||
dict(
|
||||
pv_prognose_wh=[0.0],
|
||||
strompreis_euro_pro_wh=[0.001],
|
||||
@@ -295,7 +300,7 @@ def test_ev_charging_uses_raw_input_energy_for_load_and_grid(config_eos):
|
||||
preis_euro_pro_wh_akku=0.0,
|
||||
gesamtlast=[0.0],
|
||||
)
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=1,
|
||||
prediction_hours=1,
|
||||
inverter=inverter,
|
||||
@@ -320,7 +325,7 @@ def test_direct_marketing_curtails_negative_feed_in(config_eos, monkeypatch):
|
||||
}
|
||||
)
|
||||
|
||||
inverter = Inverter(InverterParameters(device_id="inverter1", max_power_wh=1000.0))
|
||||
inverter = GeneticInverter(GeneticInverterRequest(device_id="inverter1", max_power_wh=1000.0).to_parameters())
|
||||
monkeypatch.setattr(
|
||||
inverter.self_consumption_predictor,
|
||||
"calculate_expected_direct_consumption",
|
||||
@@ -329,7 +334,7 @@ def test_direct_marketing_curtails_negative_feed_in(config_eos, monkeypatch):
|
||||
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(
|
||||
GeneticEnergyManagementRequest.model_validate(
|
||||
dict(
|
||||
pv_prognose_wh=[500.0, 500.0],
|
||||
strompreis_euro_pro_wh=[-0.0001, -0.0001],
|
||||
@@ -337,7 +342,7 @@ def test_direct_marketing_curtails_negative_feed_in(config_eos, monkeypatch):
|
||||
preis_euro_pro_wh_akku=0.0,
|
||||
gesamtlast=[0.0, 0.0],
|
||||
)
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=config_eos.optimization.genetic.horizon_hours,
|
||||
prediction_hours=config_eos.prediction.hours,
|
||||
inverter=inverter,
|
||||
@@ -363,8 +368,8 @@ def _direct_marketing_battery_export_simulation(
|
||||
}
|
||||
)
|
||||
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=1000,
|
||||
initial_soc_percentage=100,
|
||||
@@ -373,22 +378,22 @@ def _direct_marketing_battery_export_simulation(
|
||||
discharging_efficiency=1.0,
|
||||
levelized_cost_of_storage_kwh=levelized_cost_of_storage_kwh,
|
||||
max_charge_power_w=500,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=config_eos.prediction.hours,
|
||||
)
|
||||
inverter = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=500.0,
|
||||
battery_id=battery.parameters.device_id,
|
||||
dc_to_ac_efficiency=dc_to_ac_efficiency,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
)
|
||||
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(
|
||||
GeneticEnergyManagementRequest.model_validate(
|
||||
dict(
|
||||
pv_prognose_wh=[0.0, 0.0],
|
||||
strompreis_euro_pro_wh=[0.0, 0.0],
|
||||
@@ -396,7 +401,7 @@ def _direct_marketing_battery_export_simulation(
|
||||
preis_euro_pro_wh_akku=0.0,
|
||||
gesamtlast=[0.0, 0.0],
|
||||
)
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=config_eos.optimization.genetic.horizon_hours,
|
||||
prediction_hours=config_eos.prediction.hours,
|
||||
inverter=inverter,
|
||||
@@ -479,8 +484,8 @@ def test_disabled_ac_charging_clears_the_reported_plan(config_eos):
|
||||
}
|
||||
)
|
||||
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=10000,
|
||||
initial_soc_percentage=50,
|
||||
@@ -488,22 +493,22 @@ def test_disabled_ac_charging_clears_the_reported_plan(config_eos):
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=1.0,
|
||||
max_charge_power_w=5000,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=config_eos.prediction.hours,
|
||||
)
|
||||
inverter = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=5000.0,
|
||||
battery_id=battery.parameters.device_id,
|
||||
max_ac_charge_power_w=0, # Netzladen deaktiviert
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
)
|
||||
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(
|
||||
GeneticEnergyManagementRequest.model_validate(
|
||||
dict(
|
||||
pv_prognose_wh=[0.0, 0.0],
|
||||
strompreis_euro_pro_wh=[0.0003, 0.0003],
|
||||
@@ -511,7 +516,7 @@ def test_disabled_ac_charging_clears_the_reported_plan(config_eos):
|
||||
preis_euro_pro_wh_akku=0.0,
|
||||
gesamtlast=[0.0, 0.0],
|
||||
)
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=config_eos.optimization.genetic.horizon_hours,
|
||||
prediction_hours=config_eos.prediction.hours,
|
||||
inverter=inverter,
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
# ruff: noqa: S101
|
||||
|
||||
import numpy as np
|
||||
from conftest import genetic_optimization
|
||||
|
||||
from akkudoktoreos.devices.devicesabc import BatteryOperationMode
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic import geneticconvert
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
|
||||
|
||||
def test_battery_discharge_allowed_remains_local_load_mode(config_eos):
|
||||
config_eos.merge_settings_from_dict({"feedintariff": {"direct_marketing_enabled": True}})
|
||||
solution = GeneticSolution
|
||||
|
||||
operation_mode, operation_mode_factor = solution._battery_operation_from_solution(
|
||||
operation_mode, operation_mode_factor = geneticconvert._battery_operation_from_solution(
|
||||
ac_charge=0.0,
|
||||
dc_charge=0.0,
|
||||
discharge_allowed=True,
|
||||
@@ -23,9 +25,8 @@ def test_battery_discharge_allowed_remains_local_load_mode(config_eos):
|
||||
|
||||
def test_battery_grid_export_signal_maps_to_grid_support_export(config_eos):
|
||||
config_eos.merge_settings_from_dict({"feedintariff": {"direct_marketing_enabled": True}})
|
||||
solution = GeneticSolution
|
||||
|
||||
operation_mode, operation_mode_factor = solution._battery_operation_from_solution(
|
||||
operation_mode, operation_mode_factor = geneticconvert._battery_operation_from_solution(
|
||||
ac_charge=0.0,
|
||||
dc_charge=0.0,
|
||||
discharge_allowed=False,
|
||||
@@ -37,7 +38,7 @@ def test_battery_grid_export_signal_maps_to_grid_support_export(config_eos):
|
||||
|
||||
|
||||
def test_decode_charge_discharge_has_separate_battery_grid_export_state():
|
||||
optimization = GeneticOptimization()
|
||||
optimization = genetic_optimization()
|
||||
optimization.bat_possible_charge_values = [1.0]
|
||||
optimization.optimize_dc_charge = True
|
||||
optimization.optimize_battery_grid_export = True
|
||||
@@ -53,7 +54,7 @@ def test_decode_charge_discharge_has_separate_battery_grid_export_state():
|
||||
|
||||
|
||||
def test_decode_charge_discharge_has_self_consumption_state_after_legacy_export():
|
||||
optimization = GeneticOptimization()
|
||||
optimization = genetic_optimization()
|
||||
optimization.bat_possible_charge_values = [1.0]
|
||||
optimization.optimize_dc_charge = True
|
||||
optimization.optimize_battery_grid_export = True
|
||||
@@ -74,7 +75,7 @@ def test_decode_charge_discharge_has_self_consumption_state_after_legacy_export(
|
||||
|
||||
def test_graded_grid_export_states_decode_to_rates():
|
||||
"""Each configured export rate gets its own state; state 5 stays full power."""
|
||||
optimization = GeneticOptimization()
|
||||
optimization = genetic_optimization()
|
||||
optimization.bat_possible_charge_values = [1.0]
|
||||
optimization.bat_possible_grid_export_values = [1.0, 0.5, 0.25]
|
||||
optimization.optimize_dc_charge = True
|
||||
@@ -94,7 +95,7 @@ def test_graded_grid_export_states_decode_to_rates():
|
||||
|
||||
def test_single_export_rate_keeps_all_or_nothing_layout():
|
||||
"""Without configured rates the state space is the one from before grading."""
|
||||
optimization = GeneticOptimization()
|
||||
optimization = genetic_optimization()
|
||||
optimization.bat_possible_charge_values = [1.0]
|
||||
optimization.optimize_dc_charge = True
|
||||
optimization.optimize_battery_grid_export = True
|
||||
@@ -108,9 +109,8 @@ def test_single_export_rate_keeps_all_or_nothing_layout():
|
||||
def test_battery_grid_export_factor_becomes_operation_factor(config_eos):
|
||||
"""A partial export level is reported as the GRID_SUPPORT_EXPORT factor."""
|
||||
config_eos.merge_settings_from_dict({"feedintariff": {"direct_marketing_enabled": True}})
|
||||
solution = GeneticSolution
|
||||
|
||||
operation_mode, operation_mode_factor = solution._battery_operation_from_solution(
|
||||
operation_mode, operation_mode_factor = geneticconvert._battery_operation_from_solution(
|
||||
ac_charge=0.0,
|
||||
dc_charge=0.0,
|
||||
discharge_allowed=False,
|
||||
@@ -124,7 +124,7 @@ def test_battery_grid_export_factor_becomes_operation_factor(config_eos):
|
||||
|
||||
def test_disjoint_cycle_masks_keep_feasible_non_deadline_order(config_eos):
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
@@ -174,7 +174,7 @@ def test_disjoint_cycle_masks_keep_feasible_non_deadline_order(config_eos):
|
||||
],
|
||||
}
|
||||
)
|
||||
optimizer = GeneticOptimization(fixed_seed=42)
|
||||
optimizer = genetic_optimization(seed=42)
|
||||
solution = optimizer.optimize_ems(params, ngen=1, individuals=6)
|
||||
assert [(item.hour, item.minute) for item in solution.appliance_starts["washer"]] == [
|
||||
(0, 0),
|
||||
|
||||
@@ -1,52 +1,65 @@
|
||||
"""Economic tail scenarios and hard control/forecast boundaries."""
|
||||
|
||||
from dataclasses import replace
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from conftest import genetic_optimization, genetic_run_parameters
|
||||
from loguru import logger
|
||||
|
||||
from akkudoktoreos.config.config import SettingsEOSDefaults
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
|
||||
from akkudoktoreos.devices.genetic.homeappliance import HomeApplianceParameters
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.optimization.genetic import geneticconvert
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticforecast import bounded_forecast_array
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticHomeApplianceRequest,
|
||||
GeneticInverterRequest,
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.tailvalue import build_tail_value_curve
|
||||
from akkudoktoreos.optimization.genetic.terminalvalue import TerminalValueCurve
|
||||
from akkudoktoreos.optimization.genetic.genetictailvalue import build_tail_value_curve
|
||||
from akkudoktoreos.optimization.genetic.geneticterminalvalue import TerminalValueCurve
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
|
||||
|
||||
|
||||
def devices(power=1000, efficiency=1.0, lcos=0, ac_limit=None, export_power=5000):
|
||||
bat = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
device_id="battery1",
|
||||
capacity_wh=1000,
|
||||
max_charge_power_w=power,
|
||||
charging_efficiency=efficiency,
|
||||
discharging_efficiency=efficiency,
|
||||
initial_soc_percentage=50,
|
||||
levelized_cost_of_storage_kwh=lcos,
|
||||
charge_rates=[0, 0.5, 1],
|
||||
),
|
||||
prediction_hours=1,
|
||||
def device_requests(power=1000, efficiency=1.0, lcos=0, ac_limit=None, export_power=5000):
|
||||
"""The battery and inverter requests of the tail tests."""
|
||||
battery = GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=1000,
|
||||
max_charge_power_w=power,
|
||||
charging_efficiency=efficiency,
|
||||
discharging_efficiency=efficiency,
|
||||
initial_soc_percentage=50,
|
||||
levelized_cost_of_storage_kwh=lcos,
|
||||
charge_rates=[0, 0.5, 1],
|
||||
)
|
||||
inv = Inverter(
|
||||
InverterParameters(
|
||||
device_id="inverter1",
|
||||
battery_id="battery1",
|
||||
max_power_wh=export_power,
|
||||
dc_to_ac_efficiency=1,
|
||||
ac_to_dc_efficiency=1,
|
||||
max_ac_charge_power_w=ac_limit,
|
||||
),
|
||||
battery=bat,
|
||||
inverter = GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
battery_id="battery1",
|
||||
max_power_wh=export_power,
|
||||
dc_to_ac_efficiency=1,
|
||||
ac_to_dc_efficiency=1,
|
||||
max_ac_charge_power_w=ac_limit,
|
||||
)
|
||||
return battery, inverter
|
||||
|
||||
|
||||
def devices(**kwargs):
|
||||
battery, inverter = device_requests(**kwargs)
|
||||
bat = GeneticBattery(battery.to_parameters(), prediction_hours=1)
|
||||
inv = GeneticInverter(inverter.to_parameters(), battery=bat)
|
||||
return bat, inv
|
||||
|
||||
|
||||
@@ -184,7 +197,7 @@ def setup_run(config, interval=3600, start_hour=0, hours=72, prediction_hours=72
|
||||
)
|
||||
ems = get_ems(init=True)
|
||||
ems.set_start_datetime(to_datetime("2026-09-05T00:00:00").set(hour=start_hour))
|
||||
bat, inv = devices()
|
||||
bat, inv = device_requests()
|
||||
params = GeneticOptimizationParameters.model_validate(
|
||||
dict(
|
||||
ems={
|
||||
@@ -194,12 +207,12 @@ def setup_run(config, interval=3600, start_hour=0, hours=72, prediction_hours=72
|
||||
"einspeiseverguetung_euro_pro_wh": [0.0001] * hours,
|
||||
"preis_euro_pro_wh_akku": 0,
|
||||
},
|
||||
pv_battery=bat.parameters,
|
||||
inverter=inv.parameters,
|
||||
pv_battery=bat,
|
||||
inverter=inv,
|
||||
ev=None,
|
||||
)
|
||||
)
|
||||
return GeneticOptimization(fixed_seed=42), params
|
||||
return genetic_optimization(seed=42), params
|
||||
|
||||
|
||||
@pytest.mark.parametrize("interval", [3600, 900])
|
||||
@@ -219,7 +232,7 @@ async def test_genome_output_and_final_control_state(config_eos, interval, start
|
||||
with (
|
||||
patch.object(opt, "optimize", side_effect=choose),
|
||||
patch(
|
||||
"akkudoktoreos.optimization.genetic.genetic.build_tail_value_curve",
|
||||
"akkudoktoreos.optimization.genetic.geneticalgorithm.build_tail_value_curve",
|
||||
wraps=build_tail_value_curve,
|
||||
) as builder,
|
||||
):
|
||||
@@ -229,7 +242,7 @@ async def test_genome_output_and_final_control_state(config_eos, interval, start
|
||||
assert len(result.dc_charge) == opt.control_slots
|
||||
assert len(result.discharge_allowed) == opt.control_slots
|
||||
assert len(result.battery_grid_export_factor) == opt.control_slots
|
||||
assert len(result.result.Kosten_Euro_pro_Stunde) == opt.control_slots
|
||||
assert len(result.result.costs_per_hour) == opt.control_slots
|
||||
assert result.terminal_value.mode == "TAIL"
|
||||
assert result.terminal_value.battery_energy_wh == pytest.approx(
|
||||
max(500 - 1000 * opt.slot_duration_h, 0)
|
||||
@@ -246,7 +259,7 @@ async def test_genome_output_and_final_control_state(config_eos, interval, start
|
||||
assert result.terminal_value.tail_plan[0].hour_from_start == 24
|
||||
assert len(result.terminal_value.curve.operating_value_euro) == 101
|
||||
assert len(result.terminal_value.curve.continuation_value_euro) == 101
|
||||
assert len((await result.optimization_solution()).solution.to_dataframe()) == opt.control_slots
|
||||
assert len((await geneticconvert.optimization_solution(genetic_run_parameters(result.request), result)).solution.to_dataframe()) == opt.control_slots
|
||||
|
||||
|
||||
def test_short_tail_is_reported(config_eos, caplog):
|
||||
@@ -289,13 +302,16 @@ async def test_provider_values_are_not_extrapolated():
|
||||
def test_future_opportunity_changes_optimal_control_soc(config_eos):
|
||||
final_energy = []
|
||||
for negative_price in (0.5, -1.0):
|
||||
opt, params = setup_run(config_eos, hours=3)
|
||||
_, params = setup_run(config_eos, hours=3)
|
||||
config_eos.merge_settings_from_dict(
|
||||
{"optimization": {"genetic": {"horizon_hours": 1, "tail_horizon_hours": 2}}}
|
||||
)
|
||||
# The run settings are taken when the algorithm is created.
|
||||
opt = genetic_optimization(seed=42)
|
||||
params.ems.electricity_price_per_wh = [0.0005, negative_price / 1000, 0.0003]
|
||||
params.ems.feed_in_tariff_per_wh = [0.00002, 0, 0.0003]
|
||||
result = opt.optimize_ems(params, ngen=3, individuals=20)
|
||||
assert result.terminal_value is not None
|
||||
final_energy.append(result.terminal_value.battery_energy_wh)
|
||||
assert final_energy[0] > final_energy[1]
|
||||
|
||||
@@ -334,10 +350,12 @@ def test_missing_price_inside_tail_stops_at_first_gap(config_eos):
|
||||
|
||||
|
||||
def test_ev_genome_and_output_are_control_only(config_eos):
|
||||
from akkudoktoreos.devices.genetic.battery import ElectricVehicleParameters
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticElectricVehicleRequest,
|
||||
)
|
||||
|
||||
opt, params = setup_run(config_eos, interval=900, start_hour=10, hours=82)
|
||||
params.ev = ElectricVehicleParameters(
|
||||
params.ev = GeneticElectricVehicleRequest(
|
||||
device_id="ev1",
|
||||
capacity_wh=5000,
|
||||
initial_soc_percentage=0,
|
||||
@@ -367,7 +385,7 @@ def test_rejected_config_update_is_atomic(config_eos):
|
||||
|
||||
def test_disabled_ac_conversion_cannot_earn_negative_price_revenue():
|
||||
bat, inv = devices()
|
||||
inv.parameters.ac_to_dc_efficiency = 0
|
||||
inv = GeneticInverter(replace(inv.parameters, ac_to_dc_efficiency=0), battery=bat)
|
||||
c = build_tail_value_curve(
|
||||
battery=bat,
|
||||
inverter=inv,
|
||||
@@ -455,7 +473,7 @@ def test_daily_appliance_load_values_stored_energy_in_tail(config_eos):
|
||||
params.ems.feed_in_tariff_per_wh = [0.0] * 72
|
||||
if with_appliance:
|
||||
params.home_appliances = [
|
||||
HomeApplianceParameters.model_validate(
|
||||
GeneticHomeApplianceRequest.model_validate(
|
||||
dict(
|
||||
device_id="water_heater",
|
||||
consumption_wh=6000,
|
||||
@@ -519,7 +537,7 @@ def test_daily_appliance_day_planned_in_control_is_not_counted_again_in_tail(
|
||||
"""
|
||||
opt, params = setup_run(config_eos, start_hour=start_hour, hours=72 + start_hour)
|
||||
params.home_appliances = [
|
||||
HomeApplianceParameters.model_validate(
|
||||
GeneticHomeApplianceRequest.model_validate(
|
||||
dict(
|
||||
device_id="water_heater",
|
||||
consumption_wh=3000,
|
||||
@@ -543,7 +561,7 @@ def test_daily_appliance_day_planned_in_control_is_not_counted_again_in_tail(
|
||||
with (
|
||||
patch.object(opt, "optimize", side_effect=choose),
|
||||
patch(
|
||||
"akkudoktoreos.optimization.genetic.genetic.build_tail_value_curve",
|
||||
"akkudoktoreos.optimization.genetic.geneticalgorithm.build_tail_value_curve",
|
||||
wraps=build_tail_value_curve,
|
||||
) as builder,
|
||||
):
|
||||
@@ -582,7 +600,7 @@ def test_daily_appliance_run_in_progress_counts_for_its_day_in_estimate(config_e
|
||||
)
|
||||
if running:
|
||||
appliance["run_started_datetime"] = to_datetime("2026-09-05T01:30:00")
|
||||
params.home_appliances = [HomeApplianceParameters.model_validate(appliance)]
|
||||
params.home_appliances = [GeneticHomeApplianceRequest.model_validate(appliance)]
|
||||
|
||||
def choose(*args, **kwargs):
|
||||
genome = opt.create_individual()
|
||||
@@ -610,7 +628,7 @@ def test_daily_appliance_deadline_does_not_cap_tail(config_eos, policy):
|
||||
"""
|
||||
opt, params = setup_run(config_eos, start_hour=22, hours=72 + 22)
|
||||
params.home_appliances = [
|
||||
HomeApplianceParameters.model_validate(
|
||||
GeneticHomeApplianceRequest.model_validate(
|
||||
dict(
|
||||
device_id="water_heater",
|
||||
consumption_wh=3000,
|
||||
@@ -637,7 +655,7 @@ def test_daily_appliance_deadline_does_not_cap_tail(config_eos, policy):
|
||||
with (
|
||||
patch.object(opt, "optimize", side_effect=choose),
|
||||
patch(
|
||||
"akkudoktoreos.optimization.genetic.genetic.build_tail_value_curve",
|
||||
"akkudoktoreos.optimization.genetic.geneticalgorithm.build_tail_value_curve",
|
||||
wraps=build_tail_value_curve,
|
||||
) as builder,
|
||||
):
|
||||
|
||||
@@ -4,10 +4,15 @@ from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from conftest import genetic_optimization, genetic_run_parameters
|
||||
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.core.emplan import FRBCInstruction
|
||||
from akkudoktoreos.optimization.genetic import geneticconvert
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
@@ -60,24 +65,22 @@ async def test_native_result_retains_dst_grid_and_owned_inputs(config_eos, times
|
||||
"ev": None,
|
||||
}
|
||||
)
|
||||
optimizer = GeneticOptimization(fixed_seed=42)
|
||||
optimizer = genetic_optimization(seed=42)
|
||||
native = optimizer.optimize_ems(parameters, ngen=1, individuals=6)
|
||||
repeat = GeneticOptimization(fixed_seed=42).optimize_ems(parameters, ngen=1, individuals=6)
|
||||
repeat = genetic_optimization(seed=42).optimize_ems(parameters, ngen=1, individuals=6)
|
||||
assert native.start_solution == repeat.start_solution
|
||||
assert native.interval_seconds == 900
|
||||
assert native.start_solution_datetime == start
|
||||
assert native.controls_start_at_now
|
||||
assert len(native.result.load_wh_per_hour) == 4
|
||||
assert native.parameters.ems.total_load == [25.0] * 4
|
||||
assert native.request.ems.total_load == [25.0] * 4
|
||||
parameters.ems.total_load[elapsed_slots] = 999.0
|
||||
get_ems().set_start_datetime(start.add(days=1))
|
||||
config_eos.optimization.genetic.interval_sec = 3600
|
||||
with patch(
|
||||
"akkudoktoreos.optimization.genetic.geneticsolution.get_prediction",
|
||||
side_effect=AssertionError("Native serialization must not reread providers"),
|
||||
):
|
||||
generic = await native.optimization_solution()
|
||||
plan = native.energy_management_plan()
|
||||
# The conversion reads no prediction store: it converts from parameters and result only.
|
||||
run_parameters = genetic_run_parameters(native.request, optimizer)
|
||||
generic = await geneticconvert.optimization_solution(run_parameters, native)
|
||||
plan = geneticconvert.energy_management_plan(run_parameters, native)
|
||||
assert generic.valid_from == start
|
||||
assert generic.valid_until == start.add(hours=1)
|
||||
assert plan.valid_from == start
|
||||
@@ -119,7 +122,7 @@ def test_native_quarter_hour_temperatures_average_when_coarsened(config_eos):
|
||||
"inverter": None,
|
||||
}
|
||||
)
|
||||
normalized = GeneticOptimization()._parameters_for_slot_grid(parameters)
|
||||
normalized = genetic_optimization()._parameters_for_slot_grid(parameters)
|
||||
assert normalized.temperature_forecast == [13.0]
|
||||
assert normalized.ems.pv_forecast_wh == [100.0]
|
||||
assert normalized.ems.total_load == [200.0]
|
||||
@@ -134,10 +137,10 @@ def test_snapshot_and_warm_start_preserve_aware_instants(
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from akkudoktoreos.optimization.genetic.configrequest import (
|
||||
ConfigOptimizationRequest,
|
||||
from akkudoktoreos.optimization.genetic.geneticapi import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
|
||||
set_other_timezone(host_timezone)
|
||||
expected = to_datetime(f"2026-10-25T02:30:00{offset}", in_timezone="Europe/Berlin")
|
||||
@@ -150,7 +153,7 @@ def test_snapshot_and_warm_start_preserve_aware_instants(
|
||||
parameters = GeneticOptimizationParameters.model_validate(
|
||||
native.parameters.model_dump() | {"start_solution_datetime": supplied}
|
||||
)
|
||||
request = ConfigOptimizationRequest.model_validate({"start_solution_datetime": supplied})
|
||||
request = GeneticRequest.model_validate({"start_solution_datetime": supplied})
|
||||
for model in (native, parameters, request):
|
||||
value = model.start_solution_datetime
|
||||
assert value is not None
|
||||
@@ -218,7 +221,7 @@ def _partial_first_slot_run(config_eos, timestamp: str, initial_soc_percentage:
|
||||
"ev": None,
|
||||
}
|
||||
)
|
||||
optimizer = GeneticOptimization(fixed_seed=42)
|
||||
optimizer = genetic_optimization(seed=42)
|
||||
|
||||
def full_ac_charge_in_first_slot(*args, **kwargs):
|
||||
genome = optimizer.create_individual()
|
||||
@@ -274,8 +277,10 @@ def test_running_slot_ac_charge_factor_is_not_cut_for_a_full_slot(config_eos):
|
||||
config_eos, "2026-09-16T10:45:00+02:00", initial_soc_percentage=90
|
||||
)
|
||||
assert solution.result.battery_soc_per_hour[:2] == pytest.approx([90.0, 95.0])
|
||||
plan = solution.energy_management_plan()
|
||||
plan = geneticconvert.energy_management_plan(genetic_run_parameters(solution.request), solution)
|
||||
battery_instructions = [
|
||||
instruction for instruction in plan.instructions if instruction.resource_id == "battery1"
|
||||
instruction
|
||||
for instruction in plan.instructions
|
||||
if isinstance(instruction, FRBCInstruction) and instruction.resource_id == "battery1"
|
||||
]
|
||||
assert battery_instructions[0].operation_mode_factor == pytest.approx(1.0)
|
||||
|
||||
@@ -5,16 +5,20 @@ price horizon moves on during the night) may update the configuration while a
|
||||
run is in progress. Genomes and device arrays are sized when the run starts, so
|
||||
a mid-run change of horizon, tail or prediction hours must not reach the final
|
||||
evaluation - before the snapshot it failed with
|
||||
``IndexError: index 84 is out of bounds for axis 0 with size 84``.
|
||||
``IndexError: index 84 is out of bounds for axis 0 with size 84``. The run reads
|
||||
its settings from the optimization parameters, prepared before it starts.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from conftest import genetic_optimization
|
||||
|
||||
from akkudoktoreos.config.config import ConfigEOS
|
||||
from akkudoktoreos.core.cache import CacheEnergyManagementStore
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
@@ -79,7 +83,7 @@ def test_horizon_change_during_run_does_not_reach_the_run(
|
||||
config_eos: ConfigEOS, start_horizon: int, changed_horizon: int
|
||||
):
|
||||
parameters = _setup(config_eos, start_horizon)
|
||||
optimization = GeneticOptimization(fixed_seed=42)
|
||||
optimization = genetic_optimization(seed=42)
|
||||
|
||||
original_optimize = optimization.optimize
|
||||
|
||||
@@ -99,12 +103,12 @@ def test_horizon_change_during_run_does_not_reach_the_run(
|
||||
assert len(solution.battery_grid_export_factor) == start_horizon
|
||||
# ... and the new value is live for the next run.
|
||||
assert config_eos.optimization.genetic.horizon_hours == changed_horizon
|
||||
assert optimization._run_genetic_cfg is None
|
||||
assert optimization.settings.horizon_hours == start_horizon
|
||||
|
||||
|
||||
def test_snapshot_is_released_when_the_run_fails(config_eos: ConfigEOS):
|
||||
def test_run_state_is_released_when_the_run_fails(config_eos: ConfigEOS):
|
||||
parameters = _setup(config_eos, 24)
|
||||
optimization = GeneticOptimization(fixed_seed=42)
|
||||
optimization = genetic_optimization(seed=42)
|
||||
|
||||
def failing_optimize(*args, **kwargs):
|
||||
raise RuntimeError("boom")
|
||||
@@ -112,5 +116,4 @@ def test_snapshot_is_released_when_the_run_fails(config_eos: ConfigEOS):
|
||||
optimization.optimize = failing_optimize # type: ignore[method-assign]
|
||||
with pytest.raises(RuntimeError):
|
||||
optimization.optimize_ems(parameters=parameters, start_hour=0, ngen=1)
|
||||
assert optimization._run_genetic_cfg is None
|
||||
assert optimization._run_prediction_hours is None
|
||||
assert optimization._run_control_end_slot is None
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Configuration-owned requests and the real automatic GENETIC path."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Optional
|
||||
from typing import Any, Optional, cast
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
import httpx
|
||||
@@ -16,8 +16,12 @@ from akkudoktoreos.config.configmigrate import migrate_config_data
|
||||
from akkudoktoreos.core.coreabc import get_measurement
|
||||
from akkudoktoreos.core.ems import EnergyManagement, EnergyManagementStage
|
||||
from akkudoktoreos.core.emsettings import EnergyManagementMode
|
||||
from akkudoktoreos.optimization.genetic import configrequest
|
||||
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticHomeApplianceRequest,
|
||||
GeneticOptimizationParameters,
|
||||
GeneticRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.optimization import (
|
||||
OptimizationAlgorithm,
|
||||
OptimizationCommonSettings,
|
||||
@@ -25,6 +29,16 @@ from akkudoktoreos.optimization.optimization import (
|
||||
from akkudoktoreos.prediction.pvforecastforecastsolar import PVForecastForecastSolar
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
# Run start and observation time of the run the tests prepare; the fixture sets them.
|
||||
RUN = SimpleNamespace(ems=None)
|
||||
|
||||
|
||||
async def resolve(request: GeneticRequest, warm_start: Any = None) -> GeneticOptimizationParameters:
|
||||
"""Prepare ``request`` at the run start and observation time of ``RUN.ems``."""
|
||||
return await geneticprepare.resolve_request(
|
||||
request, RUN.ems.start_datetime, RUN.ems.observation_datetime, warm_start
|
||||
)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def isolated_measurement(config_eos):
|
||||
@@ -79,12 +93,10 @@ def configured_request(config_eos, monkeypatch):
|
||||
}
|
||||
)
|
||||
start = to_datetime("2026-09-12T10:15:00Z", in_timezone="UTC")
|
||||
ems = SimpleNamespace(
|
||||
start_datetime=start, observation_datetime=start, genetic_solution=lambda: None
|
||||
)
|
||||
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
|
||||
ems = SimpleNamespace(start_datetime=start, observation_datetime=start)
|
||||
monkeypatch.setattr(RUN, "ems", ems)
|
||||
measurement = Mock(key_to_lists=AsyncMock(return_value=([], [])))
|
||||
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", measurement)
|
||||
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=measurement))
|
||||
data = {
|
||||
"soc": {"storage": 42},
|
||||
"forecasts": {
|
||||
@@ -155,14 +167,14 @@ async def test_forecastsolar_resolves_without_runtime_override(
|
||||
await pv._update_data(force_update=True)
|
||||
|
||||
prediction = SimpleNamespace(update_data=AsyncMock(side_effect=update), key_to_raw_series=read)
|
||||
monkeypatch.setattr(ConfigOptimizationRequest, "prediction", prediction)
|
||||
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
|
||||
response = Mock()
|
||||
response.json.return_value = {
|
||||
"result": {"watts": watts},
|
||||
"message": {"info": {"timezone": "Europe/Berlin"}},
|
||||
}
|
||||
with patch("requests.get", return_value=response):
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
prediction.update_data.assert_awaited_once()
|
||||
energy = parameters.ems.pv_forecast_wh
|
||||
assert energy[10 * 3600 // interval] == pytest.approx(1000 * interval / 3600)
|
||||
@@ -171,11 +183,110 @@ async def test_forecastsolar_resolves_without_runtime_override(
|
||||
await pv.delete_by_datetime()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_echoed_warm_start_gets_the_start_of_the_last_solution(configured_request):
|
||||
"""A client that only echoes the genome of this server's last solution keeps its start.
|
||||
|
||||
The run gets the start of the last solution; the request is echoed as the client sent it.
|
||||
"""
|
||||
_, ems, _, data = configured_request
|
||||
last_start = ems.start_datetime.subtract(minutes=15)
|
||||
warm_start = SimpleNamespace(start_solution=[19.0, 32.0, 14.0], start_solution_datetime=last_start)
|
||||
explicit_start = ems.start_datetime.subtract(minutes=30)
|
||||
|
||||
async def resolved_start(**fields: Any) -> tuple[Any, Any]:
|
||||
"""The start of the run's start solution, and the one echoed in its request."""
|
||||
request = GeneticRequest.model_validate({**data, **fields})
|
||||
parameters = await geneticprepare.prepare_from_request(
|
||||
request, RUN.ems.start_datetime, RUN.ems.observation_datetime, cast(Any, warm_start)
|
||||
)
|
||||
return parameters.start_solution_datetime, parameters.request.start_solution_datetime
|
||||
|
||||
assert await resolved_start(start_solution=[19, 32, 14]) == (last_start, None)
|
||||
assert await resolved_start(start_solution=[19, 32, 15]) == (None, None)
|
||||
assert await resolved_start(
|
||||
start_solution=[19, 32, 14], start_solution_datetime=explicit_start
|
||||
) == (explicit_start, explicit_start)
|
||||
# Without a genome of its own the run starts from the last solution, as the echo shows.
|
||||
assert await resolved_start() == (last_start, last_start)
|
||||
|
||||
|
||||
class TestSchedulableAppliances:
|
||||
"""Preparation keeps only what the run can schedule of each home appliance."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"fields, cycles",
|
||||
[
|
||||
({}, 1), # fits
|
||||
({"deadline_datetime": "2026-09-12T09:00:00Z", "deadline_policy": "BEST_EFFORT"}, 1),
|
||||
({"deadline_datetime": "2026-09-12T09:00:00Z", "deadline_policy": "STRICT"}, None),
|
||||
({"shared_time_windows": {"windows": [{"start_time": "12:00", "end_time": "12:30"}]}}, None),
|
||||
(
|
||||
{
|
||||
"duration_h": 2,
|
||||
"num_cycles": 3,
|
||||
"shared_time_windows": {"windows": [{"start_time": "11:00", "end_time": "15:30"}]},
|
||||
},
|
||||
2,
|
||||
),
|
||||
(
|
||||
{
|
||||
"duration_h": 5,
|
||||
"schedule_mode": "DAILY",
|
||||
"shared_time_windows": {"windows": [{"start_time": "11:00", "end_time": "14:00"}]},
|
||||
},
|
||||
None,
|
||||
),
|
||||
],
|
||||
ids=[
|
||||
"fits",
|
||||
"best-effort-late",
|
||||
"strict-late",
|
||||
"window-too-short",
|
||||
"too-many-cycles",
|
||||
"daily-window-too-short",
|
||||
],
|
||||
)
|
||||
async def test_appliance_is_capped_or_left_out(
|
||||
self, configured_request, monkeypatch, caplog, fields, cycles
|
||||
):
|
||||
"""STRICT past its deadline, a window shorter than a run or too many cycles: no 503."""
|
||||
config, ems, _, data = configured_request
|
||||
config.merge_settings_from_dict({"general": {"timezone_override": "UTC"}})
|
||||
monkeypatch.setattr(config.optimization.genetic, "horizon_hours", 6) # 10:15 to 16:15
|
||||
resolved = await resolve(GeneticRequest.model_validate(data))
|
||||
appliance = GeneticHomeApplianceRequest(
|
||||
**{
|
||||
"device_id": "dishwasher",
|
||||
"consumption_wh": 1000,
|
||||
"duration_h": 1,
|
||||
"num_cycles": 1,
|
||||
**fields,
|
||||
}
|
||||
)
|
||||
request = resolved.model_copy(update={"home_appliances": [appliance]})
|
||||
|
||||
parameters = geneticprepare._complete(
|
||||
request, ems.start_datetime, ems.observation_datetime, None, None
|
||||
)
|
||||
|
||||
appliances = parameters.request.resolved_home_appliances()
|
||||
if cycles is None:
|
||||
assert appliances == []
|
||||
assert "Home appliance 'dishwasher' cannot be scheduled" in caplog.text
|
||||
elif cycles == appliance.num_cycles:
|
||||
assert parameters.request is request
|
||||
else:
|
||||
assert [a.num_cycles for a in appliances] == [cycles]
|
||||
assert "fits 2 of its 3 cycles" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hardware_costs_and_state_are_resolved_without_config_changes(configured_request):
|
||||
config, _, _, data = configured_request
|
||||
before = config.model_dump_json()
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.device_id == "storage"
|
||||
assert parameters.pv_battery.capacity_wh == 2000
|
||||
@@ -189,7 +300,7 @@ async def test_hardware_costs_and_state_are_resolved_without_config_changes(conf
|
||||
@pytest.mark.parametrize("field", ["devices", "optimization", "pv_battery", "inverter", "ems"])
|
||||
def test_static_http_overrides_are_rejected(field):
|
||||
with pytest.raises(ValidationError):
|
||||
ConfigOptimizationRequest.model_validate({field: {}})
|
||||
GeneticRequest.model_validate({field: {}})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host_timezone", ["UTC", "Europe/Berlin"])
|
||||
@@ -198,11 +309,11 @@ def test_warmstart_timestamp_retains_explicit_zone_and_json_instant(
|
||||
):
|
||||
set_other_timezone(host_timezone)
|
||||
previous = to_datetime("2026-10-25T02:30:00+01:00", in_timezone="Europe/Berlin")
|
||||
request = ConfigOptimizationRequest(start_solution_datetime=previous)
|
||||
request = GeneticRequest(start_solution_datetime=previous)
|
||||
assert request.start_solution_datetime is not None
|
||||
assert request.start_solution_datetime.timezone_name == "Europe/Berlin"
|
||||
assert request.start_solution_datetime.timestamp() == previous.timestamp()
|
||||
restored = ConfigOptimizationRequest.model_validate_json(request.model_dump_json())
|
||||
restored = GeneticRequest.model_validate_json(request.model_dump_json())
|
||||
assert restored.start_solution_datetime is not None
|
||||
assert restored.start_solution_datetime.timestamp() == previous.timestamp()
|
||||
assert restored.start_solution_datetime.utcoffset() == previous.utcoffset()
|
||||
@@ -222,7 +333,7 @@ async def test_stale_future_or_invalid_soc_defaults_to_zero(
|
||||
[ems.observation_datetime.subtract(seconds=age)],
|
||||
[value],
|
||||
)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 0
|
||||
|
||||
@@ -236,7 +347,7 @@ async def test_soc_freshness_uses_actual_run_time_inside_quarter_hour(configured
|
||||
[ems.observation_datetime.subtract(seconds=30)],
|
||||
[0.456],
|
||||
)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 45
|
||||
assert measurement.key_to_lists.call_args.kwargs[
|
||||
@@ -253,22 +364,29 @@ async def test_future_soc_in_repeated_hour_defaults_to_zero(configured_request):
|
||||
[to_datetime("2026-10-25T02:15:00+01:00", in_timezone="Europe/Berlin")],
|
||||
[0.8],
|
||||
)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_soc_and_mismatched_device_link_are_rejected(configured_request):
|
||||
async def test_unknown_soc_and_mismatched_device_link_fall_back(configured_request, caplog):
|
||||
"""An unknown SoC is ignored; a battery its inverter does not reach is left out."""
|
||||
config, _, _, data = configured_request
|
||||
request = ConfigOptimizationRequest.model_validate(data)
|
||||
request = GeneticRequest.model_validate(data)
|
||||
request.soc["unknown"] = 20
|
||||
with pytest.raises(ValueError, match="unconfigured"):
|
||||
await request.resolve()
|
||||
parameters = await resolve(request)
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 42
|
||||
assert "SoC 20% supplied for unconfigured device 'unknown', ignored" in caplog.text
|
||||
assert config.devices.inverters is not None
|
||||
config.devices.inverters["inverter"].battery_id = "missing"
|
||||
with pytest.raises(ValueError, match="battery_id"):
|
||||
await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is None
|
||||
assert parameters.inverter is not None
|
||||
assert "Battery 'storage' is not connected to the inverter (battery_id missing)" in caplog.text
|
||||
# The configuration is never changed.
|
||||
assert config.devices.inverters["inverter"].battery_id == "missing"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -278,21 +396,28 @@ async def test_direct_marketing_keeps_explicit_imported_sale_prices(configured_r
|
||||
config.feedintariff.direct_marketing_enabled = True
|
||||
config.feedintariff.provider = "FeedInTariffImport"
|
||||
data["forecasts"]["feed_in_tariff_per_wh"] = [tariff] * 96
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.ems.feed_in_tariff_per_wh == [tariff] * 96
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_control_gaps_fail_but_shorter_tail_is_accepted(configured_request):
|
||||
async def test_control_gaps_are_filled_and_shorter_tail_is_accepted(configured_request, caplog):
|
||||
_, _, _, data = configured_request
|
||||
data["forecasts"]["electricity_price_per_wh"] = [0.0003] * 50
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert len(parameters.ems.total_load) == 50
|
||||
data["forecasts"]["electricity_price_per_wh"][41] = 0.0004
|
||||
data["forecasts"]["electricity_price_per_wh"][42] = np.nan
|
||||
with pytest.raises(ValueError, match="control horizon") as error:
|
||||
await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
assert "2026-09-12T10:30:00+00:00, 2026-09-12T10:45:00+00:00" in str(error.value)
|
||||
assert "1 invalid interval(s)" in str(error.value)
|
||||
data["forecasts"]["electricity_price_per_wh"][48] = np.inf # after the control horizon
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
# The last known price is carried forward.
|
||||
assert parameters.ems.electricity_price_per_wh[42] == 0.0004
|
||||
# After the control horizon an infinite value is a gap, as NaN is: it shortens the tail.
|
||||
assert np.isnan(parameters.ems.electricity_price_per_wh[48])
|
||||
assert (
|
||||
"electricity price missing or invalid in 1 slot(s) of the control horizon, first at "
|
||||
"2026-09-12T10:30:00+00:00 (nan), replaced by 0.0004" in caplog.text
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -314,8 +439,8 @@ async def test_provider_power_is_integrated_once_and_update_is_awaited(
|
||||
)
|
||||
|
||||
prediction = Mock(update_data=AsyncMock(), key_to_raw_series=AsyncMock(side_effect=read))
|
||||
monkeypatch.setattr(ConfigOptimizationRequest, "prediction", prediction)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.ems.pv_forecast_wh == [250.0] * len(parameters.ems.pv_forecast_wh)
|
||||
assert parameters.ems.total_load == [500.0] * len(parameters.ems.total_load)
|
||||
assert parameters.ems.feed_in_tariff_per_wh == [-0.00005] * len(parameters.ems.total_load)
|
||||
@@ -376,7 +501,7 @@ def test_http_empty_body_is_configuration_request_and_failure_cannot_return_cach
|
||||
client = TestClient(eos.app)
|
||||
response = client.post("/v1/optimize")
|
||||
assert response.status_code == 503
|
||||
assert isinstance(run.call_args.kwargs["genetic_parameters"], ConfigOptimizationRequest)
|
||||
assert isinstance(run.call_args.kwargs["request"], GeneticRequest)
|
||||
assert run.call_args.kwargs["algorithm"] == OptimizationAlgorithm.GENETIC
|
||||
response = client.post("/v1/optimize", json={"devices": {}})
|
||||
assert response.status_code == 422
|
||||
@@ -391,7 +516,9 @@ def test_http_configuration_request_rejects_query_overrides(monkeypatch, query):
|
||||
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(run=run))
|
||||
response = TestClient(eos.app).post(f"/v1/optimize?{query}", json={})
|
||||
assert response.status_code == 422
|
||||
assert "query overrides are not supported" in response.text
|
||||
assert response.headers["content-type"] == "application/problem+json"
|
||||
assert response.json()["title"] == "HTTP Error"
|
||||
assert "query overrides are not supported" in response.json()["detail"]
|
||||
run.assert_not_awaited()
|
||||
|
||||
|
||||
@@ -402,26 +529,24 @@ async def test_real_ems_returns_coherent_quarter_hour_solution_and_plan(
|
||||
):
|
||||
_, fake, _, data = configured_request
|
||||
ems = EnergyManagement()
|
||||
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
|
||||
monkeypatch.setattr(EnergyManagement, "prediction", Mock(update_data=AsyncMock()))
|
||||
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
|
||||
request = ConfigOptimizationRequest.model_validate(data)
|
||||
request = GeneticRequest.model_validate(data)
|
||||
if automatic:
|
||||
original = ConfigOptimizationRequest.resolve
|
||||
original = geneticprepare.resolve_request
|
||||
|
||||
async def resolve_default(self):
|
||||
return await original(request)
|
||||
async def resolve_default(_default: GeneticRequest, *args: Any) -> Any:
|
||||
return await original(request, *args)
|
||||
|
||||
monkeypatch.setattr(ConfigOptimizationRequest, "resolve", resolve_default)
|
||||
monkeypatch.setattr(geneticprepare, "resolve_request", resolve_default)
|
||||
solution = await ems.run(
|
||||
start_datetime=fake.start_datetime.add(minutes=2),
|
||||
mode=EnergyManagementMode.OPTIMIZATION,
|
||||
genetic_parameters=None if automatic else request,
|
||||
genetic_generations=10,
|
||||
genetic_seed=42,
|
||||
request=None if automatic else request,
|
||||
overrides={"generations": 10, "seed": 42},
|
||||
)
|
||||
assert solution is not None
|
||||
assert solution is ems.genetic_solution()
|
||||
assert solution is ems.optimizer_result("GENETIC")
|
||||
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
|
||||
@@ -436,8 +561,7 @@ async def test_automatic_run_reads_real_resolver_provider_units_and_measured_soc
|
||||
):
|
||||
_, fake, measurement, _ = configured_request
|
||||
ems = EnergyManagement()
|
||||
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
|
||||
monkeypatch.setattr(EnergyManagement, "_genetic_solution", None)
|
||||
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
|
||||
measurement.key_to_lists.return_value = ([fake.start_datetime], [0.42])
|
||||
values = {
|
||||
"pvforecast_ac_power": 1000.0,
|
||||
@@ -453,20 +577,19 @@ async def test_automatic_run_reads_real_resolver_provider_units_and_measured_soc
|
||||
|
||||
prediction = Mock(update_data=AsyncMock(), key_to_raw_series=AsyncMock(side_effect=read))
|
||||
monkeypatch.setattr(EnergyManagement, "prediction", prediction)
|
||||
monkeypatch.setattr(ConfigOptimizationRequest, "prediction", prediction)
|
||||
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
|
||||
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
|
||||
solution = await ems.run(
|
||||
start_datetime=fake.start_datetime,
|
||||
mode=EnergyManagementMode.OPTIMIZATION,
|
||||
genetic_generations=10,
|
||||
genetic_seed=42,
|
||||
overrides={"generations": 10, "seed": 42},
|
||||
)
|
||||
assert solution is not None
|
||||
assert solution.parameters is not None
|
||||
assert solution.parameters.pv_battery is not None
|
||||
assert solution.parameters.pv_battery.initial_soc_percentage == 42
|
||||
assert solution.parameters.ems.pv_forecast_wh[:4] == [250.0] * 4
|
||||
assert solution.parameters.ems.total_load[:4] == [500.0] * 4
|
||||
assert solution.request is not None
|
||||
assert solution.request.pv_battery is not None
|
||||
assert solution.request.pv_battery.initial_soc_percentage == 42
|
||||
assert solution.request.ems.pv_forecast_wh[:4] == [250.0] * 4
|
||||
assert solution.request.ems.total_load[:4] == [500.0] * 4
|
||||
assert len(solution.ac_charge) == 4
|
||||
prediction.key_to_raw_series.assert_awaited()
|
||||
|
||||
@@ -482,8 +605,7 @@ async def test_http_real_genetic_result_serializes_native_quarter_hour_contract(
|
||||
if missing_soc:
|
||||
data["soc"] = {}
|
||||
ems = EnergyManagement()
|
||||
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
|
||||
monkeypatch.setattr(EnergyManagement, "_genetic_solution", None)
|
||||
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
|
||||
monkeypatch.setattr(EnergyManagement, "prediction", Mock(update_data=AsyncMock()))
|
||||
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
|
||||
|
||||
@@ -516,7 +638,7 @@ async def test_missing_soc_defaults_to_zero_without_mutating_inputs(
|
||||
before = config.model_dump_json()
|
||||
if missing_key:
|
||||
measurement.key_to_lists.side_effect = KeyError("SoC channel unavailable")
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 0
|
||||
assert config.model_dump_json() == before
|
||||
@@ -530,7 +652,7 @@ async def test_missing_soc_defaults_to_zero_without_mutating_inputs(
|
||||
async def test_explicit_soc_overrides_measurements(configured_request, soc):
|
||||
_, _, measurement, data = configured_request
|
||||
data["soc"] = {"storage": soc}
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == soc
|
||||
measurement.key_to_lists.assert_not_awaited()
|
||||
@@ -543,7 +665,7 @@ async def test_missing_ev_soc_does_not_replace_explicit_battery_soc(configured_r
|
||||
{"devices": {"max_electric_vehicles": 1,
|
||||
"electric_vehicles": {"car": {"profile_adjustment": {"nominal_capacity_wh": 60000}}}}}
|
||||
)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.ev is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 42
|
||||
@@ -563,8 +685,7 @@ async def test_http_config_and_real_optimizer_allow_full_ev_target(configured_re
|
||||
"max_soc_percentage": 100}}}})
|
||||
data["soc"]["ev"] = soc
|
||||
ems = EnergyManagement()
|
||||
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
|
||||
monkeypatch.setattr(EnergyManagement, "_genetic_solution", None)
|
||||
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
|
||||
monkeypatch.setattr(EnergyManagement, "prediction", Mock(update_data=AsyncMock()))
|
||||
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
|
||||
|
||||
@@ -604,7 +725,7 @@ async def test_explicit_ev_soc_has_no_measurement_age_limit(configured_request,
|
||||
measurement.key_to_lists.return_value = ([old_sample], [0.35])
|
||||
data["soc"]["car"] = 70
|
||||
config_before = config.model_dump_json()
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.ev is not None
|
||||
assert parameters.ev.initial_soc_percentage == 70
|
||||
assert parameters.ev.min_soc_percentage == 100
|
||||
@@ -635,18 +756,18 @@ async def test_home_assistant_soc_read_mid_slot_is_fresh_for_resolver(
|
||||
monkeypatch.setattr(EnergyManagement, "_observation_datetime", None)
|
||||
monkeypatch.setattr(EnergyManagement, "_stage", EnergyManagementStage.DATA_ACQUISITION)
|
||||
ems = EnergyManagement()
|
||||
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
|
||||
monkeypatch.setattr(RUN, "ems", ems)
|
||||
# Run 11 minutes into the 10:15 slot: older than measurement_max_age_seconds (300 s)
|
||||
# if the reading were stamped with the slot start.
|
||||
run_time = to_datetime("2026-09-12T10:26:00Z", in_timezone="UTC")
|
||||
ems.set_start_datetime(run_time, interval_seconds=900)
|
||||
assert ems.start_datetime == run_time.subtract(minutes=11)
|
||||
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", isolated_measurement)
|
||||
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=isolated_measurement))
|
||||
monkeypatch.setattr(HomeAssistantAdapter, "get_entity_state", lambda self, entity_id: "0.42")
|
||||
|
||||
await HomeAssistantAdapter()._update_data()
|
||||
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 42
|
||||
|
||||
@@ -667,20 +788,20 @@ async def test_meter_only_adapter_reading_does_not_mask_api_soc(
|
||||
monkeypatch.setattr(EnergyManagement, "_observation_datetime", None)
|
||||
monkeypatch.setattr(EnergyManagement, "_stage", EnergyManagementStage.DATA_ACQUISITION)
|
||||
ems = EnergyManagement()
|
||||
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
|
||||
monkeypatch.setattr(RUN, "ems", ems)
|
||||
# Run one minute into the 10:15 slot: the adapter's meter reading (slot start)
|
||||
# is newer than the SoC supplied four minutes earlier, still within 300 s.
|
||||
run_time = to_datetime("2026-09-12T10:16:00Z", in_timezone="UTC")
|
||||
ems.set_start_datetime(run_time, interval_seconds=900)
|
||||
measurement = isolated_measurement
|
||||
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", measurement)
|
||||
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=measurement))
|
||||
# SoC arrives through the measurement API, the meter through Home Assistant.
|
||||
await measurement.update_value(run_time.subtract(minutes=4), "storage-soc-factor", 0.42)
|
||||
monkeypatch.setattr(HomeAssistantAdapter, "get_entity_state", lambda self, entity_id: "1234.5")
|
||||
|
||||
await HomeAssistantAdapter()._update_data()
|
||||
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 42
|
||||
|
||||
@@ -727,14 +848,14 @@ async def test_missing_newest_soc_value_falls_back_to_older_fresh_sample(
|
||||
monkeypatch.setattr(EnergyManagement, "_start_datetime", None)
|
||||
monkeypatch.setattr(EnergyManagement, "_observation_datetime", None)
|
||||
ems = EnergyManagement()
|
||||
monkeypatch.setattr(configrequest, "get_ems", lambda: ems)
|
||||
monkeypatch.setattr(RUN, "ems", ems)
|
||||
run_time = to_datetime("2026-09-12T10:26:00Z", in_timezone="UTC")
|
||||
ems.set_start_datetime(run_time, interval_seconds=900)
|
||||
monkeypatch.setattr(ConfigOptimizationRequest, "measurement", isolated_measurement)
|
||||
monkeypatch.setattr(geneticprepare, "get_measurement", Mock(return_value=isolated_measurement))
|
||||
await isolated_measurement.update_value(run_time.subtract(minutes=2), "storage-soc-factor", 0.42)
|
||||
await isolated_measurement.update_value(run_time.subtract(minutes=1), "storage-soc-factor", pd.NA)
|
||||
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 42
|
||||
|
||||
@@ -751,7 +872,7 @@ async def test_battery_configuration_error_uses_defaults_and_logs_error(configur
|
||||
messages: list[str] = []
|
||||
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
|
||||
try:
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
finally:
|
||||
logger.remove(sink_id)
|
||||
assert parameters.pv_battery is not None
|
||||
@@ -784,7 +905,7 @@ async def test_inverter_is_derated_at_measured_temperature(
|
||||
return temperature_degc if key == "inverter-temperature-degc" else None
|
||||
|
||||
monkeypatch.setattr(invertermeasurement, "get_measured_value", measured)
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.inverter is not None
|
||||
assert parameters.inverter.max_power_wh == pytest.approx(expected_max_power_w)
|
||||
assert parameters.inverter.max_ac_charge_power_w == pytest.approx(expected_max_power_w)
|
||||
@@ -803,7 +924,7 @@ async def test_unusable_inverter_profile_falls_back_to_generic(configured_reques
|
||||
messages: list[str] = []
|
||||
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
|
||||
try:
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
finally:
|
||||
logger.remove(sink_id)
|
||||
assert parameters.inverter is not None
|
||||
@@ -830,9 +951,246 @@ async def test_inverter_without_nominal_power_uses_the_fallback_power(configured
|
||||
messages: list[str] = []
|
||||
sink_id = logger.add(lambda message: messages.append(message.record["message"]), level="ERROR")
|
||||
try:
|
||||
parameters = await ConfigOptimizationRequest.model_validate(data).resolve()
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
finally:
|
||||
logger.remove(sink_id)
|
||||
assert parameters.inverter is not None
|
||||
assert parameters.inverter.max_power_wh == pytest.approx(INVERTER_FALLBACK_NOMINAL_POWER_W)
|
||||
assert any("nominal_power_w" in m for m in messages)
|
||||
|
||||
|
||||
# The preparation always creates valid parameters (energy-domain skill): every input that
|
||||
# cannot serve the run is replaced by a fallback and logged at error level.
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_surplus_and_duplicate_devices_are_left_out(configured_request, caplog):
|
||||
config, _, _, data = configured_request
|
||||
config.merge_settings_from_dict(
|
||||
{
|
||||
"devices": {
|
||||
"max_batteries": 2,
|
||||
"max_electric_vehicles": 1,
|
||||
"batteries": {
|
||||
"second": {"profile_adjustment": {"nominal_capacity_wh": 1000}},
|
||||
},
|
||||
"electric_vehicles": {
|
||||
"storage": {"profile_adjustment": {"nominal_capacity_wh": 1000}},
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.device_id == "storage"
|
||||
assert parameters.ev is None
|
||||
assert "devices.batteries holds more than 1 device(s), 'second' left out" in caplog.text
|
||||
assert "Device ID 'storage' in devices.electric_vehicles is not unique" in caplog.text
|
||||
assert list(config.devices.batteries) == ["storage", "second"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"group, key, method, field, message",
|
||||
[
|
||||
("batteries", "storage", "battery_request", "pv_battery", "Battery 'storage'"),
|
||||
("electric_vehicles", "car", "electric_vehicle_request", "ev", "Electric vehicle 'car'"),
|
||||
("inverters", "inverter", "inverter_request", "inverter", "Inverter 'inverter'"),
|
||||
],
|
||||
)
|
||||
async def test_unresolvable_device_is_left_out(
|
||||
configured_request, monkeypatch, caplog, group, key, method, field, message
|
||||
):
|
||||
config, _, _, data = configured_request
|
||||
config.merge_settings_from_dict(
|
||||
{
|
||||
"devices": {
|
||||
"max_electric_vehicles": 1,
|
||||
"electric_vehicles": {
|
||||
"car": {"profile_adjustment": {"nominal_capacity_wh": 1000}},
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
def fail(*args: Any, **kwargs: Any) -> Any:
|
||||
raise ValueError("no profile")
|
||||
|
||||
monkeypatch.setattr(geneticprepare, method, fail)
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert getattr(parameters, field) is None
|
||||
assert f"{message} cannot be resolved, left out: no profile" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_without_inverter_the_run_plans_grid_energy_only(
|
||||
configured_request, monkeypatch, caplog
|
||||
):
|
||||
config, _, _, data = configured_request
|
||||
monkeypatch.setattr(config.devices, "inverters", {})
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.inverter is None
|
||||
assert parameters.pv_battery is None
|
||||
assert "No usable inverter; planning grid energy only" in caplog.text
|
||||
assert "Battery 'storage' is not connected to the inverter (battery_id None)" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unreadable_predictions_use_fallback_values(configured_request, monkeypatch, caplog):
|
||||
_, _, _, data = configured_request
|
||||
data["forecasts"] = {}
|
||||
prediction = Mock(
|
||||
update_data=AsyncMock(side_effect=RuntimeError("offline")),
|
||||
key_to_raw_series=AsyncMock(side_effect=RuntimeError("no data")),
|
||||
)
|
||||
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
first, last = 41, 45 # 10:15 to 11:15 in quarter-hour slots
|
||||
ems = parameters.ems
|
||||
assert ems.pv_forecast_wh[first:last] == [0.0] * 4
|
||||
load = geneticprepare.FALLBACK_LOAD_W * 900 / 3600
|
||||
assert ems.total_load[first:last] == pytest.approx([load] * 4)
|
||||
assert ems.electricity_price_per_wh[first:last] == [0.0] * 4
|
||||
assert isinstance(ems.feed_in_tariff_per_wh, list)
|
||||
assert ems.feed_in_tariff_per_wh[first:last] == [0.0] * 4
|
||||
assert "Prediction update failed, using stored data: offline" in caplog.text
|
||||
assert "Prediction 'pvforecast_ac_power' not readable, treated as missing" in caplog.text
|
||||
assert "load forecast missing or invalid in 4 slot(s)" in caplog.text
|
||||
# The fallback price 0 would make charging from the grid look free.
|
||||
assert parameters.inverter is not None
|
||||
assert parameters.inverter.max_ac_charge_power_w == 0.0
|
||||
assert "No electricity price known; no charging from the grid" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_negative_energy_and_short_genome_are_replaced(configured_request, caplog):
|
||||
_, _, _, data = configured_request
|
||||
data["forecasts"]["pv_forecast_wh"][42] = -5.0
|
||||
data["start_solution"] = [1.0]
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.ems.pv_forecast_wh[42] == 0.0
|
||||
assert parameters.start_solution is None
|
||||
assert parameters.inverter is not None
|
||||
assert parameters.inverter.max_ac_charge_power_w != 0 # prices are known
|
||||
assert "PV forecast missing or invalid in 1 slot(s)" in caplog.text
|
||||
assert "start_solution of the request [1.0] has fewer than two genes" in caplog.text
|
||||
|
||||
|
||||
def test_unset_settings_use_their_defaults(configured_request, monkeypatch, caplog):
|
||||
config, ems, _, _ = configured_request
|
||||
monkeypatch.setattr(config.prediction, "hours", None)
|
||||
monkeypatch.setattr(config.optimization.genetic, "horizon_hours", 0)
|
||||
monkeypatch.setattr(config.optimization.genetic, "generations", None)
|
||||
monkeypatch.setattr(config.optimization.genetic, "individuals", None)
|
||||
settings = geneticprepare.run_settings(ems.start_datetime, ems.observation_datetime)
|
||||
assert settings.prediction_hours == geneticprepare.FALLBACK_PREDICTION_HOURS
|
||||
assert settings.horizon_hours == geneticprepare.FALLBACK_HORIZON_HOURS
|
||||
assert settings.generations == geneticprepare.FALLBACK_GENERATIONS
|
||||
assert settings.individuals == geneticprepare.FALLBACK_INDIVIDUALS
|
||||
assert "prediction.hours not set, using 48" in caplog.text
|
||||
assert "horizon_hours 0 is not positive, using 24" in caplog.text
|
||||
assert "optimization.genetic.generations not set, using 400" in caplog.text
|
||||
assert "optimization.genetic.individuals not set, using 300" in caplog.text
|
||||
|
||||
|
||||
def test_prediction_hours_shorter_than_the_control_horizon(configured_request, monkeypatch, caplog):
|
||||
config, ems, _, _ = configured_request
|
||||
monkeypatch.setattr(config.prediction, "hours", 2)
|
||||
monkeypatch.setattr(config.optimization.genetic, "horizon_hours", 6)
|
||||
settings = geneticprepare.run_settings(ems.start_datetime, ems.observation_datetime)
|
||||
assert settings.prediction_hours == 6
|
||||
assert "prediction.hours 2 is shorter than the control horizon, using 6" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_automatic_run_without_inverter_or_predictions_is_not_cancelled(
|
||||
configured_request, monkeypatch, caplog
|
||||
):
|
||||
"""Inputs that cancelled a run before now fall back; the run publishes a plan."""
|
||||
config, fake, _, _ = configured_request
|
||||
monkeypatch.setattr(config.devices, "inverters", {})
|
||||
ems = EnergyManagement()
|
||||
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
|
||||
monkeypatch.setattr(EnergyManagement, "_plan", None)
|
||||
prediction = Mock(
|
||||
update_data=AsyncMock(), key_to_raw_series=AsyncMock(side_effect=KeyError("none"))
|
||||
)
|
||||
monkeypatch.setattr(EnergyManagement, "prediction", prediction)
|
||||
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
|
||||
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
|
||||
solution = await ems.run(
|
||||
start_datetime=fake.start_datetime,
|
||||
mode=EnergyManagementMode.OPTIMIZATION,
|
||||
overrides={"generations": 10, "seed": 42},
|
||||
)
|
||||
assert solution is not None
|
||||
assert ems.plan() is not None
|
||||
assert "Energy management run canceled" not in caplog.text
|
||||
assert "No usable inverter" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_inverter_without_its_battery(configured_request, monkeypatch, caplog):
|
||||
config, _, _, data = configured_request
|
||||
monkeypatch.setattr(config.devices, "batteries", {})
|
||||
data["soc"] = {}
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is None
|
||||
assert parameters.inverter is not None
|
||||
assert "Battery 'storage' of inverter 'inverter' is not available" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_energy_and_leading_price_gap_are_replaced(configured_request, caplog):
|
||||
_, _, _, data = configured_request
|
||||
forecasts = data["forecasts"]
|
||||
forecasts["total_load"][41] = -3.0
|
||||
forecasts["pv_forecast_wh"][43] = np.inf
|
||||
forecasts["electricity_price_per_wh"] = [np.nan] * 42 + [0.0005] * 54
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
ems = parameters.ems
|
||||
assert ems.total_load[41] == 0.0
|
||||
assert ems.pv_forecast_wh[43] == 0.0
|
||||
# No price known before the start: the next known one.
|
||||
assert ems.electricity_price_per_wh[41] == 0.0005
|
||||
assert "load forecast missing or invalid in 1 slot(s)" in caplog.text
|
||||
assert "PV forecast missing or invalid in 1 slot(s)" in caplog.text
|
||||
assert "electricity price missing or invalid in 1 slot(s)" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"age_seconds, values, reason",
|
||||
[
|
||||
(0, [], "(no measurement)"),
|
||||
(0, [None], "(no measurement)"),
|
||||
(0, [1.5], "(measured SoC factor 1.5 not a number within 0 to 1)"),
|
||||
(0, [float("nan")], "(measured SoC factor nan not a number within 0 to 1)"),
|
||||
(0, ["full"], "(measured SoC factor 'full' not a number within 0 to 1)"),
|
||||
(7200, [0.5], "(latest measurement 7200 s old, limit 3600 s)"),
|
||||
],
|
||||
ids=["none", "no-value", "out-of-range", "nan", "non-numeric", "stale"],
|
||||
)
|
||||
async def test_soc_fallback_names_the_reason(
|
||||
configured_request, monkeypatch, caplog, age_seconds, values, reason
|
||||
):
|
||||
"""The fallback log says why no SoC is usable, not Python's exception text."""
|
||||
config, fake, measurement, data = configured_request
|
||||
data["soc"] = {}
|
||||
monkeypatch.setattr(config.optimization.genetic, "measurement_max_age_seconds", 3600)
|
||||
sample_time = fake.observation_datetime.subtract(seconds=age_seconds)
|
||||
measurement.key_to_lists.return_value = ([sample_time] * len(values), values)
|
||||
parameters = await resolve(GeneticRequest.model_validate(data))
|
||||
assert parameters.pv_battery is not None
|
||||
assert parameters.pv_battery.initial_soc_percentage == 0
|
||||
assert f"No usable fresh SoC for storage {reason}; assuming 0% initial SoC" in caplog.text
|
||||
assert "iterable argument is empty" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_short_genome_of_the_last_run_is_not_used(configured_request, caplog):
|
||||
_, _, _, data = configured_request
|
||||
warm_start = SimpleNamespace(start_solution=[3.0], start_solution_datetime=None)
|
||||
parameters = await resolve(GeneticRequest.model_validate(data), warm_start)
|
||||
assert parameters.start_solution is None
|
||||
assert "start_solution of the last run [3.0] has fewer than two genes" in caplog.text
|
||||
|
||||
@@ -6,20 +6,32 @@ from typing import Any
|
||||
import numpy as np
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from conftest import genetic_optimization, genetic_run_parameters
|
||||
|
||||
from akkudoktoreos.config.config import ConfigEOS
|
||||
from akkudoktoreos.core.coreabc import get_ems, get_measurement
|
||||
from akkudoktoreos.core.emplan import DDBCInstruction
|
||||
from akkudoktoreos.measurement.measurement import Measurement
|
||||
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticOptimizationParameters,
|
||||
from akkudoktoreos.optimization.genetic import geneticconvert, geneticprepare
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
GeneticRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
|
||||
async def resolve(request: GeneticRequest) -> GeneticOptimizationParameters:
|
||||
"""Prepare ``request`` at the run start and observation time of the energy management."""
|
||||
ems = get_ems()
|
||||
return await geneticprepare.resolve_request(
|
||||
request, ems.start_datetime, ems.observation_datetime, None
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True, params=["UTC", "Europe/Berlin"])
|
||||
def local_clock(request: pytest.FixtureRequest, set_other_timezone: Callable[[str], str]) -> None:
|
||||
"""Run the same local-wall-clock schedules in UTC and a DST-observing zone.
|
||||
@@ -91,13 +103,13 @@ def parameters(
|
||||
)
|
||||
|
||||
|
||||
def run(params: GeneticOptimizationParameters) -> tuple[GeneticOptimization, GeneticSolution]:
|
||||
optimizer = GeneticOptimization(fixed_seed=42)
|
||||
def run(params: GeneticOptimizationParameters) -> tuple[GeneticOptimization, GeneticResult]:
|
||||
optimizer = genetic_optimization(seed=42)
|
||||
solution = optimizer.optimize_ems(params, ngen=1, individuals=12)
|
||||
return optimizer, solution
|
||||
|
||||
|
||||
def run_local_starts(solution: GeneticSolution) -> list[DateTime]:
|
||||
def run_local_starts(solution: GeneticResult) -> list[DateTime]:
|
||||
"""Compare scheduled instants in the run zone, independently of output zone."""
|
||||
timezone = get_ems().start_datetime.timezone_name
|
||||
assert timezone is not None
|
||||
@@ -113,6 +125,18 @@ def profile(**kwargs: Any) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def test_real_run_echoes_the_request_without_inventing_windows(config_eos: ConfigEOS) -> None:
|
||||
"""A consumer without windows stays without windows in the request the result echoes."""
|
||||
configure(config_eos)
|
||||
request = parameters(consumers=[profile()])
|
||||
_, solution = run(request)
|
||||
assert request.home_appliances is not None
|
||||
assert request.home_appliances[0].time_windows is None
|
||||
assert solution.request.home_appliances is not None
|
||||
assert solution.request.home_appliances[0].time_windows is None
|
||||
assert len(run_local_starts(solution)) == 1
|
||||
|
||||
|
||||
def test_real_optimizer_keeps_reverse_cycle_window_identity(config_eos: ConfigEOS) -> None:
|
||||
configure(config_eos)
|
||||
consumer = profile(
|
||||
@@ -346,7 +370,7 @@ async def test_real_measurement_completed_cycles_reach_request_and_optimizer(
|
||||
key=key, start_datetime=zero, end_datetime=zero.add(seconds=1)
|
||||
)
|
||||
assert len(dates) == 1 and counts == [1.0]
|
||||
prepared = await ConfigOptimizationRequest.model_validate(
|
||||
prepared = await resolve(GeneticRequest.model_validate(
|
||||
{
|
||||
"forecasts": {
|
||||
"pv_forecast_wh": [0.0] * 16,
|
||||
@@ -355,7 +379,7 @@ async def test_real_measurement_completed_cycles_reach_request_and_optimizer(
|
||||
"feed_in_tariff_per_wh": [0.0001] * 16,
|
||||
}
|
||||
}
|
||||
).resolve()
|
||||
))
|
||||
assert prepared.home_appliances is not None
|
||||
assert prepared.home_appliances[0].completed_cycles == 1
|
||||
_, solution = run(prepared)
|
||||
@@ -363,6 +387,87 @@ async def test_real_measurement_completed_cycles_reach_request_and_optimizer(
|
||||
assert sum(solution.result.home_appliance_energy_wh["washer"]) == pytest.approx(350.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("count", [3.0, 1.5, -1.0, "two"])
|
||||
async def test_invalid_completed_cycle_count_is_ignored(
|
||||
config_eos: ConfigEOS,
|
||||
isolated_measurement: Measurement,
|
||||
count: Any,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""A count that is no whole number of the appliance's cycles is logged and ignored."""
|
||||
configure(config_eos)
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"devices": {
|
||||
"max_batteries": 0,
|
||||
"batteries": {},
|
||||
"max_electric_vehicles": 0,
|
||||
"electric_vehicles": {},
|
||||
"max_inverters": 1,
|
||||
"inverters": {"inv": {"profile_adjustment": {"nominal_power_w": 10000}}},
|
||||
"max_home_appliances": 1,
|
||||
"home_appliances": {"washer": profile(num_cycles=2)},
|
||||
}
|
||||
}
|
||||
)
|
||||
await isolated_measurement.update_value(
|
||||
get_ems().start_datetime, "washer.cycles_completed", count
|
||||
)
|
||||
prepared = await resolve(GeneticRequest.model_validate(
|
||||
{
|
||||
"forecasts": {
|
||||
"pv_forecast_wh": [0.0] * 16,
|
||||
"total_load": [0.0] * 16,
|
||||
"electricity_price_per_wh": [0.0003] * 16,
|
||||
"feed_in_tariff_per_wh": [0.0001] * 16,
|
||||
}
|
||||
}
|
||||
))
|
||||
assert prepared.home_appliances is not None
|
||||
assert prepared.home_appliances[0].completed_cycles == 0
|
||||
assert f"Invalid completed cycle count {count!r}" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unresolvable_home_appliance_is_left_out(
|
||||
config_eos: ConfigEOS, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""A home appliance whose parameters cannot be derived is left out, logged."""
|
||||
configure(config_eos)
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"devices": {
|
||||
"max_batteries": 0,
|
||||
"batteries": {},
|
||||
"max_electric_vehicles": 0,
|
||||
"electric_vehicles": {},
|
||||
"max_inverters": 1,
|
||||
"inverters": {"inv": {"profile_adjustment": {"nominal_power_w": 10000}}},
|
||||
"max_home_appliances": 1,
|
||||
"home_appliances": {"washer": profile(num_cycles=1)},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
def fail(*args: Any, **kwargs: Any) -> Any:
|
||||
raise ValueError("no profile")
|
||||
|
||||
monkeypatch.setattr(geneticprepare, "home_appliance_request", fail)
|
||||
prepared = await resolve(GeneticRequest.model_validate(
|
||||
{
|
||||
"forecasts": {
|
||||
"pv_forecast_wh": [0.0] * 16,
|
||||
"total_load": [0.0] * 16,
|
||||
"electricity_price_per_wh": [0.0003] * 16,
|
||||
"feed_in_tariff_per_wh": [0.0001] * 16,
|
||||
}
|
||||
}
|
||||
))
|
||||
assert not prepared.home_appliances
|
||||
assert "Home appliance 'washer' cannot be resolved, left out: no profile" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_real_multiple_consumers_keep_separate_solution_channels(
|
||||
config_eos: ConfigEOS,
|
||||
@@ -383,7 +488,7 @@ async def test_real_multiple_consumers_keep_separate_solution_channels(
|
||||
assert sum(solution.result.home_appliance_energy_wh["washer"]) == pytest.approx(350.0)
|
||||
assert sum(solution.result.home_appliance_energy_wh["dryer"]) == pytest.approx(500.0)
|
||||
assert sum(solution.result.grid_consumption_wh_per_hour) == pytest.approx(850.0)
|
||||
exported = await solution.optimization_solution()
|
||||
exported = await geneticconvert.optimization_solution(genetic_run_parameters(solution.request), solution)
|
||||
table = exported.solution.to_dataframe()
|
||||
assert table["washer_energy_wh"].sum() == pytest.approx(350.0)
|
||||
assert table["dryer_energy_wh"].sum() == pytest.approx(500.0)
|
||||
@@ -403,11 +508,11 @@ async def test_profile_zero_power_phase_keeps_device_running_until_complete(
|
||||
shared_time_windows={"windows": [{"start_time": "01:00", "duration": "45 minutes"}]},
|
||||
)
|
||||
_, solution = run(parameters(consumers=[consumer]))
|
||||
exported = await solution.optimization_solution()
|
||||
exported = await geneticconvert.optimization_solution(genetic_run_parameters(solution.request), solution)
|
||||
table = exported.solution.to_dataframe()
|
||||
assert table["washer_energy_wh"].tolist()[4:7] == [300.0, 0.0, 300.0]
|
||||
assert table["washer_run_op_mode"].tolist()[4:7] == [1.0, 1.0, 1.0]
|
||||
plan = solution.energy_management_plan()
|
||||
plan = geneticconvert.energy_management_plan(genetic_run_parameters(solution.request), solution)
|
||||
assert {item.resource_id for item in plan.instructions} == {"washer"}
|
||||
commands = [
|
||||
(item.execution_time.hour, item.execution_time.minute, str(item.operation_mode_id))
|
||||
@@ -454,7 +559,7 @@ async def test_meter_only_record_does_not_hide_completed_cycles(
|
||||
# Cycle count through the measurement API, then the adapter's meter reading.
|
||||
await measurement.update_value(run_time.subtract(seconds=30), "washer.cycles_completed", 1.0)
|
||||
await measurement.update_value(run_time, "load_meter", 1234.5)
|
||||
prepared = await ConfigOptimizationRequest.model_validate(
|
||||
prepared = await resolve(GeneticRequest.model_validate(
|
||||
{
|
||||
"forecasts": {
|
||||
"pv_forecast_wh": [0.0] * 20,
|
||||
@@ -463,7 +568,7 @@ async def test_meter_only_record_does_not_hide_completed_cycles(
|
||||
"feed_in_tariff_per_wh": [0.0001] * 20,
|
||||
}
|
||||
}
|
||||
).resolve()
|
||||
))
|
||||
assert prepared.home_appliances is not None
|
||||
assert prepared.home_appliances[0].completed_cycles == 1
|
||||
|
||||
@@ -497,7 +602,7 @@ def run_zone() -> str:
|
||||
return timezone
|
||||
|
||||
|
||||
def heater_commands(solution: GeneticSolution) -> list[tuple[int, int, str]]:
|
||||
def heater_commands(solution: GeneticResult) -> list[tuple[int, int, str]]:
|
||||
timezone = run_zone()
|
||||
return [
|
||||
(
|
||||
@@ -505,12 +610,12 @@ def heater_commands(solution: GeneticSolution) -> list[tuple[int, int, str]]:
|
||||
item.execution_time.in_timezone(timezone).minute,
|
||||
str(item.operation_mode_id),
|
||||
)
|
||||
for item in solution.energy_management_plan().instructions
|
||||
for item in geneticconvert.energy_management_plan(genetic_run_parameters(solution.request), solution).instructions
|
||||
if isinstance(item, DDBCInstruction) and item.resource_id == "heater"
|
||||
]
|
||||
|
||||
|
||||
def heater_starts(solution: GeneticSolution) -> list[tuple[int, int]]:
|
||||
def heater_starts(solution: GeneticResult) -> list[tuple[int, int]]:
|
||||
timezone = run_zone()
|
||||
return [
|
||||
(moment.in_timezone(timezone).hour, moment.in_timezone(timezone).minute)
|
||||
@@ -628,7 +733,7 @@ def configure_heater_device(config: ConfigEOS, **kwargs: Any) -> None:
|
||||
|
||||
|
||||
async def resolve_heater() -> GeneticOptimizationParameters:
|
||||
prepared = await ConfigOptimizationRequest.model_validate(
|
||||
prepared = await resolve(GeneticRequest.model_validate(
|
||||
{
|
||||
"forecasts": {
|
||||
"pv_forecast_wh": [0.0] * 24,
|
||||
@@ -637,7 +742,7 @@ async def resolve_heater() -> GeneticOptimizationParameters:
|
||||
"feed_in_tariff_per_wh": [0.0001] * 24,
|
||||
}
|
||||
}
|
||||
).resolve()
|
||||
))
|
||||
assert prepared.home_appliances is not None
|
||||
return prepared
|
||||
|
||||
|
||||
@@ -9,17 +9,21 @@ from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from conftest import genetic_optimization
|
||||
from deap import creator
|
||||
from pydantic import ValidationError
|
||||
|
||||
from akkudoktoreos.config.config import ConfigEOS
|
||||
from akkudoktoreos.core.cache import CacheEnergyManagementStore
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.optimization.genetic import geneticapi
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import GeneticCommonSettings
|
||||
from akkudoktoreos.optimization.genetic.geneticsettings import GeneticSettings
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
DIR_TESTDATA = Path(__file__).parent / "testdata" / "genetic"
|
||||
@@ -38,17 +42,17 @@ def _configure_hourly_grid(config_eos: ConfigEOS) -> None:
|
||||
|
||||
|
||||
def test_fitness_cache_max_entries_setting_defaults_to_unbounded():
|
||||
assert GeneticCommonSettings().fitness_cache_max_entries is None
|
||||
assert GeneticCommonSettings(fitness_cache_max_entries=0).fitness_cache_max_entries == 0
|
||||
assert GeneticCommonSettings(fitness_cache_max_entries=5000).fitness_cache_max_entries == 5000
|
||||
assert GeneticSettings().fitness_cache_max_entries is None
|
||||
assert GeneticSettings(fitness_cache_max_entries=0).fitness_cache_max_entries == 0
|
||||
assert GeneticSettings(fitness_cache_max_entries=5000).fitness_cache_max_entries == 5000
|
||||
with pytest.raises(ValidationError):
|
||||
GeneticCommonSettings(fitness_cache_max_entries=-1)
|
||||
GeneticSettings(fitness_cache_max_entries=-1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("max_entries", [1, 2, 3, 10])
|
||||
def test_bounded_fitness_cache_evicts_oldest_keys(config_eos: ConfigEOS, max_entries: int):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
parameters = SimpleNamespace(ems=SimpleNamespace(price_per_wh_battery=0.0), ev=None)
|
||||
@@ -80,7 +84,7 @@ def test_bounded_fitness_cache_evicts_oldest_keys(config_eos: ConfigEOS, max_ent
|
||||
|
||||
|
||||
def test_evict_fitness_cache_also_bounds_a_plain_dict(config_eos: ConfigEOS):
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt._fitness_cache = {(bytes([value]),): None for value in range(10)} # type: ignore[misc]
|
||||
opt._evict_fitness_cache(3)
|
||||
assert list(opt._fitness_cache) == [(bytes([value]),) for value in (7, 8, 9)]
|
||||
@@ -121,7 +125,7 @@ def _run_optimization(
|
||||
)
|
||||
CacheEnergyManagementStore().clear()
|
||||
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
max_cache_size = 0
|
||||
uncached = opt._evaluate_uncached
|
||||
|
||||
@@ -133,7 +137,7 @@ def _run_optimization(
|
||||
with patch.object(opt, "_evaluate_uncached", side_effect=spy):
|
||||
solution = opt.optimize_ems(parameters=parameters, start_hour=10, ngen=12)
|
||||
|
||||
dump = solution.model_dump(mode="json")
|
||||
dump = geneticapi.solution_response(solution).model_dump(mode="json")
|
||||
history = dump.pop("fitness_history")
|
||||
cache_stats = history.pop("fitness_cache")
|
||||
max_cache_size = max(max_cache_size, cache_stats["keys"])
|
||||
|
||||
@@ -6,7 +6,7 @@ import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.optimization.genetic.forecast import bounded_forecast_array
|
||||
from akkudoktoreos.optimization.genetic.geneticforecast import bounded_forecast_array
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
|
||||
|
||||
|
||||
|
||||
@@ -1,27 +1,23 @@
|
||||
"""Regression test suite for the repaired HomeAppliance module.
|
||||
|
||||
TODO: fix this import to match wherever HomeApplianceParameters / HomeAppliance
|
||||
actually live in the repo.
|
||||
"""
|
||||
"""Regression test suite for the repaired GENETIC home appliance simulation."""
|
||||
from typing import Any
|
||||
from unittest.mock import Mock
|
||||
|
||||
import numpy as np
|
||||
import pendulum
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.config.configabc import CycleTimeWindowSequence, ValueTimeWindow
|
||||
from akkudoktoreos.devices.genetic.homeappliance import (
|
||||
HomeAppliance,
|
||||
HomeApplianceParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticHomeApplianceRequest,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures / factories
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def make_params(**overrides) -> HomeApplianceParameters:
|
||||
def make_params(**overrides) -> GeneticHomeApplianceRequest:
|
||||
defaults: dict[str, Any] = dict(
|
||||
device_id="dishwasher",
|
||||
consumption_wh=2000,
|
||||
@@ -31,76 +27,34 @@ def make_params(**overrides) -> HomeApplianceParameters:
|
||||
time_windows=None,
|
||||
)
|
||||
defaults.update(overrides)
|
||||
return HomeApplianceParameters(**defaults)
|
||||
return GeneticHomeApplianceRequest(**defaults)
|
||||
|
||||
|
||||
def make_appliance(
|
||||
prediction_hours: int = 24,
|
||||
optimization_hours: int = 24,
|
||||
**param_overrides,
|
||||
) -> HomeAppliance:
|
||||
) -> GeneticHomeAppliance:
|
||||
"""Build the simulated appliance from a request."""
|
||||
params = make_params(**param_overrides)
|
||||
return HomeAppliance(
|
||||
parameters=params,
|
||||
return GeneticHomeAppliance(
|
||||
parameters=params.to_parameters(),
|
||||
optimization_hours=optimization_hours,
|
||||
prediction_hours=prediction_hours,
|
||||
)
|
||||
|
||||
|
||||
def cycle_window(cycle: int, start: str, duration: str) -> CycleTimeWindowSequence:
|
||||
"""Build a CycleTimeWindowSequence with a single window for one cycle."""
|
||||
return CycleTimeWindowSequence(
|
||||
windows=[
|
||||
ValueTimeWindow(
|
||||
start_time=to_time(start),
|
||||
duration=to_duration(duration),
|
||||
value=float(cycle),
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def mock_cycle_windows(cycle_matrix: dict[int, np.ndarray]) -> Mock:
|
||||
"""Build a Mock standing in for CycleTimeWindowSequence.
|
||||
|
||||
``Mock(spec=CycleTimeWindowSequence)`` satisfies both the pydantic
|
||||
field-type check on ``HomeApplianceParameters.time_windows`` and any
|
||||
isinstance check in the module, without needing real windows/pendulum
|
||||
datetimes -- useful for isolating _build_duration_feasibility and the
|
||||
scheduling/repair logic from the real cycles_to_matrix() implementation.
|
||||
"""
|
||||
cycle_indices = list(cycle_matrix.keys())
|
||||
matrix = np.array([cycle_matrix[c] for c in cycle_indices])
|
||||
mock = Mock(spec=CycleTimeWindowSequence)
|
||||
mock.cycles_to_matrix = Mock(return_value=(cycle_indices, matrix))
|
||||
return mock
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Setup / defaults
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSetup:
|
||||
def test_default_time_windows_created_when_none_given(self):
|
||||
appliance = make_appliance(time_windows=None, num_cycles=1)
|
||||
assert appliance.parameters.time_windows is not None
|
||||
assert isinstance(appliance.parameters.time_windows, CycleTimeWindowSequence)
|
||||
"""Building the appliance."""
|
||||
|
||||
def test_default_time_window_value_left_unset(self):
|
||||
# A None-valued window is invisible to cycles_to_matrix() and so
|
||||
# never masquerades as a real per-cycle window; every remaining
|
||||
# cycle instead falls through to the "unconstrained" fallback.
|
||||
appliance = make_appliance(time_windows=None, num_cycles=3)
|
||||
assert appliance.parameters.time_windows is not None
|
||||
windows = appliance.parameters.time_windows.windows
|
||||
assert len(windows) == 1
|
||||
assert windows[0].value is None
|
||||
|
||||
def test_default_time_window_serializes_without_a_cycle_value(self):
|
||||
appliance = make_appliance(time_windows=None, num_cycles=1)
|
||||
assert appliance.parameters.time_windows is not None
|
||||
dumped = appliance.parameters.time_windows.model_dump()
|
||||
assert dumped["windows"][0]["value"] is None
|
||||
def test_simulation_leaves_the_request_unchanged(self):
|
||||
params = make_params(time_windows=None, num_cycles=1)
|
||||
GeneticHomeAppliance(params.to_parameters(), 24, 24)
|
||||
assert params.time_windows is None
|
||||
|
||||
def test_num_remaining_cycles_initial(self):
|
||||
appliance = make_appliance(num_cycles=3)
|
||||
@@ -113,76 +67,9 @@ class TestSetup:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Allowed-start computation: default (unconstrained) per-cycle windows
|
||||
# Allowed start slots: daylight saving time
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestDefaultStartAllowed:
|
||||
def test_starts_allowed_up_to_horizon_minus_duration(self):
|
||||
appliance = make_appliance(prediction_hours=10, duration_h=3)
|
||||
max_start = 10 - 3
|
||||
allowed = appliance.start_allowed[0]
|
||||
assert allowed[: max_start + 1].all()
|
||||
|
||||
def test_starts_beyond_horizon_minus_duration_forbidden(self):
|
||||
appliance = make_appliance(prediction_hours=10, duration_h=3)
|
||||
max_start = 10 - 3
|
||||
allowed = appliance.start_allowed[0]
|
||||
assert not allowed[max_start + 1 :].any()
|
||||
|
||||
def test_start_earliest_and_latest(self):
|
||||
appliance = make_appliance(prediction_hours=10, duration_h=3)
|
||||
assert appliance.start_earliest[0] == 0
|
||||
assert appliance.start_latest[0] == 10 - 3
|
||||
|
||||
def test_each_cycle_gets_its_own_unconstrained_mask(self):
|
||||
appliance = make_appliance(prediction_hours=10, duration_h=2, num_cycles=2)
|
||||
max_start = 10 - 2
|
||||
assert appliance.start_allowed[0][: max_start + 1].all()
|
||||
assert appliance.start_allowed[1][: max_start + 1].all()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Allowed-start computation: explicit single-cycle window
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestExplicitCycleWindow:
|
||||
def test_only_hours_inside_window_allowed(self):
|
||||
appliance = make_appliance(
|
||||
prediction_hours=24,
|
||||
duration_h=2,
|
||||
num_cycles=1,
|
||||
time_windows=cycle_window(0, "10:00", "3 hours"),
|
||||
)
|
||||
allowed = appliance.start_allowed[0]
|
||||
# Window is 10:00-13:00, appliance needs 2h -> valid starts 10, 11.
|
||||
assert allowed[10] and allowed[11]
|
||||
assert not allowed[9]
|
||||
assert not allowed[12]
|
||||
|
||||
def test_earliest_latest_reflect_window(self):
|
||||
appliance = make_appliance(
|
||||
prediction_hours=24,
|
||||
duration_h=2,
|
||||
num_cycles=1,
|
||||
time_windows=cycle_window(0, "10:00", "3 hours"),
|
||||
)
|
||||
assert appliance.start_earliest[0] == 10
|
||||
assert appliance.start_latest[0] == 11
|
||||
|
||||
def test_window_with_no_valid_start_falls_back(self):
|
||||
# Window shorter than the appliance's own duration -> nothing fits.
|
||||
appliance = make_appliance(
|
||||
prediction_hours=24,
|
||||
duration_h=3,
|
||||
num_cycles=1,
|
||||
time_windows=cycle_window(0, "10:00", "1 hour"),
|
||||
)
|
||||
allowed = appliance.start_allowed[0]
|
||||
assert not allowed.any()
|
||||
assert appliance.start_earliest[0] == 0
|
||||
assert appliance.start_latest[0] == 24 - 3
|
||||
|
||||
|
||||
class TestDSTAllowedStartSlots:
|
||||
"""The optimizer must distinguish both occurrences of the autumn hour."""
|
||||
|
||||
@@ -190,15 +77,15 @@ class TestDSTAllowedStartSlots:
|
||||
def _appliance(window_field, windows, run_minutes=15):
|
||||
if window_field == "time_windows":
|
||||
windows = [{**window, "value": 0} for window in windows]
|
||||
return HomeAppliance(
|
||||
parameters=HomeApplianceParameters.model_validate(
|
||||
return GeneticHomeAppliance(
|
||||
parameters=GeneticHomeApplianceRequest.model_validate(
|
||||
{
|
||||
"device_id": "dishwasher",
|
||||
"load_profile_power_w": [1000],
|
||||
"load_profile_interval_seconds": run_minutes * 60,
|
||||
window_field: {"windows": windows},
|
||||
}
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=25,
|
||||
prediction_hours=100,
|
||||
slot_duration_h=0.25,
|
||||
@@ -260,52 +147,6 @@ class TestDSTAllowedStartSlots:
|
||||
assert allowed == expected
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Allowed-start computation: mocked per-cycle windows (CycleTimeWindowSequence)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestCycleStartAllowed:
|
||||
def test_missing_cycle_row_is_unconstrained(self):
|
||||
# num_cycles=2 but the mock only provides a window for cycle 0.
|
||||
prediction_hours = 10
|
||||
duration_h = 2
|
||||
steps = np.zeros(prediction_hours)
|
||||
steps[2:6] = 1.0
|
||||
windows = mock_cycle_windows({0: steps})
|
||||
|
||||
appliance = make_appliance(
|
||||
prediction_hours=prediction_hours,
|
||||
duration_h=duration_h,
|
||||
num_cycles=2,
|
||||
time_windows=windows,
|
||||
)
|
||||
|
||||
max_start = prediction_hours - duration_h
|
||||
# Cycle 1 has no matrix row -> should be allowed everywhere it fits.
|
||||
assert appliance.start_allowed[1][: max_start + 1].all()
|
||||
|
||||
def test_duration_feasibility_uses_correct_window(self):
|
||||
# Steps 2,3,4,5 are inside the window (1.0); everything else is 0.
|
||||
# duration_h=2 -> valid starts are 2, 3, 4 (each 2h block fully inside).
|
||||
prediction_hours = 10
|
||||
duration_h = 2
|
||||
steps = np.zeros(prediction_hours)
|
||||
steps[2:6] = 1.0
|
||||
windows = mock_cycle_windows({0: steps})
|
||||
|
||||
appliance = make_appliance(
|
||||
prediction_hours=prediction_hours,
|
||||
duration_h=duration_h,
|
||||
num_cycles=1,
|
||||
time_windows=windows,
|
||||
)
|
||||
|
||||
allowed = appliance.start_allowed[0]
|
||||
expected = np.zeros(prediction_hours, dtype=bool)
|
||||
expected[2:5] = True # starts 2, 3, 4
|
||||
np.testing.assert_array_equal(allowed, expected)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# set_completed_cycles
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -321,12 +162,6 @@ class TestSetCompletedCycles:
|
||||
assert appliance.start_hours == []
|
||||
assert (appliance.load_curve == 0).all()
|
||||
|
||||
def test_remaining_cycle_indices_updated(self):
|
||||
appliance = make_appliance(num_cycles=4)
|
||||
appliance.set_completed_cycles(2)
|
||||
assert appliance.remaining_cycle_indices == [2, 3]
|
||||
assert appliance.num_remaining_cycles == 2
|
||||
|
||||
def test_clamped_to_valid_range(self):
|
||||
appliance = make_appliance(num_cycles=3)
|
||||
appliance.set_completed_cycles(-5)
|
||||
@@ -335,97 +170,6 @@ class TestSetCompletedCycles:
|
||||
assert appliance.completed_cycles == 3
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# set_starting_times -- the core scheduling / repair logic
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSetStartingTimes:
|
||||
def test_single_cycle_schedule_returns_requested_start(self):
|
||||
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
|
||||
result = appliance.set_starting_times([5])
|
||||
assert result == [5]
|
||||
|
||||
def test_two_cycles_enforce_minimum_gap(self):
|
||||
appliance = make_appliance(
|
||||
prediction_hours=24, duration_h=2, num_cycles=2, min_cycle_gap_h=1
|
||||
)
|
||||
# Requested starts overlap; cycle 1 must be pushed to start >= 0+2+1=3.
|
||||
result = appliance.set_starting_times([0, 1])
|
||||
assert result[0] == 0
|
||||
assert result[1] >= 3
|
||||
|
||||
def test_three_cycles_are_all_gap_repaired(self):
|
||||
appliance = make_appliance(
|
||||
prediction_hours=24, duration_h=1, num_cycles=3, min_cycle_gap_h=0
|
||||
)
|
||||
result = appliance.set_starting_times([0, 0, 0])
|
||||
# Each cycle is 1h with no gap -> expect 0, 1, 2.
|
||||
assert result == [0, 1, 2]
|
||||
|
||||
def test_load_curve_reflects_final_start_hours(self):
|
||||
appliance = make_appliance(
|
||||
prediction_hours=10, duration_h=2, consumption_wh=2000, num_cycles=1
|
||||
)
|
||||
appliance.set_starting_times([3])
|
||||
expected = np.zeros(10)
|
||||
expected[3:5] = 1000 # 2000 Wh over 2h
|
||||
np.testing.assert_array_equal(appliance.get_load_curve(), expected)
|
||||
|
||||
def test_sorting_preserves_per_cycle_window_alignment(self):
|
||||
prediction_hours = 24
|
||||
duration_h = 1
|
||||
# Cycle 0 only allowed late (hour 20), cycle 1 only allowed early (hour 2).
|
||||
steps0 = np.zeros(prediction_hours)
|
||||
steps0[20] = 1.0
|
||||
steps1 = np.zeros(prediction_hours)
|
||||
steps1[2] = 1.0
|
||||
windows = mock_cycle_windows({0: steps0, 1: steps1})
|
||||
|
||||
appliance = make_appliance(
|
||||
prediction_hours=prediction_hours,
|
||||
duration_h=duration_h,
|
||||
num_cycles=2,
|
||||
time_windows=windows,
|
||||
)
|
||||
|
||||
result = appliance.set_starting_times([20, 2])
|
||||
# Cycle 0 must land at 20 (its only allowed hour), cycle 1 at 2,
|
||||
# regardless of chronological sorting during repair.
|
||||
assert 20 in result
|
||||
assert 2 in result
|
||||
|
||||
def test_raises_on_wrong_number_of_start_times(self):
|
||||
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=2)
|
||||
with pytest.raises(ValueError):
|
||||
appliance.set_starting_times([5])
|
||||
|
||||
def test_no_remaining_cycles_returns_empty_list(self):
|
||||
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
|
||||
appliance.completed_cycles = 1
|
||||
result = appliance.set_starting_times([])
|
||||
assert result == []
|
||||
assert (appliance.load_curve == 0).all()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backwards-compatible single-cycle interface
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestSetStartingTimeBackCompat:
|
||||
def test_single_cycle_wrapper_returns_int(self):
|
||||
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
|
||||
result = appliance.set_starting_time(5)
|
||||
assert isinstance(result, int)
|
||||
assert result == 5
|
||||
|
||||
def test_no_remaining_cycles_returns_input_unchanged(self):
|
||||
appliance = make_appliance(prediction_hours=24, duration_h=2, num_cycles=1)
|
||||
appliance.completed_cycles = 1 # nothing left to schedule
|
||||
result = appliance.set_starting_time(7)
|
||||
assert result == 7
|
||||
assert (appliance.load_curve == 0).all()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Load curve utilities
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -459,7 +203,7 @@ class TestRunInProgress:
|
||||
|
||||
SLOT0 = "2026-11-14T01:00:00+01:00"
|
||||
|
||||
def pinned(self, started: str, now: str, slot0: str = SLOT0, **overrides) -> HomeAppliance:
|
||||
def pinned(self, started: str, now: str, slot0: str = SLOT0, **overrides) -> GeneticHomeAppliance:
|
||||
appliance = make_appliance(
|
||||
prediction_hours=overrides.pop("prediction_hours", 6),
|
||||
run_started_datetime=started,
|
||||
@@ -488,8 +232,8 @@ class TestRunInProgress:
|
||||
load_profile_interval_seconds=900,
|
||||
run_started_datetime="2026-11-14T00:00:00+01:00",
|
||||
)
|
||||
appliance = HomeAppliance(
|
||||
parameters=params, optimization_hours=4, prediction_hours=16, slot_duration_h=0.25
|
||||
appliance = GeneticHomeAppliance(
|
||||
parameters=params.to_parameters(), optimization_hours=4, prediction_hours=16, slot_duration_h=0.25
|
||||
)
|
||||
appliance.pin_run_in_progress(
|
||||
to_datetime("2026-11-14T00:15:00+01:00"), to_datetime("2026-11-14T00:20:00+01:00")
|
||||
|
||||
@@ -3,13 +3,19 @@ from unittest.mock import Mock, call, patch
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
Battery,
|
||||
SolarPanelBatteryParameters,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
from akkudoktoreos.devices.settings.invertersettings import InverterCommonSettings
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic0 import genetic0prepare
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticInverterRequest,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -25,17 +31,17 @@ def mock_battery() -> Mock:
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def inverter(mock_battery) -> Inverter:
|
||||
def inverter(mock_battery) -> GeneticInverter:
|
||||
mock_self_consumption_predictor = Mock()
|
||||
mock_self_consumption_predictor.calculate_expected_direct_consumption.side_effect = min
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
|
||||
return_value=mock_self_consumption_predictor,
|
||||
):
|
||||
iv = Inverter(
|
||||
InverterParameters(
|
||||
iv = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="iv1", max_power_wh=500.0, battery_id=mock_battery.parameters.device_id
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=mock_battery,
|
||||
)
|
||||
return iv
|
||||
@@ -43,27 +49,27 @@ def inverter(mock_battery) -> Inverter:
|
||||
|
||||
def test_quarter_hour_load_and_grid_export_share_discharge_power_limit():
|
||||
"""Local supply plus direct export may not exceed one slot's battery budget."""
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery",
|
||||
capacity_wh=10000,
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=1.0,
|
||||
max_charge_power_w=7000,
|
||||
initial_soc_percentage=100,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=1,
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
battery.set_discharge_per_hour(np.array([1]))
|
||||
quarter_hour_inverter = Inverter(
|
||||
InverterParameters(
|
||||
quarter_hour_inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter",
|
||||
max_power_wh=10000,
|
||||
battery_id="battery",
|
||||
dc_to_ac_efficiency=1.0,
|
||||
ac_to_dc_efficiency=1.0,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
@@ -133,11 +139,11 @@ def test_probabilistic_bypass_conserves_energy_without_battery():
|
||||
predictor = Mock()
|
||||
predictor.calculate_expected_direct_consumption.return_value = 150.0
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
|
||||
return_value=predictor,
|
||||
):
|
||||
inverter_without_battery = Inverter(
|
||||
InverterParameters(device_id="inverter", max_power_wh=1000.0)
|
||||
inverter_without_battery = GeneticInverter(
|
||||
GeneticInverterRequest(device_id="inverter", max_power_wh=1000.0).to_parameters()
|
||||
)
|
||||
|
||||
generation = 600.0
|
||||
@@ -159,11 +165,11 @@ def test_probabilistic_bypass_conserves_energy_on_quarter_hour_grid():
|
||||
predictor = Mock()
|
||||
predictor.calculate_expected_direct_consumption.return_value = 600.0
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
|
||||
return_value=predictor,
|
||||
):
|
||||
inverter_without_battery = Inverter(
|
||||
InverterParameters(device_id="inverter", max_power_wh=2000.0),
|
||||
inverter_without_battery = GeneticInverter(
|
||||
GeneticInverterRequest(device_id="inverter", max_power_wh=2000.0).to_parameters(),
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
|
||||
@@ -499,7 +505,7 @@ class TestInverterSettings:
|
||||
convert = (
|
||||
(lambda: genetic0prepare.inverter_request(settings))
|
||||
if converter == "to_genetic0_param"
|
||||
else getattr(settings, converter)
|
||||
else (lambda: geneticprepare.inverter_request(settings))
|
||||
)
|
||||
with pytest.raises(ValueError, match="nominal_power_w"):
|
||||
convert()
|
||||
@@ -509,8 +515,8 @@ class TestInverterSettings:
|
||||
|
||||
def test_battery_discharge_limit_caps_load_and_grid_export():
|
||||
"""The inverter's inlined discharge uses the battery's discharge power limit."""
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery",
|
||||
capacity_wh=10000,
|
||||
charging_efficiency=1.0,
|
||||
@@ -518,19 +524,19 @@ def test_battery_discharge_limit_caps_load_and_grid_export():
|
||||
max_charge_power_w=7000,
|
||||
max_discharge_power_w=4000,
|
||||
initial_soc_percentage=100,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=1,
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
battery.set_discharge_per_hour(np.array([1]))
|
||||
quarter_hour_inverter = Inverter(
|
||||
InverterParameters(
|
||||
quarter_hour_inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter",
|
||||
max_power_wh=10000,
|
||||
battery_id="battery",
|
||||
dc_to_ac_efficiency=1.0,
|
||||
ac_to_dc_efficiency=1.0,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
@@ -557,16 +563,16 @@ class TestFirstSlotFraction:
|
||||
predictor = Mock()
|
||||
predictor.calculate_expected_direct_consumption.side_effect = min
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
|
||||
return_value=predictor,
|
||||
):
|
||||
inverter = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=4000.0,
|
||||
battery_id=battery.parameters.device_id if battery else None,
|
||||
**parameters,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
first_slot_fraction=first_slot_fraction,
|
||||
)
|
||||
@@ -596,15 +602,15 @@ class TestFirstSlotFraction:
|
||||
assert inverter.dc_to_ac_efficiency_at(1000.0) == pytest.approx(0.97)
|
||||
|
||||
def test_ac_charge_in_slot_0_uses_the_remaining_part(self):
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=40_000,
|
||||
initial_soc_percentage=0,
|
||||
min_soc_percentage=0,
|
||||
max_charge_power_w=8_000,
|
||||
charging_efficiency=1.0,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=2,
|
||||
first_slot_fraction=0.25,
|
||||
)
|
||||
|
||||
+635
-21
@@ -1,24 +1,48 @@
|
||||
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 typing import Any, NamedTuple, Optional
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from conftest import genetic_optimization, genetic_run_parameters
|
||||
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.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.core.ems import EnergyManagement
|
||||
from akkudoktoreos.core.emsettings import EnergyManagementMode
|
||||
from akkudoktoreos.optimization.genetic import (
|
||||
geneticapi,
|
||||
geneticconvert,
|
||||
geneticprepare,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticapi import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic.geneticoptimizer import GeneticOptimizer
|
||||
from akkudoktoreos.optimization.genetic.geneticparameters import (
|
||||
GeneticParameters,
|
||||
parameters_from_dict,
|
||||
parameters_to_dict,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic.geneticresult import GeneticResult
|
||||
from akkudoktoreos.optimization.genetic.geneticvisualize import (
|
||||
GeneticVisualizationReport,
|
||||
genetic_prepare_visualize,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime
|
||||
|
||||
ems_eos = get_ems(init=True) # init once
|
||||
|
||||
@@ -107,14 +131,14 @@ async def test_optimize(
|
||||
# Throw away any cached results of the last energy management run.
|
||||
CacheEnergyManagementStore().clear()
|
||||
|
||||
genetic_optimization = GeneticOptimization(fixed_seed=fixed_seed)
|
||||
optimization = genetic_optimization(seed=fixed_seed)
|
||||
|
||||
# Activate with pytest --finalize
|
||||
if ngen > 10 and not is_finalize:
|
||||
pytest.skip()
|
||||
|
||||
# Call the optimization function
|
||||
genetic_solution = genetic_optimization.optimize_ems(
|
||||
genetic_solution = optimization.optimize_ems(
|
||||
parameters=input_data, start_hour=fixed_start_hour, ngen=ngen
|
||||
)
|
||||
|
||||
@@ -124,13 +148,15 @@ async def test_optimize(
|
||||
|
||||
# Keep the output contract, but do not demand an identical stochastic
|
||||
# schedule or monetary golden from the previous direct-consumption model.
|
||||
assert set(genetic_solution.model_dump()) == set(expected_result.model_dump())
|
||||
assert set(geneticapi.solution_response(genetic_solution).model_dump()) == set(
|
||||
expected_result.model_dump()
|
||||
)
|
||||
result = genetic_solution.result
|
||||
expected_slots = len(input_data.ems.pv_forecast_wh) - fixed_start_hour
|
||||
assert len(result.grid_consumption_wh_per_hour) == expected_slots
|
||||
assert len(result.grid_feed_in_wh_per_hour) == expected_slots
|
||||
prices = np.asarray(genetic_solution.parameters.ems.electricity_price_per_wh)
|
||||
tariffs = np.asarray(genetic_solution.parameters.ems.feed_in_tariff_per_wh)[:expected_slots]
|
||||
prices = np.asarray(genetic_solution.request.ems.electricity_price_per_wh)
|
||||
tariffs = np.asarray(genetic_solution.request.ems.feed_in_tariff_per_wh)[:expected_slots]
|
||||
expected_costs = np.asarray(result.grid_consumption_wh_per_hour) * prices
|
||||
expected_revenues = np.asarray(result.grid_feed_in_wh_per_hour) * tariffs
|
||||
np.testing.assert_allclose(result.costs_per_hour, expected_costs)
|
||||
@@ -145,7 +171,7 @@ async def test_optimize(
|
||||
assert all(0 <= value <= 100 for value in result.ev_soc_per_hour)
|
||||
|
||||
# Check the correct generic optimization solution is created
|
||||
optimization_solution = await genetic_solution.optimization_solution()
|
||||
optimization_solution = await geneticconvert.optimization_solution(genetic_run_parameters(genetic_solution.request), genetic_solution)
|
||||
dataframe = optimization_solution.solution.to_dataframe()
|
||||
assert len(dataframe) == expected_slots
|
||||
assert optimization_solution.valid_from == genetic_solution.start_solution_datetime
|
||||
@@ -156,7 +182,7 @@ async def test_optimize(
|
||||
assert len(genetic_solution.discharge_allowed) == expected_slots
|
||||
|
||||
# Check the correct generic energy management plan is created
|
||||
plan = genetic_solution.energy_management_plan()
|
||||
plan = geneticconvert.energy_management_plan(genetic_run_parameters(genetic_solution.request), genetic_solution)
|
||||
assert plan.valid_from == optimization_solution.valid_from
|
||||
assert plan.valid_until is None
|
||||
assert optimization_solution.valid_from is not None
|
||||
@@ -167,16 +193,14 @@ async def test_optimize(
|
||||
)
|
||||
|
||||
# Check visualization works
|
||||
pdf = genetic_prepare_visualize(
|
||||
solution=genetic_solution,
|
||||
)
|
||||
pdf = genetic_prepare_visualize(genetic_run_parameters(genetic_solution.request), genetic_solution)
|
||||
assert pdf.startswith(b"%PDF-")
|
||||
|
||||
reader = PdfReader(BytesIO(pdf))
|
||||
assert len(reader.pages) >= 6
|
||||
|
||||
|
||||
def test_solution_inverter_parameters_come_from_the_run_or_the_profile(config_eos: ConfigEOS):
|
||||
def test_solution_inverter_parameters_come_from_the_run(config_eos: ConfigEOS):
|
||||
"""Inverter settings hold no efficiencies; the solution never reads them directly."""
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
@@ -193,9 +217,599 @@ def test_solution_inverter_parameters_come_from_the_run_or_the_profile(config_eo
|
||||
)
|
||||
with (DIR_TESTDATA / "optimize_result_1.json").open("r") as f_in:
|
||||
solution = GeneticSolution.model_validate(json.load(f_in))
|
||||
stored = solution._inverter_parameters_list(solution.parameters)
|
||||
stored = geneticconvert._inverter_parameters_list(solution.parameters)
|
||||
assert stored == ([solution.parameters.inverter] if solution.parameters.inverter else [])
|
||||
resolved = solution._inverter_parameters_list(None)
|
||||
assert len(resolved) == 1
|
||||
assert resolved[0].max_power_wh == pytest.approx(8000)
|
||||
assert 0.0 < resolved[0].ac_to_dc_efficiency < 1.0
|
||||
# Without stored parameters there is no inverter: the conversion reads no configuration.
|
||||
assert geneticconvert._inverter_parameters_list(None) == []
|
||||
|
||||
|
||||
# --- Characterization of the whole output (ADR 0008) ---------------------------------------
|
||||
#
|
||||
# Pins, per golden input, the raw result, the optimization solution, the energy management plan
|
||||
# and the visualization of the current code, so that the migration to the optimizer architecture
|
||||
# can prove that it keeps GENETIC's results. Generated once from the current code; a refactoring
|
||||
# never regenerates them.
|
||||
|
||||
GOLDEN_TIMEZONE = "Europe/Berlin"
|
||||
GOLDEN_START = "2026-09-16T10:00:00"
|
||||
# The horizon crosses the switch to daylight saving time (Europe/Berlin, 2026-03-29).
|
||||
DST_START = "2026-03-28T10:00:00"
|
||||
GOLDEN_SEED = 42
|
||||
|
||||
# Report methods whose arguments are the input of the visualization; charts added directly
|
||||
# through add_chart_to_group are pinned by their titles.
|
||||
REPORT_METHODS = (
|
||||
"create_line_chart_date",
|
||||
"create_line_chart",
|
||||
"create_scatter_plot",
|
||||
"create_bar_chart",
|
||||
"create_violin_plot",
|
||||
"add_text_page",
|
||||
"add_json_page",
|
||||
"add_chart_to_group",
|
||||
)
|
||||
|
||||
# Placeholder for the wall-clock time of the conversion in IDs and timestamps.
|
||||
NOW = "<now>"
|
||||
|
||||
# Random UUIDs, e.g. in instruction IDs.
|
||||
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 GoldenCase(NamedTuple):
|
||||
"""One golden run: input file, settings and run start."""
|
||||
|
||||
stem: str
|
||||
input_file: str
|
||||
break_even: int
|
||||
start: str
|
||||
interval_sec: int
|
||||
observation_offset_minutes: int
|
||||
tail: bool
|
||||
generations: int
|
||||
|
||||
|
||||
def golden_case(stem: str, input_file: str, break_even: int, **changes: Any) -> GoldenCase:
|
||||
"""A golden case: hourly slots from GOLDEN_START, no tail, 3 generations unless changed."""
|
||||
case = GoldenCase(stem, input_file, break_even, GOLDEN_START, 3600, 0, False, 3)
|
||||
return case._replace(**changes)
|
||||
|
||||
|
||||
GOLDEN_CASES = (
|
||||
golden_case("1", "optimize_input_1.json", break_even=0),
|
||||
golden_case("2", "optimize_input_2.json", break_even=1),
|
||||
# Quarter-hour slots, the run starts within a slot.
|
||||
golden_case(
|
||||
"1_quarter",
|
||||
"optimize_input_1.json",
|
||||
break_even=0,
|
||||
interval_sec=900,
|
||||
observation_offset_minutes=20,
|
||||
),
|
||||
golden_case("2_dst", "optimize_input_2.json", break_even=1, start=DST_START),
|
||||
# Tail horizon and automatic terminal value.
|
||||
golden_case("2_tail", "optimize_input_2.json", break_even=1, tail=True),
|
||||
golden_case("2_full", "optimize_input_2.json", break_even=1, generations=400),
|
||||
)
|
||||
# Runs with more generations take minutes; they run only with --finalize.
|
||||
QUICK_GENERATIONS = 10
|
||||
|
||||
|
||||
def mask_now(value: Any) -> Any:
|
||||
"""Replace the wall-clock time of the conversion in ``id`` and ``generated_at``."""
|
||||
if isinstance(value, dict):
|
||||
masked = {key: mask_now(item) for key, item in value.items()}
|
||||
if isinstance(masked.get("id"), str) and "@" in masked["id"]:
|
||||
prefix, _, _ = masked["id"].partition("@")
|
||||
masked["id"] = f"{prefix}@{NOW}"
|
||||
if "generated_at" in masked:
|
||||
masked["generated_at"] = NOW
|
||||
return masked
|
||||
if isinstance(value, list):
|
||||
return [mask_now(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
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
|
||||
if callable(value):
|
||||
return f"<{type(value).__name__}>"
|
||||
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, new_prefix: str = "new_") -> None:
|
||||
"""Compare ``actual`` with the golden file; write ``<new_prefix><golden>`` for review on a miss.
|
||||
|
||||
Tests that compare with the same golden file pass different prefixes, so that parallel
|
||||
workers do not write and delete each other's review file.
|
||||
"""
|
||||
actual = to_jsonable(actual)
|
||||
new_file = DIR_TESTDATA / f"{new_prefix}{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(GeneticVisualizationReport, name)) for name in REPORT_METHODS
|
||||
}
|
||||
return calls, patches
|
||||
|
||||
|
||||
def golden_settings(case: GoldenCase, workers: Optional[int] = None) -> dict[str, Any]:
|
||||
"""The configuration of a golden run."""
|
||||
genetic: dict[str, Any] = {
|
||||
"interval_sec": case.interval_sec,
|
||||
"horizon_hours": 38,
|
||||
"tail_horizon_hours": 0,
|
||||
"terminal_value_mode": "FIXED",
|
||||
"individuals": 300,
|
||||
# The run's ngen argument (case.generations) takes precedence.
|
||||
"generations": 10,
|
||||
"seed": GOLDEN_SEED,
|
||||
"penalties": {"ev_soc_miss": 10, "ac_charge_break_even": case.break_even},
|
||||
"workers": workers,
|
||||
}
|
||||
if case.interval_sec == 900:
|
||||
# The 48 hourly input values cover 24 hours of quarter-hour slots from a 10:15 start.
|
||||
genetic["horizon_hours"] = 24
|
||||
if case.tail:
|
||||
genetic.update(
|
||||
{"horizon_hours": 24, "tail_horizon_hours": 24, "terminal_value_mode": "AUTO"}
|
||||
)
|
||||
return {
|
||||
"general": {"timezone": GOLDEN_TIMEZONE},
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"algorithm": "GENETIC", "genetic": genetic},
|
||||
"devices": {
|
||||
"max_electric_vehicles": 1,
|
||||
"electric_vehicles": {
|
||||
"ev1": {"charge_rates": [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def golden_parameters(
|
||||
case: GoldenCase, config_eos: ConfigEOS, workers: Optional[int] = None
|
||||
) -> GeneticParameters:
|
||||
"""The parameters of a golden input with its settings and run start."""
|
||||
config_eos.merge_settings_from_dict(golden_settings(case, workers))
|
||||
with (DIR_TESTDATA / case.input_file).open("r") as f_in:
|
||||
request = GeneticOptimizationParameters(**json.load(f_in))
|
||||
observation = to_datetime(case.start, in_timezone=GOLDEN_TIMEZONE).add(
|
||||
minutes=case.observation_offset_minutes
|
||||
)
|
||||
start = ems_eos.set_start_datetime(observation, interval_seconds=case.interval_sec)
|
||||
CacheEnergyManagementStore().clear()
|
||||
# The golden input holds complete forecast and device parameters; the preparation adds the
|
||||
# run settings.
|
||||
settings = geneticprepare.run_settings(
|
||||
start, observation, {"generations": case.generations, "seed": GOLDEN_SEED}
|
||||
)
|
||||
return GeneticParameters(request=request, start_hour=start.hour, settings=settings)
|
||||
|
||||
|
||||
def run_golden_case(
|
||||
case: GoldenCase, config_eos: ConfigEOS, workers: Optional[int] = None
|
||||
) -> GeneticResult:
|
||||
"""Run a golden input with its settings and run start; check its replay file."""
|
||||
parameters = golden_parameters(case, config_eos, workers)
|
||||
solution = GeneticOptimizer().run(parameters)
|
||||
if workers is None:
|
||||
check_replay(parameters, f"golden_{case.stem}", f"golden_{case.stem}_result.json")
|
||||
return solution
|
||||
|
||||
|
||||
def check_replay(parameters: GeneticParameters, 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 (compared as JSON text, so a
|
||||
# NaN of a forecast gap compares equal).
|
||||
written = json.dumps(replay["parameters"])
|
||||
assert json.dumps(parameters_to_dict(parameters_from_dict(json.loads(written)))) == written
|
||||
check_golden(replay, f"replay_{stem}.json")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("case", GOLDEN_CASES, ids=[case.stem for case in GOLDEN_CASES])
|
||||
async def test_golden_output(
|
||||
case: GoldenCase, config_eos: ConfigEOS, is_finalize: bool, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A golden input gives the pinned result, solution, plan and visualization."""
|
||||
if case.generations > QUICK_GENERATIONS and not is_finalize:
|
||||
pytest.skip("Activate with pytest --finalize")
|
||||
solution = run_golden_case(case, config_eos)
|
||||
check_golden(
|
||||
geneticapi.solution_response(solution).model_dump(mode="json"),
|
||||
f"golden_{case.stem}_result.json",
|
||||
)
|
||||
|
||||
optimization_solution = await geneticconvert.optimization_solution(genetic_run_parameters(solution.request), solution)
|
||||
check_golden(
|
||||
mask_now(optimization_solution.model_dump(mode="json")),
|
||||
f"golden_{case.stem}_optimization_solution.json",
|
||||
)
|
||||
plan = geneticconvert.energy_management_plan(genetic_run_parameters(solution.request), solution)
|
||||
check_golden(mask_now(plan.model_dump(mode="json")), f"golden_{case.stem}_plan.json")
|
||||
|
||||
calls, patches = record_report_calls()
|
||||
with patch.multiple(GeneticVisualizationReport, **patches):
|
||||
pdf = genetic_prepare_visualize(genetic_run_parameters(solution.request), solution)
|
||||
pages = len(PdfReader(BytesIO(pdf)).pages)
|
||||
check_golden({"pages": pages, "calls": calls}, f"golden_{case.stem}_visualize.json")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("workers", [1, 2])
|
||||
def test_golden_result_does_not_depend_on_the_workers(workers: int, config_eos: ConfigEOS) -> None:
|
||||
"""Serial and parallel evaluation give the pinned result (the default picks by CPU count)."""
|
||||
case = next(case for case in GOLDEN_CASES if case.stem == "2")
|
||||
solution = run_golden_case(case, config_eos, workers)
|
||||
check_golden(
|
||||
geneticapi.solution_response(solution).model_dump(mode="json"),
|
||||
f"golden_{case.stem}_result.json",
|
||||
new_prefix=f"new_workers{workers}_",
|
||||
)
|
||||
|
||||
|
||||
# Origin of the fake prediction series: a value depends on its time, not its index.
|
||||
PREDICTION_ORIGIN = "2026-01-01T00:00:00+00:00"
|
||||
PREDICTION_DAYS = 4
|
||||
|
||||
|
||||
def fake_prediction_series(key: str, around: DateTime, gap: bool = False) -> pd.Series:
|
||||
"""An hourly series per key from the day before ``around``; values follow the time (UTC).
|
||||
|
||||
With ``gap`` the load misses one value before the run start, which the preparation keeps.
|
||||
"""
|
||||
first = to_datetime(around.in_timezone("UTC").start_of("day").subtract(days=1))
|
||||
index = pd.date_range(first.isoformat(), periods=24 * PREDICTION_DAYS, freq="h")
|
||||
hours = (index - pd.Timestamp(PREDICTION_ORIGIN)).total_seconds().to_numpy() / 3600
|
||||
day_hour = hours % 24
|
||||
week_hour = hours % (24 * 7)
|
||||
if key == "pvforecast_ac_power":
|
||||
values = np.maximum(0.0, 4000.0 * np.sin(np.pi * (day_hour - 4.0) / 14.0))
|
||||
elif key == "loadforecast_power_w":
|
||||
values = 350.0 + 15.0 * day_hour + 0.5 * week_hour
|
||||
elif key == "elecprice_marketprice_wh":
|
||||
values = 0.00020 + 0.000008 * day_hour + 0.0000002 * week_hour
|
||||
elif key == "feed_in_tariff_wh":
|
||||
values = np.full(len(index), 0.00008)
|
||||
else:
|
||||
raise KeyError(key)
|
||||
if gap and key == "loadforecast_power_w":
|
||||
# 01:00 UTC of the run's day; the series starts at 00:00 UTC of the day before.
|
||||
values = values.copy()
|
||||
values[24 + 1] = np.nan
|
||||
return pd.Series(values, index=index)
|
||||
|
||||
|
||||
class FakeConfigMeasurement:
|
||||
"""Measured states of charge shortly before the run; with ``rich`` also appliance states."""
|
||||
|
||||
def __init__(self, observation: DateTime, rich: bool = False) -> None:
|
||||
self.records = {
|
||||
"storage-soc-factor": ([observation.subtract(seconds=60)], [0.42]),
|
||||
"car-soc-factor": ([observation.subtract(seconds=60)], [0.30]),
|
||||
}
|
||||
if rich:
|
||||
# A full charge three days ago, the dishwasher runs since 30 minutes, no cycle done.
|
||||
self.records["storage-soc-factor"] = (
|
||||
[observation.subtract(days=3), observation.subtract(seconds=60)],
|
||||
[1.0, 0.42],
|
||||
)
|
||||
self.records["dishwasher.run_started_at"] = (
|
||||
[observation.subtract(minutes=30)],
|
||||
[observation.subtract(minutes=30).timestamp()],
|
||||
)
|
||||
self.records["dishwasher.cycles_completed"] = ([observation.start_of("day")], [0])
|
||||
|
||||
async def key_to_lists(self, key: str, **kwargs: Any) -> tuple[list[Any], list[Any]]:
|
||||
"""The records of ``key``.
|
||||
|
||||
Args:
|
||||
key: Measurement key.
|
||||
**kwargs: Time range and options of the real method; ignored.
|
||||
|
||||
Returns:
|
||||
Dates and values of the key.
|
||||
|
||||
Raises:
|
||||
KeyError: Nothing is measured for ``key``.
|
||||
"""
|
||||
if key not in self.records:
|
||||
raise KeyError(key)
|
||||
return self.records[key]
|
||||
|
||||
|
||||
class ConfigCase(NamedTuple):
|
||||
"""One golden run that prepares its parameters from the configuration."""
|
||||
|
||||
stem: str
|
||||
start: str
|
||||
interval_sec: int
|
||||
observation_offset_minutes: int
|
||||
tail: bool
|
||||
# Appliance measurements, periodic full charge, direct marketing, a warm start and a
|
||||
# forecast gap before the run start.
|
||||
rich: bool = False
|
||||
|
||||
|
||||
CONFIG_CASES = (
|
||||
ConfigCase(
|
||||
"config_hour", GOLDEN_START, interval_sec=3600, observation_offset_minutes=0, tail=True
|
||||
),
|
||||
ConfigCase(
|
||||
"config_quarter", GOLDEN_START, interval_sec=900, observation_offset_minutes=20, tail=False
|
||||
),
|
||||
ConfigCase(
|
||||
"config_dst", DST_START, interval_sec=3600, observation_offset_minutes=0, tail=False
|
||||
),
|
||||
ConfigCase(
|
||||
"config_rich",
|
||||
GOLDEN_START,
|
||||
interval_sec=3600,
|
||||
observation_offset_minutes=0,
|
||||
tail=False,
|
||||
rich=True,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def config_case_settings(case: ConfigCase) -> dict[str, Any]:
|
||||
"""Configured devices and settings of a configuration-driven golden run."""
|
||||
genetic: dict[str, Any] = {
|
||||
"interval_sec": case.interval_sec,
|
||||
"horizon_hours": 24,
|
||||
"tail_horizon_hours": 24 if case.tail else 0,
|
||||
"terminal_value_mode": "AUTO" if case.tail else "FIXED",
|
||||
"terminal_value_euro_per_kwh": 0.23,
|
||||
"individuals": 300,
|
||||
"generations": 10,
|
||||
"seed": GOLDEN_SEED,
|
||||
}
|
||||
settings: dict[str, Any] = {
|
||||
"general": {"timezone": GOLDEN_TIMEZONE},
|
||||
"prediction": {"hours": 48},
|
||||
"optimization": {"algorithm": "GENETIC", "genetic": genetic},
|
||||
"devices": {
|
||||
"max_batteries": 1,
|
||||
"max_electric_vehicles": 1,
|
||||
"max_inverters": 1,
|
||||
"max_home_appliances": 1,
|
||||
"batteries": {
|
||||
"storage": {
|
||||
"profile_adjustment": {
|
||||
"nominal_capacity_wh": 10000,
|
||||
"max_charge_power_w": 5000,
|
||||
},
|
||||
"levelized_cost_of_storage_amt_kwh": 0.01,
|
||||
"measurement_key_soc_factor": "storage-soc-factor",
|
||||
}
|
||||
},
|
||||
"electric_vehicles": {
|
||||
"car": {
|
||||
"profile_adjustment": {
|
||||
"nominal_capacity_wh": 40000,
|
||||
"max_charge_power_w": 11000,
|
||||
},
|
||||
"min_soc_percentage": 60,
|
||||
"charge_rates": [0.0, 0.5, 1.0],
|
||||
"measurement_key_soc_factor": "car-soc-factor",
|
||||
}
|
||||
},
|
||||
"inverters": {
|
||||
"inverter": {
|
||||
"battery_id": "storage",
|
||||
"profile_adjustment": {"nominal_power_w": 8000},
|
||||
}
|
||||
},
|
||||
"home_appliances": {
|
||||
"dishwasher": {"consumption_wh": 2000, "duration_h": 2},
|
||||
},
|
||||
},
|
||||
}
|
||||
if case.rich:
|
||||
storage = settings["devices"]["batteries"]["storage"]
|
||||
storage["profile_adjustment"]["full_charge_interval_days"] = 3
|
||||
storage["full_charge_allow_grid"] = True
|
||||
settings["feedintariff"] = {"direct_marketing_enabled": True}
|
||||
return settings
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("case", CONFIG_CASES, ids=[case.stem for case in CONFIG_CASES])
|
||||
async def test_golden_output_from_configuration(
|
||||
case: ConfigCase, config_eos: ConfigEOS, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A run prepared from the configuration gives the pinned parameters and output.
|
||||
|
||||
The prepared parameters are pinned as the preparation returns them; the result holds them
|
||||
trimmed to the run start.
|
||||
"""
|
||||
config_eos.merge_settings_from_dict(config_case_settings(case))
|
||||
observation = to_datetime(case.start, in_timezone=GOLDEN_TIMEZONE).add(
|
||||
minutes=case.observation_offset_minutes
|
||||
)
|
||||
prediction = Mock(
|
||||
update_data=AsyncMock(),
|
||||
key_to_raw_series=AsyncMock(
|
||||
side_effect=lambda key, **kwargs: fake_prediction_series(key, observation, case.rich)
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(EnergyManagement, "prediction", prediction)
|
||||
monkeypatch.setattr(geneticprepare, "get_prediction", Mock(return_value=prediction))
|
||||
monkeypatch.setattr(EnergyManagement, "adapter", Mock(update_data=AsyncMock()))
|
||||
monkeypatch.setattr(EnergyManagement, "_optimizer_runs", {})
|
||||
if case.rich:
|
||||
# The previous run, an hour earlier, is the warm start of the pinned one.
|
||||
previous = observation.subtract(hours=1)
|
||||
monkeypatch.setattr(
|
||||
geneticprepare,
|
||||
"get_measurement",
|
||||
Mock(return_value=FakeConfigMeasurement(previous, rich=True)),
|
||||
)
|
||||
CacheEnergyManagementStore().clear()
|
||||
warm_start = await ems_eos.run(
|
||||
start_datetime=previous,
|
||||
mode=EnergyManagementMode.OPTIMIZATION,
|
||||
overrides={"generations": 3, "seed": GOLDEN_SEED},
|
||||
)
|
||||
assert warm_start is not None
|
||||
monkeypatch.setattr(
|
||||
geneticprepare,
|
||||
"get_measurement",
|
||||
Mock(return_value=FakeConfigMeasurement(observation, case.rich)),
|
||||
)
|
||||
prepared: list[GeneticOptimizationParameters] = []
|
||||
resolve = geneticprepare.resolve_request
|
||||
|
||||
async def record_resolve(*args: Any) -> GeneticOptimizationParameters:
|
||||
parameters = await resolve(*args)
|
||||
prepared.append(parameters)
|
||||
return parameters
|
||||
|
||||
monkeypatch.setattr(geneticprepare, "resolve_request", record_resolve)
|
||||
CacheEnergyManagementStore().clear()
|
||||
|
||||
solution = await ems_eos.run(
|
||||
start_datetime=observation,
|
||||
mode=EnergyManagementMode.OPTIMIZATION,
|
||||
overrides={"generations": 3, "seed": GOLDEN_SEED},
|
||||
)
|
||||
assert solution is not None
|
||||
assert len(prepared) == 1
|
||||
check_golden(prepared[0].model_dump(mode="json"), f"golden_{case.stem}_parameters.json")
|
||||
run = ems_eos.optimizer_run("GENETIC")
|
||||
assert run is not None
|
||||
check_replay(run.parameters, f"golden_{case.stem}", f"golden_{case.stem}_result.json")
|
||||
check_golden(
|
||||
geneticapi.solution_response(solution).model_dump(mode="json"),
|
||||
f"golden_{case.stem}_result.json",
|
||||
)
|
||||
optimization_solution = ems_eos.optimization_solution()
|
||||
assert optimization_solution is not None
|
||||
check_golden(
|
||||
mask_now(optimization_solution.model_dump(mode="json")),
|
||||
f"golden_{case.stem}_optimization_solution.json",
|
||||
)
|
||||
plan = ems_eos.plan()
|
||||
assert plan is not None
|
||||
check_golden(mask_now(plan.model_dump(mode="json")), f"golden_{case.stem}_plan.json")
|
||||
|
||||
calls, patches = record_report_calls()
|
||||
with patch.multiple(GeneticVisualizationReport, **patches):
|
||||
pdf = genetic_prepare_visualize(genetic_run_parameters(solution.request), solution)
|
||||
pages = len(PdfReader(BytesIO(pdf)).pages)
|
||||
check_golden({"pages": pages, "calls": calls}, f"golden_{case.stem}_visualize.json")
|
||||
|
||||
|
||||
REPLAY_STEMS = [f"golden_{case.stem}" for case in GOLDEN_CASES] + [
|
||||
f"golden_{case.stem}" for case in CONFIG_CASES
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stem", REPLAY_STEMS)
|
||||
def test_replay(stem: str, config_eos: ConfigEOS, is_finalize: bool) -> None:
|
||||
"""A run reproduces its golden result from the stored parameters alone (ADR 0006, 0008).
|
||||
|
||||
The configuration and the run start are set to different values on purpose: the run must
|
||||
not read them.
|
||||
"""
|
||||
replay = json.loads((DIR_TESTDATA / f"replay_{stem}.json").read_text())
|
||||
parameters = parameters_from_dict(replay["parameters"])
|
||||
generations = parameters.settings.generations
|
||||
if generations is not None and generations > QUICK_GENERATIONS and not is_finalize:
|
||||
pytest.skip("Activate with pytest --finalize")
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"general": {"timezone_override": "America/New_York"},
|
||||
"prediction": {"hours": 30},
|
||||
"optimization": {
|
||||
"genetic": {
|
||||
"interval_sec": 3600 if parameters.settings.interval_sec == 900 else 900,
|
||||
"horizon_hours": 6,
|
||||
"tail_horizon_hours": 0,
|
||||
"individuals": 11,
|
||||
"generations": 12,
|
||||
"seed": 1,
|
||||
"terminal_value_mode": "FIXED",
|
||||
"penalties": {"ev_soc_miss": 99, "ac_charge_break_even": 3},
|
||||
}
|
||||
},
|
||||
"feedintariff": {"direct_marketing_enabled": False},
|
||||
"devices": {"max_electric_vehicles": 0, "max_home_appliances": 0},
|
||||
}
|
||||
)
|
||||
config_eos.merge_settings_from_dict({"optimization": {"self_consumption_interpolator": "numpy"}})
|
||||
ems_eos.set_start_datetime(to_datetime("2027-01-05T03:00:00+00:00", in_timezone="UTC"))
|
||||
|
||||
result = GeneticOptimizer().run(parameters)
|
||||
|
||||
check_golden(
|
||||
geneticapi.solution_response(result).model_dump(mode="json"),
|
||||
replay["expected_result"],
|
||||
new_prefix="new_replay_",
|
||||
)
|
||||
|
||||
|
||||
def test_replay_keeps_a_forecast_gap() -> None:
|
||||
"""A gap the preparation keeps is ``null`` in the replay file and NaN in the parameters."""
|
||||
replay = json.loads((DIR_TESTDATA / "replay_golden_config_rich.json").read_text())
|
||||
assert replay["parameters"]["request"]["ems"]["total_load"][3] is None
|
||||
parameters = parameters_from_dict(replay["parameters"])
|
||||
assert math.isnan(parameters.request.ems.total_load[3])
|
||||
assert parameters_to_dict(parameters)["request"]["ems"]["total_load"][3] is None
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Tests of the GENETIC adapter of the optimizer interface."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
from unittest.mock import patch
|
||||
|
||||
from akkudoktoreos.optimization.genetic import geneticalgorithm
|
||||
from akkudoktoreos.optimization.genetic.geneticoptimizer import GeneticOptimizer
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
|
||||
class TestGeneticOptimizer:
|
||||
"""The GENETIC adapter hands the run parameters to the algorithm."""
|
||||
|
||||
def test_run_starts_from_the_start_of_the_parameters(self) -> None:
|
||||
"""The run aligns the start solution with the start of the parameters, not the request."""
|
||||
start = to_datetime("2026-09-12T09:45:00+00:00", in_timezone="UTC")
|
||||
parameters = SimpleNamespace(
|
||||
settings=SimpleNamespace(generations=10, individuals=10),
|
||||
start_hour=10,
|
||||
request=SimpleNamespace(start_solution_datetime=None),
|
||||
start_solution_datetime=start,
|
||||
)
|
||||
|
||||
with patch.object(geneticalgorithm, "GeneticOptimization") as optimization:
|
||||
GeneticOptimizer().run(cast(Any, parameters))
|
||||
|
||||
kwargs = optimization.return_value.optimize_ems.call_args.kwargs
|
||||
assert kwargs["start_solution_datetime"] == start
|
||||
assert kwargs["parameters"].start_solution_datetime is None
|
||||
@@ -10,16 +10,17 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import uvicorn
|
||||
from conftest import genetic_optimization
|
||||
|
||||
from akkudoktoreos.config.config import ConfigEOS
|
||||
from akkudoktoreos.core.cache import CacheEnergyManagementStore
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.optimization.genetic import genetic as genetic_module
|
||||
from akkudoktoreos.optimization.genetic.genetic import (
|
||||
from akkudoktoreos.optimization.genetic import geneticalgorithm as genetic_module
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
auto_evaluation_workers,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
@@ -104,7 +105,7 @@ def _parameters(
|
||||
|
||||
def _run(config_eos: ConfigEOS, workers: int, cache_entries):
|
||||
parameters = _parameters(config_eos, workers, cache_entries)
|
||||
optimization = GeneticOptimization(fixed_seed=7)
|
||||
optimization = genetic_optimization(seed=7)
|
||||
used: list[int] = []
|
||||
original_start = optimization._start_evaluation_pool
|
||||
|
||||
@@ -438,7 +439,9 @@ def test_unsupported_fork_falls_back_to_serial(config_eos: ConfigEOS, monkeypatc
|
||||
|
||||
|
||||
def test_cgroup_cpu_limit_reads_own_and_parent_cgroups(tmp_path, monkeypatch):
|
||||
from akkudoktoreos.optimization.genetic.genetic import _cgroup_cpu_limit
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
_cgroup_cpu_limit,
|
||||
)
|
||||
|
||||
service = tmp_path / "system.slice" / "eos.service"
|
||||
service.mkdir(parents=True)
|
||||
@@ -475,7 +478,9 @@ def test_cgroup_cpu_limit_reads_own_and_parent_cgroups(tmp_path, monkeypatch):
|
||||
],
|
||||
)
|
||||
def test_worker_cpu_set(workers, allowed, expected):
|
||||
from akkudoktoreos.optimization.genetic.genetic import worker_cpu_set
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
worker_cpu_set,
|
||||
)
|
||||
|
||||
assert worker_cpu_set(workers, allowed) == expected
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
Adapted from PRs #1224 (Christin) and #1304 (Normann). Main has no direct-marketing
|
||||
parameter override yet: these regressions cover its existing preparation/simulation
|
||||
contract and refuse unavailable imported revenue instead of creating a demo tariff.
|
||||
contract. Unavailable imported revenue falls back to the last known revenue (0 without
|
||||
any) instead of creating a demo tariff.
|
||||
"""
|
||||
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
@@ -11,11 +12,15 @@ import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
from akkudoktoreos.optimization.genetic.configrequest import ConfigOptimizationRequest
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticOptimizationParameters,
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticInverterRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsimulation import (
|
||||
GeneticSimulation,
|
||||
)
|
||||
from akkudoktoreos.prediction.feedintariffabc import FeedInTariffDataRecord
|
||||
from akkudoktoreos.prediction.feedintariffimport import FeedInTariffImport
|
||||
@@ -64,16 +69,9 @@ def prepare_tariffs(config_eos):
|
||||
prediction = Mock(
|
||||
update_data=AsyncMock(), key_to_raw_series=AsyncMock(side_effect=read_series)
|
||||
)
|
||||
ems = Mock(
|
||||
start_datetime=to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC"),
|
||||
observation_datetime=to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC"),
|
||||
)
|
||||
ems.genetic_solution.return_value = None
|
||||
with (
|
||||
patch("akkudoktoreos.optimization.genetic.configrequest.get_ems", return_value=ems),
|
||||
patch.object(ConfigOptimizationRequest, "prediction", prediction),
|
||||
):
|
||||
parameters = await GeneticOptimizationParameters.prepare()
|
||||
start = to_datetime("2026-08-01T00:00:00+00:00", in_timezone="UTC")
|
||||
with patch.object(geneticprepare, "get_prediction", return_value=prediction):
|
||||
parameters = (await geneticprepare.prepare(start, start, None)).request
|
||||
return parameters, prices, prediction
|
||||
|
||||
return prepare
|
||||
@@ -107,12 +105,12 @@ async def test_provider_revenues_survive_preparation_and_simulation(
|
||||
|
||||
# A 1 kWh export at 0.00007 amount/Wh earns 0.07, not 70 or 0.00007.
|
||||
# No battery or household load is needed to expose tariff substitution/unit bugs.
|
||||
inverter = Inverter(InverterParameters(device_id="inverter1", max_power_wh=10000))
|
||||
inverter = GeneticInverter(GeneticInverterRequest(device_id="inverter1", max_power_wh=10000).to_parameters())
|
||||
inverter.self_consumption_predictor = Mock()
|
||||
inverter.self_consumption_predictor.calculate_expected_direct_consumption.return_value = 0.0
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
parameters.ems, optimization_hours=24, prediction_hours=24, inverter=inverter
|
||||
parameters.ems.to_parameters(), optimization_hours=24, prediction_hours=24, inverter=inverter
|
||||
)
|
||||
result = simulation.simulate(start_hour=0)
|
||||
assert result["Netzeinspeisung_Wh_pro_Stunde"] == pytest.approx([1000.0] * 24)
|
||||
@@ -138,15 +136,18 @@ async def test_provider_revenues_survive_preparation_and_simulation(
|
||||
[[0.00007]] * 24,
|
||||
],
|
||||
)
|
||||
async def test_invalid_import_cancels_without_replacing_provider(
|
||||
async def test_invalid_import_falls_back_without_replacing_provider(
|
||||
prepare_tariffs, revenues, config_eos, caplog
|
||||
):
|
||||
"""Missing revenues are carried forward or 0, logged; the provider stays configured."""
|
||||
parameters, _, prediction = await prepare_tariffs("FeedInTariffImport", revenues)
|
||||
assert parameters is None
|
||||
tariffs = parameters.ems.feed_in_tariff_per_wh
|
||||
assert isinstance(tariffs, list) and len(tariffs) == 24
|
||||
assert all(np.isfinite(tariffs))
|
||||
assert set(tariffs) <= {0.00007, 0.0}
|
||||
assert config_eos.feedintariff.provider == "FeedInTariffImport"
|
||||
prediction.update_data.assert_awaited_once()
|
||||
assert "canceling optimization" in caplog.text
|
||||
assert "FeedInTariffImport" in caplog.text
|
||||
assert "feed-in tariff missing or invalid" in caplog.text
|
||||
assert "defaulting to demo" not in caplog.text
|
||||
|
||||
|
||||
@@ -170,7 +171,8 @@ async def test_timestamped_import_records_are_read_in_order(prepare_tariffs, val
|
||||
"FeedInTariffImport", [], tariff_reader=provider.key_to_raw_series
|
||||
)
|
||||
if values[0] is None:
|
||||
assert parameters is None
|
||||
# No revenue known at all: no feed-in revenue.
|
||||
assert parameters.ems.feed_in_tariff_per_wh == [0.0] * 24
|
||||
else:
|
||||
assert parameters is not None
|
||||
assert parameters.ems.feed_in_tariff_per_wh == pytest.approx(values)
|
||||
|
||||
+17
-18
@@ -6,11 +6,13 @@ from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from conftest import genetic_result_of, genetic_run_parameters
|
||||
from fastapi.testclient import TestClient
|
||||
from pypdf import PdfReader
|
||||
|
||||
from akkudoktoreos.optimization.genetic import geneticvisualize
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic import geneticapi, geneticvisualize
|
||||
from akkudoktoreos.optimization.genetic.geneticapi import GeneticSolution
|
||||
from akkudoktoreos.optimization.optimizer import OptimizerRun
|
||||
from akkudoktoreos.server import eos
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
@@ -20,11 +22,11 @@ def retained_result():
|
||||
path = Path(__file__).parent / "testdata/genetic/optimize_result_1.json"
|
||||
solution = GeneticSolution.model_validate_json(path.read_text())
|
||||
solution.start_solution_datetime = to_datetime("2026-09-16T10:00:00+02:00")
|
||||
return solution
|
||||
return genetic_result_of(solution)
|
||||
|
||||
|
||||
def test_missing_algorithm_report_returns_404(config_eos, monkeypatch):
|
||||
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(genetic_solution=lambda: None))
|
||||
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(optimizer_run=lambda name: None))
|
||||
response = TestClient(eos.app).get("/v1/energy-management/optimization/solution/GENETIC/pdf")
|
||||
assert response.status_code == 404
|
||||
assert response.headers["content-type"].startswith("application/problem+json")
|
||||
@@ -32,24 +34,21 @@ def test_missing_algorithm_report_returns_404(config_eos, monkeypatch):
|
||||
|
||||
def test_retained_algorithm_result_renders_real_pdf(config_eos, monkeypatch, retained_result):
|
||||
solution = retained_result
|
||||
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(genetic_solution=lambda: solution))
|
||||
run = OptimizerRun(parameters=genetic_run_parameters(solution.request), result=solution)
|
||||
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(optimizer_run={"GENETIC": run}.get))
|
||||
# A later run and changed configuration must not retime the retained report.
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.optimization.genetic import geneticvisualize
|
||||
|
||||
get_ems().set_start_datetime(to_datetime("2027-01-01T00:00:00+01:00"))
|
||||
config_eos.optimization.genetic.interval_sec = 900
|
||||
monkeypatch.setattr(
|
||||
geneticvisualize, "get_ems", lambda: pytest.fail("Report must retain its own time grid")
|
||||
)
|
||||
before = solution.model_dump_json()
|
||||
before = geneticapi.solution_response(solution).model_dump_json()
|
||||
response = TestClient(eos.app).get("/v1/energy-management/optimization/solution/GENETIC/pdf")
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-type"] == "application/pdf"
|
||||
assert "genetic" in response.headers["content-disposition"]
|
||||
assert response.content.startswith(b"%PDF-")
|
||||
assert len(PdfReader(BytesIO(response.content)).pages) >= 4
|
||||
assert solution.model_dump_json() == before
|
||||
assert geneticapi.solution_response(solution).model_dump_json() == before
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -57,21 +56,21 @@ async def test_render_is_offloaded_and_uses_an_owned_copy(config_eos, monkeypatc
|
||||
solution = retained_result
|
||||
caller_thread = threading.get_ident()
|
||||
captured = []
|
||||
monkeypatch.setattr(
|
||||
eos,
|
||||
"get_ems",
|
||||
lambda: SimpleNamespace(genetic_solution=lambda: solution),
|
||||
)
|
||||
run = OptimizerRun(parameters=genetic_run_parameters(solution.request), result=solution)
|
||||
monkeypatch.setattr(eos, "get_ems", lambda: SimpleNamespace(optimizer_run={"GENETIC": run}.get))
|
||||
original_controls = list(solution.ac_charge)
|
||||
|
||||
def render(*, solution):
|
||||
def render(*, parameters, result):
|
||||
solution = result
|
||||
captured.append((threading.get_ident(), solution))
|
||||
solution.ac_charge[0] = 0.123
|
||||
return b"%PDF-isolated-render"
|
||||
|
||||
# The PDF stack is imported on first use, so patch it at its source.
|
||||
monkeypatch.setattr(geneticvisualize, "genetic_prepare_visualize", render)
|
||||
response = await eos.fastapi_energy_management_optimization_solution_genetic_pdf_get()
|
||||
response = await geneticapi.fastapi_energy_management_optimization_solution_genetic_pdf_get(
|
||||
latest=run
|
||||
)
|
||||
assert response.body == b"%PDF-isolated-render"
|
||||
assert captured[0][0] != caller_thread
|
||||
assert captured[0][1] is not solution
|
||||
|
||||
@@ -4,18 +4,19 @@ from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from conftest import genetic_optimization
|
||||
from deap import creator, tools
|
||||
|
||||
from akkudoktoreos.config.config import ConfigEOS
|
||||
from akkudoktoreos.core.coreabc import get_ems
|
||||
from akkudoktoreos.optimization.genetic.genetic import (
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
_pack_genes,
|
||||
_release_freed_memory,
|
||||
_unpack_genes,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticEnergyManagementParameters,
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticEnergyManagementRequest,
|
||||
GeneticOptimizationParameters,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, compare_datetimes, to_datetime
|
||||
@@ -35,7 +36,7 @@ def _configure_hourly_grid(config_eos: ConfigEOS, *, start_hour: int = 0) -> Non
|
||||
|
||||
def test_ev_repair_is_resimulated_before_fitness_assignment(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = True
|
||||
opt.ev_possible_charge_values = [0.0, 1.0]
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
@@ -115,7 +116,7 @@ def test_release_freed_memory_is_safe_to_call():
|
||||
|
||||
def test_fitness_cache_restores_canonical_ev_genome(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = True
|
||||
opt.ev_possible_charge_values = [0.0, 1.0]
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
@@ -149,7 +150,7 @@ def test_fitness_cache_restores_canonical_ev_genome(config_eos: ConfigEOS):
|
||||
|
||||
def test_fitness_cache_never_stores_failed_evaluations(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
parameters = SimpleNamespace(
|
||||
@@ -172,7 +173,7 @@ def test_fitness_cache_never_stores_failed_evaluations(config_eos: ConfigEOS):
|
||||
|
||||
def test_fitness_cache_includes_first_run_relative_control(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos, start_hour=10)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=10)
|
||||
parameters = SimpleNamespace(
|
||||
@@ -200,7 +201,7 @@ def test_fitness_cache_includes_first_run_relative_control(config_eos: ConfigEOS
|
||||
|
||||
def test_mutated_warm_start_neighbors_stay_within_control_horizon(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos, start_hour=10)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=10)
|
||||
start_solution = [0.0] * opt.control_slots
|
||||
@@ -218,7 +219,7 @@ def test_initial_population_uses_fixed_seed_budget_and_configured_population(
|
||||
):
|
||||
_configure_hourly_grid(config_eos)
|
||||
config_eos.optimization.genetic.individuals = 300
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
start_solution = [5.0] * opt.control_slots
|
||||
@@ -263,7 +264,7 @@ def test_initial_population_uses_fixed_seed_budget_and_configured_population(
|
||||
def test_small_population_scales_warm_and_educated_seed_families(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
config_eos.optimization.genetic.individuals = 100
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
start_solution = [5.0] * opt.control_slots
|
||||
@@ -315,7 +316,7 @@ def test_small_population_scales_warm_and_educated_seed_families(config_eos: Con
|
||||
|
||||
def test_adaptive_evolution_soft_restarts_collapsed_population(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
opt.toolbox.register("evaluate", lambda individual: (float(sum(individual)),))
|
||||
@@ -347,7 +348,7 @@ def test_adaptive_evolution_soft_restarts_collapsed_population(config_eos: Confi
|
||||
|
||||
def test_local_search_moves_weak_export_to_later_expensive_import(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.optimize_dc_charge = True
|
||||
opt.optimize_battery_grid_export = True
|
||||
@@ -395,7 +396,7 @@ def test_local_search_moves_weak_export_to_later_expensive_import(config_eos: Co
|
||||
|
||||
def test_educated_guesses_encode_high_price_direct_marketing(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.optimize_dc_charge = True
|
||||
opt.optimize_battery_grid_export = True
|
||||
@@ -422,7 +423,7 @@ def test_educated_guesses_encode_high_price_direct_marketing(config_eos: ConfigE
|
||||
|
||||
def test_flat_feed_in_tariff_does_not_seed_direct_marketing(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.optimize_dc_charge = True
|
||||
opt.optimize_battery_grid_export = True
|
||||
@@ -483,7 +484,7 @@ def _immigrant_selection_pool(opt: GeneticOptimization, protection: int):
|
||||
|
||||
def test_protected_immigrants_survive_the_selection(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
|
||||
@@ -503,7 +504,7 @@ def test_protected_immigrants_survive_the_selection(config_eos: ConfigEOS):
|
||||
|
||||
def test_immigrant_protection_expires_after_its_generations(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
|
||||
@@ -520,7 +521,7 @@ def test_immigrant_protection_expires_after_its_generations(config_eos: ConfigEO
|
||||
|
||||
def test_offspring_do_not_inherit_immigrant_protection(config_eos: ConfigEOS):
|
||||
_configure_hourly_grid(config_eos)
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = False
|
||||
opt.setup_deap_environment({"home_appliance": 0}, start_hour=0)
|
||||
opt.toolbox.register("evaluate", lambda individual: (float(sum(individual)),))
|
||||
@@ -549,7 +550,7 @@ def _warm_start_optimizer(
|
||||
}
|
||||
)
|
||||
slot0 = get_ems(init=True).set_start_datetime(to_datetime().set(hour=8, minute=0, second=0))
|
||||
opt = GeneticOptimization(fixed_seed=42)
|
||||
opt = genetic_optimization(seed=42)
|
||||
opt.optimize_ev = optimize_ev
|
||||
opt.appliance_layout = SimpleNamespace(n_genes=n_appliance_genes, genes=[]) # type: ignore[assignment]
|
||||
opt._slot0_datetime = slot0
|
||||
@@ -609,30 +610,10 @@ class TestWarmStartAlignment:
|
||||
|
||||
assert opt._start_solution_for_run_start(previous, slot0.add(minutes=offset_minutes)) is None
|
||||
|
||||
def test_start_datetime_falls_back_to_last_solution_of_this_server(self,
|
||||
config_eos: ConfigEOS, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
opt, slot0 = _warm_start_optimizer(config_eos, interval=900)
|
||||
last_start = slot0.subtract(minutes=15)
|
||||
monkeypatch.setattr(
|
||||
type(get_ems()),
|
||||
"_genetic_solution",
|
||||
SimpleNamespace(start_solution=[19.0, 32.0, 14.0], start_solution_datetime=last_start),
|
||||
)
|
||||
|
||||
same = SimpleNamespace(start_solution=[19, 32, 14], start_solution_datetime=None)
|
||||
other = SimpleNamespace(start_solution=[19, 32, 15], start_solution_datetime=None)
|
||||
explicit_start = slot0.subtract(minutes=30)
|
||||
explicit = SimpleNamespace(start_solution=[19, 32, 14], start_solution_datetime=explicit_start)
|
||||
|
||||
assert opt._resolve_start_solution_datetime(same) == last_start # type: ignore[arg-type]
|
||||
assert opt._resolve_start_solution_datetime(other) is None # type: ignore[arg-type]
|
||||
assert opt._resolve_start_solution_datetime(explicit) == explicit_start # type: ignore[arg-type]
|
||||
|
||||
def test_parameters_accept_iso_start_solution_datetime(self, config_eos: ConfigEOS):
|
||||
parameters = GeneticOptimizationParameters.model_validate(
|
||||
dict(
|
||||
ems=GeneticEnergyManagementParameters.model_validate(
|
||||
ems=GeneticEnergyManagementRequest.model_validate(
|
||||
dict(
|
||||
pv_prognose_wh=[0.0, 0.0],
|
||||
strompreis_euro_pro_wh=[0.0, 0.0],
|
||||
|
||||
@@ -2,24 +2,28 @@ import numpy as np
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
Battery,
|
||||
ElectricVehicleParameters,
|
||||
SolarPanelBatteryParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.homeappliance import (
|
||||
HomeAppliance,
|
||||
HomeApplianceParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.inverter import (
|
||||
Inverter,
|
||||
InverterParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.genetic import (
|
||||
GeneticEnergyManagementParameters,
|
||||
GeneticSimulation,
|
||||
from akkudoktoreos.optimization.genetic.geneticapi import (
|
||||
GeneticSimulationResult,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticElectricVehicleRequest,
|
||||
GeneticEnergyManagementRequest,
|
||||
GeneticHomeApplianceRequest,
|
||||
GeneticInverterRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsimulation import (
|
||||
GeneticSimulation,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_duration, to_time
|
||||
|
||||
start_hour = 1
|
||||
@@ -28,8 +32,8 @@ start_hour = 1
|
||||
@pytest.mark.parametrize("efficiency_curve", [None, [(0.0, 0.8), (1.0, 0.97)]])
|
||||
def test_below_min_soc_requires_real_charging_energy(efficiency_curve):
|
||||
"""Discharge attempts before and after partial charging must not create energy."""
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=26_400,
|
||||
initial_soc_percentage=0,
|
||||
@@ -37,12 +41,12 @@ def test_below_min_soc_requires_real_charging_energy(efficiency_curve):
|
||||
max_charge_power_w=7_000,
|
||||
charging_efficiency=0.95,
|
||||
discharging_efficiency=0.95,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=4,
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
inverter = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
battery_id="battery1",
|
||||
max_power_wh=10_000,
|
||||
@@ -50,19 +54,19 @@ def test_below_min_soc_requires_real_charging_energy(efficiency_curve):
|
||||
ac_to_dc_efficiency=0.97,
|
||||
dc_to_ac_efficiency=0.97,
|
||||
dc_to_ac_efficiency_curve=efficiency_curve,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters(
|
||||
GeneticEnergyManagementRequest(
|
||||
pv_forecast_wh=[0.0] * 4,
|
||||
total_load=[280.0] * 4,
|
||||
electricity_price_per_wh=[0.00037, 0.00037, 0.00050, 0.00063],
|
||||
feed_in_tariff_per_wh=0.0,
|
||||
price_per_wh_battery=0.0,
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=4,
|
||||
prediction_hours=4,
|
||||
inverter=inverter,
|
||||
@@ -96,39 +100,39 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
|
||||
assert config_eos.optimization.genetic.horizon_hours == 24
|
||||
|
||||
# Initialize the battery and the inverter
|
||||
akku = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
akku = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
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 = Inverter(
|
||||
InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id),
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(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 = HomeAppliance(
|
||||
HomeApplianceParameters(
|
||||
home_appliance = GeneticHomeAppliance(
|
||||
GeneticHomeApplianceRequest(
|
||||
device_id="dishwasher1",
|
||||
consumption_wh=2000,
|
||||
duration_h=2,
|
||||
time_windows=None,
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours = config_eos.optimization.genetic.horizon_hours,
|
||||
prediction_hours = config_eos.prediction.hours,
|
||||
)
|
||||
|
||||
# Example initialization of electric car battery
|
||||
eauto = Battery(
|
||||
ElectricVehicleParameters(
|
||||
eauto = GeneticBattery(
|
||||
GeneticElectricVehicleRequest(
|
||||
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))
|
||||
@@ -293,13 +297,13 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
|
||||
# Initialize the energy management system with the respective parameters
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(dict(
|
||||
GeneticEnergyManagementRequest.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.genetic.horizon_hours,
|
||||
prediction_hours = config_eos.prediction.hours,
|
||||
inverter=inverter,
|
||||
@@ -316,7 +320,8 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
|
||||
simulation.dc_charge_hours[start_hour] = 1.0
|
||||
simulation.bat_discharge_hours[start_hour] = 1.0
|
||||
simulation.ev_charge_hours[start_hour] = 1.0
|
||||
simulation.home_appliance_start_hour = 2
|
||||
assert simulation.home_appliance is not None
|
||||
simulation.home_appliance.build_load_curve([2])
|
||||
|
||||
return simulation
|
||||
|
||||
@@ -435,11 +440,11 @@ def test_simulation(genetic_simulation):
|
||||
|
||||
def _profile_simulation(
|
||||
battery_curves: dict, initial_soc_percentage: int = 50
|
||||
) -> tuple[GeneticSimulation, Battery]:
|
||||
) -> tuple[GeneticSimulation, GeneticBattery]:
|
||||
"""48 slots with a battery that has the given profile curves, if any."""
|
||||
hours = 48
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=8000,
|
||||
initial_soc_percentage=initial_soc_percentage,
|
||||
@@ -450,17 +455,17 @@ def _profile_simulation(
|
||||
discharging_efficiency=0.9,
|
||||
levelized_cost_of_storage_kwh=0.05,
|
||||
**battery_curves,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=hours,
|
||||
)
|
||||
inverter = Inverter(
|
||||
InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id="battery1"),
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(device_id="inverter1", max_power_wh=10000, battery_id="battery1").to_parameters(),
|
||||
battery=battery,
|
||||
)
|
||||
rng = np.random.default_rng(7)
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(
|
||||
GeneticEnergyManagementRequest.model_validate(
|
||||
dict(
|
||||
pv_prognose_wh=(
|
||||
np.clip(np.sin(np.linspace(0, 4 * np.pi, hours)), 0, None) * 6000
|
||||
@@ -470,7 +475,7 @@ def _profile_simulation(
|
||||
preis_euro_pro_wh_akku=0.0001,
|
||||
gesamtlast=rng.uniform(300, 2500, hours).tolist(),
|
||||
)
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=24,
|
||||
prediction_hours=hours,
|
||||
inverter=inverter,
|
||||
@@ -478,7 +483,7 @@ def _profile_simulation(
|
||||
return simulation, battery
|
||||
|
||||
|
||||
def _run_plans(simulation: GeneticSimulation, battery: Battery) -> list[dict]:
|
||||
def _run_plans(simulation: GeneticSimulation, battery: GeneticBattery) -> list[dict]:
|
||||
rng = np.random.default_rng(11)
|
||||
hours = battery.prediction_hours
|
||||
results = []
|
||||
@@ -546,3 +551,25 @@ def test_soc_taper_slows_charging_near_full(config_eos):
|
||||
# The tapered battery takes at most 500 W x 1 h (before efficiency) per slot.
|
||||
assert results["taper"][1] < results["flat"][1]
|
||||
assert results["taper"][1] - results["taper"][0] <= 500.0 * 0.95 / 8000 * 100 + 1e-9
|
||||
|
||||
|
||||
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 = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementRequest(
|
||||
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
|
||||
|
||||
@@ -2,24 +2,28 @@ import numpy as np
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
Battery,
|
||||
ElectricVehicleParameters,
|
||||
SolarPanelBatteryParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.homeappliance import (
|
||||
HomeAppliance,
|
||||
HomeApplianceParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.inverter import (
|
||||
Inverter,
|
||||
InverterParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.genetic import (
|
||||
GeneticEnergyManagementParameters,
|
||||
GeneticSimulation,
|
||||
from akkudoktoreos.optimization.genetic.geneticapi import (
|
||||
GeneticSimulationResult,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticElectricVehicleRequest,
|
||||
GeneticEnergyManagementRequest,
|
||||
GeneticHomeApplianceRequest,
|
||||
GeneticInverterRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsimulation import (
|
||||
GeneticSimulation,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_duration, to_time
|
||||
|
||||
start_hour = 0
|
||||
@@ -37,39 +41,39 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation:
|
||||
assert config_eos.optimization.genetic.horizon_hours == 24
|
||||
|
||||
# Initialize the battery and the inverter
|
||||
akku = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
akku = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
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 = Inverter(
|
||||
InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id),
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(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 = HomeAppliance(
|
||||
HomeApplianceParameters(
|
||||
home_appliance = GeneticHomeAppliance(
|
||||
GeneticHomeApplianceRequest(
|
||||
device_id="dishwasher1",
|
||||
consumption_wh=2000,
|
||||
duration_h=2,
|
||||
time_windows=None,
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours = config_eos.optimization.genetic.horizon_hours,
|
||||
prediction_hours = config_eos.prediction.hours,
|
||||
)
|
||||
|
||||
# Example initialization of electric car battery
|
||||
eauto = Battery(
|
||||
ElectricVehicleParameters(
|
||||
eauto = GeneticBattery(
|
||||
GeneticElectricVehicleRequest(
|
||||
device_id="ev1", capacity_wh=26400, initial_soc_percentage=10, min_soc_percentage=10
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours = config_eos.prediction.hours,
|
||||
)
|
||||
|
||||
@@ -140,13 +144,13 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation:
|
||||
# Initialize the energy management system with the respective parameters
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(dict(
|
||||
GeneticEnergyManagementRequest.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.genetic.horizon_hours,
|
||||
prediction_hours = config_eos.prediction.hours,
|
||||
inverter=inverter,
|
||||
@@ -160,7 +164,8 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation:
|
||||
dc = np.full(config_eos.prediction.hours, 0.0)
|
||||
dc[11] = 1
|
||||
simulation.dc_charge_hours = dc
|
||||
simulation.home_appliance_start_hour = 2
|
||||
assert simulation.home_appliance is not None
|
||||
simulation.home_appliance.build_load_curve([2])
|
||||
|
||||
return simulation
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""GENETIC's own time windows give the same coverage as the shared settings windows (ADR 0004)."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.config.configabc import CycleTimeWindowSequence
|
||||
from akkudoktoreos.optimization.genetic.devices.genetichomeappliance import (
|
||||
GeneticHomeAppliance,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticHomeApplianceRequest,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
|
||||
|
||||
WINDOWS: list[dict[str, Any]] = [
|
||||
# Plain window per cycle, two windows sharing cycle 1.
|
||||
{"start_time": "08:00", "duration": "3 hours", "value": 0},
|
||||
{"start_time": "13:00", "duration": "2 hours", "value": 1},
|
||||
{"start_time": "16:00", "duration": "1 hour", "value": 1},
|
||||
# Overnight with an explicit end time, restricted to a weekday.
|
||||
{"start_time": "22:00", "duration": "1 hour", "end_time": "02:30", "day_of_week": 5,
|
||||
"value": 2},
|
||||
# Date restriction (within the tested ranges).
|
||||
{"start_time": "10:00", "duration": "2 hours", "date": "2026-09-17", "value": 4},
|
||||
{"start_time": "10:00", "duration": "2 hours", "date": "2026-03-29", "value": 4},
|
||||
# Month restriction and a window that belongs to no cycle.
|
||||
{"start_time": "00:00", "duration": "6 hours", "month": 3, "value": 3},
|
||||
{"start_time": "00:00", "duration": "24 hours"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"start, interval_s",
|
||||
[
|
||||
("2026-09-16T00:00:00", 3600),
|
||||
("2026-09-16T10:20:00", 900),
|
||||
# Spring forward and fall back in Berlin.
|
||||
("2026-03-28T00:00:00", 900),
|
||||
("2026-10-24T00:00:00", 3600),
|
||||
],
|
||||
)
|
||||
def test_window_coverage_matches_the_settings_windows(start: str, interval_s: int) -> None:
|
||||
"""Per cycle, the run's window check covers the same grid steps as the settings windows.
|
||||
|
||||
A one-second run is allowed where a window contains its start (the end is exclusive), so the
|
||||
run's check (``_windows_allow_run``) is compared with the settings' per-step coverage.
|
||||
"""
|
||||
settings = CycleTimeWindowSequence.model_validate({"windows": WINDOWS})
|
||||
request = GeneticHomeApplianceRequest(
|
||||
device_id="washer", consumption_wh=1000, duration_h=1, time_windows=settings
|
||||
)
|
||||
windows = request.to_parameters().time_windows
|
||||
assert windows is not None
|
||||
first = to_datetime(start, in_timezone="Europe/Berlin")
|
||||
last = first.add(hours=72)
|
||||
interval = to_duration(interval_s)
|
||||
|
||||
expected_cycles, expected = settings.cycles_to_matrix(first, last, interval)
|
||||
# The settings floor the grid start to the interval in wall-clock time.
|
||||
wall_s = first.hour * 3600 + first.minute * 60 + first.second + first.microsecond / 1_000_000
|
||||
grid = [
|
||||
first.subtract(seconds=wall_s % interval_s).add(seconds=step * interval_s)
|
||||
for step in range(expected.shape[1])
|
||||
]
|
||||
one_second = to_duration(1)
|
||||
cycles = sorted({int(window.value) for window in windows if window.value is not None})
|
||||
matrix = np.array(
|
||||
[
|
||||
[
|
||||
1.0
|
||||
if GeneticHomeAppliance._windows_allow_run(
|
||||
[w for w in windows if w.value is not None and int(w.value) == cycle],
|
||||
moment,
|
||||
one_second,
|
||||
merge=True,
|
||||
)
|
||||
else 0.0
|
||||
for moment in grid
|
||||
]
|
||||
for cycle in cycles
|
||||
]
|
||||
)
|
||||
|
||||
assert cycles == expected_cycles
|
||||
np.testing.assert_array_equal(matrix, expected)
|
||||
|
||||
def test_window_start_and_end_match_the_settings_windows() -> None:
|
||||
settings = CycleTimeWindowSequence.model_validate({"windows": WINDOWS})
|
||||
request = GeneticHomeApplianceRequest(
|
||||
device_id="washer", consumption_wh=1000, duration_h=1, time_windows=settings
|
||||
)
|
||||
windows = request.to_parameters().time_windows
|
||||
assert windows is not None
|
||||
for day in range(7):
|
||||
anchor = to_datetime("2026-10-24T12:00:00", in_timezone="Europe/Berlin").add(days=day)
|
||||
for own, shared in zip(windows, settings.windows):
|
||||
assert own.start_end(anchor) == shared._window_start_end(anchor)
|
||||
@@ -1,3 +1,4 @@
|
||||
from dataclasses import replace
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
@@ -7,20 +8,21 @@ import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pendulum
|
||||
import pytest
|
||||
from conftest import genetic_result_of, genetic_run_parameters
|
||||
from matplotlib.testing.compare import compare_images
|
||||
from pypdf import PdfReader
|
||||
|
||||
from akkudoktoreos.optimization.genetic import geneticvisualize as visualize
|
||||
from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic.geneticvisualize import (
|
||||
genetic_generate_example_report,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.terminalvalue import (
|
||||
from akkudoktoreos.optimization.genetic.geneticapi import GeneticSolution
|
||||
from akkudoktoreos.optimization.genetic.geneticterminalvalue import (
|
||||
TailDiagnostics,
|
||||
TailPlanSlot,
|
||||
TerminalValueCurve,
|
||||
TerminalValueResult,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticvisualize import (
|
||||
genetic_generate_example_report,
|
||||
)
|
||||
|
||||
filename = "example_report.pdf"
|
||||
|
||||
@@ -73,7 +75,7 @@ class TestGeneticVisualizationIntervals:
|
||||
home_appliance_energy_wh={"water-heater": energy},
|
||||
)
|
||||
return SimpleNamespace(
|
||||
parameters=SimpleNamespace(
|
||||
request=SimpleNamespace(
|
||||
ems=SimpleNamespace(
|
||||
total_load=energy,
|
||||
pv_forecast_wh=energy,
|
||||
@@ -131,8 +133,7 @@ class TestGeneticVisualizationIntervals:
|
||||
return original(self, start_date, y_list, **kwargs)
|
||||
|
||||
monkeypatch.setattr(visualize.GeneticVisualizationReport, "create_line_chart_date", capture)
|
||||
monkeypatch.setattr(visualize, "get_ems", lambda: pytest.fail("Snapshot must own report timing"))
|
||||
pdf = visualize.genetic_prepare_visualize(report_solution)
|
||||
pdf = visualize.genetic_prepare_visualize(genetic_run_parameters(report_solution.request), report_solution)
|
||||
assert pdf.startswith(b"%PDF-")
|
||||
assert all(row[0] == report_solution.start_solution_datetime for row in captured)
|
||||
assert all(row[3] == interval_seconds for row in captured)
|
||||
@@ -178,8 +179,12 @@ class TestGeneticVisualizationIntervals:
|
||||
assert not solution.controls_start_at_now
|
||||
assert solution.terminal_value is None
|
||||
start = pendulum.datetime(2026, 9, 16, solution.start_hour, tz="UTC")
|
||||
monkeypatch.setattr(visualize, "get_ems", lambda: SimpleNamespace(start_datetime=start))
|
||||
pdf = visualize.genetic_prepare_visualize(solution)
|
||||
# A historical solution has no start; the run start of the parameters is the fallback.
|
||||
parameters = genetic_run_parameters(solution.parameters)
|
||||
parameters = replace(
|
||||
parameters, settings=replace(parameters.settings, start_datetime=start)
|
||||
)
|
||||
pdf = visualize.genetic_prepare_visualize(parameters, genetic_result_of(solution))
|
||||
assert len(PdfReader(BytesIO(pdf)).pages) >= 4
|
||||
|
||||
def test_fixed_fallback_does_not_invent_tail_charts(self, config_eos, report_solution):
|
||||
@@ -188,7 +193,7 @@ class TestGeneticVisualizationIntervals:
|
||||
battery_energy_wh=500, requested_tail_hours=24,
|
||||
)
|
||||
report_solution.result.home_appliance_energy_wh = {}
|
||||
pdf = visualize.genetic_prepare_visualize(report_solution)
|
||||
pdf = visualize.genetic_prepare_visualize(genetic_run_parameters(report_solution.request), report_solution)
|
||||
text = " ".join(page.extract_text() for page in PdfReader(BytesIO(pdf)).pages)
|
||||
assert "No complete tail forecast" in text
|
||||
assert "effective tail: 0 h" in text
|
||||
@@ -219,9 +224,9 @@ class TestGeneticVisualizationIntervals:
|
||||
def test_pdf_clips_forecast_tail_and_accepts_historical_diagnostics(self,
|
||||
config_eos, monkeypatch, report_solution, tariff
|
||||
):
|
||||
report_solution.parameters.ems.total_load = [100.0] * 6
|
||||
report_solution.parameters.ems.pv_forecast_wh = [200.0] * 6
|
||||
report_solution.parameters.ems.feed_in_tariff_per_wh = tariff
|
||||
report_solution.request.ems.total_load = [100.0] * 6
|
||||
report_solution.request.ems.pv_forecast_wh = [200.0] * 6
|
||||
report_solution.request.ems.feed_in_tariff_per_wh = tariff
|
||||
report_solution.extra_data = {
|
||||
"verluste": [1.0, 2.0, 3.0], "bilanz": [0.1, 0.2, 0.3],
|
||||
"nebenbedingung": [0.0, 0.0, 0.0],
|
||||
@@ -234,7 +239,7 @@ class TestGeneticVisualizationIntervals:
|
||||
return original(self, start_date, y_list, **kwargs)
|
||||
|
||||
monkeypatch.setattr(visualize.GeneticVisualizationReport, "create_line_chart_date", capture)
|
||||
pdf = visualize.genetic_prepare_visualize(report_solution)
|
||||
pdf = visualize.genetic_prepare_visualize(genetic_run_parameters(report_solution.request), report_solution)
|
||||
assert pdf.startswith(b"%PDF-")
|
||||
tariff_plot = next(series for series, kwargs in captured if kwargs.get("title") == "Remuneration")
|
||||
assert np.asarray(tariff_plot[0]).tolist() == [0.00007] * 4
|
||||
|
||||
@@ -16,12 +16,18 @@ from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from conftest import genetic_optimization
|
||||
|
||||
from akkudoktoreos.devices.genetic.battery import (
|
||||
Battery,
|
||||
SolarPanelBatteryParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticInverterRequest,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers / Fixtures
|
||||
@@ -34,12 +40,12 @@ def _make_inverter(
|
||||
max_ac_charge_power_w=None,
|
||||
max_power_wh: float = 10000.0,
|
||||
mock_battery=None,
|
||||
) -> Inverter:
|
||||
) -> GeneticInverter:
|
||||
"""Create an Inverter with custom efficiency parameters and a mock battery."""
|
||||
mock_self_consumption_predictor = Mock()
|
||||
mock_self_consumption_predictor.calculate_expected_direct_consumption.side_effect = min
|
||||
|
||||
params = InverterParameters(
|
||||
params = GeneticInverterRequest(
|
||||
device_id="inv1",
|
||||
max_power_wh=max_power_wh,
|
||||
battery_id=mock_battery.parameters.device_id if mock_battery else None,
|
||||
@@ -48,10 +54,10 @@ def _make_inverter(
|
||||
max_ac_charge_power_w=max_ac_charge_power_w,
|
||||
)
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
|
||||
return_value=mock_self_consumption_predictor,
|
||||
):
|
||||
return Inverter(params, battery=mock_battery)
|
||||
return GeneticInverter(params.to_parameters(), battery=mock_battery)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -64,7 +70,7 @@ def mock_battery() -> Mock:
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# 1. InverterParameters – new fields and defaults
|
||||
# 1. GeneticInverterRequest – new fields and defaults
|
||||
# ===================================================================
|
||||
|
||||
|
||||
@@ -72,13 +78,13 @@ class TestInverterParametersDefaults:
|
||||
"""Verify backward-compatible defaults for new parameters."""
|
||||
|
||||
def test_defaults(self):
|
||||
params = InverterParameters(device_id="inv1", max_power_wh=5000)
|
||||
params = GeneticInverterRequest(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 = InverterParameters(
|
||||
params = GeneticInverterRequest(
|
||||
device_id="inv1",
|
||||
max_power_wh=5000,
|
||||
dc_to_ac_efficiency=0.95,
|
||||
@@ -90,17 +96,17 @@ class TestInverterParametersDefaults:
|
||||
assert params.max_ac_charge_power_w == 3000
|
||||
|
||||
def test_ac_to_dc_zero_disables_ac_charging(self):
|
||||
params = InverterParameters(
|
||||
params = GeneticInverterRequest(
|
||||
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):
|
||||
InverterParameters(device_id="inv1", max_power_wh=5000, dc_to_ac_efficiency=0.0)
|
||||
GeneticInverterRequest(device_id="inv1", max_power_wh=5000, dc_to_ac_efficiency=0.0)
|
||||
|
||||
def test_max_ac_charge_power_zero(self):
|
||||
params = InverterParameters(
|
||||
params = GeneticInverterRequest(
|
||||
device_id="inv1", max_power_wh=5000, max_ac_charge_power_w=0
|
||||
)
|
||||
assert params.max_ac_charge_power_w == 0
|
||||
@@ -215,9 +221,11 @@ class TestAcChargingInSimulation:
|
||||
@pytest.fixture
|
||||
def simulation_setup(self, config_eos):
|
||||
"""Set up a minimal GeneticSimulation with battery and inverter."""
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticEnergyManagementParameters,
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticEnergyManagementRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsimulation import (
|
||||
GeneticSimulation,
|
||||
)
|
||||
|
||||
config_eos.merge_settings_from_dict(
|
||||
@@ -236,8 +244,8 @@ class TestAcChargingInSimulation:
|
||||
battery_initial_soc_pct: int = 50,
|
||||
battery_max_charge_power_w: int = 5000,
|
||||
):
|
||||
akku = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
akku = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=battery_capacity_wh,
|
||||
initial_soc_percentage=battery_initial_soc_pct,
|
||||
@@ -246,32 +254,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 = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
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 = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(dict(
|
||||
GeneticEnergyManagementRequest.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.genetic.horizon_hours,
|
||||
prediction_hours=prediction_hours,
|
||||
inverter=inverter,
|
||||
@@ -465,14 +473,14 @@ class TestResidualBatteryValue:
|
||||
|
||||
def test_current_energy_content_unaffected(self):
|
||||
"""Battery.current_energy_content() is DC-only; inverter eff applied in optimizer."""
|
||||
akku = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
akku = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
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()
|
||||
@@ -551,7 +559,9 @@ def _run_evaluate_with_mocked_sim(
|
||||
- self.simulation is replaced by mock_sim
|
||||
Then call evaluate() and return the fitness tuple.
|
||||
"""
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization
|
||||
from akkudoktoreos.optimization.genetic.geneticalgorithm import (
|
||||
GeneticOptimization,
|
||||
)
|
||||
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
@@ -565,8 +575,8 @@ def _run_evaluate_with_mocked_sim(
|
||||
}
|
||||
|
||||
optim = GeneticOptimization.__new__(GeneticOptimization)
|
||||
# Minimal __init__ state expected by evaluate()
|
||||
optim.config = config_eos
|
||||
# Minimal __init__ state expected by evaluate(): the run settings of the configuration.
|
||||
optim.settings = genetic_optimization().settings
|
||||
optim.optimize_ev = False
|
||||
optim.verbose = False
|
||||
optim.opti_param = {"home_appliance": 0}
|
||||
|
||||
@@ -20,19 +20,28 @@ from akkudoktoreos.devices.devicesabc import (
|
||||
solve_ac_for_dc_energy,
|
||||
validate_efficiency_curve,
|
||||
)
|
||||
from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryParameters
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
from akkudoktoreos.devices.settings.invertersettings import (
|
||||
InverterCommonSettings,
|
||||
InverterProfileAdjustment,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic0 import genetic0prepare
|
||||
from akkudoktoreos.optimization.genetic.genetic import GeneticSimulation
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticEnergyManagementParameters,
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticbattery import (
|
||||
GeneticBattery,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.tailvalue import build_tail_value_curve
|
||||
from akkudoktoreos.optimization.genetic.terminalvalue import TerminalValueCurve
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticBatteryRequest,
|
||||
GeneticEnergyManagementRequest,
|
||||
GeneticInverterRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticsimulation import (
|
||||
GeneticSimulation,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.genetictailvalue import build_tail_value_curve
|
||||
from akkudoktoreos.optimization.genetic.geneticterminalvalue import TerminalValueCurve
|
||||
|
||||
CURVE = [(0.05, 0.80), (0.20, 0.90), (0.50, 0.95), (1.0, 0.93)]
|
||||
|
||||
@@ -43,22 +52,22 @@ def _make_inverter(
|
||||
battery=None,
|
||||
dc_to_ac_efficiency: float = 1.0,
|
||||
**kwargs,
|
||||
) -> Inverter:
|
||||
) -> GeneticInverter:
|
||||
predictor = Mock()
|
||||
predictor.calculate_expected_direct_consumption.side_effect = min
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
|
||||
return_value=predictor,
|
||||
):
|
||||
return Inverter(
|
||||
InverterParameters(
|
||||
return GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=max_power_wh,
|
||||
battery_id=battery.parameters.device_id if battery else None,
|
||||
dc_to_ac_efficiency=dc_to_ac_efficiency,
|
||||
dc_to_ac_efficiency_curve=curve,
|
||||
**kwargs,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
)
|
||||
|
||||
@@ -80,18 +89,18 @@ def _passthrough_battery() -> Mock:
|
||||
class TestCurveValidation:
|
||||
def test_none_is_allowed(self):
|
||||
assert validate_efficiency_curve(None) is None
|
||||
params = InverterParameters(device_id="inverter1", max_power_wh=1000)
|
||||
params = GeneticInverterRequest(device_id="inverter1", max_power_wh=1000)
|
||||
assert params.dc_to_ac_efficiency_curve is None
|
||||
assert params.dc_to_ac_efficiency_reference_load_fraction == pytest.approx(0.06)
|
||||
|
||||
def test_valid_curve_is_accepted(self):
|
||||
params = InverterParameters(
|
||||
params = GeneticInverterRequest(
|
||||
device_id="inverter1", max_power_wh=1000, dc_to_ac_efficiency_curve=CURVE
|
||||
)
|
||||
assert params.dc_to_ac_efficiency_curve == CURVE
|
||||
|
||||
def test_json_lists_are_accepted(self):
|
||||
params = InverterParameters.model_validate(
|
||||
params = GeneticInverterRequest.model_validate(
|
||||
{
|
||||
"device_id": "inverter1",
|
||||
"max_power_wh": 1000,
|
||||
@@ -116,14 +125,14 @@ class TestCurveValidation:
|
||||
)
|
||||
def test_invalid_curve_is_rejected(self, curve):
|
||||
with pytest.raises(ValidationError):
|
||||
InverterParameters(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1", max_power_wh=1000, dc_to_ac_efficiency_curve=curve
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("fraction", [-0.1, 1.1])
|
||||
def test_reference_load_fraction_range(self, fraction):
|
||||
with pytest.raises(ValidationError):
|
||||
InverterParameters(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=1000,
|
||||
dc_to_ac_efficiency_reference_load_fraction=fraction,
|
||||
@@ -166,15 +175,15 @@ class TestInterpolation:
|
||||
"""max_power_wh is scaled to the slot, so 250 Wh in 15 min is 1 kW."""
|
||||
predictor = Mock()
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
|
||||
return_value=predictor,
|
||||
):
|
||||
inverter = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=5000.0,
|
||||
dc_to_ac_efficiency_curve=CURVE,
|
||||
),
|
||||
).to_parameters(),
|
||||
slot_duration_h=0.25,
|
||||
)
|
||||
# 1 kW of 5 kW -> load fraction 0.2
|
||||
@@ -237,8 +246,8 @@ class TestProcessEnergyWithCurve:
|
||||
|
||||
def test_grid_export_uses_efficiency_at_export_level(self, config_eos):
|
||||
"""A full-power export runs at the efficiency of the rated load."""
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=10000,
|
||||
initial_soc_percentage=100,
|
||||
@@ -246,7 +255,7 @@ class TestProcessEnergyWithCurve:
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=1.0,
|
||||
max_charge_power_w=1000,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=1,
|
||||
)
|
||||
battery.reset()
|
||||
@@ -289,8 +298,8 @@ class TestReferenceEfficiency:
|
||||
"""Stored energy is valued with the efficiency at the reference load."""
|
||||
|
||||
def tail_curve(efficiency_curve):
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=1000,
|
||||
max_charge_power_w=1000,
|
||||
@@ -298,16 +307,16 @@ class TestReferenceEfficiency:
|
||||
discharging_efficiency=1.0,
|
||||
initial_soc_percentage=50,
|
||||
charge_rates=[0, 0.5, 1],
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=1,
|
||||
)
|
||||
inverter = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
battery_id="battery1",
|
||||
max_power_wh=5000,
|
||||
dc_to_ac_efficiency_curve=efficiency_curve,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
)
|
||||
return build_tail_value_curve(
|
||||
@@ -344,8 +353,8 @@ def _simulate(config_eos, efficiency_curve, dc_to_ac_efficiency=0.95):
|
||||
"optimization": {"genetic": {"tail_horizon_hours": 0, "horizon_hours": hours}},
|
||||
}
|
||||
)
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=10000,
|
||||
initial_soc_percentage=60,
|
||||
@@ -353,25 +362,25 @@ def _simulate(config_eos, efficiency_curve, dc_to_ac_efficiency=0.95):
|
||||
charging_efficiency=0.95,
|
||||
discharging_efficiency=0.95,
|
||||
max_charge_power_w=4000,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=hours,
|
||||
)
|
||||
battery.reset()
|
||||
inverter = Inverter(
|
||||
InverterParameters(
|
||||
inverter = GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=5000,
|
||||
battery_id="battery1",
|
||||
dc_to_ac_efficiency=dc_to_ac_efficiency,
|
||||
ac_to_dc_efficiency=0.95,
|
||||
dc_to_ac_efficiency_curve=efficiency_curve,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
)
|
||||
rng = np.random.default_rng(42)
|
||||
simulation = GeneticSimulation()
|
||||
simulation.prepare(
|
||||
GeneticEnergyManagementParameters.model_validate(
|
||||
GeneticEnergyManagementRequest.model_validate(
|
||||
dict(
|
||||
pv_prognose_wh=list(np.maximum(rng.normal(1500, 1500, hours), 0.0)),
|
||||
strompreis_euro_pro_wh=list(rng.uniform(0.0001, 0.0004, hours)),
|
||||
@@ -379,7 +388,7 @@ def _simulate(config_eos, efficiency_curve, dc_to_ac_efficiency=0.95):
|
||||
preis_euro_pro_wh_akku=0.0001,
|
||||
gesamtlast=list(rng.uniform(100, 3000, hours)),
|
||||
)
|
||||
),
|
||||
).to_parameters(),
|
||||
optimization_hours=hours,
|
||||
prediction_hours=hours,
|
||||
inverter=inverter,
|
||||
@@ -427,7 +436,7 @@ class TestSettings:
|
||||
dc_to_ac_efficiency_reference_load_fraction=0.1,
|
||||
)
|
||||
profile = settings.get_inverter_profile()
|
||||
params = settings.to_genetic_param()
|
||||
params = geneticprepare.inverter_request(settings)
|
||||
assert params.dc_to_ac_efficiency_curve is not None
|
||||
# Not derated at 45 degC: the curve is the profile curve over [0, 1].
|
||||
expected = list(zip(profile.dc_to_ac_efficiency.x, profile.dc_to_ac_efficiency.y))
|
||||
@@ -464,9 +473,9 @@ def _real_battery(
|
||||
max_power_w: float = 1000.0,
|
||||
discharging_efficiency: float = 1.0,
|
||||
slot_duration_h: float = 1.0,
|
||||
) -> Battery:
|
||||
battery = Battery(
|
||||
SolarPanelBatteryParameters(
|
||||
) -> GeneticBattery:
|
||||
battery = GeneticBattery(
|
||||
GeneticBatteryRequest(
|
||||
device_id="battery1",
|
||||
capacity_wh=capacity_wh,
|
||||
initial_soc_percentage=soc_percentage,
|
||||
@@ -474,7 +483,7 @@ def _real_battery(
|
||||
charging_efficiency=1.0,
|
||||
discharging_efficiency=discharging_efficiency,
|
||||
max_charge_power_w=max_power_w,
|
||||
),
|
||||
).to_parameters(),
|
||||
prediction_hours=1,
|
||||
slot_duration_h=slot_duration_h,
|
||||
)
|
||||
@@ -483,21 +492,21 @@ def _real_battery(
|
||||
return battery
|
||||
|
||||
|
||||
def _real_inverter(battery: Battery, curve=None, slot_duration_h: float = 1.0, **kwargs) -> Inverter:
|
||||
def _real_inverter(battery: GeneticBattery, curve=None, slot_duration_h: float = 1.0, **kwargs) -> GeneticInverter:
|
||||
predictor = Mock()
|
||||
predictor.calculate_expected_direct_consumption.side_effect = min
|
||||
with patch(
|
||||
"akkudoktoreos.devices.genetic.inverter.get_eos_load_interpolator",
|
||||
"akkudoktoreos.optimization.genetic.devices.geneticinverter.get_genetic_load_interpolator",
|
||||
return_value=predictor,
|
||||
):
|
||||
return Inverter(
|
||||
InverterParameters(
|
||||
return GeneticInverter(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1",
|
||||
max_power_wh=1000.0,
|
||||
battery_id="battery1",
|
||||
dc_to_ac_efficiency_curve=curve,
|
||||
**kwargs,
|
||||
),
|
||||
).to_parameters(),
|
||||
battery=battery,
|
||||
slot_duration_h=slot_duration_h,
|
||||
)
|
||||
@@ -672,12 +681,12 @@ class TestSolveAcForChargeDcEnergy:
|
||||
class TestChargeFromGridWithCurve:
|
||||
def test_curve_is_validated(self):
|
||||
with pytest.raises(ValidationError):
|
||||
InverterParameters(
|
||||
GeneticInverterRequest(
|
||||
device_id="inverter1", max_power_wh=1000, ac_to_dc_efficiency_curve=[(0.5, 0.9)]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _empty_battery() -> Battery:
|
||||
def _empty_battery() -> GeneticBattery:
|
||||
battery = _real_battery(soc_percentage=0)
|
||||
battery.charge_array = np.ones(1)
|
||||
return battery
|
||||
@@ -705,7 +714,7 @@ class TestChargeFromGridWithCurve:
|
||||
profile_adjustment=InverterProfileAdjustment(nominal_power_w=5000),
|
||||
)
|
||||
profile = settings.get_inverter_profile()
|
||||
params = settings.to_genetic_param()
|
||||
params = geneticprepare.inverter_request(settings)
|
||||
assert params.ac_to_dc_efficiency_curve is not None
|
||||
assert [y for _, y in params.ac_to_dc_efficiency_curve] == pytest.approx(
|
||||
list(profile.ac_to_dc_efficiency.y)
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.devices.genetic.heatpump import Heatpump
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticheatpump import GeneticHeatpump
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def hp_5kw_24h() -> Heatpump:
|
||||
def hp_5kw_24h() -> GeneticHeatpump:
|
||||
"""Heatpump with 5 kW heating power and 24 h prediction."""
|
||||
return Heatpump(5000, 24)
|
||||
return GeneticHeatpump(5000, 24)
|
||||
|
||||
|
||||
class TestHeatpump:
|
||||
def test_cop(self, hp_5kw_24h: Heatpump):
|
||||
def test_cop(self, hp_5kw_24h: GeneticHeatpump):
|
||||
"""Testing calculate COP for various outside temperatures."""
|
||||
assert hp_5kw_24h.calculate_cop(-10) == 2.0
|
||||
assert hp_5kw_24h.calculate_cop(0) == 3.0
|
||||
@@ -23,13 +23,13 @@ class TestHeatpump:
|
||||
with pytest.raises(ValueError, match=f"'{out_temp_max}' not in range"):
|
||||
hp_5kw_24h.calculate_cop(out_temp_max)
|
||||
|
||||
def test_heating_output(self, hp_5kw_24h: Heatpump):
|
||||
def test_heating_output(self, hp_5kw_24h: GeneticHeatpump):
|
||||
"""Testing calculation of heating output."""
|
||||
assert hp_5kw_24h.calculate_heating_output(-10.0) == 5000
|
||||
assert hp_5kw_24h.calculate_heating_output(0.0) == 5000
|
||||
assert hp_5kw_24h.calculate_heating_output(10.0) == pytest.approx(4939.583)
|
||||
|
||||
def test_heating_power(self, hp_5kw_24h: Heatpump):
|
||||
def test_heating_power(self, hp_5kw_24h: GeneticHeatpump):
|
||||
"""Testing calculation of heating power."""
|
||||
assert hp_5kw_24h.calculate_heat_power(-10.0) == 2104
|
||||
assert hp_5kw_24h.calculate_heat_power(0.0) == 1164
|
||||
|
||||
@@ -104,9 +104,14 @@ def test_genetic0_inverter_keeps_its_independent_interpolator():
|
||||
|
||||
@pytest.mark.parametrize("load,pv", [(4000.0, 5000.0), (10000.0, 20000.0)])
|
||||
def test_genetic_inverter_boundary_flows_remain_nonnegative(load, pv):
|
||||
from akkudoktoreos.devices.genetic.inverter import Inverter, InverterParameters
|
||||
from akkudoktoreos.optimization.genetic.devices.geneticinverter import (
|
||||
GeneticInverter,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticInverterRequest,
|
||||
)
|
||||
|
||||
inverter = Inverter(InverterParameters(device_id="boundary", max_power_wh=25000))
|
||||
inverter = GeneticInverter(GeneticInverterRequest(device_id="boundary", max_power_wh=25000).to_parameters())
|
||||
flows = inverter.process_energy(generation=pv, consumption=load, hour=0)
|
||||
assert all(np.isfinite(value) and value >= 0.0 for value in flows)
|
||||
|
||||
|
||||
@@ -6,17 +6,18 @@ from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.optimization.genetic import geneticprepare
|
||||
from akkudoktoreos.optimization.genetic0.genetic0request import (
|
||||
Genetic0EnergyManagementRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.genetic.geneticparams import (
|
||||
GeneticEnergyManagementParameters,
|
||||
from akkudoktoreos.optimization.genetic.geneticrequest import (
|
||||
GeneticEnergyManagementRequest,
|
||||
)
|
||||
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model", [GeneticEnergyManagementParameters, Genetic0EnergyManagementRequest]
|
||||
"model", [GeneticEnergyManagementRequest, Genetic0EnergyManagementRequest]
|
||||
)
|
||||
@pytest.mark.parametrize("tariff", [0.00008, [0.00008, -0.00002]])
|
||||
def test_energy_parameter_aliases_preserve_wh_prices(model, tariff):
|
||||
@@ -46,15 +47,12 @@ 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)."""
|
||||
"""Each optimizer serves its own solution from its router (ADR 0005, 0011)."""
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from akkudoktoreos.server import eos
|
||||
|
||||
fake = SimpleNamespace(
|
||||
genetic_solution=Mock(return_value=None),
|
||||
optimizer_run=Mock(return_value=None),
|
||||
)
|
||||
fake = SimpleNamespace(optimizer_run=Mock(return_value=None))
|
||||
monkeypatch.setattr(eos, "get_ems", lambda: fake)
|
||||
monkeypatch.setattr(
|
||||
eos,
|
||||
@@ -67,12 +65,27 @@ async def test_algorithm_result_endpoint_keeps_solution_types_separate(monkeypat
|
||||
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:
|
||||
fake.genetic_solution.assert_called_once_with()
|
||||
fake.optimizer_run.assert_not_called()
|
||||
else:
|
||||
fake.optimizer_run.assert_called_once_with("GENETIC0")
|
||||
fake.genetic_solution.assert_not_called()
|
||||
fake.optimizer_run.assert_called_once_with(str(algorithm))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("algorithm", ["genetic", "FOO"])
|
||||
async def test_unknown_algorithm_solution_is_a_problem_response(algorithm):
|
||||
"""An algorithm without its own solution endpoint gets a 404 problem response, not HTML."""
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from akkudoktoreos.server import eos
|
||||
|
||||
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.headers["content-type"].startswith("application/problem+json")
|
||||
problem = response.json()
|
||||
assert problem["title"] == "Unknown optimization algorithm"
|
||||
assert f"'{algorithm}' unknown" in problem["detail"]
|
||||
assert "GENETIC0" in problem["detail"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("algorithm", ["genetic", "genetic0"])
|
||||
@@ -118,10 +131,10 @@ def test_device_maps_feed_algorithm_specific_converters(algorithm):
|
||||
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()
|
||||
battery = geneticprepare.battery_request(storage)
|
||||
ev = geneticprepare.electric_vehicle_request(car)
|
||||
inverter = geneticprepare.inverter_request(hybrid)
|
||||
appliance = geneticprepare.home_appliance_request(washer)
|
||||
assert (battery.device_id, ev.device_id, inverter.device_id, appliance.device_id) == (
|
||||
"storage",
|
||||
"car",
|
||||
|
||||
@@ -149,14 +149,22 @@ WORLD_NAMES: dict[str, frozenset[str]] = {
|
||||
# Modules that mix the output contract or the public request schema with
|
||||
# configuration or Pydantic: from them an optimizer imports only the listed
|
||||
# names (ADR 0004, 0007): the solution, its DataFrame type, the operation-mode
|
||||
# enums of the plan's instructions and the time windows of a request.
|
||||
# enums of the plan's instructions, and the time windows and consumer schedule
|
||||
# enums of a request.
|
||||
CONTRACT_NAMES: dict[str, frozenset[str]] = {
|
||||
"akkudoktoreos.optimization.optimization": frozenset({"OptimizationSolution"}),
|
||||
"akkudoktoreos.core.pydantic": frozenset({"PydanticDateTimeDataFrame"}),
|
||||
"akkudoktoreos.devices.devicesabc": frozenset(
|
||||
{"ApplianceOperationMode", "BatteryOperationMode"}
|
||||
{
|
||||
"ApplianceOperationMode",
|
||||
"BatteryOperationMode",
|
||||
"ConsumerDeadlinePolicy",
|
||||
"ConsumerScheduleMode",
|
||||
}
|
||||
),
|
||||
"akkudoktoreos.config.configabc": frozenset(
|
||||
{"TimeWindow", "TimeWindowSequence", "ValueTimeWindow", "CycleTimeWindowSequence"}
|
||||
),
|
||||
"akkudoktoreos.config.configabc": frozenset({"TimeWindow", "TimeWindowSequence"}),
|
||||
}
|
||||
# The roles that build the output or define the public schema, the only ones
|
||||
# that may import the contract names of these modules; the parameters and the
|
||||
@@ -374,261 +382,6 @@ def collect_violations() -> frozenset[Violation]:
|
||||
# the existing uses revealed by a new list entry (ADR 0007).
|
||||
BASELINE: frozenset[Violation] = frozenset(
|
||||
{
|
||||
Violation(
|
||||
"internals",
|
||||
"akkudoktoreos.config.configmigrate",
|
||||
"akkudoktoreos.optimization.genetic.geneticsettings",
|
||||
),
|
||||
Violation(
|
||||
"internals",
|
||||
"akkudoktoreos.core.ems",
|
||||
"akkudoktoreos.optimization.genetic.configrequest",
|
||||
),
|
||||
Violation(
|
||||
"internals",
|
||||
"akkudoktoreos.core.ems",
|
||||
"akkudoktoreos.optimization.genetic.genetic",
|
||||
),
|
||||
Violation(
|
||||
"internals",
|
||||
"akkudoktoreos.core.ems",
|
||||
"akkudoktoreos.optimization.genetic.geneticparams",
|
||||
),
|
||||
Violation(
|
||||
"internals",
|
||||
"akkudoktoreos.core.ems",
|
||||
"akkudoktoreos.optimization.genetic.geneticsolution",
|
||||
),
|
||||
Violation(
|
||||
"internals",
|
||||
"akkudoktoreos.optimization.optimization",
|
||||
"akkudoktoreos.optimization.genetic.geneticsettings",
|
||||
),
|
||||
Violation(
|
||||
"internals",
|
||||
"akkudoktoreos.server.eos",
|
||||
"akkudoktoreos.optimization.genetic.configrequest",
|
||||
),
|
||||
Violation(
|
||||
"internals",
|
||||
"akkudoktoreos.server.eos",
|
||||
"akkudoktoreos.optimization.genetic.geneticsolution",
|
||||
),
|
||||
Violation(
|
||||
"internals",
|
||||
"akkudoktoreos.server.eos",
|
||||
"akkudoktoreos.optimization.genetic.geneticvisualize",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.devices.genetic.battery",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.devices.genetic.homeappliance",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.devices.genetic.inverter",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.configrequest",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.genetic",
|
||||
"akkudoktoreos.core.pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.genetic",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.geneticabc",
|
||||
"akkudoktoreos.core.pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.geneticabc",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.geneticdevices",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.geneticparams",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.geneticsolution",
|
||||
"akkudoktoreos.core.pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.geneticsolution",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.tailvalue",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.terminalvalue",
|
||||
"akkudoktoreos.core.pydantic",
|
||||
),
|
||||
Violation(
|
||||
"pydantic",
|
||||
"akkudoktoreos.optimization.genetic.terminalvalue",
|
||||
"pydantic",
|
||||
),
|
||||
Violation(
|
||||
"shared-config",
|
||||
"akkudoktoreos.devices.settings.batterysettings",
|
||||
"akkudoktoreos.devices.genetic.battery",
|
||||
),
|
||||
Violation(
|
||||
"shared-config",
|
||||
"akkudoktoreos.devices.settings.homeappliancesettings",
|
||||
"akkudoktoreos.devices.genetic.homeappliance",
|
||||
),
|
||||
Violation(
|
||||
"shared-config",
|
||||
"akkudoktoreos.devices.settings.invertersettings",
|
||||
"akkudoktoreos.devices.genetic.inverter",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.devices.genetic.battery",
|
||||
"akkudoktoreos.devices.devicesabc",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.devices.genetic.battery",
|
||||
"akkudoktoreos.devices.settings.batteryresolution",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.devices.genetic.battery",
|
||||
"akkudoktoreos.devices.settings.batterysettings",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.devices.genetic.homeappliance",
|
||||
"akkudoktoreos.config.configabc",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.devices.genetic.homeappliance",
|
||||
"akkudoktoreos.devices.devicesabc",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.devices.genetic.inverter",
|
||||
"akkudoktoreos.devices.devicesabc",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.devices.genetic.inverter",
|
||||
"akkudoktoreos.prediction.interpolator",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.configrequest",
|
||||
"akkudoktoreos.core.coreabc:ConfigMixin",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.configrequest",
|
||||
"akkudoktoreos.core.coreabc:MeasurementMixin",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.configrequest",
|
||||
"akkudoktoreos.core.coreabc:PredictionMixin",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.configrequest",
|
||||
"akkudoktoreos.core.coreabc:get_ems",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.configrequest",
|
||||
"akkudoktoreos.devices.settings.batteryresolution",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.configrequest",
|
||||
"akkudoktoreos.devices.settings.batterysettings",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.genetic",
|
||||
"akkudoktoreos.devices.devicesabc",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.genetic",
|
||||
"akkudoktoreos.optimization.optimizationabc:OptimizationBase",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.geneticparams",
|
||||
"akkudoktoreos.core.coreabc:ConfigMixin",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.geneticparams",
|
||||
"akkudoktoreos.core.coreabc:MeasurementMixin",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.geneticparams",
|
||||
"akkudoktoreos.core.coreabc:PredictionMixin",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.geneticsolution",
|
||||
"akkudoktoreos.core.coreabc:ConfigMixin",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.geneticsolution",
|
||||
"akkudoktoreos.core.coreabc:get_ems",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.geneticsolution",
|
||||
"akkudoktoreos.core.coreabc:get_prediction",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.geneticsolution",
|
||||
"akkudoktoreos.devices.devicesabc",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.geneticvisualize",
|
||||
"akkudoktoreos.core.coreabc:ConfigMixin",
|
||||
),
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.genetic.geneticvisualize",
|
||||
"akkudoktoreos.core.coreabc:get_ems",
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1030,7 +783,7 @@ class TestOptimizerArchitecture:
|
||||
),
|
||||
(
|
||||
"from akkudoktoreos.devices.devicesabc import BatteryOperationMode, "
|
||||
"ConsumerScheduleMode\n",
|
||||
"validate_efficiency_curve\n",
|
||||
Violation(
|
||||
"world-access",
|
||||
"akkudoktoreos.optimization.alpha.alphaconvert",
|
||||
|
||||
@@ -2,14 +2,19 @@
|
||||
|
||||
import pytest
|
||||
|
||||
from akkudoktoreos.config.config import ConfigEOS
|
||||
from akkudoktoreos.optimization.optimization import OptimizationAlgorithm
|
||||
from akkudoktoreos.optimization.optimizerregistry import get_optimizer
|
||||
from akkudoktoreos.optimization.optimizer import RunClock
|
||||
from akkudoktoreos.optimization.optimizerregistry import get_optimizer, optimizer_names
|
||||
|
||||
|
||||
class TestOptimizerRegistry:
|
||||
"""Finding optimizers by name."""
|
||||
|
||||
@pytest.mark.parametrize("name", ["GENETIC0"])
|
||||
def test_every_algorithm_is_registered(self) -> None:
|
||||
assert sorted(optimizer_names()) == sorted(OptimizationAlgorithm)
|
||||
|
||||
@pytest.mark.parametrize("name", ["GENETIC", "GENETIC0"])
|
||||
def test_registered_optimizer_carries_its_name(self, name: str) -> None:
|
||||
optimizer = get_optimizer(name)
|
||||
assert optimizer is not None
|
||||
@@ -20,6 +25,31 @@ class TestOptimizerRegistry:
|
||||
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"])
|
||||
@pytest.mark.parametrize("name", ["UNKNOWN", "", "genetic", "genetic0"])
|
||||
def test_unregistered_name_gives_none(self, name: str) -> None:
|
||||
assert get_optimizer(name) is None
|
||||
|
||||
|
||||
class TestRunClock:
|
||||
"""The slot length and time zone the energy management starts a run in (ADR 0006)."""
|
||||
|
||||
@pytest.mark.parametrize("interval", [900, 3600])
|
||||
def test_genetic_follows_its_slot_setting_and_the_site_time_zone(
|
||||
self, config_eos: ConfigEOS, interval: int
|
||||
) -> None:
|
||||
config_eos.merge_settings_from_dict(
|
||||
{
|
||||
"general": {"timezone_override": "America/New_York"},
|
||||
"optimization": {"genetic": {"interval_sec": interval}},
|
||||
}
|
||||
)
|
||||
optimizer = get_optimizer("GENETIC")
|
||||
assert optimizer is not None
|
||||
assert optimizer.run_clock() == RunClock(
|
||||
slot_seconds=interval, timezone="America/New_York"
|
||||
)
|
||||
|
||||
def test_genetic0_runs_hourly_in_server_time(self) -> None:
|
||||
optimizer = get_optimizer("GENETIC0")
|
||||
assert optimizer is not None
|
||||
assert optimizer.run_clock() == RunClock(slot_seconds=3600, timezone=None)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user