From e23bb7b497c9705e8b3b391aaa30a299c65b14d1 Mon Sep 17 00:00:00 2001 From: Bobby Noelte Date: Wed, 29 Jul 2026 12:56:08 +0200 Subject: [PATCH] chore: prepare for update of genetic algorithm (#1190) Andreas will update the genetic algorithm for 15-minutes optimization intervals. Copy the current GENETIC optimization algorithm to GENETIC0 to enable to keep the algorithm with the current functionality. Also copy resources like the load interpolator to the GENETIC0 algorithm to keep them despite possible later changes to the interpolator. Make the deprecated legacy /optimize endpoint use the GENETIC0 optimization algorithm to in-fact behave the same way even if there will later be changes to the GENETIC algorithm by Andreas. Add a new REST endpoint to provide the unprocessed optimisation results of the GENETIC and GENETIC0 algorithm in case one wants to use them as done with the deprecated /optimize endpoint. Adapt the optimization configuration to have distinct configurations for the GENETIC and the GENETIC0 algorithm. Create a copy of the current tests for the GENETIC algorithm to be used for the GENETIC0 algorithm. This avoids the tests for the GENETIC0 algorithm to be influenced by later changes by Andreas. Signed-off-by: Bobby Noelte --- .env | 2 +- config.yaml | 2 +- docs/_generated/configexample.md | 13 +- docs/_generated/configoptimization.md | 147 +- docs/_generated/openapi.md | 38 +- openapi.json | 2129 ++++++++++++----- src/akkudoktoreos/config/configmigrate.py | 6 +- src/akkudoktoreos/core/ems.py | 212 +- .../data/genetic0_load_interpolator.pkl | Bin 0 -> 57788 bytes .../devices/genetic0/__init__.py | 0 .../devices/genetic0/genetic0battery.py | 283 +++ .../devices/genetic0/genetic0homeappliance.py | 102 + .../devices/genetic0/genetic0inverter.py | 136 ++ .../optimization/genetic/genetic.py | 8 +- .../optimization/genetic/geneticparams.py | 19 +- .../optimization/genetic/geneticsettings.py | 82 + .../optimization/genetic/geneticsolution.py | 2 +- .../optimization/genetic0/genetic0.py | 1262 ++++++++++ .../optimization/genetic0/genetic0abc.py | 11 + .../optimization/genetic0/genetic0devices.py | 196 ++ .../genetic0/genetic0loadinterpolator.py | 100 + .../optimization/genetic0/genetic0params.py | 702 ++++++ .../optimization/genetic0/genetic0settings.py | 78 + .../optimization/genetic0/genetic0solution.py | 893 +++++++ .../optimization/optimization.py | 99 +- .../prediction/elecpricefixed.py | 2 +- src/akkudoktoreos/server/eos.py | 51 +- tests/single_test_genetic0optimization.py | 525 ++++ tests/single_test_optimization.py | 6 +- tests/test_elecpricefixed.py | 71 +- tests/test_genetic0battery.py | 299 +++ tests/test_genetic0inverter.py | 343 +++ tests/test_genetic0inverterefficiency.py | 886 +++++++ tests/test_genetic0optimize.py | 155 ++ tests/test_genetic0simulation.py | 654 +++++ ...ations.py => test_genetic0translations.py} | 40 +- tests/test_geneticoptimize.py | 3 +- tests/test_geneticsimulation.py | 6 +- tests/test_geneticsimulation2.py | 6 +- tests/test_inverter_efficiency.py | 2 +- .../testdata/docs/_generated/configexample.md | 13 +- .../docs/_generated/configoptimization.md | 147 +- tests/testdata/eos_config_andreas_now.json | 6 +- tests/testdata/eos_config_minimal_now.json | 6 +- tests/testdata/genetic0optimize_input_1.json | 69 + tests/testdata/genetic0optimize_input_2.json | 231 ++ tests/testdata/genetic0optimize_result_1.json | 772 ++++++ .../genetic0optimize_result_1_be.json | 772 ++++++ tests/testdata/genetic0optimize_result_2.json | 818 +++++++ .../genetic0optimize_result_2_be.json | 818 +++++++ .../genetic0optimize_result_2_full.json | 818 +++++++ 51 files changed, 13086 insertions(+), 955 deletions(-) create mode 100644 src/akkudoktoreos/data/genetic0_load_interpolator.pkl create mode 100644 src/akkudoktoreos/devices/genetic0/__init__.py create mode 100644 src/akkudoktoreos/devices/genetic0/genetic0battery.py create mode 100644 src/akkudoktoreos/devices/genetic0/genetic0homeappliance.py create mode 100644 src/akkudoktoreos/devices/genetic0/genetic0inverter.py create mode 100644 src/akkudoktoreos/optimization/genetic/geneticsettings.py create mode 100644 src/akkudoktoreos/optimization/genetic0/genetic0.py create mode 100644 src/akkudoktoreos/optimization/genetic0/genetic0abc.py create mode 100644 src/akkudoktoreos/optimization/genetic0/genetic0devices.py create mode 100644 src/akkudoktoreos/optimization/genetic0/genetic0loadinterpolator.py create mode 100644 src/akkudoktoreos/optimization/genetic0/genetic0params.py create mode 100644 src/akkudoktoreos/optimization/genetic0/genetic0settings.py create mode 100644 src/akkudoktoreos/optimization/genetic0/genetic0solution.py create mode 100755 tests/single_test_genetic0optimization.py create mode 100644 tests/test_genetic0battery.py create mode 100644 tests/test_genetic0inverter.py create mode 100644 tests/test_genetic0inverterefficiency.py create mode 100644 tests/test_genetic0optimize.py create mode 100644 tests/test_genetic0simulation.py rename tests/{test_translations.py => test_genetic0translations.py} (84%) create mode 100644 tests/testdata/genetic0optimize_input_1.json create mode 100644 tests/testdata/genetic0optimize_input_2.json create mode 100644 tests/testdata/genetic0optimize_result_1.json create mode 100644 tests/testdata/genetic0optimize_result_1_be.json create mode 100644 tests/testdata/genetic0optimize_result_2.json create mode 100644 tests/testdata/genetic0optimize_result_2_be.json create mode 100644 tests/testdata/genetic0optimize_result_2_full.json diff --git a/.env b/.env index 9ab4433..f19a00b 100644 --- a/.env +++ b/.env @@ -11,7 +11,7 @@ DOCKER_COMPOSE_DATA_DIR=${HOME}/.local/share/net.akkudoktor.eos # ----------------------------------------------------------------------------- # Image / build # ----------------------------------------------------------------------------- -VERSION=0.3.0.dev2607241195820468 +VERSION=0.3.0.dev2607290898922686 PYTHON_VERSION=3.13.9 # ----------------------------------------------------------------------------- diff --git a/config.yaml b/config.yaml index 14202d3..3e44d50 100644 --- a/config.yaml +++ b/config.yaml @@ -6,7 +6,7 @@ # the root directory (no add-on folder as usual). name: "Akkudoktor-EOS" -version: "0.3.0.dev2607241195820468" +version: "0.3.0.dev2607290898922686" slug: "eos" description: "Akkudoktor-EOS add-on" url: "https://github.com/Akkudoktor-EOS/EOS" diff --git a/docs/_generated/configexample.md b/docs/_generated/configexample.md index 521182f..53c340f 100644 --- a/docs/_generated/configexample.md +++ b/docs/_generated/configexample.md @@ -177,10 +177,19 @@ ] }, "optimization": { - "horizon_hours": 24, - "interval": 3600, "algorithm": "GENETIC", "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, + "individuals": 400, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + } + }, + "genetic0": { + "horizon_hours": 24, "individuals": 400, "generations": 400, "seed": null, diff --git a/docs/_generated/configoptimization.md b/docs/_generated/configoptimization.md index e53d6d6..11c85e7 100644 --- a/docs/_generated/configoptimization.md +++ b/docs/_generated/configoptimization.md @@ -8,10 +8,9 @@ | Name | Environment Variable | Type | Read-Only | Default | Description | | ---- | -------------------- | ---- | --------- | ------- | ----------- | | algorithm | `EOS_OPTIMIZATION__ALGORITHM` | `str` | `rw` | `GENETIC` | The optimization algorithm. Defaults to GENETIC | -| genetic | `EOS_OPTIMIZATION__GENETIC` | `GeneticCommonSettings` | `rw` | `required` | Genetic optimization algorithm configuration. | -| horizon | | `int` | `ro` | `N/A` | Number of optimization steps. | -| horizon_hours | `EOS_OPTIMIZATION__HORIZON_HOURS` | `int` | `rw` | `24` | The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours. | -| interval | `EOS_OPTIMIZATION__INTERVAL` | `int` | `rw` | `3600` | The optimization interval [sec]. Defaults to 3600 seconds (1 hour) | +| algorithms | | `list[str]` | `ro` | `N/A` | Available optimization algorithms. | +| genetic | `EOS_OPTIMIZATION__GENETIC` | `GeneticCommonSettings` | `rw` | `required` | GENETIC optimization algorithm configuration. | +| genetic0 | `EOS_OPTIMIZATION__GENETIC0` | `Genetic0CommonSettings` | `rw` | `required` | GENETIC0 optimization algorithm configuration. | | keys | | `list[str]` | `ro` | `N/A` | The keys of the solution. | ::: @@ -24,10 +23,19 @@ ```json { "optimization": { - "horizon_hours": 24, - "interval": 3600, "algorithm": "GENETIC", "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, + "individuals": 400, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + } + }, + "genetic0": { + "horizon_hours": 24, "individuals": 400, "generations": 400, "seed": null, @@ -48,49 +56,68 @@ ```json { "optimization": { - "horizon_hours": 24, - "interval": 3600, "algorithm": "GENETIC", "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, "individuals": 400, "generations": 400, "seed": null, "penalties": { "ev_soc_miss": 10 - } + }, + "horizon": 24 }, - "keys": [], - "horizon": 24 + "genetic0": { + "horizon_hours": 24, + "individuals": 400, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + }, + "interval_sec": 3600, + "horizon": 24 + }, + "algorithms": [ + "GENETIC", + "GENETIC0" + ], + "keys": [] } } ``` -### General Genetic Optimization Algorithm Configuration +### GENETIC0 Optimization Algorithm Configuration -:::{table} optimization::genetic +:::{table} optimization::genetic0 :widths: 10 10 5 5 30 :align: left | Name | Type | Read-Only | Default | Description | | ---- | ---- | --------- | ------- | ----------- | | generations | `int | None` | `rw` | `400` | Number of generations to evolve [>= 10]. Defaults to 400. | +| horizon | `int` | `ro` | `N/A` | Number of optimization steps. | +| horizon_hours | `int` | `rw` | `24` | The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours. | | individuals | `int | None` | `rw` | `300` | Number of individuals (solutions) in the population [>= 10]. Defaults to 300. | +| interval_sec | `int` | `ro` | `N/A` | The optimization interval [sec]. Fixed to 1 hour (3600 seconds). | | penalties | `dict[str, float | int | str]` | `rw` | `required` | Penalty parameters used in fitness evaluation. | | seed | `int | None` | `rw` | `None` | Random seed for reproducibility. None = random. | ::: -**Example Input/Output** +**Example Input** ```json { "optimization": { - "genetic": { + "genetic0": { + "horizon_hours": 24, "individuals": 300, "generations": 400, "seed": null, @@ -102,3 +129,93 @@ } ``` + + +**Example Output** + + + +```json + { + "optimization": { + "genetic0": { + "horizon_hours": 24, + "individuals": 300, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + }, + "interval_sec": 3600, + "horizon": 24 + } + } + } +``` + + +### GENETIC Optimization Algorithm Configuration + + +:::{table} optimization::genetic +:widths: 10 10 5 5 30 +:align: left + +| Name | Type | Read-Only | Default | Description | +| ---- | ---- | --------- | ------- | ----------- | +| generations | `int | None` | `rw` | `400` | Number of generations to evolve [>= 10]. Defaults to 400. | +| horizon | `int` | `ro` | `N/A` | Number of optimization steps. | +| horizon_hours | `int` | `rw` | `24` | The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours. | +| individuals | `int | None` | `rw` | `300` | Number of individuals (solutions) in the population [>= 10]. Defaults to 300. | +| interval_sec | `int` | `rw` | `3600` | The optimization interval [sec]. Defaults to 3600 seconds (1 hour) | +| penalties | `dict[str, float | int | str]` | `rw` | `required` | Penalty parameters used in fitness evaluation. | +| seed | `int | None` | `rw` | `None` | Random seed for reproducibility. None = random. | +::: + + + +**Example Input** + + + +```json + { + "optimization": { + "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, + "individuals": 300, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + } + } + } + } +``` + + + +**Example Output** + + + +```json + { + "optimization": { + "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, + "individuals": 300, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + }, + "horizon": 24 + } + } + } +``` + diff --git a/docs/_generated/openapi.md b/docs/_generated/openapi.md index fe08d49..5cdf6dd 100644 --- a/docs/_generated/openapi.md +++ b/docs/_generated/openapi.md @@ -1,6 +1,6 @@ # Akkudoktor-EOS -**Version**: `v0.3.0.dev2607241195820468` +**Version**: `v0.3.0.dev2607290898922686` **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. @@ -125,8 +125,11 @@ Deprecated: Optimize. Endpoint to handle optimization. +Uses the `classic` GENETIC0 optimisation algorithm (__NO__ 15-minutes slots). + Note: Use automatic optimization instead. + "v1/energy-management/optimization/solution/GENETIC0" """ ``` @@ -140,7 +143,7 @@ Note: **Request Body**: - `application/json`: { - "$ref": "#/components/schemas/GeneticOptimizationParameters" + "$ref": "#/components/schemas/Genetic0OptimizationParameters" } **Responses**: @@ -747,6 +750,37 @@ Get the latest solution of the optimization. --- +## GET /v1/energy-management/optimization/solution/{algorithm} + + +**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) + + +Fastapi Energy Management Optimization Solution Algorithm Get + + +```python +""" +Get the latest algorithm specific solution of the optimization. + +Args: + algorithm: Optimization algorithm +""" +``` + + +**Parameters**: + +- `algorithm` (path, required): No description provided. + +**Responses**: + +- **200**: Successful Response + +- **422**: Validation Error + +--- + ## GET /v1/energy-management/plan diff --git a/openapi.json b/openapi.json index 18161c1..d27b44f 100644 --- a/openapi.json +++ b/openapi.json @@ -8,7 +8,7 @@ "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html" }, - "version": "v0.3.0.dev2607241195820468" + "version": "v0.3.0.dev2607290898922686" }, "paths": { "/v1/admin/cache/clear": { @@ -1913,6 +1913,57 @@ } } }, + "/v1/energy-management/optimization/solution/{algorithm}": { + "get": { + "tags": [ + "energy-management" + ], + "summary": "Fastapi Energy Management Optimization Solution Algorithm Get", + "description": "Get the latest algorithm specific solution of the optimization.\n\nArgs:\n algorithm: Optimization algorithm", + "operationId": "fastapi_energy_management_optimization_solution_algorithm_get_v1_energy_management_optimization_solution__algorithm__get", + "parameters": [ + { + "name": "algorithm", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Algorithm" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/GeneticSolution" + }, + { + "$ref": "#/components/schemas/Genetic0Solution" + } + ], + "title": "Response Fastapi Energy Management Optimization Solution Algorithm Get V1 Energy Management Optimization Solution Algorithm Get" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/v1/energy-management/plan": { "get": { "tags": [ @@ -2085,7 +2136,7 @@ "optimize" ], "summary": "Fastapi Optimize", - "description": "Deprecated: Optimize.\n\nEndpoint to handle optimization.\n\nNote:\n Use automatic optimization instead.", + "description": "Deprecated: Optimize.\n\nEndpoint to handle optimization.\n\nUses the `classic` GENETIC0 optimisation algorithm (__NO__ 15-minutes slots).\n\nNote:\n Use automatic optimization instead.\n \"v1/energy-management/optimization/solution/GENETIC0\"", "operationId": "fastapi_optimize_optimize_post", "parameters": [ { @@ -2130,7 +2181,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GeneticOptimizationParameters" + "$ref": "#/components/schemas/Genetic0OptimizationParameters" } } } @@ -2141,7 +2192,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GeneticSolution" + "$ref": "#/components/schemas/Genetic0Solution" } } } @@ -3739,136 +3790,6 @@ "title": "ElecPriceTibberCommonSettings", "description": "Common settings for the Tibber electricity price provider." }, - "ElectricVehicleParameters": { - "properties": { - "device_id": { - "type": "string", - "title": "Device Id", - "description": "ID of electric vehicle", - "examples": [ - "ev1" - ] - }, - "hours": { - "anyOf": [ - { - "type": "integer", - "exclusiveMinimum": 0.0 - }, - { - "type": "null" - } - ], - "title": "Hours", - "description": "Number of prediction hours. Defaults to global config prediction hours.", - "examples": [ - null - ] - }, - "capacity_wh": { - "type": "integer", - "exclusiveMinimum": 0.0, - "title": "Capacity Wh", - "description": "An integer representing the capacity of the battery in watt-hours.", - "examples": [ - 8000 - ] - }, - "charging_efficiency": { - "type": "number", - "maximum": 1.0, - "exclusiveMinimum": 0.0, - "title": "Charging Efficiency", - "description": "A float representing the charging efficiency of the battery.", - "default": 0.88 - }, - "discharging_efficiency": { - "type": "number", - "maximum": 1.0, - "exclusiveMinimum": 0.0, - "title": "Discharging Efficiency", - "description": "A float representing the discharge efficiency of the battery.", - "default": 1.0 - }, - "max_charge_power_w": { - "anyOf": [ - { - "type": "number", - "exclusiveMinimum": 0.0 - }, - { - "type": "null" - } - ], - "title": "Max Charge Power W", - "description": "Maximum charging power in watts.", - "default": 5000 - }, - "initial_soc_percentage": { - "type": "integer", - "maximum": 100.0, - "minimum": 0.0, - "title": "Initial Soc Percentage", - "description": "An integer representing the current state of charge (SOC) of the battery in percentage.", - "default": 0, - "examples": [ - 42 - ] - }, - "min_soc_percentage": { - "type": "integer", - "maximum": 100.0, - "minimum": 0.0, - "title": "Min Soc Percentage", - "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", - "default": 0, - "examples": [ - 10 - ] - }, - "max_soc_percentage": { - "type": "integer", - "maximum": 100.0, - "minimum": 0.0, - "title": "Max Soc Percentage", - "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", - "default": 100 - }, - "charge_rates": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "title": "Charge Rates", - "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 - ], - null - ] - } - }, - "additionalProperties": false, - "type": "object", - "required": [ - "device_id", - "capacity_wh" - ], - "title": "ElectricVehicleParameters", - "description": "Battery Electric Vehicle Device Simulation Configuration." - }, "ElectricVehicleResult": { "properties": { "device_id": { @@ -4816,8 +4737,1307 @@ "title": "GeneralSettings", "description": "General settings." }, - "GeneticCommonSettings": { + "Genetic0CommonSettings-Input": { "properties": { + "horizon_hours": { + "type": "integer", + "minimum": 0.0, + "title": "Horizon Hours", + "description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.", + "default": 24, + "examples": [ + 24 + ] + }, + "individuals": { + "anyOf": [ + { + "type": "integer", + "minimum": 10.0 + }, + { + "type": "null" + } + ], + "title": "Individuals", + "description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.", + "default": 300, + "examples": [ + 300 + ] + }, + "generations": { + "anyOf": [ + { + "type": "integer", + "minimum": 10.0 + }, + { + "type": "null" + } + ], + "title": "Generations", + "description": "Number of generations to evolve [>= 10]. Defaults to 400.", + "default": 400, + "examples": [ + 400 + ] + }, + "seed": { + "anyOf": [ + { + "type": "integer", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Seed", + "description": "Random seed for reproducibility. None = random.", + "examples": [ + null, + 42 + ] + }, + "penalties": { + "additionalProperties": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "type": "object", + "title": "Penalties", + "description": "Penalty parameters used in fitness evaluation.", + "examples": [ + { + "ev_soc_miss": 10 + } + ] + } + }, + "type": "object", + "title": "Genetic0CommonSettings", + "description": "GENETIC0 Optimization Algorithm Configuration." + }, + "Genetic0CommonSettings-Output": { + "properties": { + "horizon_hours": { + "type": "integer", + "minimum": 0.0, + "title": "Horizon Hours", + "description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.", + "default": 24, + "examples": [ + 24 + ] + }, + "individuals": { + "anyOf": [ + { + "type": "integer", + "minimum": 10.0 + }, + { + "type": "null" + } + ], + "title": "Individuals", + "description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.", + "default": 300, + "examples": [ + 300 + ] + }, + "generations": { + "anyOf": [ + { + "type": "integer", + "minimum": 10.0 + }, + { + "type": "null" + } + ], + "title": "Generations", + "description": "Number of generations to evolve [>= 10]. Defaults to 400.", + "default": 400, + "examples": [ + 400 + ] + }, + "seed": { + "anyOf": [ + { + "type": "integer", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Seed", + "description": "Random seed for reproducibility. None = random.", + "examples": [ + null, + 42 + ] + }, + "penalties": { + "additionalProperties": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "type": "object", + "title": "Penalties", + "description": "Penalty parameters used in fitness evaluation.", + "examples": [ + { + "ev_soc_miss": 10 + } + ] + }, + "interval_sec": { + "type": "integer", + "title": "Interval Sec", + "description": "The optimization interval [sec]. Fixed to 1 hour (3600 seconds).", + "readOnly": true + }, + "horizon": { + "type": "integer", + "title": "Horizon", + "description": "Number of optimization steps.", + "readOnly": true + } + }, + "type": "object", + "required": [ + "interval_sec", + "horizon" + ], + "title": "Genetic0CommonSettings", + "description": "GENETIC0 Optimization Algorithm Configuration." + }, + "Genetic0ElectricVehicleParameters": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of electric vehicle", + "examples": [ + "ev1" + ] + }, + "hours": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [ + null + ] + }, + "capacity_wh": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Capacity Wh", + "description": "An integer representing the capacity of the battery in watt-hours.", + "examples": [ + 8000 + ] + }, + "charging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Charging Efficiency", + "description": "A float representing the charging efficiency of the battery.", + "default": 0.88 + }, + "discharging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Discharging Efficiency", + "description": "A float representing the discharge efficiency of the battery.", + "default": 1.0 + }, + "max_charge_power_w": { + "anyOf": [ + { + "type": "number", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Max Charge Power W", + "description": "Maximum charging power in watts.", + "default": 5000 + }, + "initial_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Initial Soc Percentage", + "description": "An integer representing the current state of charge (SOC) of the battery in percentage.", + "default": 0, + "examples": [ + 42 + ] + }, + "min_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Min Soc Percentage", + "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", + "default": 0, + "examples": [ + 10 + ] + }, + "max_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Max Soc Percentage", + "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", + "default": 100 + }, + "charge_rates": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Charge Rates", + "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 + ], + null + ] + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "capacity_wh" + ], + "title": "Genetic0ElectricVehicleParameters", + "description": "Battery Electric Vehicle Device Simulation Configuration." + }, + "Genetic0ElectricVehicleResult": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of electric vehicle", + "examples": [ + "ev1" + ] + }, + "hours": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Hours", + "description": "Number of hours in the simulation.", + "examples": [ + 24 + ] + }, + "charge_array": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Charge Array", + "description": "Hourly charging status (0 for no charging, 1 for charging)." + }, + "discharge_array": { + "items": { + "type": "integer" + }, + "type": "array", + "title": "Discharge Array", + "description": "Hourly discharging status (0 for no discharging, 1 for discharging)." + }, + "discharging_efficiency": { + "type": "number", + "title": "Discharging Efficiency", + "description": "The discharge efficiency as a float.." + }, + "capacity_wh": { + "type": "integer", + "title": "Capacity Wh", + "description": "Capacity of the EV\u2019s battery in watt-hours." + }, + "charging_efficiency": { + "type": "number", + "title": "Charging Efficiency", + "description": "Charging efficiency as a float.." + }, + "max_charge_power_w": { + "type": "integer", + "title": "Max Charge Power W", + "description": "Maximum charging power in watts." + }, + "soc_wh": { + "type": "number", + "title": "Soc Wh", + "description": "State of charge of the battery in watt-hours at the start of the simulation." + }, + "initial_soc_percentage": { + "type": "integer", + "title": "Initial Soc Percentage", + "description": "State of charge at the start of the simulation in percentage." + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "hours", + "charge_array", + "discharge_array", + "discharging_efficiency", + "capacity_wh", + "charging_efficiency", + "max_charge_power_w", + "soc_wh", + "initial_soc_percentage" + ], + "title": "Genetic0ElectricVehicleResult", + "description": "Result class containing information related to the electric vehicle's charging and discharging behavior." + }, + "Genetic0EnergyManagementParameters": { + "properties": { + "pv_forecast_wh": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Pv Forecast Wh", + "description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals." + }, + "electricity_price_per_wh": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Electricity Price Per Wh", + "description": "An array of floats representing the electricity price per watt-hour for different time intervals." + }, + "feed_in_tariff_per_wh": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "number" + } + ], + "title": "Feed In Tariff Per Wh", + "description": "A float or array of floats representing the feed-in compensation per watt-hour." + }, + "price_per_wh_battery": { + "type": "number", + "title": "Price Per Wh Battery", + "description": "A float representing the cost of battery energy per watt-hour." + }, + "total_load": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Total Load", + "description": "An array of floats representing the total load (consumption) in watts for different time intervals." + } + }, + "type": "object", + "required": [ + "pv_forecast_wh", + "electricity_price_per_wh", + "feed_in_tariff_per_wh", + "price_per_wh_battery", + "total_load" + ], + "title": "Genetic0EnergyManagementParameters", + "description": "Encapsulates energy-related forecasts and costs used in GENETIC optimization." + }, + "Genetic0HomeApplianceParameters": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of home appliance", + "examples": [ + "dishwasher" + ] + }, + "hours": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [ + null + ] + }, + "consumption_wh": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Consumption Wh", + "description": "An integer representing the energy consumption of a household device in watt-hours.", + "examples": [ + 2000 + ] + }, + "duration_h": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Duration H", + "description": "An integer representing the usage duration of a household device in hours.", + "examples": [ + 3 + ] + }, + "time_windows": { + "anyOf": [ + { + "$ref": "#/components/schemas/TimeWindowSequence-Input" + }, + { + "type": "null" + } + ], + "description": "List of allowed time windows. Defaults to optimization general time window.", + "examples": [ + [ + { + "duration": "3 hours", + "start_time": "10:00" + } + ] + ] + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "consumption_wh", + "duration_h" + ], + "title": "Genetic0HomeApplianceParameters", + "description": "Home Appliance Device Simulation Configuration." + }, + "Genetic0InverterParameters": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of inverter", + "examples": [ + "inverter1" + ] + }, + "hours": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [ + null + ] + }, + "max_power_wh": { + "type": "number", + "exclusiveMinimum": 0.0, + "title": "Max Power Wh", + "examples": [ + 10000 + ] + }, + "battery_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Battery Id", + "description": "ID of battery", + "examples": [ + null, + "battery1" + ] + }, + "ac_to_dc_efficiency": { + "type": "number", + "maximum": 1.0, + "minimum": 0.0, + "title": "Ac To Dc Efficiency", + "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).", + "default": 1.0, + "examples": [ + 0.95, + 1.0, + 0.0 + ] + }, + "dc_to_ac_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Dc To Ac Efficiency", + "description": "Efficiency of DC to AC conversion (for battery discharging to AC load/grid). Default 1.0 for backward compatibility (no additional inverter loss).", + "default": 1.0, + "examples": [ + 0.95, + 1.0 + ] + }, + "max_ac_charge_power_w": { + "anyOf": [ + { + "type": "number", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Max Ac Charge Power W", + "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": [ + null, + 0, + 5000 + ] + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "max_power_wh" + ], + "title": "Genetic0InverterParameters", + "description": "Inverter Device Simulation Configuration." + }, + "Genetic0OptimizationParameters": { + "properties": { + "ems": { + "$ref": "#/components/schemas/Genetic0EnergyManagementParameters" + }, + "pv_battery": { + "anyOf": [ + { + "$ref": "#/components/schemas/Genetic0SolarPanelBatteryParameters" + }, + { + "type": "null" + } + ], + "description": "PV battery parameters." + }, + "inverter": { + "anyOf": [ + { + "$ref": "#/components/schemas/Genetic0InverterParameters" + }, + { + "type": "null" + } + ] + }, + "ev": { + "anyOf": [ + { + "$ref": "#/components/schemas/Genetic0ElectricVehicleParameters" + }, + { + "type": "null" + } + ], + "description": "Electric vehicle parameters." + }, + "dishwasher": { + "anyOf": [ + { + "$ref": "#/components/schemas/Genetic0HomeApplianceParameters" + }, + { + "type": "null" + } + ] + }, + "temperature_forecast": { + "anyOf": [ + { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Temperature Forecast", + "description": "An array of floats representing the temperature forecast in degrees Celsius for different time intervals." + }, + "start_solution": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Start Solution", + "description": "Can be `null` or contain a previous solution (if available)." + } + }, + "type": "object", + "required": [ + "ems", + "pv_battery", + "inverter", + "ev" + ], + "title": "Genetic0OptimizationParameters", + "description": "Main parameter class for running the genetic energy optimization.\n\nCollects all model and configuration parameters necessary to run the\noptimization process, such as forecasts, pricing, battery and appliance models." + }, + "Genetic0SimulationResult": { + "properties": { + "load_wh_per_hour": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Load Wh Per Hour", + "description": "The load in watt-hours per hour." + }, + "ev_soc_per_hour": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Ev Soc Per Hour", + "description": "The state of charge of the EV for each hour." + }, + "revenue_per_hour": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Revenue Per Hour", + "description": "The revenue from grid feed-in or other sources per hour." + }, + "total_losses": { + "type": "number", + "title": "Total Losses", + "description": "The total losses in watt-hours over the entire period." + }, + "total_balance": { + "type": "number", + "title": "Total Balance", + "description": "The total balance of revenues minus costs." + }, + "total_revenue": { + "type": "number", + "title": "Total Revenue", + "description": "The total revenues." + }, + "total_costs": { + "type": "number", + "title": "Total Costs", + "description": "The total costs." + }, + "home_appliance_wh_per_hour": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Home Appliance Wh Per Hour", + "description": "The energy consumption of a household appliance in watt-hours per hour." + }, + "costs_per_hour": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Costs Per Hour", + "description": "The costs per hour." + }, + "grid_consumption_wh_per_hour": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Grid Consumption Wh Per Hour", + "description": "The grid energy drawn in watt-hours per hour." + }, + "grid_feed_in_wh_per_hour": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Grid Feed In Wh Per Hour", + "description": "The energy fed into the grid in watt-hours per hour." + }, + "losses_per_hour": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Losses Per Hour", + "description": "The losses in watt-hours per hour." + }, + "battery_soc_per_hour": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Battery Soc Per Hour", + "description": "The state of charge of the battery (not the EV) in percentage per hour." + }, + "electricity_price": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Electricity Price", + "description": "Used Electricity Price, including predictions" + }, + "Last_Wh_pro_Stunde": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Last Wh Pro Stunde", + "description": "Deprecated: Use load_wh_per_hour instead.", + "deprecated": true, + "readOnly": true + }, + "EAuto_SoC_pro_Stunde": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Eauto Soc Pro Stunde", + "description": "Deprecated: Use ev_soc_per_hour instead.", + "deprecated": true, + "readOnly": true + }, + "Einnahmen_Euro_pro_Stunde": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Einnahmen Euro Pro Stunde", + "description": "Deprecated: Use revenue_per_hour instead.", + "deprecated": true, + "readOnly": true + }, + "Gesamt_Verluste": { + "type": "number", + "title": "Gesamt Verluste", + "description": "Deprecated: Use total_losses instead.", + "deprecated": true, + "readOnly": true + }, + "Gesamtbilanz_Euro": { + "type": "number", + "title": "Gesamtbilanz Euro", + "description": "Deprecated: Use total_balance instead.", + "deprecated": true, + "readOnly": true + }, + "Gesamteinnahmen_Euro": { + "type": "number", + "title": "Gesamteinnahmen Euro", + "description": "Deprecated: Use total_revenue instead.", + "deprecated": true, + "readOnly": true + }, + "Gesamtkosten_Euro": { + "type": "number", + "title": "Gesamtkosten Euro", + "description": "Deprecated: Use total_costs instead.", + "deprecated": true, + "readOnly": true + }, + "Home_appliance_wh_per_hour": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Home Appliance Wh Per Hour", + "description": "Deprecated: Use home_appliance_wh_per_hour instead.", + "deprecated": true, + "readOnly": true + }, + "Kosten_Euro_pro_Stunde": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Kosten Euro Pro Stunde", + "description": "Deprecated: Use costs_per_hour instead.", + "deprecated": true, + "readOnly": true + }, + "Netzbezug_Wh_pro_Stunde": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Netzbezug Wh Pro Stunde", + "description": "Deprecated: Use grid_consumption_wh_per_hour instead.", + "deprecated": true, + "readOnly": true + }, + "Netzeinspeisung_Wh_pro_Stunde": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Netzeinspeisung Wh Pro Stunde", + "description": "Deprecated: Use grid_feed_in_wh_per_hour instead.", + "deprecated": true, + "readOnly": true + }, + "Verluste_Pro_Stunde": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Verluste Pro Stunde", + "description": "Deprecated: Use losses_per_hour instead.", + "deprecated": true, + "readOnly": true + }, + "akku_soc_pro_stunde": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Akku Soc Pro Stunde", + "description": "Deprecated: Use battery_soc_per_hour instead.", + "deprecated": true, + "readOnly": true + }, + "Electricity_price": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Electricity Price", + "description": "Deprecated: Use electricity_price instead.", + "deprecated": true, + "readOnly": true + } + }, + "type": "object", + "required": [ + "load_wh_per_hour", + "ev_soc_per_hour", + "revenue_per_hour", + "total_losses", + "total_balance", + "total_revenue", + "total_costs", + "home_appliance_wh_per_hour", + "costs_per_hour", + "grid_consumption_wh_per_hour", + "grid_feed_in_wh_per_hour", + "losses_per_hour", + "battery_soc_per_hour", + "electricity_price", + "Last_Wh_pro_Stunde", + "EAuto_SoC_pro_Stunde", + "Einnahmen_Euro_pro_Stunde", + "Gesamt_Verluste", + "Gesamtbilanz_Euro", + "Gesamteinnahmen_Euro", + "Gesamtkosten_Euro", + "Home_appliance_wh_per_hour", + "Kosten_Euro_pro_Stunde", + "Netzbezug_Wh_pro_Stunde", + "Netzeinspeisung_Wh_pro_Stunde", + "Verluste_Pro_Stunde", + "akku_soc_pro_stunde", + "Electricity_price" + ], + "title": "Genetic0SimulationResult", + "description": "This object contains the results of the simulation and provides insights into various parameters over the entire forecast period." + }, + "Genetic0SolarPanelBatteryParameters": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of battery", + "examples": [ + "battery1" + ] + }, + "hours": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [ + null + ] + }, + "capacity_wh": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Capacity Wh", + "description": "An integer representing the capacity of the battery in watt-hours.", + "examples": [ + 8000 + ] + }, + "charging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Charging Efficiency", + "description": "A float representing the charging efficiency of the battery.", + "default": 0.88 + }, + "discharging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Discharging Efficiency", + "description": "A float representing the discharge efficiency of the battery.", + "default": 0.88 + }, + "max_charge_power_w": { + "anyOf": [ + { + "type": "number", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Max Charge Power W", + "description": "Maximum charging power in watts.", + "default": 5000 + }, + "initial_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Initial Soc Percentage", + "description": "An integer representing the state of charge of the battery at the **start** of the current hour (not the current state).", + "default": 0, + "examples": [ + 42 + ] + }, + "min_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Min Soc Percentage", + "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", + "default": 0, + "examples": [ + 10 + ] + }, + "max_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Max Soc Percentage", + "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", + "default": 100 + }, + "charge_rates": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Charge Rates", + "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 + ], + null + ] + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "capacity_wh" + ], + "title": "Genetic0SolarPanelBatteryParameters", + "description": "PV battery device simulation configuration." + }, + "Genetic0Solution": { + "properties": { + "ac_charge": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Ac Charge", + "description": "Array with AC charging values as relative power (0.0-1.0), other values set to 0." + }, + "dc_charge": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Dc Charge", + "description": "Array with DC charging values as relative power (0-1), other values set to 0." + }, + "discharge_allowed": { + "items": { + "type": "integer" + }, + "type": "array", + "title": "Discharge Allowed", + "description": "Array with discharge values (1 for discharge, 0 otherwise)." + }, + "ev_charge_hours_float": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Ev Charge Hours Float", + "description": "Array with EV charging values as relative power (0.0-1.0), or `null` if no EV is optimized." + }, + "result": { + "$ref": "#/components/schemas/Genetic0SimulationResult" + }, + "ev_obj": { + "anyOf": [ + { + "$ref": "#/components/schemas/Genetic0ElectricVehicleResult" + }, + { + "type": "null" + } + ], + "description": "Electric vehicle state after optimization." + }, + "start_solution": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Start Solution", + "description": "An array of binary values (0 or 1) representing a possible starting solution for the simulation." + }, + "washingstart": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Washingstart", + "description": "Can be `null` or contain an object representing the start of washing (if applicable)." + }, + "eautocharge_hours_float": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Eautocharge Hours Float", + "description": "Deprecated: Use ev_charge_hours_float instead.", + "deprecated": true, + "readOnly": true + }, + "eauto_obj": { + "anyOf": [ + { + "$ref": "#/components/schemas/Genetic0ElectricVehicleResult" + }, + { + "type": "null" + } + ], + "description": "Deprecated: Use ev_obj instead.", + "deprecated": true, + "readOnly": true + } + }, + "type": "object", + "required": [ + "ac_charge", + "dc_charge", + "discharge_allowed", + "ev_charge_hours_float", + "result", + "ev_obj", + "eautocharge_hours_float", + "eauto_obj" + ], + "title": "Genetic0Solution", + "description": "**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." + }, + "GeneticCommonSettings-Input": { + "properties": { + "interval_sec": { + "type": "integer", + "maximum": 3600.0, + "minimum": 900.0, + "title": "Interval Sec", + "description": "The optimization interval [sec]. Defaults to 3600 seconds (1 hour)", + "default": 3600, + "examples": [ + 3600, + 900 + ] + }, + "horizon_hours": { + "type": "integer", + "minimum": 0.0, + "title": "Horizon Hours", + "description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.", + "default": 24, + "examples": [ + 24 + ] + }, "individuals": { "anyOf": [ { @@ -4895,160 +6115,119 @@ }, "type": "object", "title": "GeneticCommonSettings", - "description": "General Genetic Optimization Algorithm Configuration." + "description": "GENETIC Optimization Algorithm Configuration." }, - "GeneticEnergyManagementParameters": { + "GeneticCommonSettings-Output": { "properties": { - "pv_forecast_wh": { - "items": { - "type": "number" - }, - "type": "array", - "title": "Pv Forecast Wh", - "description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals." + "interval_sec": { + "type": "integer", + "maximum": 3600.0, + "minimum": 900.0, + "title": "Interval Sec", + "description": "The optimization interval [sec]. Defaults to 3600 seconds (1 hour)", + "default": 3600, + "examples": [ + 3600, + 900 + ] }, - "electricity_price_per_wh": { - "items": { - "type": "number" - }, - "type": "array", - "title": "Electricity Price Per Wh", - "description": "An array of floats representing the electricity price per watt-hour for different time intervals." + "horizon_hours": { + "type": "integer", + "minimum": 0.0, + "title": "Horizon Hours", + "description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.", + "default": 24, + "examples": [ + 24 + ] }, - "feed_in_tariff_per_wh": { + "individuals": { "anyOf": [ { - "items": { - "type": "number" - }, - "type": "array" + "type": "integer", + "minimum": 10.0 }, { - "type": "number" + "type": "null" } ], - "title": "Feed In Tariff Per Wh", - "description": "A float or array of floats representing the feed-in compensation per watt-hour." + "title": "Individuals", + "description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.", + "default": 300, + "examples": [ + 300 + ] }, - "price_per_wh_battery": { - "type": "number", - "title": "Price Per Wh Battery", - "description": "A float representing the cost of battery energy per watt-hour." + "generations": { + "anyOf": [ + { + "type": "integer", + "minimum": 10.0 + }, + { + "type": "null" + } + ], + "title": "Generations", + "description": "Number of generations to evolve [>= 10]. Defaults to 400.", + "default": 400, + "examples": [ + 400 + ] }, - "total_load": { - "items": { - "type": "number" + "seed": { + "anyOf": [ + { + "type": "integer", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Seed", + "description": "Random seed for reproducibility. None = random.", + "examples": [ + null, + 42 + ] + }, + "penalties": { + "additionalProperties": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "integer" + }, + { + "type": "string" + } + ] }, - "type": "array", - "title": "Total Load", - "description": "An array of floats representing the total load (consumption) in watts for different time intervals." + "type": "object", + "title": "Penalties", + "description": "Penalty parameters used in fitness evaluation.", + "examples": [ + { + "ev_soc_miss": 10 + } + ] + }, + "horizon": { + "type": "integer", + "title": "Horizon", + "description": "Number of optimization steps.", + "readOnly": true } }, "type": "object", "required": [ - "pv_forecast_wh", - "electricity_price_per_wh", - "feed_in_tariff_per_wh", - "price_per_wh_battery", - "total_load" + "horizon" ], - "title": "GeneticEnergyManagementParameters", - "description": "Encapsulates energy-related forecasts and costs used in GENETIC optimization." - }, - "GeneticOptimizationParameters": { - "properties": { - "ems": { - "$ref": "#/components/schemas/GeneticEnergyManagementParameters" - }, - "pv_battery": { - "anyOf": [ - { - "$ref": "#/components/schemas/SolarPanelBatteryParameters" - }, - { - "type": "null" - } - ], - "description": "PV battery parameters." - }, - "inverter": { - "anyOf": [ - { - "$ref": "#/components/schemas/InverterParameters" - }, - { - "type": "null" - } - ] - }, - "ev": { - "anyOf": [ - { - "$ref": "#/components/schemas/ElectricVehicleParameters" - }, - { - "type": "null" - } - ], - "description": "Electric vehicle parameters." - }, - "dishwasher": { - "anyOf": [ - { - "$ref": "#/components/schemas/HomeApplianceParameters" - }, - { - "type": "null" - } - ] - }, - "temperature_forecast": { - "anyOf": [ - { - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "type": "array" - }, - { - "type": "null" - } - ], - "title": "Temperature Forecast", - "description": "An array of floats representing the temperature forecast in degrees Celsius for different time intervals." - }, - "start_solution": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "title": "Start Solution", - "description": "Can be `null` or contain a previous solution (if available)." - } - }, - "type": "object", - "required": [ - "ems", - "pv_battery", - "inverter", - "ev" - ], - "title": "GeneticOptimizationParameters", - "description": "Main parameter class for running the genetic energy optimization.\n\nCollects all model and configuration parameters necessary to run the\noptimization process, such as forecasts, pricing, battery and appliance models." + "title": "GeneticCommonSettings", + "description": "GENETIC Optimization Algorithm Configuration." }, "GeneticSimulationResult": { "properties": { @@ -5639,80 +6818,6 @@ "title": "HomeApplianceCommonSettings", "description": "Home Appliance devices base settings." }, - "HomeApplianceParameters": { - "properties": { - "device_id": { - "type": "string", - "title": "Device Id", - "description": "ID of home appliance", - "examples": [ - "dishwasher" - ] - }, - "hours": { - "anyOf": [ - { - "type": "integer", - "exclusiveMinimum": 0.0 - }, - { - "type": "null" - } - ], - "title": "Hours", - "description": "Number of prediction hours. Defaults to global config prediction hours.", - "examples": [ - null - ] - }, - "consumption_wh": { - "type": "integer", - "exclusiveMinimum": 0.0, - "title": "Consumption Wh", - "description": "An integer representing the energy consumption of a household device in watt-hours.", - "examples": [ - 2000 - ] - }, - "duration_h": { - "type": "integer", - "exclusiveMinimum": 0.0, - "title": "Duration H", - "description": "An integer representing the usage duration of a household device in hours.", - "examples": [ - 3 - ] - }, - "time_windows": { - "anyOf": [ - { - "$ref": "#/components/schemas/TimeWindowSequence-Input" - }, - { - "type": "null" - } - ], - "description": "List of allowed time windows. Defaults to optimization general time window.", - "examples": [ - [ - { - "duration": "3 hours", - "start_time": "10:00" - } - ] - ] - } - }, - "additionalProperties": false, - "type": "object", - "required": [ - "device_id", - "consumption_wh", - "duration_h" - ], - "title": "HomeApplianceParameters", - "description": "Home Appliance Device Simulation Configuration." - }, "HomeAssistantAdapterCommonSettings-Input": { "properties": { "config_entity_ids": { @@ -6304,109 +7409,6 @@ "title": "InverterCommonSettings", "description": "Inverter devices base settings." }, - "InverterParameters": { - "properties": { - "device_id": { - "type": "string", - "title": "Device Id", - "description": "ID of inverter", - "examples": [ - "inverter1" - ] - }, - "hours": { - "anyOf": [ - { - "type": "integer", - "exclusiveMinimum": 0.0 - }, - { - "type": "null" - } - ], - "title": "Hours", - "description": "Number of prediction hours. Defaults to global config prediction hours.", - "examples": [ - null - ] - }, - "max_power_wh": { - "type": "number", - "exclusiveMinimum": 0.0, - "title": "Max Power Wh", - "examples": [ - 10000 - ] - }, - "battery_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "title": "Battery Id", - "description": "ID of battery", - "examples": [ - null, - "battery1" - ] - }, - "ac_to_dc_efficiency": { - "type": "number", - "maximum": 1.0, - "minimum": 0.0, - "title": "Ac To Dc Efficiency", - "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).", - "default": 1.0, - "examples": [ - 0.95, - 1.0, - 0.0 - ] - }, - "dc_to_ac_efficiency": { - "type": "number", - "maximum": 1.0, - "exclusiveMinimum": 0.0, - "title": "Dc To Ac Efficiency", - "description": "Efficiency of DC to AC conversion (for battery discharging to AC load/grid). Default 1.0 for backward compatibility (no additional inverter loss).", - "default": 1.0, - "examples": [ - 0.95, - 1.0 - ] - }, - "max_ac_charge_power_w": { - "anyOf": [ - { - "type": "number", - "minimum": 0.0 - }, - { - "type": "null" - } - ], - "title": "Max Ac Charge Power W", - "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": [ - null, - 0, - 5000 - ] - } - }, - "additionalProperties": false, - "type": "object", - "required": [ - "device_id", - "max_power_wh" - ], - "title": "InverterParameters", - "description": "Inverter Device Simulation Configuration." - }, "LoadAkkudoktorCommonSettings": { "properties": { "loadakkudoktor_year_energy_kwh": { @@ -7064,40 +8066,31 @@ }, "OptimizationCommonSettings-Input": { "properties": { - "horizon_hours": { - "type": "integer", - "minimum": 0.0, - "title": "Horizon Hours", - "description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.", - "default": 24, - "examples": [ - 24 - ] - }, - "interval": { - "type": "integer", - "maximum": 3600.0, - "minimum": 900.0, - "title": "Interval", - "description": "The optimization interval [sec]. Defaults to 3600 seconds (1 hour)", - "default": 3600, - "examples": [ - 3600, - 900 - ] - }, "algorithm": { "type": "string", "title": "Algorithm", "description": "The optimization algorithm. Defaults to GENETIC", "default": "GENETIC", "examples": [ - "GENETIC" + "GENETIC", + "GENETIC0" ] }, "genetic": { - "$ref": "#/components/schemas/GeneticCommonSettings", - "description": "Genetic optimization algorithm configuration.", + "$ref": "#/components/schemas/GeneticCommonSettings-Input", + "description": "GENETIC optimization algorithm configuration.", + "examples": [ + { + "individuals": 400, + "penalties": { + "ev_soc_miss": 10 + } + } + ] + }, + "genetic0": { + "$ref": "#/components/schemas/Genetic0CommonSettings-Input", + "description": "GENETIC0 optimization algorithm configuration.", "examples": [ { "individuals": 400, @@ -7114,40 +8107,19 @@ }, "OptimizationCommonSettings-Output": { "properties": { - "horizon_hours": { - "type": "integer", - "minimum": 0.0, - "title": "Horizon Hours", - "description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.", - "default": 24, - "examples": [ - 24 - ] - }, - "interval": { - "type": "integer", - "maximum": 3600.0, - "minimum": 900.0, - "title": "Interval", - "description": "The optimization interval [sec]. Defaults to 3600 seconds (1 hour)", - "default": 3600, - "examples": [ - 3600, - 900 - ] - }, "algorithm": { "type": "string", "title": "Algorithm", "description": "The optimization algorithm. Defaults to GENETIC", "default": "GENETIC", "examples": [ - "GENETIC" + "GENETIC", + "GENETIC0" ] }, "genetic": { - "$ref": "#/components/schemas/GeneticCommonSettings", - "description": "Genetic optimization algorithm configuration.", + "$ref": "#/components/schemas/GeneticCommonSettings-Output", + "description": "GENETIC optimization algorithm configuration.", "examples": [ { "individuals": 400, @@ -7157,6 +8129,27 @@ } ] }, + "genetic0": { + "$ref": "#/components/schemas/Genetic0CommonSettings-Output", + "description": "GENETIC0 optimization algorithm configuration.", + "examples": [ + { + "individuals": 400, + "penalties": { + "ev_soc_miss": 10 + } + } + ] + }, + "algorithms": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Algorithms", + "description": "Available optimization algorithms.", + "readOnly": true + }, "keys": { "items": { "type": "string" @@ -7165,18 +8158,12 @@ "title": "Keys", "description": "The keys of the solution.", "readOnly": true - }, - "horizon": { - "type": "integer", - "title": "Horizon", - "description": "Number of optimization steps.", - "readOnly": true } }, "type": "object", "required": [ - "keys", - "horizon" + "algorithms", + "keys" ], "title": "OptimizationCommonSettings", "description": "General Optimization Configuration." @@ -8900,136 +9887,6 @@ "title": "SettingsEOS", "description": "Settings for all EOS.\n\nOnly used to update the configuration with specific settings." }, - "SolarPanelBatteryParameters": { - "properties": { - "device_id": { - "type": "string", - "title": "Device Id", - "description": "ID of battery", - "examples": [ - "battery1" - ] - }, - "hours": { - "anyOf": [ - { - "type": "integer", - "exclusiveMinimum": 0.0 - }, - { - "type": "null" - } - ], - "title": "Hours", - "description": "Number of prediction hours. Defaults to global config prediction hours.", - "examples": [ - null - ] - }, - "capacity_wh": { - "type": "integer", - "exclusiveMinimum": 0.0, - "title": "Capacity Wh", - "description": "An integer representing the capacity of the battery in watt-hours.", - "examples": [ - 8000 - ] - }, - "charging_efficiency": { - "type": "number", - "maximum": 1.0, - "exclusiveMinimum": 0.0, - "title": "Charging Efficiency", - "description": "A float representing the charging efficiency of the battery.", - "default": 0.88 - }, - "discharging_efficiency": { - "type": "number", - "maximum": 1.0, - "exclusiveMinimum": 0.0, - "title": "Discharging Efficiency", - "description": "A float representing the discharge efficiency of the battery.", - "default": 0.88 - }, - "max_charge_power_w": { - "anyOf": [ - { - "type": "number", - "exclusiveMinimum": 0.0 - }, - { - "type": "null" - } - ], - "title": "Max Charge Power W", - "description": "Maximum charging power in watts.", - "default": 5000 - }, - "initial_soc_percentage": { - "type": "integer", - "maximum": 100.0, - "minimum": 0.0, - "title": "Initial Soc Percentage", - "description": "An integer representing the state of charge of the battery at the **start** of the current hour (not the current state).", - "default": 0, - "examples": [ - 42 - ] - }, - "min_soc_percentage": { - "type": "integer", - "maximum": 100.0, - "minimum": 0.0, - "title": "Min Soc Percentage", - "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", - "default": 0, - "examples": [ - 10 - ] - }, - "max_soc_percentage": { - "type": "integer", - "maximum": 100.0, - "minimum": 0.0, - "title": "Max Soc Percentage", - "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", - "default": 100 - }, - "charge_rates": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "title": "Charge Rates", - "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 - ], - null - ] - } - }, - "additionalProperties": false, - "type": "object", - "required": [ - "device_id", - "capacity_wh" - ], - "title": "SolarPanelBatteryParameters", - "description": "PV battery device simulation configuration." - }, "TimeWindow-Input": { "properties": { "start_time": { diff --git a/src/akkudoktoreos/config/configmigrate.py b/src/akkudoktoreos/config/configmigrate.py index f993ecf..1320123 100644 --- a/src/akkudoktoreos/config/configmigrate.py +++ b/src/akkudoktoreos/config/configmigrate.py @@ -112,12 +112,14 @@ MIGRATION_MAP: Dict[ "measurement/load4_name": "measurement/load_emr_keys/4", # optimization # ============ + "optimization/interval": None, + "optimization/horizon_hours": "optimization/genetic0/horizon_hours", "optimization/ev_available_charge_rates_percent": ( "devices/electric_vehicles/0/charge_rates", lambda v: [x / 100 for x in v], ), - "optimization/hours": "optimization/horizon_hours", - "optimization/penalty": ("optimization/genetic/penalties/ev_soc_miss", lambda v: float(v)), + "optimization/hours": "optimization/genetic0/horizon_hours", + "optimization/penalty": ("optimization/genetic0/penalties/ev_soc_miss", lambda v: float(v)), # pvforecast # ========== # - PVForecastAkkudoktor diff --git a/src/akkudoktoreos/core/ems.py b/src/akkudoktoreos/core/ems.py index d5b7f42..0cc1017 100644 --- a/src/akkudoktoreos/core/ems.py +++ b/src/akkudoktoreos/core/ems.py @@ -17,6 +17,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.genetic0.genetic0 import Genetic0Optimization +from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0OptimizationParameters, +) +from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution from akkudoktoreos.optimization.genetic.genetic import GeneticOptimization from akkudoktoreos.optimization.genetic.geneticparams import ( GeneticOptimizationParameters, @@ -72,6 +77,10 @@ class EnergyManagement( # For classic API _genetic_solution: ClassVar[Optional[GeneticSolution]] = None + # Solution of the genetic0 algorithm of latest energy management run with optimization + # For classic API + _genetic0_solution: ClassVar[Optional[Genetic0Solution]] = None + # energy management lock (for energy management run) _run_lock: ClassVar[Lock] = Lock() @@ -146,14 +155,26 @@ class EnergyManagement( """ return cls._genetic_solution + @classmethod + def genetic0_solution(cls) -> Optional[Genetic0Solution]: + """Get the latest solution of the genetic0 algorithm. + + Returns: + Optional[Genetic0Solution]: The latest solution of the genetic algorithm. + """ + return cls._genetic0_solution + async def run( self, start_datetime: Optional[DateTime] = None, mode: Optional[EnergyManagementMode] = None, algorithm: Optional[str] = None, genetic_parameters: Optional[GeneticOptimizationParameters] = None, - genetic_individuals: Optional[int] = None, + genetic_generations: Optional[int] = None, genetic_seed: Optional[int] = None, + genetic0_parameters: Optional[Genetic0OptimizationParameters] = None, + genetic0_generations: Optional[int] = None, + genetic0_seed: Optional[int] = None, force_enable: Optional[bool] = False, force_update: Optional[bool] = False, ) -> None: @@ -174,16 +195,25 @@ class EnergyManagement( algorithm (str, optional): The algorithm to use. Must be one of: - "GENETIC": Optimization uses the `GENETIC` optimization algorithm. + - "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_individuals (int, optional): The number of individuals for the + genetic_generations (int, optional): The number of generations for the `GENETIC` algorithm. Defaults to the algorithm's internal default (400) if not specified. genetic_seed (int, optional): The seed for the `GENETIC` algorithm. Defaults to the algorithm's internal random seed if not specified. + genetic0_parameters (Genetic0OptimizationParameters, optional): The + parameter set for the `GENETIC0` algorithm. If not provided, it will + be constructed based on the current configuration and predictions. + genetic0_generations (int, optional): The number of generations for the + `GENETIC0` algorithm. Defaults to the algorithm's internal default (400) + if not specified. + genetic0_seed (int, optional): The seed for the `GENETIC0` algorithm. Defaults + to the algorithm's internal random seed if not specified. force_enable (bool, optional): If True, bypasses any disabled state to force the update process. This is mostly applicable to prediction providers. @@ -245,53 +275,138 @@ class EnergyManagement( if algorithm is None: algorithm = self.config.optimization.algorithm + # --- GENETIC algorithm --- if algorithm == "GENETIC": # Prepare optimization parameters # This also creates default configurations for missing values and updates the predictions - logger.info("Starting optimzation parameter preparation.") + logger.info(f"{algorithm}: Starting optimzation parameter preparation.") if genetic_parameters is None: genetic_parameters = await GeneticOptimizationParameters.prepare() if genetic_parameters is None: logger.error( - "Energy management run canceled. Could not prepare optimisation parameters." + f"{algorithm}: Energy management run canceled. " + "Could not prepare optimisation parameters." ) EnergyManagement._stage = EnergyManagementStage.IDLE return # Take values from config if not given - if genetic_individuals is None: - genetic_individuals = self.config.optimization.genetic.individuals + 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("Start datetime not set.") + raise RuntimeError(f"{algorithm}: Start datetime not set.") # --- Optimization (CPU-bound → MUST offload) --- try: - optimization = GeneticOptimization( + genetic_optimization = GeneticOptimization( verbose=bool(self.config.server.verbose), fixed_seed=genetic_seed, ) loop = get_running_loop() start_hour = EnergyManagement._start_datetime.hour - solution = await loop.run_in_executor( + genetic_solution = await loop.run_in_executor( None, - lambda: optimization.optimize_ems( + lambda: genetic_optimization.optimize_ems( start_hour=start_hour, parameters=cast( GeneticOptimizationParameters, genetic_parameters ), # cast for mypy - ngen=genetic_individuals, + ngen=genetic_generations, ), ) except Exception: - logger.exception("Energy management optimization failed.") + logger.exception(f"{algorithm}: Energy management optimization failed.") EnergyManagement._stage = EnergyManagementStage.IDLE return + # Make genetic solution public + EnergyManagement._genetic_solution = genetic_solution + + # Make optimization solution public + EnergyManagement._optimization_solution = ( + await genetic_solution.optimization_solution() + ) + + # Make plan public + EnergyManagement._plan = genetic_solution.energy_management_plan() + + logger.debug( + "{}: Energy management genetic solution:\n{}", + algorithm, + EnergyManagement._genetic_solution, + ) + + # --- GENETIC0 algorithm --- + elif algorithm == "GENETIC0": + # Prepare optimization parameters + # This also creates default configurations for missing values and updates the predictions + logger.info(f"{algorithm}: Starting optimzation parameter preparation.") + if genetic0_parameters is None: + genetic0_parameters = await Genetic0OptimizationParameters.prepare() + if genetic0_parameters is None: + logger.error( + f"{algorithm}: Energy management run canceled. " + "Could not prepare optimisation parameters." + ) + EnergyManagement._stage = EnergyManagementStage.IDLE + return + + # Take values from config if not given + if genetic0_generations is None: + genetic0_generations = self.config.optimization.genetic0.generations + if genetic0_seed is None: + genetic0_seed = self.config.optimization.genetic0.seed + + if EnergyManagement._start_datetime is None: # Make mypy happy - already set by us + raise RuntimeError(f"{algorithm}: Start datetime not set.") + + # --- Optimization (CPU-bound → MUST offload) --- + try: + genetic0_optimization = Genetic0Optimization( + verbose=bool(self.config.server.verbose), + fixed_seed=genetic0_seed, + ) + + loop = get_running_loop() + start_hour = EnergyManagement._start_datetime.hour + genetic0_solution = await loop.run_in_executor( + None, + lambda: genetic0_optimization.optimize_ems( + start_hour=start_hour, + parameters=cast( + Genetic0OptimizationParameters, genetic0_parameters + ), # cast for mypy + ngen=genetic0_generations, + ), + ) + + except Exception: + logger.exception(f"{algorithm}: Energy management optimization failed.") + EnergyManagement._stage = EnergyManagementStage.IDLE + return + + # Make genetic0 solution public + EnergyManagement._genetic0_solution = genetic0_solution + + # Make optimization solution public + EnergyManagement._optimization_solution = ( + await genetic0_solution.optimization_solution() + ) + + # Make plan public + EnergyManagement._plan = genetic0_solution.energy_management_plan() + + logger.debug( + "{}: Energy management genetic solution:\n{}", + algorithm, + EnergyManagement._genetic0_solution, + ) + else: logger.error(f"Unknown optimization algorithm: '{algorithm}'. Skipping.") EnergyManagement._stage = EnergyManagementStage.IDLE @@ -299,82 +414,19 @@ class EnergyManagement( optimization_duration = to_datetime() - optimization_start logger.info( - "Energy management optimization ({}) completed in {:.1f} seconds.", + "{}: Energy management optimization completed in {:.1f} seconds.", algorithm, optimization_duration.total_seconds(), ) logger.debug( - "Energy management optimization solution:\n{}", + "{}: Energy management optimization solution:\n{}", + algorithm, EnergyManagement._optimization_solution, ) - logger.debug("Energy management plan:\n{}", EnergyManagement._plan) + logger.debug("{}: Energy management plan:\n{}", algorithm, EnergyManagement._plan) - # --- Control dispatch by adapters --- - EnergyManagement._stage = EnergyManagementStage.CONTROL_DISPATCH - - # Make genetic solution public - EnergyManagement._genetic_solution = solution - - # Make optimization solution public - EnergyManagement._optimization_solution = await solution.optimization_solution() - - # Make plan public - EnergyManagement._plan = solution.energy_management_plan() - - logger.debug( - "Energy management genetic solution:\n{}", EnergyManagement._genetic_solution - ) - - if genetic_parameters is None: - genetic_parameters = await GeneticOptimizationParameters.prepare() - - if not genetic_parameters: - logger.error("Energy management run canceled. Could not prepare parameters.") - EnergyManagement._stage = EnergyManagementStage.IDLE - return - - EnergyManagement._stage = EnergyManagementStage.OPTIMIZATION - - if genetic_individuals is None: - genetic_individuals = self.config.optimization.genetic.individuals - if genetic_seed is None: - genetic_seed = self.config.optimization.genetic.seed - - if EnergyManagement._start_datetime is None: - raise RuntimeError("Start datetime not set.") - - # --- Optimization (CPU-bound → MUST offload) --- - try: - optimization = GeneticOptimization( - verbose=bool(self.config.server.verbose), - fixed_seed=genetic_seed, - ) - - loop = get_running_loop() - start_hour = EnergyManagement._start_datetime.hour - solution = await loop.run_in_executor( - None, - lambda: optimization.optimize_ems( - start_hour=start_hour, - parameters=genetic_parameters, - ngen=genetic_individuals, - ), - ) - - except Exception: - logger.exception("Energy management optimization failed.") - EnergyManagement._stage = EnergyManagementStage.IDLE - return - - EnergyManagement._genetic_solution = solution - EnergyManagement._optimization_solution = await solution.optimization_solution() - EnergyManagement._plan = solution.energy_management_plan() - - logger.debug("Genetic solution:\n{}", EnergyManagement._genetic_solution) - logger.debug("Optimization solution:\n{}", EnergyManagement._optimization_solution) - logger.debug("Plan:\n{}", EnergyManagement._plan) - logger.info("Energy management run done (optimization updated)") + logger.info("{}: Energy management run done (optimization updated)", algorithm) # --- Dispatch control by adapters --- EnergyManagement._stage = EnergyManagementStage.CONTROL_DISPATCH diff --git a/src/akkudoktoreos/data/genetic0_load_interpolator.pkl b/src/akkudoktoreos/data/genetic0_load_interpolator.pkl new file mode 100644 index 0000000000000000000000000000000000000000..9d6197abfabf2c220ccdc5c4a169ddf718e6bd7b GIT binary patch literal 57788 zcmeFYWmr~SwD(IXV1pu{NQ)pX5)$iAcQ*pk-7Sa+Qc@}@2%?m9*?}kq0-~ZQD4`-@ zfP#oY2X>sl~y1BjPwk?sEorIyveJ*oB~~a z95a$vd%Af$+4*NAue0|F@^%ccaq{;k873sJadz|cvP*Nxxe~lupFdh;ff@D*iXs$?XW~EpYRE7CZ?VWb_DizcBISLS^!|%{7qrwKx=8l$Mamyp zq)5~v?;KsEe#|1@#V*n}evxDei#(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QN3UrncGhOoy1PtF9j#5w9qb)VU8ikzv!`RG VcGjjY7A~o=A~-E2)y-_${{V&hmKOj3 literal 0 HcmV?d00001 diff --git a/src/akkudoktoreos/devices/genetic0/__init__.py b/src/akkudoktoreos/devices/genetic0/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/akkudoktoreos/devices/genetic0/genetic0battery.py b/src/akkudoktoreos/devices/genetic0/genetic0battery.py new file mode 100644 index 0000000..c55e519 --- /dev/null +++ b/src/akkudoktoreos/devices/genetic0/genetic0battery.py @@ -0,0 +1,283 @@ +from typing import Any, Iterator, Optional + +import numpy as np + +from akkudoktoreos.devices.devices import BATTERY_DEFAULT_CHARGE_RATES +from akkudoktoreos.optimization.genetic0.genetic0devices import ( + Genetic0BaseBatteryParameters, + Genetic0SolarPanelBatteryParameters, +) + + +class Genetic0Battery: + """Represents a battery device with methods to simulate energy charging and discharging.""" + + def __init__(self, parameters: Genetic0BaseBatteryParameters, prediction_hours: int): + self.parameters = parameters + self.prediction_hours = prediction_hours + self._setup() + + def _setup(self) -> None: + """Sets up the battery parameters based on provided parameters.""" + self.capacity_wh = self.parameters.capacity_wh + self.initial_soc_percentage = self.parameters.initial_soc_percentage + self.charging_efficiency = self.parameters.charging_efficiency + self.discharging_efficiency = self.parameters.discharging_efficiency + + # Charge rates, in case of None use default + self.charge_rates = np.array(BATTERY_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, Genetic0SolarPanelBatteryParameters) + else 0 + ) + self.max_soc_percentage = self.parameters.max_soc_percentage + + # Initialize state of charge + if self.parameters.max_charge_power_w is not None: + self.max_charge_power_w = self.parameters.max_charge_power_w + else: + self.max_charge_power_w = self.capacity_wh # TODO this should not be equal capacity_wh + self.discharge_array = np.full(self.prediction_hours, 0) + self.charge_array = np.full(self.prediction_hours, 0) + self.soc_wh = (self.initial_soc_percentage / 100) * self.capacity_wh + self.min_soc_wh = (self.min_soc_percentage / 100) * self.capacity_wh + self.max_soc_wh = (self.max_soc_percentage / 100) * self.capacity_wh + + def _lower_charge_rates_desc(self, start_rate: float) -> Iterator[float]: + """Yield all charge rates lower than a given rate in descending order. + + Args: + charge_rates (np.ndarray): Sorted 1D array of available charge rates. + start_rate (float): The reference charge rate. + + Yields: + float: Charge rates lower than `start_rate`, in descending order. + """ + charge_rates_fast = self.charge_rates + + # Find the insertion index for start_rate (left-most position) + idx = np.searchsorted(charge_rates_fast, start_rate, side="left") + + # Yield values before idx in reverse (descending) + return (charge_rates_fast[j] for j in range(idx - 1, -1, -1)) + + def to_dict(self) -> dict[str, Any]: + """Converts the object to a dictionary representation.""" + return { + "device_id": self.parameters.device_id, + "capacity_wh": self.capacity_wh, + "initial_soc_percentage": self.initial_soc_percentage, + "soc_wh": self.soc_wh, + "hours": self.prediction_hours, + "discharge_array": self.discharge_array, + "charge_array": self.charge_array, + "charging_efficiency": self.charging_efficiency, + "discharging_efficiency": self.discharging_efficiency, + "max_charge_power_w": self.max_charge_power_w, + } + + def reset(self) -> None: + """Resets the battery state to its initial values.""" + self.soc_wh = (self.initial_soc_percentage / 100) * self.capacity_wh + self.soc_wh = min(self.soc_wh, self.max_soc_wh) # Only clamp to max + self.discharge_array = np.full(self.prediction_hours, 0) + self.charge_array = np.full(self.prediction_hours, 0) + + def set_discharge_per_hour(self, discharge_array: np.ndarray) -> None: + """Sets the discharge values for each hour.""" + if len(discharge_array) != self.prediction_hours: + raise ValueError( + f"Discharge array must have exactly {self.prediction_hours} elements. Got {len(discharge_array)} elements." + ) + self.discharge_array = np.array(discharge_array) + + def set_charge_per_hour(self, charge_array: np.ndarray) -> None: + """Sets the charge values for each hour.""" + if len(charge_array) != self.prediction_hours: + raise ValueError( + f"Charge array must have exactly {self.prediction_hours} elements. Got {len(charge_array)} elements." + ) + self.charge_array = np.array(charge_array) + + def current_soc_percentage(self) -> float: + """Calculates the current state of charge in percentage.""" + return (self.soc_wh / self.capacity_wh) * 100 + + def discharge_energy(self, wh: float, hour: int) -> tuple[float, float]: + """Discharge energy from the battery. + + Discharge is limited by: + * Requested delivered energy + * Remaining energy above minimum SoC + * Maximum discharge power + * Discharge efficiency + + Args: + wh (float): Requested delivered energy in watt-hours. + hour (int): Time index. If `self.discharge_array[hour] == 0`, + no discharge occurs. + + Returns: + tuple[float, float]: + delivered_wh (float): Actual delivered energy [Wh]. + losses_wh (float): Conversion losses [Wh]. + + """ + if self.discharge_array[hour] == 0: + return 0.0, 0.0 + + # Raw extractable energy above minimum SoC + raw_available_wh = max(self.soc_wh - self.min_soc_wh, 0.0) + + # Maximum raw discharge due to power limit + max_raw_wh = self.max_charge_power_w # TODO rename to max_discharge_power_w + + # Actual raw withdrawal (internal) + raw_withdrawal_wh = min(raw_available_wh, max_raw_wh) + + # Convert raw to delivered + max_deliverable_wh = raw_withdrawal_wh * self.discharging_efficiency + + # Cap by requested delivered energy + delivered_wh = min(wh, max_deliverable_wh) + + # Effective raw withdrawal based on what is delivered + raw_used_wh = delivered_wh / self.discharging_efficiency + + # Update SoC + self.soc_wh -= raw_used_wh + self.soc_wh = max(self.soc_wh, self.min_soc_wh) + + # Losses + losses_wh = raw_used_wh - delivered_wh + + return delivered_wh, losses_wh + + def charge_energy( + self, + wh: Optional[float], + hour: int, + charge_factor: float = 0.0, + ) -> tuple[float, float]: + """Charge energy into the battery. + + Two **exclusive** modes: + + **Mode 1:** + + - `wh is not None` and `charge_factor == 0` + - The raw requested charge energy is `wh` (pre-efficiency). + - If remaining capacity is insufficient, charging is automatically limited. + - No exception is raised due to capacity limits. + + **Mode 2:** + + - `wh is None` and `charge_factor > 0` + - The raw requested energy is `max_charge_power_w * charge_factor`. + - If the request exceeds remaining capacity, the algorithm tries to find a lower + `charge_factor` that is compatible. If such a charge factor exists, this hour’s + `charge_factor` is replaced. + - If no charge factor can accommodate charging, the request is ignored (``(0.0, 0.0)`` is + returned) and a penalty is applied elsewhere. + + Charging is constrained by: + + - Available SoC headroom (``max_soc_wh − soc_wh``) + - ``max_charge_power_w`` + - ``charging_efficiency`` + + Args: + wh (float | None): + Requested raw energy [Wh] before efficiency. + Must be provided only for Mode 1 (charge_factor must be 0). + + hour (int): + Time index. If charging is disabled at this hour (charge_array[hour] == 0), + returns `(0.0, 0.0)`. + + charge_factor (float): + Fraction (0–1) of max charge power. + Must be >0 only in Mode 2 (`wh is None`). + + Returns: + tuple[float, float]: + stored_wh : float + Energy stored after efficiency [Wh]. + losses_wh : float + Conversion losses [Wh]. + + Raises: + ValueError: + - If the mode is ambiguous (neither Mode 1 nor Mode 2). + - If the final new SoC would exceed capacity_wh. + + Notes: + stored_wh = raw_input_wh * charging_efficiency + losses_wh = raw_input_wh − stored_wh + """ + # Charging allowed in this hour? + if hour is not None and self.charge_array[hour] == 0: + return 0.0, 0.0 + + # Provide fast (3x..5x) local read access (vs. self.xxx) for repetitive read access + soc_wh_fast = self.soc_wh + max_charge_power_w_fast = self.max_charge_power_w + charging_efficiency_fast = self.charging_efficiency + + # Decide mode & determine raw_request_wh and raw_charge_wh + if wh is not None and charge_factor == 0.0: # mode 1 + raw_request_wh = wh + raw_charge_wh = max(self.max_soc_wh - soc_wh_fast, 0.0) / charging_efficiency_fast + elif wh is None and charge_factor > 0.0: # mode 2 + raw_request_wh = max_charge_power_w_fast * charge_factor + raw_charge_wh = max(self.max_soc_wh - soc_wh_fast, 0.0) / charging_efficiency_fast + if raw_request_wh > raw_charge_wh: + # Use a lower charge factor + lower_charge_factors = self._lower_charge_rates_desc(charge_factor) + for charge_factor in lower_charge_factors: + raw_request_wh = max_charge_power_w_fast * charge_factor + if raw_request_wh <= raw_charge_wh: + self.charge_array[hour] = charge_factor + break + if raw_request_wh > raw_charge_wh: + # ignore request - penalty for missing SoC will be applied + self.charge_array[hour] = 0 + return 0.0, 0.0 + else: + raise ValueError( + f"{self.parameters.device_id}: charge_energy must be called either " + "with wh != None and charge_factor == 0, or with wh == None and charge_factor > 0." + ) + + # Remaining capacity + max_raw_wh = min(raw_charge_wh, max_charge_power_w_fast) + + # Actual raw intake + raw_input_wh = raw_request_wh if raw_request_wh < max_raw_wh else max_raw_wh + + # Apply efficiency + stored_wh = raw_input_wh * charging_efficiency_fast + new_soc = soc_wh_fast + stored_wh + + if new_soc > self.capacity_wh: + raise ValueError( + f"{self.parameters.device_id}: SoC {new_soc} Wh exceeds capacity {self.capacity_wh} Wh" + ) + + self.soc_wh = new_soc + losses_wh = raw_input_wh - stored_wh + + return stored_wh, losses_wh + + def current_energy_content(self) -> float: + """Returns the current usable energy in the battery.""" + usable_energy = (self.soc_wh - self.min_soc_wh) * self.discharging_efficiency + return max(usable_energy, 0.0) diff --git a/src/akkudoktoreos/devices/genetic0/genetic0homeappliance.py b/src/akkudoktoreos/devices/genetic0/genetic0homeappliance.py new file mode 100644 index 0000000..a1fe388 --- /dev/null +++ b/src/akkudoktoreos/devices/genetic0/genetic0homeappliance.py @@ -0,0 +1,102 @@ +import numpy as np + +from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence +from akkudoktoreos.optimization.genetic0.genetic0devices import ( + Genetic0HomeApplianceParameters, +) +from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_time + + +class Genetic0HomeAppliance: + def __init__( + self, + parameters: Genetic0HomeApplianceParameters, + optimization_hours: int, + prediction_hours: int, + ): + self.parameters: Genetic0HomeApplianceParameters = parameters + self.prediction_hours = prediction_hours + self._setup() + + def _setup(self) -> None: + """Sets up the home appliance parameters based provided parameters.""" + self.load_curve = np.zeros(self.prediction_hours) # Initialize the load curve with zeros + self.duration_h = self.parameters.duration_h + self.consumption_wh = self.parameters.consumption_wh + # setup possible start times + if self.parameters.time_windows is None: + self.parameters.time_windows = TimeWindowSequence( + windows=[ + TimeWindow( + start_time=to_time("00:00"), + duration=to_duration(f"{self.prediction_hours} hours"), + ), + ] + ) + start_datetime = to_datetime().set(hour=0, minute=0, second=0) + duration = to_duration(f"{self.duration_h} hours") + self.start_allowed: list[bool] = [] + for hour in range(0, self.prediction_hours): + self.start_allowed.append( + self.parameters.time_windows.contains( + start_datetime.add(hours=hour), duration=duration + ) + ) + start_earliest = self.parameters.time_windows.earliest_start_time(duration, start_datetime) + if start_earliest: + self.start_earliest = start_earliest.hour + else: + self.start_earliest = 0 + start_latest = self.parameters.time_windows.latest_start_time(duration, start_datetime) + if start_latest: + self.start_latest = start_latest.hour + else: + self.start_latest = 23 + + def set_starting_time(self, start_hour: int, global_start_hour: int = 0) -> int: + """Sets the start time of the device and generates the corresponding load curve. + + :param start_hour: The hour at which the device should start. + """ + if not self.start_allowed[start_hour]: + # It is not allowed (by the time windows) to start the application at this time + if global_start_hour <= self.start_latest: + # There is a time window left to start the appliance. Use it + start_hour = self.start_latest + else: + # There is no time window left to run the application + # Set the start into tomorrow + start_hour = self.start_earliest + 24 + + self.reset_load_curve() + + # Calculate power per hour based on total consumption and duration + power_per_hour = self.consumption_wh / self.duration_h # Convert to watt-hours + + # Set the power for the duration of use in the load curve array + if start_hour < len(self.load_curve): + end_hour = min(start_hour + self.duration_h, self.prediction_hours) + self.load_curve[start_hour:end_hour] = power_per_hour + + return start_hour + + def reset_load_curve(self) -> None: + """Resets the load curve.""" + self.load_curve = np.zeros(self.prediction_hours) + + def get_load_curve(self) -> np.ndarray: + """Returns the current load curve.""" + return self.load_curve + + def get_load_for_hour(self, hour: int) -> float: + """Returns the load for a specific hour. + + :param hour: The hour for which the load is queried. + :return: The load in watts for the specified hour. + """ + if hour < 0 or hour >= self.prediction_hours: + raise ValueError( + f"The specified hour {hour} is outside the available time frame {self.prediction_hours}." + ) + + return self.load_curve[hour] diff --git a/src/akkudoktoreos/devices/genetic0/genetic0inverter.py b/src/akkudoktoreos/devices/genetic0/genetic0inverter.py new file mode 100644 index 0000000..4d169b0 --- /dev/null +++ b/src/akkudoktoreos/devices/genetic0/genetic0inverter.py @@ -0,0 +1,136 @@ +from typing import Optional + +from loguru import logger + +from akkudoktoreos.devices.genetic0.genetic0battery import Genetic0Battery +from akkudoktoreos.optimization.genetic0.genetic0devices import ( + Genetic0InverterParameters, +) +from akkudoktoreos.optimization.genetic0.genetic0loadinterpolator import ( + get_genetic0_load_interpolator, +) + + +class Genetic0Inverter: + def __init__( + self, + parameters: Genetic0InverterParameters, + battery: Optional[Genetic0Battery] = None, + ): + self.parameters: Genetic0InverterParameters = parameters + self.battery: Optional[Genetic0Battery] = battery + self._setup() + + def _setup(self) -> None: + if self.battery and self.parameters.battery_id != self.battery.parameters.device_id: + error_msg = f"Battery ID mismatch - {self.parameters.battery_id} is configured; got {self.battery.parameters.device_id}." + logger.error(error_msg) + raise ValueError(error_msg) + self.self_consumption_predictor = get_genetic0_load_interpolator() + self.max_power_wh = ( + self.parameters.max_power_wh + ) # Maximum power that the inverter can handle + self.dc_to_ac_efficiency = self.parameters.dc_to_ac_efficiency + self.ac_to_dc_efficiency = self.parameters.ac_to_dc_efficiency + self.max_ac_charge_power_w = self.parameters.max_ac_charge_power_w + + def process_energy( + self, generation: float, consumption: float, hour: int + ) -> tuple[float, float, float, float]: + losses = 0.0 + grid_export = 0.0 + grid_import = 0.0 + self_consumption = 0.0 + + # Cache inverter DC→AC efficiency for discharge path + dc_to_ac_eff = self.dc_to_ac_efficiency + + if generation >= consumption: + if consumption > self.max_power_wh: + # If consumption exceeds maximum inverter power + losses += generation - self.max_power_wh + remaining_power = self.max_power_wh - consumption + grid_import = -remaining_power # Negative indicates feeding into the grid + self_consumption = self.max_power_wh + else: + # Calculate scr using cached results per energy management/optimization run + scr = self.self_consumption_predictor.calculate_self_consumption( + consumption, generation + ) + + # Remaining power after consumption + remaining_power = (generation - consumption) * scr # EVQ + # Remaining load Self Consumption not perfect + remaining_load_evq = (generation - consumption) * (1.0 - scr) + + if remaining_load_evq > 0: + # The battery must cover the remaining consumption + if self.battery: + # Request more DC from battery to account for DC→AC conversion loss + dc_request = remaining_load_evq / dc_to_ac_eff + from_battery_dc, discharge_losses = self.battery.discharge_energy( + dc_request, hour + ) + # Convert DC output to AC + from_battery_ac = from_battery_dc * dc_to_ac_eff + inverter_discharge_losses = from_battery_dc - from_battery_ac + remaining_load_evq -= from_battery_ac + losses += discharge_losses + inverter_discharge_losses + else: + from_battery_ac = 0.0 + + # If the battery cannot fully cover the remaining consumption, the rest is drawn from the grid + if remaining_load_evq > 0: + grid_import += remaining_load_evq + remaining_load_evq = 0 + else: + from_battery_ac = 0.0 + + if remaining_power > 0: + # Load battery with excess energy (DC path, no inverter conversion needed) + charge_losses = 0.0 + if self.battery: + charged_energie, charge_losses = self.battery.charge_energy( + remaining_power, hour + ) + remaining_surplus = remaining_power - (charged_energie + charge_losses) + else: + remaining_surplus = remaining_power + + # Feed-in to the grid based on remaining capacity + if remaining_surplus > self.max_power_wh - consumption: + grid_export = self.max_power_wh - consumption + losses += remaining_surplus - grid_export + else: + grid_export = remaining_surplus + + losses += charge_losses + self_consumption = ( + consumption + from_battery_ac + ) # Self-consumption is equal to the load + + else: + # Case 2: Insufficient generation, cover shortfall + shortfall = consumption - generation + available_ac_power = max(self.max_power_wh - generation, 0) + + # Discharge battery to cover shortfall, if possible + if self.battery: + # Need shortfall in AC, request more DC from battery for DC→AC conversion + ac_needed = min(shortfall, available_ac_power) + dc_request = ac_needed / dc_to_ac_eff + battery_discharge_dc, discharge_losses = self.battery.discharge_energy( + dc_request, hour + ) + # Convert DC output to AC + battery_discharge_ac = battery_discharge_dc * dc_to_ac_eff + inverter_discharge_losses = battery_discharge_dc - battery_discharge_ac + losses += discharge_losses + inverter_discharge_losses + else: + battery_discharge_ac = 0 + + # Draw remaining required power from the grid (discharge_losses are already subtracted in the battery) + grid_import = shortfall - battery_discharge_ac + self_consumption = generation + battery_discharge_ac + + return grid_export, grid_import, losses, self_consumption diff --git a/src/akkudoktoreos/optimization/genetic/genetic.py b/src/akkudoktoreos/optimization/genetic/genetic.py index 3dd3f54..6aeee17 100644 --- a/src/akkudoktoreos/optimization/genetic/genetic.py +++ b/src/akkudoktoreos/optimization/genetic/genetic.py @@ -435,7 +435,9 @@ class GeneticOptimization(OptimizationBase): ): """Initialize the optimization problem with the required parameters.""" self.opti_param: dict[str, Any] = {} - self.fixed_ev_hours = self.config.prediction.hours - self.config.optimization.horizon_hours + self.fixed_ev_hours = ( + self.config.prediction.hours - self.config.optimization.genetic.horizon_hours + ) self.ev_possible_charge_values: list[float] = [1.0] # Separate charge-level list for battery AC charging (independent of EV rates). # Populated from parameters.pv_battery.charge_rates in optimize_ems. @@ -1148,7 +1150,7 @@ class GeneticOptimization(OptimizationBase): dishwasher = ( HomeAppliance( parameters=parameters.dishwasher, - optimization_hours=self.config.optimization.horizon_hours, + optimization_hours=self.config.optimization.genetic.horizon_hours, prediction_hours=self.config.prediction.hours, ) if parameters.dishwasher is not None @@ -1166,7 +1168,7 @@ class GeneticOptimization(OptimizationBase): # Prepare device simulation self.simulation.prepare( parameters=parameters.ems, - optimization_hours=self.config.optimization.horizon_hours, + optimization_hours=self.config.optimization.genetic.horizon_hours, prediction_hours=self.config.prediction.hours, inverter=inverter, # battery is part of inverter ev=ev, diff --git a/src/akkudoktoreos/optimization/genetic/geneticparams.py b/src/akkudoktoreos/optimization/genetic/geneticparams.py index 5bac89a..d83f01a 100644 --- a/src/akkudoktoreos/optimization/genetic/geneticparams.py +++ b/src/akkudoktoreos/optimization/genetic/geneticparams.py @@ -247,17 +247,18 @@ class GeneticOptimizationParameters( logger.info("Prediction historic hours unknown - defaulting to 24 hours.") cls.config.prediction.historic_hours = 24 # Check optimization definitions - if cls.config.optimization.horizon_hours is None: + if cls.config.optimization.genetic.horizon_hours is None: logger.info("Optimization horizon unknown - defaulting to 24 hours.") - cls.config.optimization.horizon_hours = 24 - if cls.config.optimization.interval is None: + cls.config.optimization.genetic.horizon_hours = 24 + if cls.config.optimization.genetic.interval_sec is None: logger.info("Optimization interval unknown - defaulting to 3600 seconds.") - cls.config.optimization.interval = 3600 - if cls.config.optimization.interval != 3600: + cls.config.optimization.genetic.interval_sec = 3600 + if cls.config.optimization.genetic.interval_sec != 3600: logger.info( - "Optimization interval '{}' seconds not supported - forced to 3600 seconds." + f"Optimization interval '{cls.config.optimization.genetic.interval_sec}' seconds " + "not supported - forced to 3600 seconds." ) - cls.config.optimization.interval = 3600 + cls.config.optimization.genetic.interval_sec = 3600 # Check genetic algorithm definitions if cls.config.optimization.genetic.individuals is None: logger.info("Genetic individuals unknown - defaulting to 300.") @@ -276,8 +277,8 @@ class GeneticOptimizationParameters( start_solution = last_solution.start_solution # Add forecast and device data - interval = to_duration(cls.config.optimization.interval) - power_to_energy_per_interval_factor = cls.config.optimization.interval / 3600 + interval = to_duration(cls.config.optimization.genetic.interval_sec) + power_to_energy_per_interval_factor = cls.config.optimization.genetic.interval_sec / 3600 parameter_start_datetime = ems.start_datetime.set(hour=0, second=0, microsecond=0) parameter_end_datetime = parameter_start_datetime.add(hours=cls.config.prediction.hours) max_retries = 10 diff --git a/src/akkudoktoreos/optimization/genetic/geneticsettings.py b/src/akkudoktoreos/optimization/genetic/geneticsettings.py new file mode 100644 index 0000000..039fe65 --- /dev/null +++ b/src/akkudoktoreos/optimization/genetic/geneticsettings.py @@ -0,0 +1,82 @@ +"""Settings for the GENETIC optimization algorithm. + +Kept in an extra module to avoid cyclic dependencies on package import. +""" + +from typing import Optional, Union + +from pydantic import Field, computed_field + +from akkudoktoreos.config.configabc import SettingsBaseModel + + +class GeneticCommonSettings(SettingsBaseModel): + """GENETIC Optimization Algorithm Configuration.""" + + interval_sec: int = Field( + default=3600, + ge=15 * 60, + le=60 * 60, + json_schema_extra={ + "description": "The optimization interval [sec]. Defaults to 3600 seconds (1 hour)", + "examples": [60 * 60, 15 * 60], + }, + ) + + horizon_hours: int = Field( + default=24, + ge=0, + json_schema_extra={ + "description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.", + "examples": [24], + }, + ) + + individuals: Optional[int] = Field( + default=300, + ge=10, + json_schema_extra={ + "description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.", + "examples": [300], + }, + ) + + generations: Optional[int] = Field( + default=400, + ge=10, + json_schema_extra={ + "description": "Number of generations to evolve [>= 10]. Defaults to 400.", + "examples": [400], + }, + ) + + seed: Optional[int] = Field( + default=None, + ge=0, + json_schema_extra={ + "description": "Random seed for reproducibility. None = random.", + "examples": [None, 42], + }, + ) + + # --- Penalties (existing) ------------------------------------------------- + + penalties: dict[str, Union[float, int, str]] = Field( + default_factory=lambda: { + "ev_soc_miss": 10, + "ac_charge_break_even": 1.0, + }, + json_schema_extra={ + "description": "Penalty parameters used in fitness evaluation.", + "examples": [{"ev_soc_miss": 10}], + }, + ) + + @computed_field # type: ignore[prop-decorator] + @property + def horizon(self) -> int: + """Number of optimization steps.""" + if self.interval_sec is None or self.interval_sec == 0 or self.horizon_hours is None: + return 0 + num_steps = int(float(self.horizon_hours * 3600) / self.interval_sec) + return num_steps diff --git a/src/akkudoktoreos/optimization/genetic/geneticsolution.py b/src/akkudoktoreos/optimization/genetic/geneticsolution.py index a3a7d85..38b0f52 100644 --- a/src/akkudoktoreos/optimization/genetic/geneticsolution.py +++ b/src/akkudoktoreos/optimization/genetic/geneticsolution.py @@ -740,7 +740,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel): generated_at=to_datetime(), comment="Optimization solution derived from GeneticSolution.", valid_from=start_datetime, - valid_until=start_datetime.add(hours=self.config.optimization.horizon_hours), + valid_until=start_datetime.add(hours=self.config.optimization.genetic.horizon_hours), total_losses_energy_wh=self.result.total_losses, total_revenues_amt=self.result.total_revenue, total_costs_amt=self.result.total_costs, diff --git a/src/akkudoktoreos/optimization/genetic0/genetic0.py b/src/akkudoktoreos/optimization/genetic0/genetic0.py new file mode 100644 index 0000000..053a338 --- /dev/null +++ b/src/akkudoktoreos/optimization/genetic0/genetic0.py @@ -0,0 +1,1262 @@ +"""Genetic0 algorithm.""" + +import random +import time +from typing import Any, Optional + +import numpy as np +from deap import algorithms, base, creator, tools +from loguru import logger +from numpydantic import NDArray, Shape +from pydantic import ConfigDict, Field + +from akkudoktoreos.core.pydantic import PydanticBaseModel +from akkudoktoreos.devices.genetic0.genetic0battery import Genetic0Battery +from akkudoktoreos.devices.genetic0.genetic0homeappliance import Genetic0HomeAppliance +from akkudoktoreos.devices.genetic0.genetic0inverter import Genetic0Inverter +from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0EnergyManagementParameters, +) +from akkudoktoreos.optimization.genetic0.genetic0solution import ( + Genetic0SimulationResult, + Genetic0Solution, +) +from akkudoktoreos.optimization.optimizationabc import OptimizationBase + + +class Genetic0Simulation(PydanticBaseModel): + """Device simulation for GENETIC optimization algorithm.""" + + # Disable validation on assignment to speed up simulation runs. + model_config = ConfigDict( + validate_assignment=False, + ) + + start_hour: int = Field( + default=0, + ge=0, + le=23, + json_schema_extra={"description": "Starting hour on day for optimizations."}, + ) + + optimization_hours: Optional[int] = Field( + default=24, + ge=0, + json_schema_extra={"description": "Number of hours into the future for optimizations."}, + ) + + prediction_hours: Optional[int] = Field( + default=48, + ge=0, + json_schema_extra={"description": "Number of hours into the future for predictions"}, + ) + + load_energy_array: Optional[NDArray[Shape["*"], float]] = Field( + default=None, + json_schema_extra={ + "description": "An array of floats representing the total load (consumption) in watts for different time intervals." + }, + ) + pv_prediction_wh: Optional[NDArray[Shape["*"], float]] = Field( + default=None, + json_schema_extra={ + "description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals." + }, + ) + elect_price_hourly: Optional[NDArray[Shape["*"], float]] = Field( + default=None, + json_schema_extra={ + "description": "An array of floats representing the electricity price per watt-hour for different time intervals." + }, + ) + elect_revenue_per_hour_arr: Optional[NDArray[Shape["*"], float]] = Field( + default=None, + json_schema_extra={ + "description": "An array of floats representing the feed-in compensation per watt-hour." + }, + ) + + battery: Optional[Genetic0Battery] = Field( + default=None, json_schema_extra={"description": "TBD."} + ) + ev: Optional[Genetic0Battery] = Field(default=None, json_schema_extra={"description": "TBD."}) + home_appliance: Optional[Genetic0HomeAppliance] = Field( + default=None, json_schema_extra={"description": "TBD."} + ) + inverter: Optional[Genetic0Inverter] = Field( + default=None, json_schema_extra={"description": "TBD."} + ) + + ac_charge_hours: Optional[NDArray[Shape["*"], float]] = Field( + default=None, json_schema_extra={"description": "TBD"} + ) + dc_charge_hours: Optional[NDArray[Shape["*"], float]] = Field( + default=None, json_schema_extra={"description": "TBD"} + ) + bat_discharge_hours: Optional[NDArray[Shape["*"], float]] = Field( + default=None, json_schema_extra={"description": "TBD"} + ) + ev_charge_hours: Optional[NDArray[Shape["*"], float]] = Field( + default=None, json_schema_extra={"description": "TBD"} + ) + ev_discharge_hours: Optional[NDArray[Shape["*"], float]] = Field( + default=None, json_schema_extra={"description": "TBD"} + ) + home_appliance_start_hour: Optional[int] = Field( + default=None, + json_schema_extra={"description": "Home appliance start hour - None denotes no start."}, + ) + + def prepare( + self, + parameters: Genetic0EnergyManagementParameters, + optimization_hours: int, + prediction_hours: int, + ev: Optional[Genetic0Battery] = None, + home_appliance: Optional[Genetic0HomeAppliance] = None, + inverter: Optional[Genetic0Inverter] = None, + ) -> None: + """Prepare simulation runs. + + Populate internal arrays and device references used during simulation. + """ + self.optimization_hours = optimization_hours + self.prediction_hours = prediction_hours + + # Load arrays from provided EMS parameters + self.load_energy_array = np.array(parameters.total_load, float) + self.pv_prediction_wh = np.array(parameters.pv_forecast_wh, float) + self.elect_price_hourly = np.array(parameters.electricity_price_per_wh, float) + self.elect_revenue_per_hour_arr = ( + parameters.feed_in_tariff_per_wh + if isinstance(parameters.feed_in_tariff_per_wh, list) + else np.full(len(self.load_energy_array), parameters.feed_in_tariff_per_wh, float) + ) + + # Associate devices + if inverter: + self.battery = inverter.battery + else: + self.battery = None + self.ev = ev + self.home_appliance = home_appliance + self.inverter = inverter + + # Initialize per-hour action arrays for the prediction horizon + self.ac_charge_hours = np.full(self.prediction_hours, 0.0) + self.dc_charge_hours = np.full(self.prediction_hours, 0.0) + self.bat_discharge_hours = np.full(self.prediction_hours, 0.0) + self.ev_charge_hours = np.full(self.prediction_hours, 0.0) + self.ev_discharge_hours = np.full(self.prediction_hours, 0.0) + self.home_appliance_start_hour = None + + def reset(self) -> None: + if self.ev: + self.ev.reset() + if self.battery: + self.battery.reset() + self.home_appliance_start_hour = None + + def simulate(self, start_hour: int) -> dict[str, Any]: + """Simulate energy usage and costs for the given start hour. + + battery_soc_per_hour begin of the hour, initial hour state! + load_wh_per_hour integral of last hour (end state) + """ + # Remember start hour + self.start_hour = start_hour + + # Provide fast (3x..5x) local read access (vs. self.xxx) for repetitive read access + load_energy_array_fast = self.load_energy_array + ev_charge_hours_fast = self.ev_charge_hours + ev_discharge_hours_fast = self.ev_discharge_hours + ac_charge_hours_fast = self.ac_charge_hours + dc_charge_hours_fast = self.dc_charge_hours + bat_discharge_hours_fast = self.bat_discharge_hours + elect_price_hourly_fast = self.elect_price_hourly + elect_revenue_per_hour_arr_fast = self.elect_revenue_per_hour_arr + pv_prediction_wh_fast = self.pv_prediction_wh + battery_fast = self.battery + ev_fast = self.ev + home_appliance_fast = self.home_appliance + inverter_fast = self.inverter + + # Check for simulation integrity (in a way that mypy understands) + if ( + load_energy_array_fast is None + or pv_prediction_wh_fast is None + or elect_price_hourly_fast is None + or ev_charge_hours_fast is None + or ac_charge_hours_fast is None + or dc_charge_hours_fast is None + or elect_revenue_per_hour_arr_fast is None + or bat_discharge_hours_fast is None + or ev_discharge_hours_fast is None + ): + missing = [] + if load_energy_array_fast is None: + missing.append("Load Energy Array") + if pv_prediction_wh_fast is None: + missing.append("PV Prediction Wh") + if elect_price_hourly_fast is None: + missing.append("Electricity Price Hourly") + if ev_charge_hours_fast is None: + missing.append("EV Charge Hours") + if ac_charge_hours_fast is None: + missing.append("AC Charge Hours") + if dc_charge_hours_fast is None: + missing.append("DC Charge Hours") + if elect_revenue_per_hour_arr_fast is None: + missing.append("Electricity Revenue Per Hour") + if bat_discharge_hours_fast is None: + missing.append("Genetic0Battery Discharge Hours") + if ev_discharge_hours_fast is None: + missing.append("EV Discharge Hours") + msg = ", ".join(missing) + logger.error("Mandatory data missing - %s", msg) + raise ValueError(f"Mandatory data missing: {msg}") + + if not ( + len(load_energy_array_fast) + == len(pv_prediction_wh_fast) + == len(elect_price_hourly_fast) + ): + error_msg = f"Array sizes do not match: Load Curve = {len(load_energy_array_fast)}, PV Forecast = {len(pv_prediction_wh_fast)}, Electricity Price = {len(elect_price_hourly_fast)}" + logger.error(error_msg) + raise ValueError(error_msg) + + end_hour = len(load_energy_array_fast) + total_hours = end_hour - start_hour + + # Pre-allocate arrays for the results, optimized for speed + loads_energy_per_hour = np.full((total_hours), np.nan) + feedin_energy_per_hour = np.full((total_hours), np.nan) + consumption_energy_per_hour = np.full((total_hours), np.nan) + costs_per_hour = np.full((total_hours), np.nan) + revenue_per_hour = np.full((total_hours), np.nan) + losses_wh_per_hour = np.full((total_hours), np.nan) + electricity_price_per_hour = np.full((total_hours), np.nan) + + # Set initial state + if battery_fast: + # Pre-allocate arrays for the results, optimized for speed + soc_per_hour = np.full((total_hours), np.nan) + + soc_per_hour[0] = battery_fast.current_soc_percentage() + + # Determine AC charging availability from inverter parameters + if inverter_fast: + ac_to_dc_eff_fast = inverter_fast.ac_to_dc_efficiency + dc_to_ac_eff_fast = inverter_fast.dc_to_ac_efficiency + max_ac_charge_w_fast = inverter_fast.max_ac_charge_power_w + else: + ac_to_dc_eff_fast = 1.0 + dc_to_ac_eff_fast = 1.0 + max_ac_charge_w_fast = None + + ac_charging_possible = ac_to_dc_eff_fast > 0 and ( + max_ac_charge_w_fast is None or max_ac_charge_w_fast > 0 + ) + + # If AC charging is disabled via inverter, zero out AC charge hours + if not ac_charging_possible: + ac_charge_hours_fast = np.zeros_like(ac_charge_hours_fast) + + # Fill the charge array of the battery + dc_charge_hours_fast[0:start_hour] = 0 + dc_charge_hours_fast[end_hour:] = 0 + ac_charge_hours_fast[0:start_hour] = 0 + ac_charge_hours_fast[end_hour:] = 0 + battery_fast.charge_array = np.where( + ac_charge_hours_fast != 0, ac_charge_hours_fast, dc_charge_hours_fast + ) + # Fill the discharge array of the battery + bat_discharge_hours_fast[0:start_hour] = 0 + bat_discharge_hours_fast[end_hour:] = 0 + battery_fast.discharge_array = bat_discharge_hours_fast + else: + # Default return if no battery is available + soc_per_hour = np.full((total_hours), 0) + ac_to_dc_eff_fast = 1.0 + dc_to_ac_eff_fast = 1.0 + max_ac_charge_w_fast = None + ac_charging_possible = False + + if ev_fast: + # Pre-allocate arrays for the results, optimized for speed + soc_ev_per_hour = np.full((total_hours), np.nan) + + soc_ev_per_hour[0] = ev_fast.current_soc_percentage() + # Fill the charge array of the ev + ev_charge_hours_fast[0:start_hour] = 0 + ev_charge_hours_fast[end_hour:] = 0 + ev_fast.charge_array = ev_charge_hours_fast + # Fill the discharge array of the ev + ev_discharge_hours_fast[0:start_hour] = 0 + ev_discharge_hours_fast[end_hour:] = 0 + ev_fast.discharge_array = ev_discharge_hours_fast + else: + # Default return if no electric vehicle is available + soc_ev_per_hour = np.full((total_hours), 0) + + if home_appliance_fast and self.home_appliance_start_hour is not None: + home_appliance_enabled = True + # Pre-allocate arrays for the results, optimized for speed + home_appliance_wh_per_hour = np.full((total_hours), np.nan) + + self.home_appliance_start_hour = home_appliance_fast.set_starting_time( + self.home_appliance_start_hour, start_hour + ) + else: + home_appliance_enabled = False + # Default return if no home appliance is available + home_appliance_wh_per_hour = np.full((total_hours), 0) + + for hour in range(start_hour, end_hour): + hour_idx = hour - start_hour + + # Accumulate loads and PV generation + consumption = load_energy_array_fast[hour] + losses_wh_per_hour[hour_idx] = 0.0 + + # Home appliances + if home_appliance_enabled: + ha_load = home_appliance_fast.get_load_for_hour(hour) # type: ignore[union-attr] + consumption += ha_load + home_appliance_wh_per_hour[hour_idx] = ha_load + + # E-Auto handling + if ev_fast: + soc_ev_per_hour[hour_idx] = ev_fast.current_soc_percentage() # save begin state + if ev_charge_hours_fast[hour] > 0: + loaded_energy_ev, ev_charge_losses = ev_fast.charge_energy( + wh=None, hour=hour, charge_factor=ev_charge_hours_fast[hour] + ) + consumption += loaded_energy_ev + losses_wh_per_hour[hour_idx] += ev_charge_losses + + # Save battery SOC before inverter processing = true begin-of-interval state. + # Must be recorded here (before DC charge/discharge) so the displayed SOC at + # timestamp T reflects what the battery actually had at the START of interval T, + # not the post-DC result. Consistent with the EV SOC convention above. + if battery_fast: + soc_per_hour[hour_idx] = battery_fast.current_soc_percentage() + + # Process inverter logic + energy_feedin_grid_actual = energy_consumption_grid_actual = losses = ( + self_consumption + ) = 0.0 + + if inverter_fast: + energy_produced = pv_prediction_wh_fast[hour] + ( + energy_feedin_grid_actual, + energy_consumption_grid_actual, + losses, + self_consumption, + ) = inverter_fast.process_energy(energy_produced, consumption, hour) + + # AC PV Battery Charge + if battery_fast: + hour_ac_charge = ac_charge_hours_fast[hour] + if hour_ac_charge > 0.0 and ac_charging_possible: + # Cap charge factor by max_ac_charge_power_w if set + effective_charge_factor = hour_ac_charge + if max_ac_charge_w_fast is not None and battery_fast.max_charge_power_w > 0: + # DC power = max_charge_power_w * factor + # AC power = DC power / ac_to_dc_eff + # AC power must be <= max_ac_charge_power_w + max_dc_factor = ( + max_ac_charge_w_fast * ac_to_dc_eff_fast + ) / battery_fast.max_charge_power_w + effective_charge_factor = min(effective_charge_factor, max_dc_factor) + + if effective_charge_factor > 0: + battery_charged_energy_actual, battery_losses_actual = ( + battery_fast.charge_energy( + None, hour, charge_factor=effective_charge_factor + ) + ) + + # DC energy entering the battery (before battery internal efficiency) + dc_energy = battery_charged_energy_actual + battery_losses_actual + # AC energy consumed from grid (accounts for AC→DC conversion loss) + ac_energy = dc_energy / ac_to_dc_eff_fast + # Genetic0Inverter AC→DC conversion losses + inverter_charge_losses = ac_energy - dc_energy + + consumption += ac_energy + energy_consumption_grid_actual += ac_energy + losses_wh_per_hour[hour_idx] += ( + battery_losses_actual + inverter_charge_losses + ) + + # Update hourly arrays + feedin_energy_per_hour[hour_idx] = energy_feedin_grid_actual + consumption_energy_per_hour[hour_idx] = energy_consumption_grid_actual + losses_wh_per_hour[hour_idx] += losses + loads_energy_per_hour[hour_idx] = consumption + hourly_electricity_price = elect_price_hourly_fast[hour] + electricity_price_per_hour[hour_idx] = hourly_electricity_price + + # Financial calculations + costs_per_hour[hour_idx] = energy_consumption_grid_actual * hourly_electricity_price + revenue_per_hour[hour_idx] = ( + energy_feedin_grid_actual * elect_revenue_per_hour_arr_fast[hour] + ) + + total_cost = np.nansum(costs_per_hour) + total_losses = np.nansum(losses_wh_per_hour) + total_revenue = np.nansum(revenue_per_hour) + + # Prepare output dictionary + return { + "Last_Wh_pro_Stunde": loads_energy_per_hour, + "Netzeinspeisung_Wh_pro_Stunde": feedin_energy_per_hour, + "Netzbezug_Wh_pro_Stunde": consumption_energy_per_hour, + "Kosten_Euro_pro_Stunde": costs_per_hour, + "akku_soc_pro_stunde": soc_per_hour, + "Einnahmen_Euro_pro_Stunde": revenue_per_hour, + "Gesamtbilanz_Euro": total_cost - total_revenue, # Fitness score ("FitnessMin") + "EAuto_SoC_pro_Stunde": soc_ev_per_hour, + "Gesamteinnahmen_Euro": total_revenue, + "Gesamtkosten_Euro": total_cost, + "Verluste_Pro_Stunde": losses_wh_per_hour, + "Gesamt_Verluste": total_losses, + "Home_appliance_wh_per_hour": home_appliance_wh_per_hour, + "Electricity_price": electricity_price_per_hour, + } + + +class Genetic0Optimization(OptimizationBase): + """GENETIC algorithm to solve energy optimization.""" + + def __init__( + self, + verbose: bool = False, + fixed_seed: Optional[int] = None, + ): + """Initialize the optimization problem with the required parameters.""" + self.opti_param: dict[str, Any] = {} + self.fixed_ev_hours = ( + self.config.prediction.hours - self.config.optimization.genetic0.horizon_hours + ) + self.ev_possible_charge_values: list[float] = [1.0] + # Separate charge-level list for battery AC charging (independent of EV rates). + # Populated from parameters.pv_battery.charge_rates in optimize_ems. + self.bat_possible_charge_values: list[float] = [1.0] + self.verbose = verbose + self.fix_seed = fixed_seed + self.optimize_ev = True + self.optimize_dc_charge = False + self.fitness_history: dict[str, Any] = {} + + # Set a fixed seed for random operations if provided or in debug mode + if self.fix_seed is not None: + random.seed(self.fix_seed) + elif logger.level == "DEBUG": + self.fix_seed = random.randint(1, 100000000000) # noqa: S311 + random.seed(self.fix_seed) + + # Create Simulation + self.simulation = Genetic0Simulation() + + def decode_charge_discharge( + self, discharge_hours_bin: np.ndarray + ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Decode the input array into ac_charge, dc_charge, and discharge arrays.""" + discharge_hours_bin_np = np.array(discharge_hours_bin) + # Genetic0Battery AC charge uses its own charge-level list (bat_possible_charge_values). + len_bat = len(self.bat_possible_charge_values) + + # Categorization (using battery charge levels): + # Idle: 0 .. len_bat-1 + # Discharge: len_bat .. 2*len_bat - 1 + # AC Charge: 2*len_bat .. 3*len_bat - 1 (maps to bat_possible_charge_values) + # DC optional: 3*len_bat (not allowed), 3*len_bat + 1 (allowed) + + # Idle states + idle_mask = (discharge_hours_bin_np >= 0) & (discharge_hours_bin_np < len_bat) + + # Discharge states + discharge_mask = (discharge_hours_bin_np >= len_bat) & ( + discharge_hours_bin_np < 2 * len_bat + ) + + # AC states + ac_mask = (discharge_hours_bin_np >= 2 * len_bat) & (discharge_hours_bin_np < 3 * len_bat) + ac_indices = (discharge_hours_bin_np[ac_mask] - 2 * len_bat).astype(int) + + # DC states (if enabled) + if self.optimize_dc_charge: + dc_not_allowed_state = 3 * len_bat + dc_allowed_state = 3 * len_bat + 1 + dc_charge = np.where(discharge_hours_bin_np == dc_allowed_state, 1, 0) + else: + dc_charge = np.ones_like(discharge_hours_bin_np, dtype=float) + + # Generate the result arrays + discharge = np.zeros_like(discharge_hours_bin_np, dtype=int) + discharge[discharge_mask] = 1 # Set Discharge states to 1 + + ac_charge = np.zeros_like(discharge_hours_bin_np, dtype=float) + ac_charge[ac_mask] = [self.bat_possible_charge_values[i] for i in ac_indices] + + # Idle is just 0, already default. + + return ac_charge, dc_charge, discharge + + def mutate(self, individual: list[int]) -> tuple[list[int]]: + """Custom mutation function for the individual.""" + # Calculate the number of states using battery charge levels + len_bat = len(self.bat_possible_charge_values) + if self.optimize_dc_charge: + total_states = 3 * len_bat + 2 + else: + total_states = 3 * len_bat + + # 1. Mutating the charge_discharge part + charge_discharge_part = individual[: self.config.prediction.hours] + (charge_discharge_mutated,) = self.toolbox.mutate_charge_discharge(charge_discharge_part) + + # Instead of a fixed clamping to 0..8 or 0..6 dynamically: + charge_discharge_mutated = np.clip(charge_discharge_mutated, 0, total_states - 1) + individual[: self.config.prediction.hours] = charge_discharge_mutated + + # 2. Mutating the EV charge part, if active + if self.optimize_ev: + ev_charge_part = individual[ + self.config.prediction.hours : self.config.prediction.hours * 2 + ] + (ev_charge_part_mutated,) = self.toolbox.mutate_ev_charge_index(ev_charge_part) + ev_charge_part_mutated[self.config.prediction.hours - self.fixed_ev_hours :] = [ + 0 + ] * self.fixed_ev_hours + individual[self.config.prediction.hours : self.config.prediction.hours * 2] = ( + ev_charge_part_mutated + ) + + # 3. Mutating the appliance start time, if applicable + if self.opti_param["home_appliance"] > 0: + appliance_part = [individual[-1]] + (appliance_part_mutated,) = self.toolbox.mutate_hour(appliance_part) + individual[-1] = appliance_part_mutated[0] + + return (individual,) + + # Method to create an individual based on the conditions + def create_individual(self) -> list[int]: + # Start with discharge states for the individual + individual_components = [ + self.toolbox.attr_discharge_state() for _ in range(self.config.prediction.hours) + ] + + # Add EV charge index values if optimize_ev is True + if self.optimize_ev: + individual_components += [ + self.toolbox.attr_ev_charge_index() for _ in range(self.config.prediction.hours) + ] + + # Add the start time of the household appliance if it's being optimized + if self.opti_param["home_appliance"] > 0: + individual_components += [self.toolbox.attr_int()] + + return creator.Individual(individual_components) + + def merge_individual( + self, + discharge_hours_bin: np.ndarray, + ev_charge_hours_index: Optional[np.ndarray], + washingstart_int: Optional[int], + ) -> list[int]: + """Merge the individual components back into a single solution list. + + Parameters: + discharge_hours_bin (np.ndarray): Binary discharge hours. + ev_charge_hours_index (Optional[np.ndarray]): EV charge hours as integers, or None. + washingstart_int (Optional[int]): Dishwasher start time as integer, or None. + + Returns: + list[int]: The merged individual solution as a list of integers. + """ + # Start with the discharge hours + individual = discharge_hours_bin.tolist() + + # Add EV charge hours if applicable + if self.optimize_ev and ev_charge_hours_index is not None: + individual.extend(ev_charge_hours_index.tolist()) + elif self.optimize_ev: + # If optimize_ev is active but no EV data is available, append zeros + individual.extend([0] * self.config.prediction.hours) + + # Add dishwasher start time if applicable + if self.opti_param.get("home_appliance", 0) > 0 and washingstart_int is not None: + individual.append(washingstart_int) + elif self.opti_param.get("home_appliance", 0) > 0: + # If a home appliance is optimized but no start time is available + individual.append(0) + + return individual + + def split_individual( + self, individual: list[int] + ) -> tuple[np.ndarray, Optional[np.ndarray], Optional[int]]: + """Split the individual solution into its components. + + Components: + 1. Discharge hours (binary as int NumPy array), + 2. Electric vehicle charge hours (float as int NumPy array, if applicable), + 3. Dishwasher start time (integer if applicable). + """ + # Discharge hours as a NumPy array of ints + discharge_hours_bin = np.array(individual[: self.config.prediction.hours], dtype=int) + + # EV charge hours as a NumPy array of ints (if optimize_ev is True) + ev_charge_hours_index = ( + # append ev charging states to individual + np.array( + individual[self.config.prediction.hours : self.config.prediction.hours * 2], + dtype=int, + ) + if self.optimize_ev + else None + ) + + # Washing machine start time as an integer (if applicable) + washingstart_int = ( + int(individual[-1]) + if self.opti_param and self.opti_param.get("home_appliance", 0) > 0 + else None + ) + + return discharge_hours_bin, ev_charge_hours_index, washingstart_int + + def setup_deap_environment(self, opti_param: dict[str, Any], start_hour: int) -> None: + """Set up the DEAP environment with fitness and individual creation rules.""" + self.opti_param = opti_param + + # Remove existing definitions if any + for attr in ["FitnessMin", "Individual"]: + if attr in creator.__dict__: + del creator.__dict__[attr] + + creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) + creator.create("Individual", list, fitness=creator.FitnessMin) + + self.toolbox = base.Toolbox() + # Genetic0Battery state space uses bat_possible_charge_values; EV index space uses ev_possible_charge_values. + len_bat = len(self.bat_possible_charge_values) + len_ev = len(self.ev_possible_charge_values) + + # Total battery/discharge states: + # Idle: len_bat states + # Discharge: len_bat states + # AC-Charge: len_bat states (maps to bat_possible_charge_values) + # With DC: + 2 additional states + if self.optimize_dc_charge: + total_states = 3 * len_bat + 2 + else: + total_states = 3 * len_bat + + # State space: 0 .. (total_states - 1) + self.toolbox.register("attr_discharge_state", random.randint, 0, total_states - 1) + + # EV attributes (separate index space) + if self.optimize_ev: + self.toolbox.register( + "attr_ev_charge_index", + random.randint, + 0, + len_ev - 1, + ) + + # Household appliance start time + self.toolbox.register("attr_int", random.randint, start_hour, 23) + + self.toolbox.register("individual", self.create_individual) + self.toolbox.register("population", tools.initRepeat, list, self.toolbox.individual) + self.toolbox.register("mate", tools.cxTwoPoint) + + # Mutation operator for battery charge/discharge states + self.toolbox.register( + "mutate_charge_discharge", tools.mutUniformInt, low=0, up=total_states - 1, indpb=0.2 + ) + + # Mutation operator for EV states (separate index space) + self.toolbox.register( + "mutate_ev_charge_index", + tools.mutUniformInt, + low=0, + up=len_ev - 1, + indpb=0.2, + ) + + # Mutation for household appliance + self.toolbox.register("mutate_hour", tools.mutUniformInt, low=start_hour, up=23, indpb=0.2) + + # Custom mutate function remains unchanged + self.toolbox.register("mutate", self.mutate) + self.toolbox.register("select", tools.selTournament, tournsize=3) + + def evaluate_inner(self, individual: list[int]) -> dict[str, Any]: + """Simulates the energy management system (EMS) using the provided individual solution. + + This is an internal function. + """ + self.simulation.reset() + discharge_hours_bin, ev_charge_hours_index, washingstart_int = self.split_individual( + individual + ) + + if self.opti_param.get("home_appliance", 0) > 0 and washingstart_int: + # Set start hour for appliance + self.simulation.home_appliance_start_hour = washingstart_int + + ac_charge_hours, dc_charge_hours, discharge = self.decode_charge_discharge( + discharge_hours_bin + ) + + self.simulation.bat_discharge_hours = discharge + # Set DC charge hours only if DC optimization is enabled + if self.optimize_dc_charge: + self.simulation.dc_charge_hours = dc_charge_hours + else: + self.simulation.dc_charge_hours = np.full(self.config.prediction.hours, 1) + self.simulation.ac_charge_hours = ac_charge_hours + + if ev_charge_hours_index is not None: + ev_charge_hours_float = np.array( + [self.ev_possible_charge_values[i] for i in ev_charge_hours_index], + float, + ) + # discharge is set to 0 by default + self.simulation.ev_charge_hours = ev_charge_hours_float + else: + # discharge is set to 0 by default + self.simulation.ev_charge_hours = np.full(self.config.prediction.hours, 0) + + # Do the simulation and return result. + return self.simulation.simulate(self.ems.start_datetime.hour) + + def evaluate( + self, + individual: list[int], + parameters: Genetic0EnergyManagementParameters, + start_hour: int, + worst_case: bool, + ) -> tuple[float]: + """Evaluate the fitness score of a single individual in the DEAP genetic algorithm. + + This method runs a simulation based on the provided individual genome and + optimization parameters. The resulting performance is converted into a + fitness score compatible with DEAP (i.e., returned as a 1-tuple). + + Args: + individual (list[int]): + The genome representing one candidate solution. + parameters (Genetic0EnergyManagementParameters): + Optimization parameters that influence simulation behavior, + constraints, and scoring logic. + start_hour (int): + The simulation start hour (0–23 or domain-specific). + Used to initialize time-based scheduling or constraints. + worst_case (bool): + If True, evaluates the solution under worst-case assumptions + (e.g., pessimistic forecasts or boundary conditions). + If False, uses nominal assumptions. + + Returns: + tuple[float]: + A single-element tuple containing the computed fitness score. + Lower score is better: "FitnessMin". + + Raises: + ValueError: If input arguments are invalid or the individual structure + is not compatible with the simulation. + RuntimeError: If the simulation fails or cannot produce results. + + Notes: + The resulting score should match DEAP's expected format: a tuple, even + if only a single scalar fitness value is returned. + """ + try: + simulation_result = self.evaluate_inner(individual) + except Exception as e: + # Return bad fitness score ("FitnessMin") in case of an exception + return (100000.0,) + + total_balance = simulation_result["Gesamtbilanz_Euro"] * (-1.0 if worst_case else 1.0) + + # EV 100% & charge not allowed + if self.optimize_ev: + discharge_hours_bin, ev_charge_hours_index, washingstart_int = self.split_individual( + individual + ) + + ev_soc_per_hour = np.array( + simulation_result.get("EAuto_SoC_pro_Stunde", []) + ) # Beispielkey + + if ev_soc_per_hour is None or ev_charge_hours_index is None: + raise ValueError("ev_soc_per_hour or ev_charge_hours_index is None") + min_length = min(ev_soc_per_hour.size, ev_charge_hours_index.size) + ev_soc_per_hour_tail = ev_soc_per_hour[-min_length:] + ev_charge_hours_index_tail = ev_charge_hours_index[-min_length:] + + # Mask + invalid_charge_mask = (ev_soc_per_hour_tail == 100) & (ev_charge_hours_index_tail > 0) + + if np.any(invalid_charge_mask): + invalid_indices = np.where(invalid_charge_mask)[0] + if len(invalid_indices) > 1: + ev_charge_hours_index_tail[invalid_indices] = 0 + + ev_charge_hours_index[-min_length:] = ev_charge_hours_index_tail.tolist() + + adjusted_individual = self.merge_individual( + discharge_hours_bin, ev_charge_hours_index, washingstart_int + ) + + individual[:] = adjusted_individual + + # New check: Activate discharge when battery SoC is 0 + # battery_soc_per_hour = np.array( + # o.get("akku_soc_pro_stunde", []) + # ) # Example key for battery SoC + + # if battery_soc_per_hour is not None: + # if battery_soc_per_hour is None or discharge_hours_bin is None: + # raise ValueError("battery_soc_per_hour or discharge_hours_bin is None") + # min_length = min(battery_soc_per_hour.size, discharge_hours_bin.size) + # battery_soc_per_hour_tail = battery_soc_per_hour[-min_length:] + # discharge_hours_bin_tail = discharge_hours_bin[-min_length:] + # len_ac = len(self.config.optimization.ev_available_charge_rates_percent) + + # # # Find hours where battery SoC is 0 + # # zero_soc_mask = battery_soc_per_hour_tail == 0 + # # discharge_hours_bin_tail[zero_soc_mask] = ( + # # len_ac + 2 + # # ) # Activate discharge for these hours + + # # When Genetic0Battery SoC then set the Discharge randomly to 0 or 1. otherwise it's very + # # unlikely to get a state where a battery can store energy for a longer time + # # Find hours where battery SoC is 0 + # zero_soc_mask = battery_soc_per_hour_tail == 0 + # # discharge_hours_bin_tail[zero_soc_mask] = ( + # # len_ac + 2 + # # ) # Activate discharge for these hours + # set_to_len_ac_plus_2 = np.random.rand() < 0.5 # True with 50% probability + + # # Werte setzen basierend auf der zufälligen Entscheidung + # value_to_set = len_ac + 2 if set_to_len_ac_plus_2 else 0 + # discharge_hours_bin_tail[zero_soc_mask] = value_to_set + + # # Merge the updated discharge_hours_bin back into the individual + # adjusted_individual = self.merge_individual( + # discharge_hours_bin, ev_charge_hours_index, washingstart_int + # ) + # individual[:] = adjusted_individual + + # More metrics + individual.extra_data = ( # type: ignore[attr-defined] + simulation_result["Gesamtbilanz_Euro"], + simulation_result["Gesamt_Verluste"], + parameters.ev.min_soc_percentage - self.simulation.ev.current_soc_percentage() + if parameters.ev and self.simulation.ev + else 0, + ) + + # Adjust total balance with battery value and penalties for unmet SOC + if self.simulation.battery: + battery_energy_content = self.simulation.battery.current_energy_content() + # Apply DC→AC inverter efficiency to residual battery value + # (stored DC energy must pass through inverter to be usable as AC) + if self.simulation.inverter: + battery_energy_content *= self.simulation.inverter.dc_to_ac_efficiency + battery_residual_value = battery_energy_content * parameters.ems.price_per_wh_battery + total_balance += -battery_residual_value + + # --- AC charging break-even penalty --- + # Penalise AC charging decisions that cannot be economically justified given the + # round-trip losses (AC→DC charge conversion, battery internal, DC→AC discharge + # conversion) and the best available future electricity prices. + # + # Key insight: energy already stored in the battery (from PV, zero grid cost) covers + # the most expensive future hours first. AC charging from the grid only makes sense + # for the hours that remain uncovered, and only when the discharge price exceeds + # P_charge / η_round_trip. + # + # This penalty does not double-count the simulation result – it amplifies the "bad + # decision" signal so that the genetic algorithm converges faster away from + # unprofitable charging regions. + if ( + self.simulation.battery + and self.simulation.inverter + and self.simulation.ac_charge_hours is not None + and self.simulation.elect_price_hourly is not None + and self.simulation.load_energy_array is not None + ): + inv = self.simulation.inverter + bat = self.simulation.battery + + # Full round-trip efficiency: 1 Wh drawn from grid → η Wh delivered to AC load + round_trip_eff = ( + inv.ac_to_dc_efficiency + * bat.charging_efficiency + * bat.discharging_efficiency + * inv.dc_to_ac_efficiency + ) + + if round_trip_eff > 0: + ac_charge_arr = self.simulation.ac_charge_hours + prices_arr = self.simulation.elect_price_hourly + load_arr = self.simulation.load_energy_array + n = len(prices_arr) + + # Usable AC energy already in battery from prior PV charging (zero grid cost). + # This covers the most expensive future hours first, pushing AC charging demand + # to cheaper hours where the break-even hurdle may not be met. + initial_soc_wh = (bat.initial_soc_percentage / 100.0) * bat.capacity_wh + free_ac_wh = ( + max(0.0, initial_soc_wh - bat.min_soc_wh) + * bat.discharging_efficiency + * inv.dc_to_ac_efficiency + ) + + # Configurable penalty multiplier (default 1 = economic loss in currency units) + try: + ac_penalty_factor = float( + self.config.optimization.genetic0.penalties["ac_charge_break_even"] + ) + except Exception: + ac_penalty_factor = 1.0 + + for hour in range(start_hour, min(len(ac_charge_arr), n)): + ac_factor = ac_charge_arr[hour] + if ac_factor <= 0.0: + continue + + charge_price = prices_arr[hour] + if charge_price <= 0: + continue + + # Price that a future discharge hour must reach to break even + break_even_price = charge_price / round_trip_eff + + # Build list of (price, load_wh) for all future hours in the horizon + future = [ + (float(prices_arr[h]), float(load_arr[h])) for h in range(hour + 1, n) + ] + # Sort descending by price so we "use" the most expensive hours first + future.sort(key=lambda x: -x[0]) + + # Consume free PV energy against the highest-price future hours. + # The first uncovered (partially or fully) hour defines the best + # price still available for the new AC charge. + remaining_free = free_ac_wh + best_uncovered_price = 0.0 + for fp, fl in future: + if remaining_free >= fl: + # Entire expensive hour is already covered by free PV energy + remaining_free -= fl + else: + # First hour not (fully) covered: this is where new charge goes + best_uncovered_price = fp + break + + if best_uncovered_price < break_even_price: + # AC charging at this hour is economically unjustified. + # Penalty = excess cost per Wh × DC energy requested this hour. + dc_wh = bat.max_charge_power_w * ac_factor + ac_wh = dc_wh / max(inv.ac_to_dc_efficiency, 1e-9) + excess_cost_per_wh = break_even_price - best_uncovered_price + total_balance += ac_wh * excess_cost_per_wh * ac_penalty_factor + + if self.optimize_ev and parameters.ev and self.simulation.ev: + try: + penalty = self.config.optimization.genetic0.penalties["ev_soc_miss"] + except Exception: + # Use default + penalty = 10 + logger.error( + "Penalty function parameter `ev_soc_miss` not configured, using {}.", penalty + ) + ev_soc_percentage = self.simulation.ev.current_soc_percentage() + if ( + ev_soc_percentage < parameters.ev.min_soc_percentage + or ev_soc_percentage > parameters.ev.max_soc_percentage + ): + total_balance += abs(parameters.ev.min_soc_percentage - ev_soc_percentage) * penalty + + return (total_balance,) + + def optimize( + self, + start_solution: Optional[list[float]] = None, + ngen: int = 200, + ) -> tuple[Any, dict[str, list[Any]]]: + """Run the optimization process using a genetic algorithm. + + @TODO: optimize() ngen default (200) is different from optimize_ems() ngen default (400). + """ + # Set the number of inviduals in a generation + try: + individuals = self.config.optimization.genetic0.individuals + if individuals is None: + raise + except Exception: + individuals = 300 + logger.error("Individuals not configured. Using {}.", individuals) + + population = self.toolbox.population(n=individuals) + hof = tools.HallOfFame(1) + stats = tools.Statistics(lambda ind: ind.fitness.values) + stats.register("min", np.min) + stats.register("avg", np.mean) + stats.register("max", np.max) + + logger.debug("Start optimize: {}", start_solution) + + # Insert the start solution into the population if provided + if start_solution is not None: + for _ in range(10): + population.insert(0, creator.Individual(start_solution)) + + # Run the evolutionary algorithm + pop, log = algorithms.eaMuPlusLambda( + population, + self.toolbox, + mu=100, + lambda_=150, + cxpb=0.6, + mutpb=0.4, + ngen=ngen, + stats=stats, + halloffame=hof, + verbose=self.verbose, + ) + + # Store fitness history + self.fitness_history = { + "gen": log.select("gen"), # Generation numbers (X-axis) + "avg": log.select("avg"), # Average fitness for each generation (Y-axis) + "max": log.select("max"), # Maximum fitness for each generation (Y-axis) + "min": log.select("min"), # Minimum fitness for each generation (Y-axis) + } + + member: dict[str, list[float]] = {"balance": [], "losses": [], "constraints": []} + for ind in population: + if hasattr(ind, "extra_data"): + extra_value1, extra_value2, extra_value3 = ind.extra_data + member["balance"].append(extra_value1) + member["losses"].append(extra_value2) + member["constraints"].append(extra_value3) + + return hof[0], member + + def optimize_ems( + self, + parameters: Genetic0EnergyManagementParameters, + start_hour: Optional[int] = None, + worst_case: bool = False, + ngen: Optional[int] = None, + ) -> Genetic0Solution: + """Perform EMS (Energy Management System) optimization and visualize results.""" + if start_hour is None: + start_hour = self.ems.start_datetime.hour + # Start hour has to be in sync with energy management + if start_hour != self.ems.start_datetime.hour: + raise ValueError( + f"Start hour not synced. EMS {self.ems.start_datetime.hour} vs. GENETIC {start_hour}." + ) + + # Set the number of generations + generations = ngen + if generations is None: + try: + generations = self.config.optimization.genetic0.generations + except Exception: + generations = 400 + logger.error("Generations not configured. Using {}.", generations) + + self.simulation.reset() + + # Initialize PV and EV batteries + battery: Optional[Genetic0Battery] = None + if parameters.pv_battery: + battery = Genetic0Battery( + parameters.pv_battery, + prediction_hours=self.config.prediction.hours, + ) + battery.set_charge_per_hour(np.full(self.config.prediction.hours, 0)) + + ev: Optional[Genetic0Battery] = None + if parameters.ev: + ev = Genetic0Battery( + parameters.ev, + prediction_hours=self.config.prediction.hours, + ) + ev.set_charge_per_hour(np.full(self.config.prediction.hours, 1)) + self.optimize_ev = ( + parameters.ev.min_soc_percentage - parameters.ev.initial_soc_percentage >= 0 + ) + # electrical vehicle charge rates + if parameters.ev.charge_rates is not None: + self.ev_possible_charge_values = parameters.ev.charge_rates + elif ( + self.config.devices.electric_vehicles + and self.config.devices.electric_vehicles[0] + and self.config.devices.electric_vehicles[0].charge_rates is not None + ): + self.ev_possible_charge_values = self.config.devices.electric_vehicles[ + 0 + ].charge_rates + else: + warning_msg = "No charge rates provided for electric vehicle - using default." + logger.warning(warning_msg) + self.ev_possible_charge_values = [ + 0.0, + 0.1, + 0.2, + 0.3, + 0.4, + 0.5, + 0.6, + 0.7, + 0.8, + 0.9, + 1.0, + ] + else: + self.optimize_ev = False + + # Genetic0Battery AC charge rates — use the battery's configured charge_rates so the + # optimizer can select partial AC charge power (e.g. 10 %, 50 %, 100 %) instead + # of always forcing full power. Falls back to [1.0] when not configured. + if parameters.pv_battery and parameters.pv_battery.charge_rates: + self.bat_possible_charge_values = [ + r for r in parameters.pv_battery.charge_rates if r > 0.0 + ] or [1.0] + elif ( + self.config.devices.batteries + and self.config.devices.batteries[0] + and self.config.devices.batteries[0].charge_rates + ): + self.bat_possible_charge_values = [ + r for r in self.config.devices.batteries[0].charge_rates if r > 0.0 + ] or [1.0] + else: + self.bat_possible_charge_values = [1.0] + logger.debug("Genetic0Battery AC charge levels: {}", self.bat_possible_charge_values) + + # Initialize household appliance if applicable + dishwasher = ( + Genetic0HomeAppliance( + parameters=parameters.dishwasher, + optimization_hours=self.config.optimization.genetic0.horizon_hours, + prediction_hours=self.config.prediction.hours, + ) + if parameters.dishwasher is not None + else None + ) + + # Initialize the inverter and energy management system + inverter: Optional[Genetic0Inverter] = None + if parameters.inverter: + inverter = Genetic0Inverter( + parameters.inverter, + battery=battery, + ) + + # Prepare device simulation + self.simulation.prepare( + parameters=parameters.ems, + optimization_hours=self.config.optimization.genetic0.horizon_hours, + prediction_hours=self.config.prediction.hours, + inverter=inverter, # battery is part of inverter + ev=ev, + home_appliance=dishwasher, + ) + + # Setup the DEAP environment and optimization process + self.setup_deap_environment({"home_appliance": 1 if dishwasher else 0}, start_hour) + self.toolbox.register( + "evaluate", + lambda ind: self.evaluate(ind, parameters, start_hour, worst_case), + ) + + start_time = time.time() + start_solution, extra_data = self.optimize(parameters.start_solution, ngen=generations) + elapsed_time = time.time() - start_time + logger.debug(f"Time evaluate inner: {elapsed_time:.4f} sec.") + + # Perform final evaluation on the best solution + simulation_result = self.evaluate_inner(start_solution) + + # Prepare results + discharge_hours_bin, ev_charge_hours_index, washingstart_int = self.split_individual( + start_solution + ) + # home appliance may have choosen a different appliance start hour + if self.simulation.home_appliance: + washingstart_int = self.simulation.home_appliance_start_hour + + ev_charge_hours_float = ( + [self.ev_possible_charge_values[i] for i in ev_charge_hours_index] + if ev_charge_hours_index is not None + else None + ) + + # Simulation may have changed something, use simulation values + ac_charge_hours = self.simulation.ac_charge_hours + if ac_charge_hours is None: + ac_charge_hours = [] + else: + ac_charge_hours = ac_charge_hours.tolist() + dc_charge_hours = self.simulation.dc_charge_hours + if dc_charge_hours is None: + dc_charge_hours = [] + else: + dc_charge_hours = dc_charge_hours.tolist() + discharge = self.simulation.bat_discharge_hours + if discharge is None: + discharge = [] + else: + discharge = discharge.tolist() + + # Visualize the results in PDF + try: + from akkudoktoreos.utils.visualize import prepare_visualize + + visualize = { + "ac_charge": ac_charge_hours, + "dc_charge": dc_charge_hours, + "discharge_allowed": discharge, + "ev_charge_hours_float": ev_charge_hours_float, + "result": Genetic0SimulationResult(**simulation_result).model_dump(), + "ev_obj": self.simulation.ev.to_dict() if self.simulation.ev else None, + "start_solution": start_solution, + "washingstart": washingstart_int, + "extra_data": extra_data, + "fitness_history": self.fitness_history, + "fixed_seed": self.fix_seed, + } + + prepare_visualize(parameters, visualize, start_hour=start_hour) + + except Exception as ex: + error_msg = f"Visualization failed: {ex}" + logger.error(error_msg) + + return Genetic0Solution( + **{ + "ac_charge": ac_charge_hours, + "dc_charge": dc_charge_hours, + "discharge_allowed": discharge, + "ev_charge_hours_float": ev_charge_hours_float, + "result": Genetic0SimulationResult(**simulation_result), + "ev_obj": self.simulation.ev, + "start_solution": start_solution, + "washingstart": washingstart_int, + } + ) diff --git a/src/akkudoktoreos/optimization/genetic0/genetic0abc.py b/src/akkudoktoreos/optimization/genetic0/genetic0abc.py new file mode 100644 index 0000000..b1926c5 --- /dev/null +++ b/src/akkudoktoreos/optimization/genetic0/genetic0abc.py @@ -0,0 +1,11 @@ +"""Genetic0 optimization algorithm abstract and base classes.""" + +from pydantic import ConfigDict + +from akkudoktoreos.core.pydantic import PydanticBaseModel + + +class Genetic0ParametersBaseModel(PydanticBaseModel): + """Pydantic base model for parameters for the GENETIC algorithm.""" + + model_config = ConfigDict(extra="forbid") diff --git a/src/akkudoktoreos/optimization/genetic0/genetic0devices.py b/src/akkudoktoreos/optimization/genetic0/genetic0devices.py new file mode 100644 index 0000000..24d8890 --- /dev/null +++ b/src/akkudoktoreos/optimization/genetic0/genetic0devices.py @@ -0,0 +1,196 @@ +"""Genetic0 optimization algorithm device interfaces/ parameters.""" + +from typing import Optional + +from pydantic import Field + +from akkudoktoreos.config.configabc import TimeWindowSequence +from akkudoktoreos.optimization.genetic0.genetic0abc import Genetic0ParametersBaseModel + + +class Genetic0DeviceParameters(Genetic0ParametersBaseModel): + device_id: str = Field(json_schema_extra={"description": "ID of device", "examples": "device1"}) + hours: Optional[int] = Field( + default=None, + gt=0, + json_schema_extra={ + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [None], + }, + ) + + +def max_charging_power_field(description: Optional[str] = None) -> float: + if description is None: + description = "Maximum charging power in watts." + return Field(default=5000, gt=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 Genetic0BaseBatteryParameters(Genetic0DeviceParameters): + """Battery Device Simulation Configuration.""" + + device_id: str = Field( + json_schema_extra={"description": "ID of battery", "examples": ["battery1"]} + ) + capacity_wh: int = Field( + gt=0, + json_schema_extra={ + "description": "An integer representing the capacity of the battery in watt-hours.", + "examples": [8000], + }, + ) + charging_efficiency: float = Field( + default=0.88, + gt=0, + le=1, + json_schema_extra={ + "description": "A float representing the charging efficiency of the battery." + }, + ) + discharging_efficiency: float = discharging_efficiency_field(0.88) + max_charge_power_w: Optional[float] = max_charging_power_field() + initial_soc_percentage: int = initial_soc_percentage_field( + "An integer representing the state of charge of the battery at the **start** of the current hour (not the current state)." + ) + min_soc_percentage: int = Field( + default=0, + ge=0, + le=100, + json_schema_extra={ + "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", + "examples": [10], + }, + ) + max_soc_percentage: int = Field( + default=100, + ge=0, + le=100, + json_schema_extra={ + "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage." + }, + ) + charge_rates: Optional[list[float]] = Field( + default=None, + json_schema_extra={ + "description": "Charge rates as factor of maximum charging power [0.00 ... 1.00]. None denotes all charge rates are available.", + "examples": [[0.0, 0.25, 0.5, 0.75, 1.0], None], + }, + ) + + +class Genetic0SolarPanelBatteryParameters(Genetic0BaseBatteryParameters): + """PV battery device simulation configuration.""" + + max_charge_power_w: Optional[float] = max_charging_power_field() + + +class Genetic0ElectricVehicleParameters(Genetic0BaseBatteryParameters): + """Battery Electric Vehicle Device Simulation Configuration.""" + + device_id: str = Field( + json_schema_extra={"description": "ID of electric vehicle", "examples": ["ev1"]} + ) + discharging_efficiency: float = discharging_efficiency_field(1.0) + initial_soc_percentage: int = initial_soc_percentage_field( + "An integer representing the current state of charge (SOC) of the battery in percentage." + ) + + +class Genetic0HomeApplianceParameters(Genetic0DeviceParameters): + """Home Appliance Device Simulation Configuration.""" + + device_id: str = Field( + json_schema_extra={"description": "ID of home appliance", "examples": ["dishwasher"]} + ) + consumption_wh: int = Field( + gt=0, + json_schema_extra={ + "description": "An integer representing the energy consumption of a household device in watt-hours.", + "examples": [2000], + }, + ) + duration_h: int = Field( + gt=0, + json_schema_extra={ + "description": "An integer representing the usage duration of a household device in hours.", + "examples": [3], + }, + ) + time_windows: Optional[TimeWindowSequence] = Field( + default=None, + json_schema_extra={ + "description": "List of allowed time windows. Defaults to optimization general time window.", + "examples": [ + [ + {"start_time": "10:00", "duration": "3 hours"}, + ], + ], + }, + ) + + +class Genetic0InverterParameters(Genetic0DeviceParameters): + """Inverter Device Simulation Configuration.""" + + device_id: str = Field( + json_schema_extra={"description": "ID of inverter", "examples": ["inverter1"]} + ) + max_power_wh: float = Field(gt=0, json_schema_extra={"examples": [10000]}) + battery_id: Optional[str] = Field( + default=None, + json_schema_extra={"description": "ID of battery", "examples": [None, "battery1"]}, + ) + ac_to_dc_efficiency: float = Field( + default=1.0, + ge=0, + le=1, + json_schema_extra={ + "description": ( + "Efficiency of AC to DC conversion (for AC/grid charging of battery). " + "Set to 0 to disable AC charging via inverter. " + "Default 1.0 for backward compatibility (no additional inverter loss)." + ), + "examples": [0.95, 1.0, 0.0], + }, + ) + dc_to_ac_efficiency: float = Field( + default=1.0, + gt=0, + le=1, + json_schema_extra={ + "description": ( + "Efficiency of DC to AC conversion (for battery discharging to AC load/grid). " + "Default 1.0 for backward compatibility (no additional inverter loss)." + ), + "examples": [0.95, 1.0], + }, + ) + max_ac_charge_power_w: Optional[float] = Field( + default=None, + ge=0, + json_schema_extra={ + "description": ( + "Maximum AC charging power in watts. " + "None means no additional limit (battery's own max_charge_power_w applies). " + "Set to 0 to disable AC charging." + ), + "examples": [None, 0, 5000], + }, + ) diff --git a/src/akkudoktoreos/optimization/genetic0/genetic0loadinterpolator.py b/src/akkudoktoreos/optimization/genetic0/genetic0loadinterpolator.py new file mode 100644 index 0000000..980822e --- /dev/null +++ b/src/akkudoktoreos/optimization/genetic0/genetic0loadinterpolator.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +import pickle +from pathlib import Path + +import numpy as np +from scipy.interpolate import RegularGridInterpolator + +from akkudoktoreos.core.cache import cache_energy_management +from akkudoktoreos.core.coreabc import SingletonMixin + + +class SelfConsumptionProbabilityInterpolator: + def __init__(self, filepath: str | Path): + self.filepath = filepath + # Load the RegularGridInterpolator + with open(self.filepath, "rb") as file: + self.interpolator: RegularGridInterpolator = pickle.load(file) # noqa: S301 + + def _generate_points( + self, load_1h_power: float, pv_power: float + ) -> tuple[np.ndarray, np.ndarray]: + """Generate the grid points for interpolation.""" + partial_loads = np.arange(0, pv_power + 50, 50) + points = np.array([np.full_like(partial_loads, load_1h_power), partial_loads]).T + return points, partial_loads + + @cache_energy_management + def calculate_self_consumption(self, load_1h_power: float, pv_power: float) -> float: + """Calculate the PV self-consumption rate using RegularGridInterpolator. + + The results are cached until the start of the next energy management run/ optimization. + + Args: + - last_1h_power: 1h power levels (W). + - pv_power: Current PV power output (W). + + Returns: + - Self-consumption rate as a float. + """ + points, partial_loads = self._generate_points(load_1h_power, pv_power) + probabilities = self.interpolator(points) + return probabilities.sum() + + # def calculate_self_consumption(self, load_1h_power: float, pv_power: float) -> float: + # """Calculate the PV self-consumption rate using RegularGridInterpolator. + + # Args: + # - last_1h_power: 1h power levels (W). + # - pv_power: Current PV power output (W). + + # Returns: + # - Self-consumption rate as a float. + # """ + # # Generate the range of partial loads (0 to last_1h_power) + # partial_loads = np.arange(0, pv_power + 50, 50) + + # # Get probabilities for all partial loads + # points = np.array([np.full_like(partial_loads, load_1h_power), partial_loads]).T + # if self.interpolator == None: + # return -1.0 + # probabilities = self.interpolator(points) + # self_consumption_rate = probabilities.sum() + + # # probabilities = probabilities / (np.sum(probabilities)) # / (pv_power / 3450)) + # # # for i, w in enumerate(partial_loads): + # # # print(w, ": ", probabilities[i]) + # # print(probabilities.sum()) + + # # # Ensure probabilities are within [0, 1] + # # probabilities = np.clip(probabilities, 0, 1) + + # # # Mask: Only include probabilities where the load is <= PV power + # # mask = partial_loads <= pv_power + + # # # Calculate the cumulative probability for covered loads + # # self_consumption_rate = np.sum(probabilities[mask]) / np.sum(probabilities) + # # print(self_consumption_rate) + # # sys.exit() + + # return self_consumption_rate + + +class Genetic0LoadInterpolator(SelfConsumptionProbabilityInterpolator, SingletonMixin): + def __init__(self) -> None: + if hasattr(self, "_initialized"): + return + filename = ( + Path(__file__).parent.parent.parent.resolve() + / "data" + / "genetic0_load_interpolator.pkl" + ) + super().__init__(filename) + + +# Initialize the Energy Management System, it is a singleton. +genetic0_load_interpolator = Genetic0LoadInterpolator() + + +def get_genetic0_load_interpolator() -> Genetic0LoadInterpolator: + return genetic0_load_interpolator diff --git a/src/akkudoktoreos/optimization/genetic0/genetic0params.py b/src/akkudoktoreos/optimization/genetic0/genetic0params.py new file mode 100644 index 0000000..a11d6fa --- /dev/null +++ b/src/akkudoktoreos/optimization/genetic0/genetic0params.py @@ -0,0 +1,702 @@ +"""GENETIC0 algorithm paramters. + +This module defines the Pydantic-based configuration and input parameter models +used in the energy optimization routines, including photovoltaic forecasts, +electricity pricing, and system component parameters. + +It also provides a method to assemble these parameters from predictions, +forecasts, and fallback defaults, preparing them for optimization runs. +""" + +from typing import 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, + get_ems, +) +from akkudoktoreos.optimization.genetic0.genetic0abc import Genetic0ParametersBaseModel +from akkudoktoreos.optimization.genetic0.genetic0devices import ( + Genetic0ElectricVehicleParameters, + Genetic0HomeApplianceParameters, + Genetic0InverterParameters, + Genetic0SolarPanelBatteryParameters, +) +from akkudoktoreos.utils.datetimeutil import to_duration + +# Do not import directly from akkudoktoreos.core.coreabc +# EnergyManagementSystemMixin - Creates circular dependency with ems.py +# StartMixin - Creates circular dependency with ems.py + + +class Genetic0EnergyManagementParameters(Genetic0ParametersBaseModel): + """Encapsulates energy-related forecasts and costs used in GENETIC optimization.""" + + model_config = ConfigDict(populate_by_name=True, extra="ignore") + + pv_forecast_wh: list[float] = Field( + validation_alias=AliasChoices("pv_forecast_wh", "pv_prognose_wh"), + json_schema_extra={ + "description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals." + }, + ) + electricity_price_per_wh: list[float] = Field( + validation_alias=AliasChoices("electricity_price_per_wh", "strompreis_euro_pro_wh"), + json_schema_extra={ + "description": "An array of floats representing the electricity price per watt-hour for different time intervals." + }, + ) + feed_in_tariff_per_wh: Union[list[float], float] = Field( + validation_alias=AliasChoices("feed_in_tariff_per_wh", "einspeiseverguetung_euro_pro_wh"), + json_schema_extra={ + "description": "A float or array of floats representing the feed-in compensation per watt-hour." + }, + ) + price_per_wh_battery: float = Field( + validation_alias=AliasChoices("price_per_wh_battery", "preis_euro_pro_wh_akku"), + json_schema_extra={ + "description": "A float representing the cost of battery energy per watt-hour." + }, + ) + total_load: list[float] = Field( + validation_alias=AliasChoices("total_load", "gesamtlast"), + json_schema_extra={ + "description": "An array of floats representing the total load (consumption) in watts for different time intervals." + }, + ) + + # Computed fields for backward compatibility (deprecated German names) + @computed_field(json_schema_extra={"deprecated": True}) + def pv_prognose_wh(self) -> list[float]: + """Deprecated: Use pv_forecast_wh instead.""" + return self.pv_forecast_wh + + @computed_field(json_schema_extra={"deprecated": True}) + def strompreis_euro_pro_wh(self) -> list[float]: + """Deprecated: Use electricity_price_per_wh instead.""" + return self.electricity_price_per_wh + + @computed_field(json_schema_extra={"deprecated": True}) + def einspeiseverguetung_euro_pro_wh(self) -> Union[list[float], float]: + """Deprecated: Use feed_in_tariff_per_wh instead.""" + return self.feed_in_tariff_per_wh + + @computed_field(json_schema_extra={"deprecated": True}) + def preis_euro_pro_wh_akku(self) -> float: + """Deprecated: Use price_per_wh_battery instead.""" + return self.price_per_wh_battery + + @computed_field(json_schema_extra={"deprecated": True}) + def gesamtlast(self) -> list[float]: + """Deprecated: Use total_load instead.""" + return self.total_load + + @model_validator(mode="after") + def validate_list_length(self) -> Self: + """Validate that all input lists are of the same length. + + Raises: + ValueError: If input list lengths differ. + """ + pv_forecast_length = len(self.pv_forecast_wh) + if ( + pv_forecast_length != len(self.electricity_price_per_wh) + or pv_forecast_length != len(self.total_load) + or ( + isinstance(self.feed_in_tariff_per_wh, list) + and pv_forecast_length != len(self.feed_in_tariff_per_wh) + ) + ): + raise ValueError("Input lists have different lengths") + return self + + +class Genetic0OptimizationParameters( + ConfigMixin, + MeasurementMixin, + PredictionMixin, + # EnergyManagementSystemMixin, # Creates circular dependency with ems.py + # StartMixin, # Creates circular dependency with ems.py + Genetic0ParametersBaseModel, +): + """Main parameter class for running the genetic energy optimization. + + Collects all model and configuration parameters necessary to run the + optimization process, such as forecasts, pricing, battery and appliance models. + """ + + model_config = ConfigDict(populate_by_name=True, extra="ignore") + + ems: Genetic0EnergyManagementParameters + pv_battery: Optional[Genetic0SolarPanelBatteryParameters] = Field( + validation_alias=AliasChoices("pv_battery", "pv_akku"), + json_schema_extra={"description": "PV battery parameters."}, + ) + inverter: Optional[Genetic0InverterParameters] + ev: Optional[Genetic0ElectricVehicleParameters] = Field( + validation_alias=AliasChoices("ev", "eauto"), + json_schema_extra={"description": "Electric vehicle parameters."}, + ) + dishwasher: Optional[Genetic0HomeApplianceParameters] = None + temperature_forecast: Optional[list[Optional[float]]] = Field( + default=None, + json_schema_extra={ + "description": "An array of floats representing the temperature forecast in degrees Celsius for different time intervals." + }, + ) + start_solution: Optional[list[float]] = Field( + default=None, + json_schema_extra={ + "description": "Can be `null` or contain a previous solution (if available)." + }, + ) + + # Computed fields for backward compatibility (deprecated German names) + @computed_field(json_schema_extra={"deprecated": True}) + def pv_akku(self) -> Optional[Genetic0SolarPanelBatteryParameters]: + """Deprecated: Use pv_battery instead.""" + return self.pv_battery + + @computed_field(json_schema_extra={"deprecated": True}) + def eauto(self) -> Optional[Genetic0ElectricVehicleParameters]: + """Deprecated: Use ev instead.""" + return self.ev + + @model_validator(mode="after") + def validate_list_length(self) -> Self: + """Ensure that temperature forecast list matches the PV forecast length. + + Raises: + ValueError: If list lengths mismatch. + """ + arr_length = len(self.ems.pv_forecast_wh) + if self.temperature_forecast is not None and arr_length != len(self.temperature_forecast): + raise ValueError("Input lists have different lengths") + return self + + @field_validator("start_solution") + def validate_start_solution( + cls, start_solution: Optional[list[float]] + ) -> Optional[list[float]]: + """Validate that the starting solution has at least two elements. + + Args: + start_solution (list[float]): Optional list of solution values. + + Returns: + list[float]: Validated list. + + Raises: + ValueError: If the solution is too short. + """ + if start_solution is not None and len(start_solution) < 2: + raise ValueError("Requires at least two values.") + return start_solution + + @classmethod + async def prepare(cls) -> "Optional[Genetic0OptimizationParameters]": + """Prepare optimization parameters from config, forecast and measurement data. + + Fills in values needed for optimization from available configuration, predictions and + measurements. If some data is missing, default or demo values are used. + + Parameters start by definition of the genetic algorithm at hour 0 of the actual date + (not at start datetime of energy management run) + + Returns: + Genetic0OptimizationParameters: The fully prepared optimization parameters. + + Raises: + ValueError: If required configuration values like start time are missing. + """ + ems = get_ems() + + # The optimization paramters + oparams: "Optional[Genetic0OptimizationParameters]" = None + + # Check for run definitions + if ems.start_datetime is None: + error_msg = "Start datetime unknown." + logger.error(error_msg) + raise ValueError(error_msg) + # Check for general predictions conditions + if cls.config.general.latitude is None: + default_latitude = 52.52 + logger.info(f"Latitude unknown - defaulting to {default_latitude}.") + cls.config.general.latitude = default_latitude + if cls.config.general.longitude is None: + default_longitude = 13.405 + logger.info(f"Longitude unknown - defaulting to {default_longitude}.") + cls.config.general.longitude = default_longitude + if cls.config.prediction.hours is None: + logger.info("Prediction hours unknown - defaulting to 48 hours.") + cls.config.prediction.hours = 48 + if cls.config.prediction.historic_hours is None: + logger.info("Prediction historic hours unknown - defaulting to 24 hours.") + cls.config.prediction.historic_hours = 24 + # Check optimization definitions. interval_sec is fixed to 1 hour. + if cls.config.optimization.genetic0.horizon_hours is None: + logger.info("Optimization horizon unknown - defaulting to 24 hours.") + cls.config.optimization.genetic0.horizon_hours = 24 + # Check genetic algorithm definitions + if cls.config.optimization.genetic0.individuals is None: + logger.info("Genetic individuals unknown - defaulting to 300.") + cls.config.optimization.genetic0.individuals = 300 + if cls.config.optimization.genetic0.generations is None: + logger.info("Genetic generations unknown - defaulting to 400.") + cls.config.optimization.genetic0.generations = 400 + if "ev_soc_miss" not in cls.config.optimization.genetic0.penalties: + logger.info("Genetic penalties unknown - defaulting to ev_soc_miss = 10.") + cls.config.optimization.genetic0.penalties["ev_soc_miss"] = 10 + + # Get start solution from last run + start_solution = None + last_solution = ems.genetic0_solution() + if last_solution and last_solution.start_solution: + start_solution = last_solution.start_solution + + # Add forecast and device data + interval = to_duration(cls.config.optimization.genetic0.interval_sec) + power_to_energy_per_interval_factor = cls.config.optimization.genetic0.interval_sec / 3600 + parameter_start_datetime = ems.start_datetime.set(hour=0, second=0, microsecond=0) + parameter_end_datetime = parameter_start_datetime.add(hours=cls.config.prediction.hours) + max_retries = 10 + + for attempt in range(1, max_retries + 1): + # Collect all the data for optimisation, but do not exceed max retries + if attempt > max_retries: + error_msg = f"Maximum retries {max_retries} for parameter collection exceeded. Parameter preparation attempt {attempt}." + logger.error(error_msg) + raise ValueError(error_msg) + + # Assure predictions are uptodate + await cls.prediction.update_data() + + try: + array = await cls.prediction.key_to_array( + key="pvforecast_ac_power", + start_datetime=parameter_start_datetime, + end_datetime=parameter_end_datetime, + interval=interval, + fill_method="linear", + ) + pvforecast_ac_power = (array * power_to_energy_per_interval_factor).tolist() + except Exception as e: + logger.info( + "No PV forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}", + attempt, + e, + ) + cls.config.merge_settings_from_dict( + { + "pvforecast": { + "provider": "PVForecastAkkudoktor", + "max_planes": 4, + "planes": [ + { + "peakpower": 5.0, + "surface_azimuth": 170, + "surface_tilt": 7, + "userhorizon": [20, 27, 22, 20], + "inverter_paco": 10000, + }, + { + "peakpower": 4.8, + "surface_azimuth": 90, + "surface_tilt": 7, + "userhorizon": [30, 30, 30, 50], + "inverter_paco": 10000, + }, + { + "peakpower": 1.4, + "surface_azimuth": 140, + "surface_tilt": 60, + "userhorizon": [60, 30, 0, 30], + "inverter_paco": 2000, + }, + { + "peakpower": 1.6, + "surface_azimuth": 185, + "surface_tilt": 45, + "userhorizon": [45, 25, 30, 60], + "inverter_paco": 1400, + }, + ], + }, + } + ) + # Retry + continue + try: + array = await cls.prediction.key_to_array( + key="elecprice_marketprice_wh", + start_datetime=parameter_start_datetime, + end_datetime=parameter_end_datetime, + interval=interval, + fill_method="ffill", + ) + elecprice_marketprice_wh = array.tolist() + except Exception as e: + logger.info( + "No Electricity Marketprice forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}", + attempt, + e, + ) + cls.config.elecprice.provider = "ElecPriceAkkudoktor" + # Retry + continue + try: + array = await cls.prediction.key_to_array( + key="loadforecast_power_w", + start_datetime=parameter_start_datetime, + end_datetime=parameter_end_datetime, + interval=interval, + fill_method="ffill", + ) + loadforecast_power_w = array.tolist() + except Exception as e: + logger.info( + "No Load forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}", + attempt, + e, + ) + cls.config.merge_settings_from_dict( + { + "load": { + "provider": "LoadAkkudoktor", + "loadakkudoktor": { + "loadakkudoktor_year_energy_kwh": "3000", + }, + }, + } + ) + # Retry + continue + try: + array = await cls.prediction.key_to_array( + key="feed_in_tariff_wh", + start_datetime=parameter_start_datetime, + end_datetime=parameter_end_datetime, + interval=interval, + fill_method="ffill", + ) + feed_in_tariff_wh = array.tolist() + except Exception as e: + logger.info( + "No feed in tariff forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}", + attempt, + e, + ) + cls.config.merge_settings_from_dict( + { + "feedintariff": { + "provider": "FeedInTariffFixed", + "feedintarifffixed": { + "feed_in_tariff_kwh": 0.078, + }, + }, + } + ) + # Retry + continue + try: + array = await cls.prediction.key_to_array( + key="weather_temp_air", + start_datetime=parameter_start_datetime, + end_datetime=parameter_end_datetime, + interval=interval, + fill_method="ffill", + ) + weather_temp_air = array.tolist() + except Exception as e: + logger.info( + "No weather forecast data available - defaulting to demo data. Parameter preparation attempt {}: {}", + attempt, + e, + ) + cls.config.weather.provider = "BrightSky" + # Retry + continue + + # Add device data + + # Batteries + # --------- + if cls.config.devices.max_batteries is None: + logger.info("Number of battery devices not configured - defaulting to 1.") + cls.config.devices.max_batteries = 1 + if cls.config.devices.max_batteries == 0: + battery_params = None + battery_lcos_kwh = 0 + else: + if cls.config.devices.batteries is None: + logger.info("No battery device data available - defaulting to demo data.") + cls.config.devices.batteries = [{"device_id": "battery1", "capacity_wh": 8000}] + try: + battery_config = cls.config.devices.batteries[0] + battery_params = Genetic0SolarPanelBatteryParameters( + device_id=battery_config.device_id, + capacity_wh=battery_config.capacity_wh, + charging_efficiency=battery_config.charging_efficiency, + discharging_efficiency=battery_config.discharging_efficiency, + max_charge_power_w=battery_config.max_charge_power_w, + min_soc_percentage=battery_config.min_soc_percentage, + max_soc_percentage=battery_config.max_soc_percentage, + charge_rates=battery_config.charge_rates, + ) + except Exception as e: + logger.info( + "No battery device data available - defaulting to demo data. Parameter preparation attempt {}: {}", + attempt, + e, + ) + cls.config.devices.batteries = [{"device_id": "battery1", "capacity_wh": 8000}] + # Retry + continue + # Levelized cost of ownership + if battery_config.levelized_cost_of_storage_kwh is None: + logger.info( + "No battery device LCOS data available - defaulting to 0 [amount/kWh]. Parameter preparation attempt {}.", + attempt, + ) + battery_config.levelized_cost_of_storage_kwh = 0 + battery_lcos_kwh = battery_config.levelized_cost_of_storage_kwh + # Initial SOC + try: + initial_soc_factor = await cls.measurement.key_to_value( + key=battery_config.measurement_key_soc_factor, + target_datetime=ems.start_datetime, + time_window=to_duration(to_duration("48 hours")), + ) + if initial_soc_factor > 1.0 or initial_soc_factor < 0.0: + logger.error( + f"Invalid battery initial SoC factor {initial_soc_factor} - defaulting to 0.0." + ) + initial_soc_factor = 0.0 + # genetic parameter is 0..100 as int + initial_soc_percentage = int(initial_soc_factor * 100) + except Exception: + initial_soc_percentage = None + if initial_soc_percentage is None: + logger.info( + f"No battery device SoC data (measurement key = '{battery_config.measurement_key_soc_factor}') available - defaulting to 0." + ) + initial_soc_percentage = 0 + battery_params.initial_soc_percentage = initial_soc_percentage + + # Electric Vehicles + # ----------------- + if cls.config.devices.max_electric_vehicles is None: + logger.info("Number of electric_vehicle devices not configured - defaulting to 1.") + cls.config.devices.max_electric_vehicles = 1 + if cls.config.devices.max_electric_vehicles == 0: + electric_vehicle_params = None + else: + if cls.config.devices.electric_vehicles is None: + logger.info( + "No electric vehicle device data available - defaulting to demo data." + ) + cls.config.devices.max_electric_vehicles = 1 + cls.config.devices.electric_vehicles = [ + { + "device_id": "ev11", + "capacity_wh": 50000, + "charge_rates": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], + "min_soc_percentage": 70, + } + ] + try: + electric_vehicle_config = cls.config.devices.electric_vehicles[0] + electric_vehicle_params = Genetic0ElectricVehicleParameters( + device_id=electric_vehicle_config.device_id, + capacity_wh=electric_vehicle_config.capacity_wh, + charging_efficiency=electric_vehicle_config.charging_efficiency, + discharging_efficiency=electric_vehicle_config.discharging_efficiency, + charge_rates=electric_vehicle_config.charge_rates, + max_charge_power_w=electric_vehicle_config.max_charge_power_w, + min_soc_percentage=electric_vehicle_config.min_soc_percentage, + max_soc_percentage=electric_vehicle_config.max_soc_percentage, + ) + except Exception as e: + logger.info( + "No electric_vehicle device data available - defaulting to demo data. Parameter preparation attempt {}: {}", + attempt, + e, + ) + cls.config.devices.max_electric_vehicles = 1 + cls.config.devices.electric_vehicles = [ + { + "device_id": "ev12", + "capacity_wh": 50000, + "charge_rates": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], + "min_soc_percentage": 70, + } + ] + # Retry + continue + # Initial SOC + try: + initial_soc_factor = await cls.measurement.key_to_value( + key=electric_vehicle_config.measurement_key_soc_factor, + target_datetime=ems.start_datetime, + time_window=to_duration(to_duration("48 hours")), + ) + if initial_soc_factor > 1.0 or initial_soc_factor < 0.0: + logger.error( + f"Invalid electric vehicle initial SoC factor {initial_soc_factor} - defaulting to 0.0." + ) + initial_soc_factor = 0.0 + # genetic parameter is 0..100 as int + initial_soc_percentage = int(initial_soc_factor * 100) + except Exception: + initial_soc_percentage = None + if initial_soc_percentage is None: + logger.info( + f"No electric vehicle device SoC data (measurement key = '{electric_vehicle_config.measurement_key_soc_factor}') available - defaulting to 0." + ) + initial_soc_percentage = 0 + electric_vehicle_params.initial_soc_percentage = initial_soc_percentage + + # Inverters + # --------- + if cls.config.devices.max_inverters is None: + logger.info("Number of inverter devices not configured - defaulting to 1.") + cls.config.devices.max_inverters = 1 + if cls.config.devices.max_inverters == 0: + inverter_params = None + else: + if cls.config.devices.inverters is None: + logger.info("No inverter device data available - defaulting to demo data.") + cls.config.devices.inverters = [ + { + "device_id": "inverter1", + "max_power_w": 10000, + "battery_id": battery_config.device_id, + } + ] + try: + inverter_config = cls.config.devices.inverters[0] + inverter_params = Genetic0InverterParameters( + device_id=inverter_config.device_id, + max_power_wh=inverter_config.max_power_w, + battery_id=inverter_config.battery_id, + ac_to_dc_efficiency=inverter_config.ac_to_dc_efficiency, + dc_to_ac_efficiency=inverter_config.dc_to_ac_efficiency, + max_ac_charge_power_w=inverter_config.max_ac_charge_power_w, + ) + except Exception as e: + logger.info( + "No inverter device data available - defaulting to demo data. Parameter preparation attempt {}: {}", + attempt, + e, + ) + cls.config.devices.inverters = [ + { + "device_id": "inverter1", + "max_power_w": 10000, + "battery_id": battery_config.device_id, + } + ] + # Retry + continue + + # Home Appliances + # --------------- + if cls.config.devices.max_home_appliances is None: + logger.info("Number of home appliance devices not configured - defaulting to 1.") + cls.config.devices.max_home_appliances = 1 + if cls.config.devices.max_home_appliances == 0: + home_appliance_params = None + else: + home_appliance_params = None + if cls.config.devices.home_appliances is None: + logger.info( + "No home appliance device data available - defaulting to demo data." + ) + cls.config.devices.home_appliances = [ + { + "device_id": "dishwasher1", + "consumption_wh": 2000, + "duration_h": 3.0, + "time_windows": { + "windows": [ + { + "start_time": "08:00", + "duration": "5 hours", + }, + { + "start_time": "15:00", + "duration": "3 hours", + }, + ], + }, + } + ] + try: + home_appliance_config = cls.config.devices.home_appliances[0] + home_appliance_params = Genetic0HomeApplianceParameters( + device_id=home_appliance_config.device_id, + consumption_wh=home_appliance_config.consumption_wh, + duration_h=home_appliance_config.duration_h, + time_windows=home_appliance_config.time_windows, + ) + except Exception as e: + logger.info( + "No home appliance device data available - defaulting to demo data. Parameter preparation attempt {}: {}", + attempt, + e, + ) + cls.config.devices.home_appliances = [ + { + "device_id": "dishwasher1", + "consumption_wh": 2000, + "duration_h": 3.0, + "time_windows": None, + } + ] + # Retry + continue + + # We got all parameter data + try: + oparams = Genetic0OptimizationParameters( + ems=Genetic0EnergyManagementParameters( + pv_forecast_wh=pvforecast_ac_power, + electricity_price_per_wh=elecprice_marketprice_wh, + feed_in_tariff_per_wh=feed_in_tariff_wh, + total_load=loadforecast_power_w, + price_per_wh_battery=battery_lcos_kwh / 1000, + ), + temperature_forecast=weather_temp_air, + pv_battery=battery_params, + ev=electric_vehicle_params, + inverter=inverter_params, + dishwasher=home_appliance_params, + start_solution=start_solution, + ) + except Exception as e: + logger.info( + "Can not prepare optimization parameters - will retry. Parameter preparation attempt {}: {}", + attempt, + e, + ) + oparams = None + # Retry + continue + + # Parameters prepared + break + + return oparams diff --git a/src/akkudoktoreos/optimization/genetic0/genetic0settings.py b/src/akkudoktoreos/optimization/genetic0/genetic0settings.py new file mode 100644 index 0000000..cb5898e --- /dev/null +++ b/src/akkudoktoreos/optimization/genetic0/genetic0settings.py @@ -0,0 +1,78 @@ +"""Settings for the GENETIC0 optimization algorithm. + +Kept in an extra module to avoid cyclic dependencies on package import. +""" + +from typing import Optional, Union + +from pydantic import Field, computed_field + +from akkudoktoreos.config.configabc import SettingsBaseModel + + +class Genetic0CommonSettings(SettingsBaseModel): + """GENETIC0 Optimization Algorithm Configuration.""" + + horizon_hours: int = Field( + default=24, + ge=0, + json_schema_extra={ + "description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.", + "examples": [24], + }, + ) + + individuals: Optional[int] = Field( + default=300, + ge=10, + json_schema_extra={ + "description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.", + "examples": [300], + }, + ) + + generations: Optional[int] = Field( + default=400, + ge=10, + json_schema_extra={ + "description": "Number of generations to evolve [>= 10]. Defaults to 400.", + "examples": [400], + }, + ) + + seed: Optional[int] = Field( + default=None, + ge=0, + json_schema_extra={ + "description": "Random seed for reproducibility. None = random.", + "examples": [None, 42], + }, + ) + + # --- Penalties (existing) ------------------------------------------------- + + penalties: dict[str, Union[float, int, str]] = Field( + default_factory=lambda: { + "ev_soc_miss": 10, + "ac_charge_break_even": 1.0, + }, + json_schema_extra={ + "description": "Penalty parameters used in fitness evaluation.", + "examples": [{"ev_soc_miss": 10}], + }, + ) + + @computed_field # type: ignore[prop-decorator] + @property + def interval_sec(self) -> int: + """The optimization interval [sec]. Fixed to 1 hour (3600 seconds).""" + return 3600 + + @computed_field # type: ignore[prop-decorator] + @property + def horizon(self) -> int: + """Number of optimization steps.""" + if self.horizon_hours is None: + return 0 + num_steps = int(float(self.horizon_hours * 3600) / self.interval_sec) + return num_steps diff --git a/src/akkudoktoreos/optimization/genetic0/genetic0solution.py b/src/akkudoktoreos/optimization/genetic0/genetic0solution.py new file mode 100644 index 0000000..d1ce43a --- /dev/null +++ b/src/akkudoktoreos/optimization/genetic0/genetic0solution.py @@ -0,0 +1,893 @@ +"""Genetic0 algorithm optimisation solution.""" + +from typing import Any, Optional + +import numpy as np +import pandas as pd +from loguru import logger +from pydantic import AliasChoices, ConfigDict, Field, computed_field, field_validator + +from akkudoktoreos.core.coreabc import ( + ConfigMixin, + get_ems, + get_prediction, +) +from akkudoktoreos.core.emplan import ( + DDBCInstruction, + EnergyManagementPlan, + FRBCInstruction, +) +from akkudoktoreos.core.pydantic import PydanticDateTimeDataFrame +from akkudoktoreos.devices.devicesabc import ( + ApplianceOperationMode, + BatteryOperationMode, +) +from akkudoktoreos.devices.genetic0.genetic0battery import Genetic0Battery +from akkudoktoreos.optimization.genetic0.genetic0devices import ( + Genetic0ParametersBaseModel, +) +from akkudoktoreos.optimization.optimization import OptimizationSolution +from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration +from akkudoktoreos.utils.utils import NumpyEncoder + + +class DeviceOptimizeResult(Genetic0ParametersBaseModel): + device_id: str = Field( + json_schema_extra={"description": "ID of device", "examples": ["device1"]} + ) + hours: int = Field( + gt=0, + json_schema_extra={"description": "Number of hours in the simulation.", "examples": [24]}, + ) + + +class Genetic0ElectricVehicleResult(DeviceOptimizeResult): + """Result class containing information related to the electric vehicle's charging and discharging behavior.""" + + device_id: str = Field( + json_schema_extra={"description": "ID of electric vehicle", "examples": ["ev1"]} + ) + charge_array: list[float] = Field( + json_schema_extra={ + "description": "Hourly charging status (0 for no charging, 1 for charging)." + } + ) + discharge_array: list[int] = Field( + json_schema_extra={ + "description": "Hourly discharging status (0 for no discharging, 1 for discharging)." + } + ) + discharging_efficiency: float = Field( + json_schema_extra={"description": "The discharge efficiency as a float.."} + ) + capacity_wh: int = Field( + json_schema_extra={"description": "Capacity of the EV’s battery in watt-hours."} + ) + charging_efficiency: float = Field( + json_schema_extra={"description": "Charging efficiency as a float.."} + ) + max_charge_power_w: int = Field( + json_schema_extra={"description": "Maximum charging power in watts."} + ) + soc_wh: float = Field( + json_schema_extra={ + "description": "State of charge of the battery in watt-hours at the start of the simulation." + } + ) + initial_soc_percentage: int = Field( + json_schema_extra={ + "description": "State of charge at the start of the simulation in percentage." + } + ) + + @field_validator("discharge_array", "charge_array", mode="before") + def convert_numpy(cls, field: Any) -> Any: + return NumpyEncoder.convert_numpy(field)[0] + + +class Genetic0SimulationResult(Genetic0ParametersBaseModel): + """This object contains the results of the simulation and provides insights into various parameters over the entire forecast period.""" + + model_config = ConfigDict(populate_by_name=True, extra="ignore") + + load_wh_per_hour: list[float] = Field( + validation_alias=AliasChoices("load_wh_per_hour", "Last_Wh_pro_Stunde"), + json_schema_extra={"description": "The load in watt-hours per hour."}, + ) + ev_soc_per_hour: list[float] = Field( + validation_alias=AliasChoices("ev_soc_per_hour", "EAuto_SoC_pro_Stunde"), + json_schema_extra={"description": "The state of charge of the EV for each hour."}, + ) + revenue_per_hour: list[float] = Field( + validation_alias=AliasChoices("revenue_per_hour", "Einnahmen_Euro_pro_Stunde"), + json_schema_extra={ + "description": "The revenue from grid feed-in or other sources per hour." + }, + ) + total_losses: float = Field( + validation_alias=AliasChoices("total_losses", "Gesamt_Verluste"), + json_schema_extra={"description": "The total losses in watt-hours over the entire period."}, + ) + total_balance: float = Field( + validation_alias=AliasChoices("total_balance", "Gesamtbilanz_Euro"), + json_schema_extra={"description": "The total balance of revenues minus costs."}, + ) + total_revenue: float = Field( + validation_alias=AliasChoices("total_revenue", "Gesamteinnahmen_Euro"), + json_schema_extra={"description": "The total revenues."}, + ) + total_costs: float = Field( + validation_alias=AliasChoices("total_costs", "Gesamtkosten_Euro"), + json_schema_extra={"description": "The total costs."}, + ) + home_appliance_wh_per_hour: list[Optional[float]] = Field( + validation_alias=AliasChoices("home_appliance_wh_per_hour", "Home_appliance_wh_per_hour"), + json_schema_extra={ + "description": "The energy consumption of a household appliance in watt-hours per hour." + }, + ) + costs_per_hour: list[float] = Field( + validation_alias=AliasChoices("costs_per_hour", "Kosten_Euro_pro_Stunde"), + json_schema_extra={"description": "The costs per hour."}, + ) + grid_consumption_wh_per_hour: list[float] = Field( + validation_alias=AliasChoices("grid_consumption_wh_per_hour", "Netzbezug_Wh_pro_Stunde"), + json_schema_extra={"description": "The grid energy drawn in watt-hours per hour."}, + ) + grid_feed_in_wh_per_hour: list[float] = Field( + validation_alias=AliasChoices("grid_feed_in_wh_per_hour", "Netzeinspeisung_Wh_pro_Stunde"), + json_schema_extra={"description": "The energy fed into the grid in watt-hours per hour."}, + ) + losses_per_hour: list[float] = Field( + validation_alias=AliasChoices("losses_per_hour", "Verluste_Pro_Stunde"), + json_schema_extra={"description": "The losses in watt-hours per hour."}, + ) + battery_soc_per_hour: list[float] = Field( + validation_alias=AliasChoices("battery_soc_per_hour", "akku_soc_pro_stunde"), + json_schema_extra={ + "description": "The state of charge of the battery (not the EV) in percentage per hour." + }, + ) + electricity_price: list[float] = Field( + validation_alias=AliasChoices("electricity_price", "Electricity_price"), + json_schema_extra={"description": "Used Electricity Price, including predictions"}, + ) + + # Computed fields for backward compatibility (deprecated German names) + @computed_field(json_schema_extra={"deprecated": True}) + def Last_Wh_pro_Stunde(self) -> list[float]: + """Deprecated: Use load_wh_per_hour instead.""" + return self.load_wh_per_hour + + @computed_field(json_schema_extra={"deprecated": True}) + def EAuto_SoC_pro_Stunde(self) -> list[float]: + """Deprecated: Use ev_soc_per_hour instead.""" + return self.ev_soc_per_hour + + @computed_field(json_schema_extra={"deprecated": True}) + def Einnahmen_Euro_pro_Stunde(self) -> list[float]: + """Deprecated: Use revenue_per_hour instead.""" + return self.revenue_per_hour + + @computed_field(json_schema_extra={"deprecated": True}) + def Gesamt_Verluste(self) -> float: + """Deprecated: Use total_losses instead.""" + return self.total_losses + + @computed_field(json_schema_extra={"deprecated": True}) + def Gesamtbilanz_Euro(self) -> float: + """Deprecated: Use total_balance instead.""" + return self.total_balance + + @computed_field(json_schema_extra={"deprecated": True}) + def Gesamteinnahmen_Euro(self) -> float: + """Deprecated: Use total_revenue instead.""" + return self.total_revenue + + @computed_field(json_schema_extra={"deprecated": True}) + def Gesamtkosten_Euro(self) -> float: + """Deprecated: Use total_costs instead.""" + return self.total_costs + + @computed_field(json_schema_extra={"deprecated": True}) + def Home_appliance_wh_per_hour(self) -> list[Optional[float]]: + """Deprecated: Use home_appliance_wh_per_hour instead.""" + return self.home_appliance_wh_per_hour + + @computed_field(json_schema_extra={"deprecated": True}) + def Kosten_Euro_pro_Stunde(self) -> list[float]: + """Deprecated: Use costs_per_hour instead.""" + return self.costs_per_hour + + @computed_field(json_schema_extra={"deprecated": True}) + def Netzbezug_Wh_pro_Stunde(self) -> list[float]: + """Deprecated: Use grid_consumption_wh_per_hour instead.""" + return self.grid_consumption_wh_per_hour + + @computed_field(json_schema_extra={"deprecated": True}) + def Netzeinspeisung_Wh_pro_Stunde(self) -> list[float]: + """Deprecated: Use grid_feed_in_wh_per_hour instead.""" + return self.grid_feed_in_wh_per_hour + + @computed_field(json_schema_extra={"deprecated": True}) + def Verluste_Pro_Stunde(self) -> list[float]: + """Deprecated: Use losses_per_hour instead.""" + return self.losses_per_hour + + @computed_field(json_schema_extra={"deprecated": True}) + def akku_soc_pro_stunde(self) -> list[float]: + """Deprecated: Use battery_soc_per_hour instead.""" + return self.battery_soc_per_hour + + @computed_field(json_schema_extra={"deprecated": True}) + def Electricity_price(self) -> list[float]: + """Deprecated: Use electricity_price instead.""" + return self.electricity_price + + @field_validator( + "load_wh_per_hour", + "grid_feed_in_wh_per_hour", + "battery_soc_per_hour", + "grid_consumption_wh_per_hour", + "costs_per_hour", + "revenue_per_hour", + "ev_soc_per_hour", + "losses_per_hour", + "home_appliance_wh_per_hour", + "electricity_price", + mode="before", + ) + def convert_numpy(cls, field: Any) -> Any: + return NumpyEncoder.convert_numpy(field)[0] + + +class Genetic0Solution(ConfigMixin, Genetic0ParametersBaseModel): + """**Note**: The first value of "load_wh_per_hour", "grid_feed_in_wh_per_hour", and "grid_consumption_wh_per_hour", will be set to null in the JSON output and represented as NaN or None in the corresponding classes' data returns. This approach is adopted to ensure that the current hour's processing remains unchanged.""" + + model_config = ConfigDict(populate_by_name=True, extra="ignore") + + ac_charge: list[float] = Field( + json_schema_extra={ + "description": "Array with AC charging values as relative power (0.0-1.0), other values set to 0." + } + ) + dc_charge: list[float] = Field( + json_schema_extra={ + "description": "Array with DC charging values as relative power (0-1), other values set to 0." + } + ) + discharge_allowed: list[int] = Field( + json_schema_extra={ + "description": "Array with discharge values (1 for discharge, 0 otherwise)." + } + ) + ev_charge_hours_float: Optional[list[float]] = Field( + validation_alias=AliasChoices("ev_charge_hours_float", "eautocharge_hours_float"), + json_schema_extra={ + "description": "Array with EV charging values as relative power (0.0-1.0), or `null` if no EV is optimized." + }, + ) + result: Genetic0SimulationResult + ev_obj: Optional[Genetic0ElectricVehicleResult] = Field( + validation_alias=AliasChoices("ev_obj", "eauto_obj"), + json_schema_extra={"description": "Electric vehicle state after optimization."}, + ) + start_solution: Optional[list[float]] = Field( + default=None, + json_schema_extra={ + "description": "An array of binary values (0 or 1) representing a possible starting solution for the simulation." + }, + ) + washingstart: Optional[int] = Field( + default=None, + json_schema_extra={ + "description": "Can be `null` or contain an object representing the start of washing (if applicable)." + }, + ) + + # Computed fields for backward compatibility (deprecated German names) + @computed_field(json_schema_extra={"deprecated": True}) + def eautocharge_hours_float(self) -> Optional[list[float]]: + """Deprecated: Use ev_charge_hours_float instead.""" + return self.ev_charge_hours_float + + @computed_field(json_schema_extra={"deprecated": True}) + def eauto_obj(self) -> Optional[Genetic0ElectricVehicleResult]: + """Deprecated: Use ev_obj instead.""" + return self.ev_obj + + @field_validator( + "ac_charge", + "dc_charge", + "discharge_allowed", + mode="before", + ) + def convert_numpy(cls, field: Any) -> Any: + return NumpyEncoder.convert_numpy(field)[0] + + @field_validator( + "ev_obj", + mode="before", + ) + def convert_eauto(cls, field: Any) -> Any: + if isinstance(field, Genetic0Battery): + return Genetic0ElectricVehicleResult(**field.to_dict()) + return field + + def _battery_device_id(self) -> str: + """Get battery device id.""" + try: + return self.config.devices.batteries[0].device_id + except Exception: + return "battery1" + + def _ev_device_id(self) -> str: + """Get electric vehicle device id.""" + try: + return self.config.devices.electric_vehicles[0].device_id + except Exception: + return "ev1" + + def _homeappliance_device_id(self) -> str: + """Get home appliance device id.""" + try: + return self.config.devices.home_appliances[0].device_id + except Exception: + return "homeappliance1" + + def _battery_operation_from_solution( + self, + ac_charge: float, + dc_charge: float, + discharge_allowed: bool, + ) -> tuple[BatteryOperationMode, float]: + """Maps low-level solution to a representative operation mode and factor. + + Args: + ac_charge (float): Allowed AC-side charging power (relative units). + dc_charge (float): Allowed DC-side charging power (relative units). + discharge_allowed (bool): Whether discharging is permitted. + + Returns: + tuple[BatteryOperationMode, float]: A tuple containing + - `BatteryOperationMode`: the representative high-level operation mode. + - `float`: the operation factor corresponding to the active signal. + + Notes: + - The mapping prioritizes AC charge > DC charge > discharge. + - Multiple strategies can produce the same low-level signals; this function + returns a representative mode based on a defined priority order. + """ + # (0,0,0) → Nothing allowed + if ac_charge <= 0.0 and dc_charge <= 0.0 and not discharge_allowed: + return BatteryOperationMode.IDLE, 1.0 + + # (0,0,1) → Discharge only + if ac_charge <= 0.0 and dc_charge <= 0.0 and discharge_allowed: + return BatteryOperationMode.PEAK_SHAVING, 1.0 + + # (ac>0,0,0) → AC charge only + if ac_charge > 0.0 and dc_charge <= 0.0 and not discharge_allowed: + return BatteryOperationMode.GRID_SUPPORT_IMPORT, ac_charge + + # (0,dc>0,0) → DC charge only + if ac_charge <= 0.0 and dc_charge > 0.0 and not discharge_allowed: + return BatteryOperationMode.NON_EXPORT, dc_charge + + # (ac>0,dc>0,0) → Both charge paths, no discharge + if ac_charge > 0.0 and dc_charge > 0.0 and not discharge_allowed: + return BatteryOperationMode.FORCED_CHARGE, ac_charge + + # (ac>0,0,1) → AC charge + discharge - does not make sense + if ac_charge > 0.0 and dc_charge <= 0.0 and discharge_allowed: + raise ValueError( + f"Illegal state: ac_charge: {ac_charge} and discharge_allowed: {discharge_allowed}" + ) + + # (0,dc>0,1) → DC charge + discharge + if ac_charge <= 0.0 and dc_charge > 0.0 and discharge_allowed: + return BatteryOperationMode.SELF_CONSUMPTION, dc_charge + + # (ac>0,dc>0,1) → Fully flexible - does not make sense + if ac_charge > 0.0 and dc_charge > 0.0 and discharge_allowed: + raise ValueError( + f"Illegal state: ac_charge: {ac_charge} and discharge_allowed: {discharge_allowed}" + ) + + # Fallback → safe idle + return BatteryOperationMode.IDLE, 1.0 + + def _soc_clamped_operation_factors( + self, + ac_charge: float, + dc_charge: float, + discharge_allowed: bool, + soc_pct: float, + ) -> tuple[float, float, bool]: + """Clamp raw genetic gene values by the battery's actual SOC at that hour. + + The raw gene values represent the optimizer's *intent* and are stored + verbatim in the ``genetic_*`` solution columns. This method derives + the *effective* values that can physically be executed given the + battery's state of charge, used for the ``battery1_*_op_*`` columns + and for ``energy_management_plan`` instructions. + + Clamping rules: + - AC charge factor: scaled down proportionally when the battery + headroom (max_soc − current_soc) is smaller than what the + commanded factor would store in one hour. Set to 0 when full. + - DC charge factor (PV): zeroed when battery is at or above max SOC + (the inverter curtails automatically, but this makes intent clear). + - Discharge: blocked when SOC is at or below min SOC. + """ + bat_list = self.config.devices.batteries + if not bat_list: + return ac_charge, dc_charge, discharge_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 = self.config.devices.inverters + 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(bat.max_charge_power_w) + ) + max_dc_per_h_wh = effective_ac * max_ac_cp_w * ac_to_dc_eff * ch_eff + if max_dc_per_h_wh > headroom_wh: + effective_ac = effective_ac * (headroom_wh / max_dc_per_h_wh) + + # --- DC charge (PV): zero when battery is full --- + effective_dc = dc_charge + if effective_dc > 0.0 and headroom_wh <= 0.0: + effective_dc = 0.0 + + # --- Discharge: block at min SOC --- + effective_dis = discharge_allowed and (soc_pct > min_soc) + + return effective_ac, effective_dc, effective_dis + + async def optimization_solution(self) -> OptimizationSolution: + """Provide the genetic solution as a general optimization solution. + + The battery modes are controlled by the grid control triggers: + - ac_charge: charge from grid + - discharge_allowed: discharge to grid + + The following battery modes are supported: + - SELF_CONSUMPTION: ac_charge == 0 and discharge_allowed == 0 + - GRID_SUPPORT_EXPORT: ac_charge == 0 and discharge_allowed == 1 + - GRID_SUPPORT_IMPORT: ac_charge > 0 and discharge_allowed == 0 or 1 + """ + start_datetime = get_ems().start_datetime + start_day_hour = start_datetime.in_timezone(self.config.general.timezone).hour + interval_hours = 1 + power_to_energy_per_interval_factor = 1.0 + + # --- Create index based on list length and interval --- + # Ensure we only use the minimum of results and commands if differing + periods = min(len(self.result.costs_per_hour), len(self.ac_charge) - start_day_hour) + time_index = pd.date_range( + start=start_datetime, + periods=periods, + freq=f"{interval_hours}h", + ) + n_points = len(time_index) + end_datetime = start_datetime.add(hours=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" + # - __op_mode: Operation mode of the device (1.0 when active)." + # - __op_factor: Operation mode factor of the device." + # - _soc_factor: State of charge of a battery/ electric vehicle device as factor of total capacity." + # - _energy_wh: Energy consumption (positive) of a device in wh." + + solution = pd.DataFrame( + { + "date_time": time_index, + # result starts at start_day_hour + "load_energy_wh": self.result.load_wh_per_hour[:n_points], + "grid_feedin_energy_wh": self.result.grid_feed_in_wh_per_hour[:n_points], + "grid_consumption_energy_wh": self.result.grid_consumption_wh_per_hour[:n_points], + "costs_amt": self.result.costs_per_hour[:n_points], + "revenue_amt": self.result.revenue_per_hour[:n_points], + "losses_energy_wh": self.result.losses_per_hour[:n_points], + }, + index=time_index, + ) + + # Add battery data + battery_device_id = self._battery_device_id() + solution[f"{battery_device_id}_soc_factor"] = [ + v / 100 + for v in self.result.battery_soc_per_hour[:n_points] # result starts at start_day_hour + ] + operation: dict[str, list[float]] = { + "genetic_ac_charge_factor": [], + "genetic_dc_charge_factor": [], + "genetic_discharge_allowed_factor": [], + } + # ac_charge, dc_charge, discharge_allowed start at hour 0 of start day + for hour_idx, rate in enumerate(self.ac_charge): + if hour_idx < start_day_hour: + continue + if hour_idx >= start_day_hour + n_points: + break + ac_charge_hour = self.ac_charge[hour_idx] + dc_charge_hour = self.dc_charge[hour_idx] + discharge_allowed_hour = bool(self.discharge_allowed[hour_idx]) + + # Raw genetic gene values — optimizer intent, stored verbatim + operation["genetic_ac_charge_factor"].append(ac_charge_hour) + operation["genetic_dc_charge_factor"].append(dc_charge_hour) + operation["genetic_discharge_allowed_factor"].append(float(discharge_allowed_hour)) + + # SOC-clamped effective values — what can physically be executed at + # this hour given the expected battery state of charge. + result_idx = hour_idx - start_day_hour + soc_h_pct = ( + self.result.battery_soc_per_hour[result_idx] + if result_idx < len(self.result.battery_soc_per_hour) + else 0.0 + ) + eff_ac, eff_dc, eff_dis = self._soc_clamped_operation_factors( + ac_charge_hour, dc_charge_hour, discharge_allowed_hour, soc_h_pct + ) + operation_mode, operation_mode_factor = self._battery_operation_from_solution( + eff_ac, eff_dc, eff_dis + ) + for mode in BatteryOperationMode: + mode_key = f"{battery_device_id}_{mode.lower()}_op_mode" + factor_key = f"{battery_device_id}_{mode.lower()}_op_factor" + if mode_key not in operation.keys(): + operation[mode_key] = [] + operation[factor_key] = [] + if mode == operation_mode: + operation[mode_key].append(1.0) + operation[factor_key].append(operation_mode_factor) + else: + operation[mode_key].append(0.0) + operation[factor_key].append(0.0) + for key in operation.keys(): + if len(operation[key]) != n_points: + error_msg = f"instruction {key} has invalid length {len(operation[key])} - expected {n_points}" + logger.error(error_msg) + raise ValueError(error_msg) + solution[key] = operation[key] + + # Add EV battery solution + # ev_charge_hours_float start at hour 0 of start day + # result.ev_soc_per_hour start at start_datetime.hour + if self.ev_obj: + ev_device_id = self._ev_device_id() + if self.ev_charge_hours_float is None: + # Electric vehicle is full enough. No load times. + solution[f"{ev_device_id}_soc_factor"] = [ + self.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 self.result.ev_soc_per_hour[:n_points] + ] + operation = { + "genetic_ev_charge_factor": [], + } + for hour_idx, rate in enumerate(self.ev_charge_hours_float): + if hour_idx < start_day_hour: + continue + if hour_idx >= start_day_hour + n_points: + break + operation["genetic_ev_charge_factor"].append(rate) + operation_mode, operation_mode_factor = self._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 + if self.config.devices.max_home_appliances and self.config.devices.max_home_appliances > 0: + # Use config and not self.washingstart as washingstart may be None (no start) + # even if configured to be started. + homeappliance_device_id = self._homeappliance_device_id() + # result starts at start_day_hour + solution[f"{homeappliance_device_id}_energy_wh"] = ( + self.result.home_appliance_wh_per_hour[:n_points] + ) + operation = { + f"{homeappliance_device_id}_run_op_mode": [], + f"{homeappliance_device_id}_run_op_factor": [], + f"{homeappliance_device_id}_off_op_mode": [], + f"{homeappliance_device_id}_off_op_factor": [], + } + for hour_idx, energy in enumerate(solution[f"{homeappliance_device_id}_energy_wh"]): + if energy > 0.0: + operation[f"{homeappliance_device_id}_run_op_mode"].append(1.0) + operation[f"{homeappliance_device_id}_run_op_factor"].append(1.0) + operation[f"{homeappliance_device_id}_off_op_mode"].append(0.0) + operation[f"{homeappliance_device_id}_off_op_factor"].append(0.0) + else: + operation[f"{homeappliance_device_id}_run_op_mode"].append(0.0) + operation[f"{homeappliance_device_id}_run_op_factor"].append(0.0) + operation[f"{homeappliance_device_id}_off_op_mode"].append(1.0) + operation[f"{homeappliance_device_id}_off_op_factor"].append(1.0) + for key in operation.keys(): + if len(operation[key]) != n_points: + error_msg = f"instruction {key} has invalid length {len(operation[key])} - expected {n_points}" + logger.error(error_msg) + raise ValueError(error_msg) + solution[key] = operation[key] + + # Fill prediction into dataframe with correct column names + # - pvforecast_ac_energy_wh_energy_wh: PV energy prediction (positive) in wh + # - elec_price_amt_kwh: Electricity price prediction in money per kwh + # - weather_temp_air_celcius: Temperature in °C" + # - loadforecast_energy_wh: Load energy prediction in wh + # - loadakkudoktor_std_energy_wh: Load energy standard deviation prediction in wh + # - loadakkudoktor_mean_energy_wh: Load mean energy prediction in wh + prediction = pd.DataFrame( + { + "date_time": time_index, + }, + index=time_index, + ) + pred = get_prediction() + + for pred_key, pred_fill_method, pred_solution_key, pred_solution_factor in [ + ( + "pvforecast_ac_power", + "linear", + "pvforecast_ac_energy_wh", + power_to_energy_per_interval_factor, + ), + ( + "pvforecast_dc_power", + "linear", + "pvforecast_dc_energy_wh", + power_to_energy_per_interval_factor, + ), + ( + "elecprice_marketprice_wh", + "ffill", + "elec_price_amt_kwh", + 1000.0, + ), + ( + "feed_in_tariff_wh", + "ffill", + "feed_in_tariff_amt_kwh", + 1000.0, + ), + ( + "weather_temp_air", + "linear", + "weather_air_temp_celcius", + 1.0, + ), + ( + "loadforecast_power_w", + "linear", + "loadforecast_energy_wh", + power_to_energy_per_interval_factor, + ), + ( + "loadakkudoktor_std_power_w", + "linear", + "loadakkudoktor_std_energy_wh", + power_to_energy_per_interval_factor, + ), + ( + "loadakkudoktor_mean_power_w", + "linear", + "loadakkudoktor_mean_energy_wh", + power_to_energy_per_interval_factor, + ), + ]: + if pred_key in pred.record_keys: + array = await pred.key_to_array( + key=pred_key, + start_datetime=start_datetime, + end_datetime=end_datetime, + interval=to_duration(f"{interval_hours} hours"), + fill_method=pred_fill_method, + ) + # 'key_to_array()' creates None values array if no data records are available. + if array is not None and array.size > 0 and not np.any(pd.isna(array)): + prediction[pred_solution_key] = (array * pred_solution_factor).tolist() + + optimization_solution = OptimizationSolution( + id=f"optimization-genetic@{to_datetime(as_string=True)}", + generated_at=to_datetime(), + comment="Optimization solution derived from GeneticSolution.", + valid_from=start_datetime, + valid_until=start_datetime.add(hours=self.config.optimization.genetic0.horizon_hours), + total_losses_energy_wh=self.result.total_losses, + total_revenues_amt=self.result.total_revenue, + total_costs_amt=self.result.total_costs, + fitness_score={ + self.result.total_costs, + }, + prediction=PydanticDateTimeDataFrame.from_dataframe(prediction), + solution=PydanticDateTimeDataFrame.from_dataframe(solution), + ) + + return optimization_solution + + def energy_management_plan(self) -> EnergyManagementPlan: + """Provide the genetic solution as an energy management plan.""" + start_datetime = get_ems().start_datetime + start_day_hour = start_datetime.in_timezone(self.config.general.timezone).hour + plan = EnergyManagementPlan( + id=f"plan-genetic@{to_datetime(as_string=True)}", + generated_at=to_datetime(), + instructions=[], + comment="Energy management plan derived from GeneticSolution.", + ) + + # Add battery instructions (fill rate based control) + last_operation_mode: Optional[str] = None + last_operation_mode_factor: Optional[float] = None + resource_id = self._battery_device_id() + # ac_charge, dc_charge, discharge_allowed start at hour 0 of start day + logger.debug("BAT: {} - {}", resource_id, self.ac_charge[start_day_hour:]) + for hour_idx, rate in enumerate(self.ac_charge): + if hour_idx < start_day_hour: + continue + # Derive SOC-clamped effective factors so that FRBCInstruction + # operation_mode_factor reflects what can physically be executed, + # while the raw genetic gene values are preserved in the solution + # dataframe (genetic_*_factor columns). + result_idx = hour_idx - start_day_hour + soc_h_pct = ( + self.result.battery_soc_per_hour[result_idx] + if result_idx < len(self.result.battery_soc_per_hour) + else 0.0 + ) + eff_ac, eff_dc, eff_dis = self._soc_clamped_operation_factors( + self.ac_charge[hour_idx], + self.dc_charge[hour_idx], + bool(self.discharge_allowed[hour_idx]), + soc_h_pct, + ) + operation_mode, operation_mode_factor = self._battery_operation_from_solution( + eff_ac, eff_dc, eff_dis + ) + if ( + operation_mode == last_operation_mode + and operation_mode_factor == last_operation_mode_factor + ): + # Skip, we already added the instruction + continue + last_operation_mode = operation_mode + last_operation_mode_factor = operation_mode_factor + execution_time = start_datetime.add(hours=hour_idx - start_day_hour) + plan.add_instruction( + FRBCInstruction( + resource_id=resource_id, + execution_time=execution_time, + actuator_id=resource_id, + operation_mode_id=operation_mode, + operation_mode_factor=operation_mode_factor, + ) + ) + + # Add EV battery instructions (fill rate based control) + # ev_charge_hours_float start at hour 0 of start day + if self.ev_obj: + resource_id = self._ev_device_id() + if self.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, self.ev_charge_hours_float[start_day_hour:] + ) + for hour_idx, rate in enumerate(self.ev_charge_hours_float): + if hour_idx < start_day_hour: + continue + operation_mode, operation_mode_factor = self._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(hours=hour_idx - start_day_hour) + plan.add_instruction( + FRBCInstruction( + resource_id=resource_id, + execution_time=execution_time, + actuator_id=resource_id, + operation_mode_id=operation_mode, + operation_mode_factor=operation_mode_factor, + ) + ) + + # Add home appliance instructions (demand driven based control) + if self.config.devices.max_home_appliances and self.config.devices.max_home_appliances > 0: + # Use config and not self.washingstart as washingstart may be None (no start) + # even if configured to be started. + resource_id = self._homeappliance_device_id() + last_energy: Optional[float] = None + for hours, energy in enumerate(self.result.home_appliance_wh_per_hour): + # hours starts at start_datetime with 0 + if energy is None: + raise ValueError( + f"Unexpected value {energy} in {self.result.home_appliance_wh_per_hour}" + ) + if last_energy is None or energy != last_energy: + if energy > 0.0: + operation_mode = ApplianceOperationMode.RUN # type: ignore[assignment] + else: + operation_mode = ApplianceOperationMode.OFF # type: ignore[assignment] + operation_mode_factor = 1.0 + execution_time = start_datetime.add(hours=hours) + plan.add_instruction( + DDBCInstruction( + resource_id=resource_id, + execution_time=execution_time, + actuator_id=resource_id, + operation_mode_id=operation_mode, + operation_mode_factor=operation_mode_factor, + ) + ) + last_energy = energy + + return plan diff --git a/src/akkudoktoreos/optimization/optimization.py b/src/akkudoktoreos/optimization/optimization.py index 3b66a6d..c0cebcb 100644 --- a/src/akkudoktoreos/optimization/optimization.py +++ b/src/akkudoktoreos/optimization/optimization.py @@ -1,4 +1,4 @@ -from typing import Optional, Union +from typing import Optional from pydantic import Field, computed_field @@ -8,92 +8,54 @@ from akkudoktoreos.core.pydantic import ( PydanticBaseModel, PydanticDateTimeDataFrame, ) +from akkudoktoreos.optimization.genetic0.genetic0settings import Genetic0CommonSettings +from akkudoktoreos.optimization.genetic.geneticsettings import GeneticCommonSettings from akkudoktoreos.utils.datetimeutil import DateTime -class GeneticCommonSettings(SettingsBaseModel): - """General Genetic Optimization Algorithm Configuration.""" - - individuals: Optional[int] = Field( - default=300, - ge=10, - json_schema_extra={ - "description": "Number of individuals (solutions) in the population [>= 10]. Defaults to 300.", - "examples": [300], - }, - ) - - generations: Optional[int] = Field( - default=400, - ge=10, - json_schema_extra={ - "description": "Number of generations to evolve [>= 10]. Defaults to 400.", - "examples": [400], - }, - ) - - seed: Optional[int] = Field( - default=None, - ge=0, - json_schema_extra={ - "description": "Random seed for reproducibility. None = random.", - "examples": [None, 42], - }, - ) - - # --- Penalties (existing) ------------------------------------------------- - - penalties: dict[str, Union[float, int, str]] = Field( - default_factory=lambda: { - "ev_soc_miss": 10, - "ac_charge_break_even": 1.0, - }, - json_schema_extra={ - "description": "Penalty parameters used in fitness evaluation.", - "examples": [{"ev_soc_miss": 10}], - }, - ) +def optimization_algorithms() -> list[str]: + """Valid optimization algorithms.""" + # Return static built-in optimization algorithms. + return [ + "GENETIC", + "GENETIC0", + ] class OptimizationCommonSettings(SettingsBaseModel): """General Optimization Configuration.""" - horizon_hours: int = Field( - default=24, - ge=0, - json_schema_extra={ - "description": "The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours.", - "examples": [24], - }, - ) - - interval: int = Field( - default=3600, - ge=15 * 60, - le=60 * 60, - json_schema_extra={ - "description": "The optimization interval [sec]. Defaults to 3600 seconds (1 hour)", - "examples": [60 * 60, 15 * 60], - }, - ) - algorithm: str = Field( default="GENETIC", json_schema_extra={ "description": "The optimization algorithm. Defaults to GENETIC", - "examples": ["GENETIC"], + "examples": ["GENETIC", "GENETIC0"], }, ) genetic: GeneticCommonSettings = Field( default_factory=GeneticCommonSettings, json_schema_extra={ - "description": "Genetic optimization algorithm configuration.", + "description": "GENETIC optimization algorithm configuration.", + "examples": [{"individuals": 400, "seed": None, "penalties": {"ev_soc_miss": 10}}], + }, + ) + + genetic0: Genetic0CommonSettings = Field( + default_factory=Genetic0CommonSettings, + json_schema_extra={ + "description": "GENETIC0 optimization algorithm configuration.", "examples": [{"individuals": 400, "seed": None, "penalties": {"ev_soc_miss": 10}}], }, ) # Computed fields + @computed_field # type: ignore[prop-decorator] + @property + def algorithms(self) -> list[str]: + """Available optimization algorithms.""" + return optimization_algorithms() + @computed_field # type: ignore[prop-decorator] @property def keys(self) -> list[str]: @@ -112,15 +74,6 @@ class OptimizationCommonSettings(SettingsBaseModel): key_list = df.columns.tolist() return sorted(set(key_list)) - @computed_field # type: ignore[prop-decorator] - @property - def horizon(self) -> int: - """Number of optimization steps.""" - if self.interval is None or self.interval == 0 or self.horizon_hours is None: - return 0 - num_steps = int(float(self.horizon_hours * 3600) / self.interval) - return num_steps - class OptimizationSolution(PydanticBaseModel): """General Optimization Solution.""" diff --git a/src/akkudoktoreos/prediction/elecpricefixed.py b/src/akkudoktoreos/prediction/elecpricefixed.py index 8b40c90..fca63c3 100644 --- a/src/akkudoktoreos/prediction/elecpricefixed.py +++ b/src/akkudoktoreos/prediction/elecpricefixed.py @@ -80,7 +80,7 @@ class ElecPriceFixed(ElecPriceProvider): raise ValueError(error_msg) start_datetime = self.ems_start_datetime - interval_seconds = self.config.optimization.interval + interval_seconds = 900 # Usual smallest time interval (15 min) used in electricty prices total_hours = self.config.prediction.hours interval = to_duration(interval_seconds) diff --git a/src/akkudoktoreos/server/eos.py b/src/akkudoktoreos/server/eos.py index 98e3111..4e87af4 100755 --- a/src/akkudoktoreos/server/eos.py +++ b/src/akkudoktoreos/server/eos.py @@ -48,9 +48,10 @@ from akkudoktoreos.core.pydantic import ( ) from akkudoktoreos.core.version import __version__ from akkudoktoreos.devices.devices import ResourceKey -from akkudoktoreos.optimization.genetic.geneticparams import ( - GeneticOptimizationParameters, +from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0OptimizationParameters, ) +from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSolution from akkudoktoreos.optimization.optimization import OptimizationSolution from akkudoktoreos.prediction.elecprice import ElecPriceCommonSettings @@ -1161,6 +1162,38 @@ 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: str, +) -> Union[GeneticSolution, Genetic0Solution]: + """Get the latest algorithm specific solution of the optimization. + + Args: + algorithm: Optimization algorithm + """ + algorithm = algorithm.upper() + if algorithm not in get_config().optimization.algorithms: + raise HTTPException( + status_code=404, detail=f"Optimization algorithm '{algorithm}' unknown." + ) + if algorithm == "GENETIC": + genetic_solution = get_ems().genetic_solution() + if genetic_solution is None: + raise HTTPException( + status_code=404, detail=f"'{algorithm}' optimization solution not available." + ) + return genetic_solution + if algorithm == "GENETIC0": + genetic0_solution = get_ems().genetic0_solution() + if genetic0_solution is None: + raise HTTPException( + status_code=404, detail=f"'{algorithm}' optimization solution not available." + ) + return genetic0_solution + # Should never happen + raise HTTPException(status_code=500, detail=f"'{algorithm}' validated but not handled.") + + @app.get("/v1/energy-management/plan", tags=["energy-management"]) def fastapi_energy_management_plan_get() -> EnergyManagementPlan: """Get the latest energy management plan.""" @@ -1458,20 +1491,23 @@ async def fastapi_pvforecast() -> ForecastResponse: @app.post("/optimize", tags=["optimize"]) async def fastapi_optimize( - parameters: GeneticOptimizationParameters, + parameters: Genetic0OptimizationParameters, start_hour: Annotated[ Optional[int], Query(description="Defaults to current hour of the day.") ] = None, ngen: Annotated[ Optional[int], Query(description="Number of indivuals to generate for genetic algorithm.") ] = None, -) -> GeneticSolution: +) -> Genetic0Solution: """Deprecated: Optimize. Endpoint to handle optimization. + Uses the `classic` GENETIC0 optimisation algorithm (__NO__ 15-minutes slots). + Note: Use automatic optimization instead. + "v1/energy-management/optimization/solution/GENETIC0" """ if start_hour is None: start_datetime = None @@ -1483,13 +1519,14 @@ async def fastapi_optimize( await get_ems().run( start_datetime=start_datetime, mode=EnergyManagementMode.OPTIMIZATION, - genetic_parameters=parameters, - genetic_individuals=ngen, + algorithm="GENETIC0", + genetic0_parameters=parameters, + genetic0_generations=ngen, ) except Exception as e: raise HTTPException(status_code=400, detail=f"Optimize error: {e}.") - solution = get_ems().genetic_solution() + solution = get_ems().genetic0_solution() if solution is None: raise HTTPException(status_code=400, detail="Optimize error: no solution stored by run.") diff --git a/tests/single_test_genetic0optimization.py b/tests/single_test_genetic0optimization.py new file mode 100755 index 0000000..24a093d --- /dev/null +++ b/tests/single_test_genetic0optimization.py @@ -0,0 +1,525 @@ +#!/usr/bin/env python3 + +import argparse +import asyncio +import cProfile +import json +import pstats +import sys +import time +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.genetic0.genetic0params import ( + Genetic0OptimizationParameters, +) +from akkudoktoreos.utils.datetimeutil import to_datetime + +config_eos = get_config() +prediction_eos = get_prediction() +ems_eos = get_ems() + + +async def prepare_optimization_real_parameters() -> Genetic0OptimizationParameters: + """Prepare and return optimization parameters with real world data. + + Returns: + GeneticOptimizationParameters: Configured optimization parameters + """ + # Make a config + settings = { + "general": { + "latitude": 52.52, + "longitude": 13.405, + }, + "prediction": { + "hours": 48, + "historic_hours": 24, + }, + "optimization": { + "algorithm": "GENETIC0", + "genetic0": { + "horizon_hours": 24, + "individuals": 300, + "generations": 400, + "seed": None, + "penalties": { + "ev_soc_miss": 10, + }, + }, + }, + # PV Forecast + "pvforecast": { + "provider": "PVForecastAkkudoktor", + "planes": [ + { + "peakpower": 5.0, + "surface_azimuth": -10, + "surface_tilt": 7, + "userhorizon": [20, 27, 22, 20], + "inverter_paco": 10000, + }, + { + "peakpower": 4.8, + "surface_azimuth": -90, + "surface_tilt": 7, + "userhorizon": [30, 30, 30, 50], + "inverter_paco": 10000, + }, + { + "peakpower": 1.4, + "surface_azimuth": -40, + "surface_tilt": 60, + "userhorizon": [60, 30, 0, 30], + "inverter_paco": 2000, + }, + { + "peakpower": 1.6, + "surface_azimuth": 5, + "surface_tilt": 45, + "userhorizon": [45, 25, 30, 60], + "inverter_paco": 1400, + }, + ], + }, + # Weather Forecast + "weather": { + "provider": "ClearOutside", + }, + # Electricity Price Forecast + "elecprice": { + "provider": "ElecPriceAkkudoktor", + }, + # Load Forecast + "load": { + "provider": "LoadAkkudoktor", + "loadakkudoktor": { + "loadakkudoktor_year_energy_kwh": 5000, # Energy consumption per year in kWh + }, + }, + # -- Simulations -- + # Assure we have charge rates for the EV + "devices": { + "max_electric_vehicles": 1, + "electric_vehicles": [ + { + "charge_rates": [ + 0.0, + 6.0 / 16.0, + 8.0 / 16.0, + 10.0 / 16.0, + 12.0 / 16.0, + 14.0 / 16.0, + 1.0, + ], + }, + ], + }, + } + + # Update/ set configuration + config_eos.merge_settings_from_dict(settings) + + # Get current prediction data for optimization run + ems_eos.set_start_datetime() + print( + f"Real data prediction from {prediction_eos.ems_start_datetime} to {prediction_eos.end_datetime}" + ) + await prediction_eos.update_data() + + # PV Forecast (in W) + pv_forecast = await prediction_eos.key_to_array( + key="pvforecast_ac_power", + start_datetime=prediction_eos.ems_start_datetime, + end_datetime=prediction_eos.end_datetime, + ) + print(f"pv_forecast: {pv_forecast}") + + # Temperature Forecast (in degree C) + temperature_forecast = await prediction_eos.key_to_array( + key="weather_temp_air", + start_datetime=prediction_eos.ems_start_datetime, + end_datetime=prediction_eos.end_datetime, + ) + print(f"temperature_forecast: {temperature_forecast}") + + # Electricity price (per Wh) + electricity_price_per_wh = await prediction_eos.key_to_array( + key="elecprice_marketprice_wh", + start_datetime=prediction_eos.ems_start_datetime, + end_datetime=prediction_eos.end_datetime, + fill_method="ffill", + ) + print(f"electricity_price_per_wh: {electricity_price_per_wh}") + + # Overall System Load (in W) + total_load = await prediction_eos.key_to_array( + key="load_mean", + start_datetime=prediction_eos.ems_start_datetime, + end_datetime=prediction_eos.end_datetime, + ) + print(f"total_load: {total_load}") + + # Start Solution (binary) + start_solution = None + print(f"start_solution: {start_solution}") + + # Define parameters for the optimization problem + return Genetic0OptimizationParameters( + **{ + "ems": { + "price_per_wh_battery": 0e-05, + "feed_in_tariff_per_wh": 7e-05, + "total_load": total_load, + "pv_forecast_wh": pv_forecast, + "electricity_price_per_wh": electricity_price_per_wh, + }, + "pv_battery": { + "device_id": "battery 1", + "capacity_wh": 26400, + "initial_soc_percentage": 15, + "min_soc_percentage": 15, + }, + "inverter": { + "device_id": "inverter 1", + "max_power_wh": 10000, + "battery_id": "battery 1", + }, + "ev": { + "device_id": "electric vehicle 1", + "min_soc_percentage": 50, + "capacity_wh": 60000, + "charging_efficiency": 0.95, + "max_charge_power_w": 11040, + "initial_soc_percentage": 5, + }, + "temperature_forecast": temperature_forecast, + "start_solution": start_solution, + } + ) + + +def prepare_optimization_parameters() -> Genetic0OptimizationParameters: + """Prepare and return optimization parameters with predefined data. + + Returns: + GeneticOptimizationParameters: Configured optimization parameters + """ + # Initialize the optimization problem using the default configuration + config_eos.merge_settings_from_dict( + { + "prediction": {"hours": 48}, + "optimization": { + "horizon_hours": 48, + "interval": 3600, + "algorithm": "GENETIC0", + "genetic0": { + "individuals": 300, + "generations": 400, + "seed": None, + "penalties": { + "ev_soc_miss": 10, + }, + }, + }, + # Assure we have charge rates for the EV + "devices": { + "max_electric_vehicles": 1, + "electric_vehicles": [ + { + "device_id": "Default EV", + "charge_rates": [ + 0.0, + 6.0 / 16.0, + 8.0 / 16.0, + 10.0 / 16.0, + 12.0 / 16.0, + 14.0 / 16.0, + 1.0, + ], + }, + ], + }, + } + ) + + # PV Forecast (in W) + pv_forecast = np.zeros(48) + pv_forecast[12] = 5000 + + # Temperature Forecast (in degree C) + temperature_forecast = [ + 18.3, + 17.8, + 16.9, + 16.2, + 15.6, + 15.1, + 14.6, + 14.2, + 14.3, + 14.8, + 15.7, + 16.7, + 17.4, + 18.0, + 18.6, + 19.2, + 19.1, + 18.7, + 18.5, + 17.7, + 16.2, + 14.6, + 13.6, + 13.0, + 12.6, + 12.2, + 11.7, + 11.6, + 11.3, + 11.0, + 10.7, + 10.2, + 11.4, + 14.4, + 16.4, + 18.3, + 19.5, + 20.7, + 21.9, + 22.7, + 23.1, + 23.1, + 22.8, + 21.8, + 20.2, + 19.1, + 18.0, + 17.4, + ] + + # Electricity price (per Wh) + electricity_price_per_wh = np.full(48, 0.001) + electricity_price_per_wh[0:10] = 0.00001 + electricity_price_per_wh[11:15] = 0.00005 + electricity_price_per_wh[20] = 0.00001 + + # Overall System Load (in W) + total_load = [ + 676.71, + 876.19, + 527.13, + 468.88, + 531.38, + 517.95, + 483.15, + 472.28, + 1011.68, + 995.00, + 1053.07, + 1063.91, + 1320.56, + 1132.03, + 1163.67, + 1176.82, + 1216.22, + 1103.78, + 1129.12, + 1178.71, + 1050.98, + 988.56, + 912.38, + 704.61, + 516.37, + 868.05, + 694.34, + 608.79, + 556.31, + 488.89, + 506.91, + 804.89, + 1141.98, + 1056.97, + 992.46, + 1155.99, + 827.01, + 1257.98, + 1232.67, + 871.26, + 860.88, + 1158.03, + 1222.72, + 1221.04, + 949.99, + 987.01, + 733.99, + 592.97, + ] + + # Start Solution (binary) + start_solution = None + + # Define parameters for the optimization problem + return Genetic0OptimizationParameters( + **{ + "ems": { + "price_per_wh_battery": 0e-05, + "feed_in_tariff_per_wh": 7e-05, + "total_load": total_load, + "pv_forecast_wh": pv_forecast, + "electricity_price_per_wh": electricity_price_per_wh, + }, + "pv_battery": { + "device_id": "battery 1", + "capacity_wh": 26400, + "initial_soc_percentage": 15, + "min_soc_percentage": 15, + }, + "inverter": { + "device_id": "inverter 1", + "max_power_wh": 10000, + "battery_id": "battery 1", + }, + "ev": { + "device_id": "electric vehicle 1", + "min_soc_percentage": 50, + "capacity_wh": 60000, + "charging_efficiency": 0.95, + "max_charge_power_w": 11040, + "initial_soc_percentage": 5, + }, + "temperature_forecast": temperature_forecast, + "start_solution": start_solution, + } + ) + + +def run_optimization( + real_world: bool, start_hour: int, verbose: bool, seed: int, parameters_file: str, ngen: int +) -> Any: + """Run the optimization problem. + + Args: + start_hour (int, optional): Starting hour for optimization. Defaults to 0. + verbose (bool, optional): Whether to print verbose output. Defaults to False. + + Returns: + dict: Optimization result as a dictionary + """ + # Prepare parameters + if parameters_file: + with open(parameters_file, "r") as f: + parameters = Genetic0OptimizationParameters(**json.load(f)) + elif real_world: + parameters = asyncio.run(prepare_optimization_real_parameters()) + else: + parameters = prepare_optimization_parameters() + logger.info("Optimization Parameters:") + logger.info(parameters.model_dump_json(indent=4)) + + if start_hour is None: + start_datetime = None + else: + start_datetime = to_datetime().set(hour=start_hour) + + asyncio.run( + ems_eos.run( + start_datetime=start_datetime, + mode=EnergyManagementMode.OPTIMIZATION, + algorithm="GENETIC0", + genetic0_parameters=parameters, + genetic0_generations=ngen, + genetic0_seed=seed, + ) + ) + + solution = ems_eos.genetic0_solution() + if solution is None: + return None + return solution.model_dump_json() + + +def main(): + """Main function to run the optimization script with optional profiling.""" + parser = argparse.ArgumentParser(description="Run Energy Optimization Simulation") + parser.add_argument("--profile", action="store_true", help="Enable performance profiling") + parser.add_argument( + "--verbose", action="store_true", help="Enable verbose output during optimization" + ) + parser.add_argument( + "--real-world", action="store_true", help="Use real world data for predictions" + ) + parser.add_argument( + "--start-hour", type=int, default=0, help="Starting hour for optimization (default: 0)" + ) + parser.add_argument( + "--parameters-file", + type=str, + default="", + help="Load optimization parameters from json file (default: unset)", + ) + parser.add_argument("--seed", type=int, default=42, help="Use fixed random seed (default: 42)") + parser.add_argument( + "--ngen", + type=int, + default=400, + help="Number of generations during optimization process (default: 400)", + ) + + args = parser.parse_args() + + if args.profile: + # Run with profiling + profiler = cProfile.Profile() + try: + result = profiler.runcall( + run_optimization, + real_world=args.real_world, + start_hour=args.start_hour, + verbose=args.verbose, + seed=args.seed, + parameters_file=args.parameters_file, + ngen=args.ngen, + ) + # Print profiling statistics + stats = pstats.Stats(profiler) + stats.strip_dirs().sort_stats("cumulative").print_stats(200) + # Print result + if args.verbose: + print("\nOptimization Result:") + print(result) + + except Exception as e: + print(f"Error during optimization: {e}", file=sys.stderr) + sys.exit(1) + else: + # Run without profiling + try: + start_time = time.time() + result = run_optimization( + real_world=args.real_world, + start_hour=args.start_hour, + verbose=args.verbose, + seed=args.seed, + parameters_file=args.parameters_file, + ngen=args.ngen, + ) + end_time = time.time() + elapsed_time = end_time - start_time + if args.verbose: + print(f"\nElapsed time: {elapsed_time:.4f} seconds.") + print("\nOptimization Result:") + print(result) + + except Exception as e: + print(f"Error during optimization: {e}", file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/tests/single_test_optimization.py b/tests/single_test_optimization.py index 1cec22b..a8c0a3f 100755 --- a/tests/single_test_optimization.py +++ b/tests/single_test_optimization.py @@ -215,10 +215,10 @@ def prepare_optimization_parameters() -> GeneticOptimizationParameters: { "prediction": {"hours": 48}, "optimization": { - "horizon_hours": 48, - "interval": 3600, "algorithm": "GENETIC", "genetic": { + "horizon_hours": 48, + "interval_sec": 3600, "individuals": 300, "generations": 400, "seed": None, @@ -433,7 +433,7 @@ def run_optimization( start_datetime=start_datetime, mode=EnergyManagementMode.OPTIMIZATION, genetic_parameters=parameters, - genetic_individuals=ngen, + genetic_generations=ngen, genetic_seed=seed, ) ) diff --git a/tests/test_elecpricefixed.py b/tests/test_elecpricefixed.py index af38ba2..a987b8b 100644 --- a/tests/test_elecpricefixed.py +++ b/tests/test_elecpricefixed.py @@ -110,38 +110,6 @@ class TestElecPriceFixed: provider.config.reset_settings() assert not provider.enabled() - @pytest.mark.asyncio - async def test_update_data_hourly_intervals(self, provider, config_eos): - """Test updating data with hourly intervals (3600s).""" - # Set start datetime - ems_eos = get_ems() - start_dt = to_datetime("2024-01-01 00:00:00", in_timezone="Europe/Berlin") - ems_eos.set_start_datetime(start_dt) - - # Configure hourly intervals - config_eos.optimization.interval = 3600 - config_eos.prediction.hours = 24 - - # Update data - await provider.update_data(force_enable=True, force_update=True) - - # Verify data was generated - assert len(provider) == 24 # 24 hours * 1 interval per hour - - # Check prices - records = provider.records - - # First 8 hours should be night rate (0.288 kWh = 0.000288 Wh) - for i in range(8): - assert abs(records[i].elecprice_marketprice_wh - 0.000288) < 1e-6 - # Verify timestamps are on hour boundaries - assert records[i].date_time.minute == 0 - assert records[i].date_time.second == 0 - - # Next 16 hours should be day rate (0.34 kWh = 0.00034 Wh) - for i in range(8, 24): - assert abs(records[i].elecprice_marketprice_wh - 0.00034) < 1e-6 - @pytest.mark.asyncio async def test_update_data_15min_intervals(self, provider, config_eos): """Test updating data with 15-minute intervals (900s).""" @@ -149,7 +117,6 @@ class TestElecPriceFixed: start_dt = to_datetime("2024-01-01 00:00:00", in_timezone="Europe/Berlin") ems_eos.set_start_datetime(start_dt) - config_eos.optimization.interval = 900 config_eos.prediction.hours = 10 # spans both windows: 00:00–10:00 = 40 intervals await provider.update_data(force_enable=True, force_update=True) @@ -176,40 +143,6 @@ class TestElecPriceFixed: f"Expected day rate at interval {i}, got {records[i].elecprice_marketprice_wh}" ) - @pytest.mark.asyncio - async def test_update_data_30min_intervals(self, provider, config_eos): - """Test updating data with 30-minute intervals (1800s).""" - ems_eos = get_ems() - start_dt = to_datetime("2024-01-01 00:00:00", in_timezone="Europe/Berlin") - ems_eos.set_start_datetime(start_dt) - - config_eos.optimization.interval = 1800 - config_eos.prediction.hours = 10 # spans both windows: 00:00–10:00 = 20 intervals - - await provider.update_data(force_enable=True, force_update=True) - - # 10 hours * 2 intervals per hour = 20 intervals - assert len(provider) == 20 - - records = provider.records - - # Check timestamps are on 30-minute boundaries - for record in records: - assert record.date_time.minute in (0, 30) - assert record.date_time.second == 0 - - # First 16 intervals: 00:00–08:00, night rate (8h * 2 = 16) - for i in range(16): - assert abs(records[i].elecprice_marketprice_wh - 0.000288) < 1e-6, ( - f"Expected night rate at interval {i}, got {records[i].elecprice_marketprice_wh}" - ) - - # Remaining 4 intervals: 08:00–10:00, day rate (2h * 2 = 4) - for i in range(16, 20): - assert abs(records[i].elecprice_marketprice_wh - 0.00034) < 1e-6, ( - f"Expected day rate at interval {i}, got {records[i].elecprice_marketprice_wh}" - ) - @pytest.mark.asyncio async def test_update_data_without_config(self, provider, config_eos): """Test update_data fails without configuration.""" @@ -232,12 +165,11 @@ class TestElecPriceFixed: @pytest.mark.asyncio async def test_key_to_array_resampling(self, provider, config_eos): """Test that key_to_array can resample to different intervals.""" - # Setup provider with hourly data + # Provider provides 15-minutes data ems_eos = get_ems() start_dt = to_datetime("2024-01-01 00:00:00", in_timezone="Europe/Berlin") ems_eos.set_start_datetime(start_dt) - config_eos.optimization.interval = 3600 config_eos.prediction.hours = 24 await provider.update_data(force_enable=True, force_update=True) @@ -315,7 +247,6 @@ class TestElecPriceFixedIntegration: config_eos.elecprice.elecpricefixed = ElecPriceFixedCommonSettings(time_windows=time_windows) config_eos.prediction.hours = 168 # 7 days - config_eos.optimization.interval = 900 # 15 minutes # Update data await provider.update_data(force_enable=True, force_update=True) diff --git a/tests/test_genetic0battery.py b/tests/test_genetic0battery.py new file mode 100644 index 0000000..39c0715 --- /dev/null +++ b/tests/test_genetic0battery.py @@ -0,0 +1,299 @@ +import numpy as np +import pytest + +from akkudoktoreos.devices.genetic0.genetic0battery import ( + Genetic0Battery, + Genetic0SolarPanelBatteryParameters, +) + + +@pytest.fixture +def setup_pv_battery(): + device_id="battery1" + capacity_wh=10000 + initial_soc_percentage=50 + charging_efficiency=0.88 + discharging_efficiency=0.88 + min_soc_percentage=20 + max_soc_percentage=80 + max_charge_power_w=8000 + hours=24 + + params = Genetic0SolarPanelBatteryParameters( + device_id=device_id, + capacity_wh=capacity_wh, + initial_soc_percentage=initial_soc_percentage, + charging_efficiency=charging_efficiency, + discharging_efficiency=discharging_efficiency, + min_soc_percentage=min_soc_percentage, + max_soc_percentage=max_soc_percentage, + max_charge_power_w=max_charge_power_w, + hours=hours, + ) + battery = Genetic0Battery( + params, + prediction_hours=48, + ) + battery.reset() + + assert battery.parameters.device_id==device_id + assert battery.capacity_wh==capacity_wh + assert battery.initial_soc_percentage==initial_soc_percentage + assert battery.charging_efficiency==charging_efficiency + assert battery.initial_soc_percentage==initial_soc_percentage + assert battery.discharging_efficiency==discharging_efficiency + assert battery.max_soc_percentage==max_soc_percentage + assert battery.max_charge_power_w==max_charge_power_w + assert battery.soc_wh==float((initial_soc_percentage / 100) * capacity_wh) + assert battery.min_soc_wh==float((min_soc_percentage / 100) * capacity_wh) + assert battery.max_soc_wh==float((max_soc_percentage / 100) * capacity_wh) + assert np.all(battery.charge_array == 0) + assert np.all(battery.discharge_array == 0) + + # Init for test + battery.charge_array = np.full(battery.prediction_hours, 1) + battery.discharge_array = np.full(battery.prediction_hours, 1) + assert np.all(battery.charge_array == 1) + assert np.all(battery.discharge_array == 1) + + return battery + + +def test_initial_state_of_charge(setup_pv_battery): + battery = setup_pv_battery + assert battery.current_soc_percentage() == 50.0, "Initial SoC should be 50%" + + +def test_battery_discharge_below_min_soc(setup_pv_battery): + battery = setup_pv_battery + discharged_wh, loss_wh = battery.discharge_energy(5000, 0) + + # Ensure it discharges energy and stops at the min SOC + assert discharged_wh > 0 + print(discharged_wh, loss_wh, battery.current_soc_percentage(), battery.min_soc_percentage) + assert battery.current_soc_percentage() >= 20 # Ensure it's above min_soc_percentage + assert loss_wh >= 0 # Losses should not be negative + assert discharged_wh == 2640.0, "The energy discharged should be limited by min_soc" + + +def test_battery_charge_above_max_soc(setup_pv_battery): + battery = setup_pv_battery + charged_wh, loss_wh = battery.charge_energy(5000, 0) + + # Ensure it charges energy and stops at the max SOC + assert charged_wh > 0 + assert battery.current_soc_percentage() <= 80 # Ensure it's below max_soc_percentage + assert loss_wh >= 0 # Losses should not be negative + assert charged_wh == 3000.0, "The energy charged should be limited by max_soc" + + +def test_battery_charge_when_full(setup_pv_battery): + battery = setup_pv_battery + battery.soc_wh = battery.max_soc_wh # Set battery to full + charged_wh, loss_wh = battery.charge_energy(5000, 0) + + # No charging should happen if battery is full + assert charged_wh == 0 + assert loss_wh == 0 + assert battery.current_soc_percentage() == 80, "SoC should remain at max_soc" + + +def test_battery_discharge_when_empty(setup_pv_battery): + battery = setup_pv_battery + battery.soc_wh = battery.min_soc_wh # Set battery to minimum SOC + discharged_wh, loss_wh = battery.discharge_energy(5000, 0) + + # No discharge should happen if battery is at min SOC + assert discharged_wh == 0 + assert loss_wh == 0 + assert battery.current_soc_percentage() == 20, "SoC should remain at min_soc" + + +def test_battery_discharge_exactly_min_soc(setup_pv_battery): + battery = setup_pv_battery + battery.soc_wh = battery.min_soc_wh # Set battery to exactly min SOC + discharged_wh, loss_wh = battery.discharge_energy(1000, 0) + + # Battery should not go below the min SOC + assert discharged_wh == 0 + assert battery.current_soc_percentage() == 20 # SOC should remain at min_SOC + + +def test_battery_charge_exactly_max_soc(setup_pv_battery): + battery = setup_pv_battery + battery.soc_wh = battery.max_soc_wh # Set battery to exactly max SOC + charged_wh, loss_wh = battery.charge_energy(1000, 0) + + # Battery should not exceed the max SOC + assert charged_wh == 0 + assert battery.current_soc_percentage() == 80 # SOC should remain at max_SOC + + +def test_battery_reset_function(setup_pv_battery): + battery = setup_pv_battery + battery.soc_wh = 8000 # Change the SOC to some value + battery.reset() + + # After reset, SOC should be equal to the initial value + assert battery.current_soc_percentage() == battery.initial_soc_percentage + + +def test_soc_limits(setup_pv_battery): + battery = setup_pv_battery + + # Manually set SoC above max limit + battery.soc_wh = battery.max_soc_wh + 1000 + battery.soc_wh = min(battery.soc_wh, battery.max_soc_wh) + assert battery.current_soc_percentage() <= 80, "SoC should not exceed max_soc" + + # Manually set SoC below min limit + battery.soc_wh = battery.min_soc_wh - 1000 + battery.soc_wh = max(battery.soc_wh, battery.min_soc_wh) + assert battery.current_soc_percentage() >= 20, "SoC should not drop below min_soc" + + +def test_max_charge_power_w(setup_pv_battery): + battery = setup_pv_battery + assert battery.parameters.max_charge_power_w == 8000, ( + "Default max charge power should be 5000W, We ask for 8000W here" + ) + + +def test_charge_energy_within_limits(setup_pv_battery): + battery = setup_pv_battery + initial_soc_wh = battery.soc_wh + + charged_wh, losses_wh = battery.charge_energy(wh=4000, hour=1) + + assert charged_wh > 0, "Charging should add energy" + assert losses_wh >= 0, "Losses should not be negative" + assert battery.soc_wh > initial_soc_wh, "State of charge should increase after charging" + assert battery.soc_wh <= battery.max_soc_wh, "SOC should not exceed max SOC" + + +def test_charge_energy_exceeds_capacity(setup_pv_battery): + battery = setup_pv_battery + initial_soc_wh = battery.soc_wh + + # Try to overcharge beyond max capacity + charged_wh, losses_wh = battery.charge_energy(wh=20000, hour=2) + + assert charged_wh + initial_soc_wh <= battery.max_soc_wh, ( + "Charging should not exceed max capacity" + ) + assert losses_wh >= 0, "Losses should not be negative" + assert battery.soc_wh == battery.max_soc_wh, "SOC should be at max after overcharge attempt" + + +def test_charge_energy_not_allowed_hour(setup_pv_battery): + battery = setup_pv_battery + + # Disable charging for all hours + battery.set_charge_per_hour(np.zeros(battery.prediction_hours)) + + charged_wh, losses_wh = battery.charge_energy(wh=4000, hour=3) + + assert charged_wh == 0, "No energy should be charged in disallowed hours" + assert losses_wh == 0, "No losses should occur if charging is not allowed" + assert ( + battery.soc_wh == (battery.parameters.initial_soc_percentage / 100) * battery.capacity_wh + ), "SOC should remain unchanged" + + +@pytest.mark.parametrize( + "wh, charge_factor, expected_raises", + [ + (None, 0.5, False), # Expected to work normally (if capacity allows) + (None, 1.0, False), # Often still OK, depending on fixture capacity + (None, 2.0, False), # Exceeds max charge → always ValueError + (1000, 0, False), + (1000, 1.0, True), + ], +) +def test_charge_energy_with_charge_factor(setup_pv_battery, wh, charge_factor, expected_raises): + battery = setup_pv_battery + hour = 4 + + if wh is not None and charge_factor == 0.0: # mode 1 + raw_request_wh = wh + else: + raw_request_wh = battery.max_charge_power_w * charge_factor + raw_capacity_wh = max(battery.max_soc_wh - battery.soc_wh, 0.0) + + if expected_raises: + # Should raise + with pytest.raises(ValueError): + battery.charge_energy( + wh=wh, + hour=hour, + charge_factor=charge_factor, + ) + return + + # Should NOT raise + charged_wh, losses_wh = battery.charge_energy( + wh=wh, + hour=hour, + charge_factor=charge_factor, + ) + + # Expectations + assert charged_wh > 0, "Charging should occur with charge factor" + assert losses_wh >= 0, "Losses must not be negative" + assert charged_wh <= raw_request_wh, "Charging must not exceed request" + assert battery.soc_wh > 0, "SOC should increase after charging" + + +@pytest.fixture +def setup_car_battery(): + from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0ElectricVehicleParameters, + ) + + params = Genetic0ElectricVehicleParameters( + device_id="ev1", + capacity_wh=40000, + initial_soc_percentage=60, + min_soc_percentage=10, + max_soc_percentage=90, + max_charge_power_w=7000, + hours=24, + ) + battery = Genetic0Battery( + params, + prediction_hours=48, + ) + battery.reset() + + # Init for test + battery.charge_array = np.full(battery.prediction_hours, 1) + battery.discharge_array = np.full(battery.prediction_hours, 1) + assert np.all(battery.charge_array == 1) + assert np.all(battery.discharge_array == 1) + + return battery + + +def test_car_and_pv_battery_discharge_and_max_charge_power(setup_pv_battery, setup_car_battery): + pv_battery = setup_pv_battery + car_battery = setup_car_battery + + # Test discharge for PV battery + pv_discharged_wh, pv_loss_wh = pv_battery.discharge_energy(3000, 5) + assert pv_discharged_wh > 0, "PV battery should discharge energy" + assert pv_battery.current_soc_percentage() >= pv_battery.parameters.min_soc_percentage, ( + "PV battery SOC should stay above min SOC" + ) + assert pv_battery.parameters.max_charge_power_w == 8000, ( + "PV battery max charge power should remain as defined" + ) + + # Test discharge for car battery + car_discharged_wh, car_loss_wh = car_battery.discharge_energy(5000, 10) + assert car_discharged_wh > 0, "Car battery should discharge energy" + assert car_battery.current_soc_percentage() >= car_battery.parameters.min_soc_percentage, ( + "Car battery SOC should stay above min SOC" + ) + assert car_battery.parameters.max_charge_power_w == 7000, ( + "Car battery max charge power should remain as defined" + ) diff --git a/tests/test_genetic0inverter.py b/tests/test_genetic0inverter.py new file mode 100644 index 0000000..57918ed --- /dev/null +++ b/tests/test_genetic0inverter.py @@ -0,0 +1,343 @@ +from unittest.mock import Mock, patch + +import pytest + +from akkudoktoreos.devices.genetic0.genetic0inverter import ( + Genetic0Inverter, + Genetic0InverterParameters, +) + + +@pytest.fixture +def mock_battery() -> Mock: + mock_battery = Mock() + mock_battery.charge_energy = Mock(return_value=(0.0, 0.0)) + mock_battery.discharge_energy = Mock(return_value=(0.0, 0.0)) + mock_battery.parameters.device_id = "battery1" + return mock_battery + + +@pytest.fixture +def inverter(mock_battery) -> Genetic0Inverter: + mock_self_consumption_predictor = Mock() + mock_self_consumption_predictor.calculate_self_consumption.return_value = 1.0 + with patch( + "akkudoktoreos.devices.genetic0.genetic0inverter.get_genetic0_load_interpolator", + return_value=mock_self_consumption_predictor, + ): + iv = Genetic0Inverter( + Genetic0InverterParameters( + device_id="iv1", max_power_wh=500.0, battery_id=mock_battery.parameters.device_id + ), + battery = mock_battery + ) + return iv + + +def test_process_energy_excess_generation(inverter, mock_battery): + # Battery charges 100 Wh with 10 Wh loss + mock_battery.charge_energy.return_value = (100.0, 10.0) + generation = 600.0 + consumption = 200.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == pytest.approx(290.0, rel=1e-2) # 290 Wh feed-in after battery charges + assert grid_import == 0.0 # No grid draw + assert losses == 10.0 # Battery charging losses + assert self_consumption == 200.0 # All consumption is met + mock_battery.charge_energy.assert_called_once_with(400.0, hour) + mock_battery.discharge_energy.assert_not_called() + inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with( + consumption, generation + ) + + +def test_process_energy_excess_generation_interpolator(inverter, mock_battery): + # Battery charges 100 Wh with 10 Wh loss + mock_battery.charge_energy.return_value = (100.0, 10.0) + mock_battery.discharge_energy.return_value = (20.0, 2.0) + inverter.self_consumption_predictor.calculate_self_consumption.return_value = 0.95 + + generation = 600.0 + consumption = 200.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == pytest.approx( + 270.0, rel=1e-2 + ) # 290 Wh feed-in - 5% of generation-consumption self consumption after battery charges + assert grid_import == pytest.approx(0.0, rel=1e-2) # No grid draw + assert losses == 12.0 # Battery charging losses + assert self_consumption == 220.0 # All consumption is met + mock_battery.charge_energy.assert_called_once_with(pytest.approx(380.0, rel=1e-2), hour) + mock_battery.discharge_energy.assert_called_once_with(pytest.approx(20.0, rel=1e-2), hour) + inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with( + consumption, generation + ) + + +def test_process_energy_generation_equals_consumption(inverter, mock_battery): + generation = 300.0 + consumption = 300.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in as generation equals consumption + assert grid_import == 0.0 # No grid draw + assert losses == 0.0 # No losses + assert self_consumption == 300.0 # All consumption is met with generation + + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_not_called() + inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with( + consumption, generation + ) + + +def test_process_energy_battery_discharges(inverter, mock_battery): + # Battery discharges 100 Wh with 10 Wh loss already accounted for in the discharge + mock_battery.discharge_energy.return_value = (100.0, 10.0) + generation = 100.0 + consumption = 250.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in as generation is insufficient + assert grid_import == pytest.approx( + 50.0, rel=1e-2 + ) # Grid supplies remaining shortfall after battery discharge + assert losses == 10.0 # Discharge losses + assert self_consumption == 200.0 # Generation + battery discharge + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_called_once_with(150.0, hour) + inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called() + + +def test_process_energy_battery_empty(inverter, mock_battery): + # Battery is empty, so no energy can be discharged + mock_battery.discharge_energy.return_value = (0.0, 0.0) + generation = 100.0 + consumption = 300.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in as generation is insufficient + assert grid_import == pytest.approx(200.0, rel=1e-2) # Grid has to cover the full shortfall + assert losses == 0.0 # No losses as the battery didn't discharge + assert self_consumption == 100.0 # Only generation is consumed + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_called_once_with(200.0, hour) + inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called() + + +def test_process_energy_battery_full_at_start(inverter, mock_battery): + # Battery is full, so no charging happens + mock_battery.charge_energy.return_value = (0.0, 0.0) + generation = 500.0 + consumption = 200.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == pytest.approx( + 300.0, rel=1e-2 + ) # All excess energy should be fed into the grid + assert grid_import == 0.0 # No grid draw + assert losses == 0.0 # No losses + assert self_consumption == 200.0 # Only consumption is met + mock_battery.charge_energy.assert_called_once_with(300.0, hour) + mock_battery.discharge_energy.assert_not_called() + inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with( + consumption, generation + ) + + +def test_process_energy_insufficient_generation_no_battery(inverter, mock_battery): + # Insufficient generation and no battery discharge + mock_battery.discharge_energy.return_value = (0.0, 0.0) + generation = 100.0 + consumption = 500.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in as generation is insufficient + assert grid_import == pytest.approx(400.0, rel=1e-2) # Grid supplies the shortfall + assert losses == 0.0 # No losses + assert self_consumption == 100.0 # Only generation is consumed + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_called_once_with(400.0, hour) + inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called() + + +def test_process_energy_insufficient_generation_battery_assists(inverter, mock_battery): + # Battery assists with some discharge to cover the shortfall + mock_battery.discharge_energy.return_value = ( + 50.0, + 5.0, + ) # Battery discharges 50 Wh with 5 Wh loss + generation = 200.0 + consumption = 400.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in as generation is insufficient + assert grid_import == pytest.approx( + 150.0, rel=1e-2 + ) # Grid supplies the remaining shortfall after battery discharge + assert losses == 5.0 # Discharge losses + assert self_consumption == 250.0 # Generation + battery discharge + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_called_once_with(200.0, hour) + inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called() + + +def test_process_energy_zero_generation(inverter, mock_battery): + # Zero generation, full reliance on battery and grid + mock_battery.discharge_energy.return_value = ( + 100.0, + 5.0, + ) # Battery discharges 100 Wh with 5 Wh loss + generation = 0.0 + consumption = 300.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in as there is zero generation + assert grid_import == pytest.approx(200.0, rel=1e-2) # Grid supplies the remaining shortfall + assert losses == 5.0 # Discharge losses + assert self_consumption == 100.0 # Only battery discharge is consumed + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_called_once_with(300.0, hour) + inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called() + + +def test_process_energy_zero_consumption(inverter, mock_battery): + # Generation exceeds consumption, but consumption is zero + mock_battery.charge_energy.return_value = (100.0, 10.0) + generation = 500.0 + consumption = 0.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == pytest.approx(390.0, rel=1e-2) # Excess energy after battery charges + assert grid_import == 0.0 # No grid draw as no consumption + assert losses == 10.0 # Charging losses + assert self_consumption == 0.0 # Zero consumption + mock_battery.charge_energy.assert_called_once_with(500.0, hour) + mock_battery.discharge_energy.assert_not_called() + inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with( + consumption, generation + ) + + +def test_process_energy_zero_generation_zero_consumption(inverter, mock_battery): + generation = 0.0 + consumption = 0.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in + assert grid_import == 0.0 # No grid draw + assert losses == 0.0 # No losses + assert self_consumption == 0.0 # No consumption + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_not_called() + inverter.self_consumption_predictor.calculate_self_consumption.assert_called_once_with( + consumption, generation + ) + + +def test_process_energy_partial_battery_discharge(inverter, mock_battery): + mock_battery.discharge_energy.return_value = (50.0, 5.0) + generation = 200.0 + consumption = 400.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in due to insufficient generation + assert grid_import == pytest.approx( + 150.0, rel=1e-2 + ) # Grid supplies the shortfall after battery assist + assert losses == 5.0 # Discharge losses + assert self_consumption == 250.0 # Generation + battery discharge + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_called_once_with(200.0, 12) + inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called() + + +def test_process_energy_consumption_exceeds_max_no_battery(inverter, mock_battery): + # Battery is empty, and consumption is much higher than the inverter's max power + mock_battery.discharge_energy.return_value = (0.0, 0.0) + generation = 100.0 + consumption = 1000.0 # Exceeds the inverter's max power + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in + assert grid_import == pytest.approx(900.0, rel=1e-2) # Grid covers the remaining shortfall + assert losses == 0.0 # No losses as the battery didn’t assist + assert self_consumption == 100.0 # Only the generation is consumed, maxing out the inverter + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_called_once_with(400.0, hour) + inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called() + + +def test_process_energy_zero_generation_full_battery_high_consumption(inverter, mock_battery): + # Full battery, no generation, and high consumption + mock_battery.discharge_energy.return_value = (500.0, 10.0) + generation = 0.0 + consumption = 600.0 + hour = 12 + + grid_export, grid_import, losses, self_consumption = inverter.process_energy( + generation, consumption, hour + ) + + assert grid_export == 0.0 # No feed-in due to zero generation + assert grid_import == pytest.approx( + 100.0, rel=1e-2 + ) # Grid covers remaining shortfall after battery discharge + assert losses == 10.0 # Battery discharge losses + assert self_consumption == 500.0 # Battery fully discharges to meet consumption + mock_battery.charge_energy.assert_not_called() + mock_battery.discharge_energy.assert_called_once_with(500.0, hour) + inverter.self_consumption_predictor.calculate_self_consumption.assert_not_called() diff --git a/tests/test_genetic0inverterefficiency.py b/tests/test_genetic0inverterefficiency.py new file mode 100644 index 0000000..139ed4c --- /dev/null +++ b/tests/test_genetic0inverterefficiency.py @@ -0,0 +1,886 @@ +"""Tests for inverter AC/DC efficiency separation and AC charging break-even penalty. + +Tests the new inverter parameters: +- dc_to_ac_efficiency: DC→AC conversion loss on battery discharge +- ac_to_dc_efficiency: AC→DC conversion loss on grid-to-battery charging +- max_ac_charge_power_w: Maximum AC charging power limit + +And the economic break-even penalty in GeneticOptimization.evaluate(): +- Penalises AC grid charging that cannot be recovered given round-trip losses and future prices +- Respects free PV-charged energy already in battery when ranking future discharge hours +""" + +from types import SimpleNamespace +from typing import cast +from unittest.mock import Mock, patch + +import numpy as np +import pytest + +from akkudoktoreos.devices.genetic0.genetic0battery import Genetic0Battery +from akkudoktoreos.devices.genetic0.genetic0inverter import Genetic0Inverter +from akkudoktoreos.optimization.genetic0.genetic0 import ( + Genetic0Simulation, +) +from akkudoktoreos.optimization.genetic0.genetic0devices import ( + Genetic0InverterParameters, + Genetic0SolarPanelBatteryParameters, +) +from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0EnergyManagementParameters, +) + +# --------------------------------------------------------------------------- +# Helpers / Fixtures +# --------------------------------------------------------------------------- + + +def _make_inverter( + dc_to_ac_efficiency: float = 1.0, + ac_to_dc_efficiency: float = 1.0, + max_ac_charge_power_w=None, + max_power_wh: float = 10000.0, + mock_battery=None, +) -> Genetic0Inverter: + """Create an Inverter with custom efficiency parameters and a mock battery.""" + mock_self_consumption_predictor = Mock() + mock_self_consumption_predictor.calculate_self_consumption.return_value = 1.0 + + params = Genetic0InverterParameters( + device_id="inv1", + max_power_wh=max_power_wh, + battery_id=mock_battery.parameters.device_id if mock_battery else None, + dc_to_ac_efficiency=dc_to_ac_efficiency, + ac_to_dc_efficiency=ac_to_dc_efficiency, + max_ac_charge_power_w=max_ac_charge_power_w, + ) + with patch( + "akkudoktoreos.devices.genetic0.genetic0inverter.get_genetic0_load_interpolator", + return_value=mock_self_consumption_predictor, + ): + return Genetic0Inverter(params, battery=mock_battery) + + +@pytest.fixture +def mock_battery() -> Mock: + mock_bat = Mock() + mock_bat.charge_energy = Mock(return_value=(0.0, 0.0)) + mock_bat.discharge_energy = Mock(return_value=(0.0, 0.0)) + mock_bat.parameters.device_id = "battery1" + return mock_bat + + +# =================================================================== +# 1. InverterParameters – new fields and defaults +# =================================================================== + + +class TestInverterParametersDefaults: + """Verify backward-compatible defaults for new parameters.""" + + def test_defaults(self): + params = Genetic0InverterParameters(device_id="inv1", max_power_wh=5000) + assert params.dc_to_ac_efficiency == 1.0 + assert params.ac_to_dc_efficiency == 1.0 + assert params.max_ac_charge_power_w is None + + def test_custom_values(self): + params = Genetic0InverterParameters( + device_id="inv1", + max_power_wh=5000, + dc_to_ac_efficiency=0.95, + ac_to_dc_efficiency=0.93, + max_ac_charge_power_w=3000, + ) + assert params.dc_to_ac_efficiency == 0.95 + assert params.ac_to_dc_efficiency == 0.93 + assert params.max_ac_charge_power_w == 3000 + + def test_ac_to_dc_zero_disables_ac_charging(self): + params = Genetic0InverterParameters( + device_id="inv1", max_power_wh=5000, ac_to_dc_efficiency=0.0 + ) + assert params.ac_to_dc_efficiency == 0.0 + + def test_dc_to_ac_must_be_positive(self): + with pytest.raises(Exception): + Genetic0InverterParameters(device_id="inv1", max_power_wh=5000, dc_to_ac_efficiency=0.0) + + def test_max_ac_charge_power_zero(self): + params = Genetic0InverterParameters( + device_id="inv1", max_power_wh=5000, max_ac_charge_power_w=0 + ) + assert params.max_ac_charge_power_w == 0 + + +# =================================================================== +# 2. dc_to_ac_efficiency – battery discharge through inverter +# =================================================================== + + +class TestDcToAcEfficiency: + """Battery discharge energy is reduced by dc_to_ac_efficiency.""" + + def test_discharge_shortfall_with_95_percent_efficiency(self, mock_battery): + """With 0.95 efficiency, 100 Wh DC from battery → 95 Wh AC delivered.""" + mock_battery.discharge_energy.return_value = (100.0, 10.0) + inv = _make_inverter(dc_to_ac_efficiency=0.95, mock_battery=mock_battery) + + generation = 0.0 + consumption = 200.0 + hour = 5 + + grid_export, grid_import, losses, self_consumption = inv.process_energy( + generation, consumption, hour + ) + + # Battery delivers 100 Wh DC → 95 Wh AC after inverter + # Inverter loss = 100 - 95 = 5 Wh + battery_discharge_ac = 100.0 * 0.95 # 95 Wh + assert self_consumption == pytest.approx(generation + battery_discharge_ac, rel=1e-5) + assert grid_import == pytest.approx(consumption - battery_discharge_ac, rel=1e-5) + + # Total losses = battery internal (10) + inverter DC→AC (5) + expected_losses = 10.0 + (100.0 * 0.05) + assert losses == pytest.approx(expected_losses, rel=1e-5) + + # Battery was asked for more DC to compensate for inverter loss + # ac_needed = min(200, max_power_wh - 0) = 200 + # dc_request = 200 / 0.95 ≈ 210.526 + expected_dc_request = 200.0 / 0.95 + mock_battery.discharge_energy.assert_called_once_with( + pytest.approx(expected_dc_request, rel=1e-3), hour + ) + + def test_discharge_with_100_percent_efficiency_unchanged(self, mock_battery): + """With 1.0 efficiency, behavior is identical to the legacy model.""" + mock_battery.discharge_energy.return_value = (100.0, 10.0) + inv = _make_inverter(dc_to_ac_efficiency=1.0, mock_battery=mock_battery) + + generation = 100.0 + consumption = 300.0 + hour = 5 + + grid_export, grid_import, losses, self_consumption = inv.process_energy( + generation, consumption, hour + ) + + # No inverter loss: battery_discharge_ac = 100 Wh + assert self_consumption == pytest.approx(200.0, rel=1e-5) + assert grid_import == pytest.approx(100.0, rel=1e-5) + assert losses == pytest.approx(10.0, rel=1e-5) # Only battery losses + + def test_discharge_surplus_path_with_efficiency(self, mock_battery): + """When generation > consumption but SCR < 1, discharge goes through inverter.""" + mock_battery.discharge_energy.return_value = (50.0, 5.0) + mock_battery.charge_energy.return_value = (100.0, 10.0) + + inv = _make_inverter(dc_to_ac_efficiency=0.90, mock_battery=mock_battery) + cast(Mock, inv.self_consumption_predictor).calculate_self_consumption.return_value = 0.90 + + generation = 500.0 + consumption = 200.0 + hour = 5 + + grid_export, grid_import, losses, self_consumption = inv.process_energy( + generation, consumption, hour + ) + + # surplus = 300, remaining_power = 300*0.9 = 270, remaining_load_evq = 300*0.1 = 30 + # DC request for discharge = 30 / 0.90 = 33.333 + expected_dc_request = 30.0 / 0.90 + mock_battery.discharge_energy.assert_called_once_with( + pytest.approx(expected_dc_request, rel=1e-3), hour + ) + + # Battery delivers 50 Wh DC → 45 Wh AC + from_battery_ac = 50.0 * 0.90 # 45 Wh + inverter_discharge_loss = 50.0 - from_battery_ac # 5 Wh + + assert self_consumption == pytest.approx(consumption + from_battery_ac, rel=1e-5) + + +# =================================================================== +# 3. ac_to_dc_efficiency + max_ac_charge_power_w – in simulation +# =================================================================== + + +class TestAcChargingInSimulation: + """Test AC charging logic with inverter efficiency in GeneticSimulation. + + These tests use a real Battery object (not a mock) and directly exercise + the AC charging path in GeneticSimulation.simulate(). + """ + + @pytest.fixture + def simulation_setup(self, config_eos): + """Set up a minimal GeneticSimulation with battery and inverter.""" + from akkudoktoreos.optimization.genetic0.genetic0 import Genetic0Simulation + from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0EnergyManagementParameters, + ) + + config_eos.merge_settings_from_dict( + {"prediction": {"hours": 48}, "optimization": {"hours": 24}} + ) + + prediction_hours = config_eos.prediction.hours + + def _build( + ac_to_dc_efficiency: float = 1.0, + dc_to_ac_efficiency: float = 1.0, + max_ac_charge_power_w=None, + battery_capacity_wh: int = 10000, + battery_charging_efficiency: float = 0.90, + battery_discharging_efficiency: float = 0.90, + battery_initial_soc_pct: int = 50, + battery_max_charge_power_w: int = 5000, + ): + akku = Genetic0Battery( + Genetic0SolarPanelBatteryParameters( + device_id="battery1", + capacity_wh=battery_capacity_wh, + initial_soc_percentage=battery_initial_soc_pct, + charging_efficiency=battery_charging_efficiency, + discharging_efficiency=battery_discharging_efficiency, + min_soc_percentage=0, + max_soc_percentage=100, + max_charge_power_w=battery_max_charge_power_w, + ), + prediction_hours=prediction_hours, + ) + akku.reset() + + inverter = Genetic0Inverter( + Genetic0InverterParameters( + 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, + ), + battery=akku, + ) + + simulation = Genetic0Simulation() + simulation.prepare( + Genetic0EnergyManagementParameters( + 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 + ), + optimization_hours=config_eos.optimization.genetic0.horizon_hours, + prediction_hours=prediction_hours, + inverter=inverter, + ev=None, + home_appliance=None, + ) + return simulation, akku, inverter + + return _build + + def test_ac_charge_with_unity_efficiency_backward_compat(self, simulation_setup): + """With ac_to_dc_efficiency=1.0, behavior matches legacy model.""" + sim, akku, inverter = simulation_setup(ac_to_dc_efficiency=1.0) + + # Enable AC charging for hour 1 at 50% power + sim.ac_charge_hours[1] = 0.5 + sim.dc_charge_hours[:] = 0 + sim.bat_discharge_hours[:] = 0 + + result = sim.simulate(start_hour=0) + + # At hour 1: AC charge at 50% of 5000W = 2500W DC requested + # With efficiency 1.0, AC consumed from grid = DC = 2500W + # Battery stores: 2500 * 0.90 (battery eff) = 2250 Wh + # Battery loss: 2500 - 2250 = 250 Wh + # Total grid consumption for that hour = 1000 (load) + 2500 (AC charge) + hour_idx = 1 + assert result["Netzbezug_Wh_pro_Stunde"][hour_idx] == pytest.approx(3500.0, rel=1e-3) + assert result["Verluste_Pro_Stunde"][hour_idx] == pytest.approx(250.0, rel=1e-3) + + def test_ac_charge_with_95_percent_efficiency(self, simulation_setup): + """With ac_to_dc_efficiency=0.95, more AC energy is consumed for same DC charge.""" + sim, akku, inverter = simulation_setup(ac_to_dc_efficiency=0.95) + + sim.ac_charge_hours[1] = 0.5 + sim.dc_charge_hours[:] = 0 + sim.bat_discharge_hours[:] = 0 + + result = sim.simulate(start_hour=0) + + # At hour 1: AC charge at 50% of 5000W = 2500W DC requested + # With ac_to_dc_efficiency=0.95: + # AC consumed = 2500 / 0.95 ≈ 2631.58 Wh + # Inverter loss = 2631.58 - 2500 = 131.58 Wh + # Battery stores: 2500 * 0.90 = 2250 Wh + # Battery loss: 2500 - 2250 = 250 Wh + # Total losses: 250 + 131.58 = 381.58 Wh + hour_idx = 1 + dc_energy = 2500.0 + ac_energy = dc_energy / 0.95 + inverter_loss = ac_energy - dc_energy + battery_loss = dc_energy * (1 - 0.90) + total_loss = battery_loss + inverter_loss + + expected_grid = 1000.0 + ac_energy + assert result["Netzbezug_Wh_pro_Stunde"][hour_idx] == pytest.approx( + expected_grid, rel=1e-3 + ) + assert result["Verluste_Pro_Stunde"][hour_idx] == pytest.approx(total_loss, rel=1e-3) + + def test_ac_charge_disabled_by_zero_efficiency(self, simulation_setup): + """With ac_to_dc_efficiency=0.0, AC charging is completely disabled.""" + sim, akku, inverter = simulation_setup(ac_to_dc_efficiency=0.0) + + sim.ac_charge_hours[1] = 1.0 # Try to AC charge + sim.dc_charge_hours[:] = 0 + sim.bat_discharge_hours[:] = 0 + + initial_soc = akku.soc_wh + result = sim.simulate(start_hour=0) + + # Battery should not charge at all (AC charging disabled) + # Grid consumption = only load + hour_idx = 1 + assert result["Netzbezug_Wh_pro_Stunde"][hour_idx] == pytest.approx(1000.0, rel=1e-3) + # Battery SoC should not change (no ac charge, no dc charge, no discharge) + assert result["akku_soc_pro_stunde"][hour_idx] == pytest.approx(50.0, rel=1e-3) + + def test_ac_charge_disabled_by_zero_max_power(self, simulation_setup): + """With max_ac_charge_power_w=0, AC charging is disabled.""" + sim, akku, inverter = simulation_setup( + ac_to_dc_efficiency=0.95, max_ac_charge_power_w=0 + ) + + sim.ac_charge_hours[1] = 1.0 + sim.dc_charge_hours[:] = 0 + sim.bat_discharge_hours[:] = 0 + + result = sim.simulate(start_hour=0) + + hour_idx = 1 + assert result["Netzbezug_Wh_pro_Stunde"][hour_idx] == pytest.approx(1000.0, rel=1e-3) + assert result["akku_soc_pro_stunde"][hour_idx] == pytest.approx(50.0, rel=1e-3) + + def test_ac_charge_limited_by_max_ac_power(self, simulation_setup): + """max_ac_charge_power_w limits the effective charge factor.""" + # battery max_charge_power_w = 5000, ac_to_dc_efficiency = 0.95 + # max_ac_charge_power_w = 2000 + # max_dc_factor = (2000 * 0.95) / 5000 = 0.38 + sim, akku, inverter = simulation_setup( + ac_to_dc_efficiency=0.95, max_ac_charge_power_w=2000 + ) + + sim.ac_charge_hours[1] = 1.0 # Request full power + sim.dc_charge_hours[:] = 0 + sim.bat_discharge_hours[:] = 0 + + result = sim.simulate(start_hour=0) + + # Effective charge factor is capped at 0.38 + # DC energy = 5000 * 0.38 = 1900 W + # AC energy = 1900 / 0.95 = 2000 W (respects limit) + hour_idx = 1 + max_dc_factor = (2000 * 0.95) / 5000 + dc_energy = 5000 * max_dc_factor + ac_energy = dc_energy / 0.95 + expected_grid = 1000.0 + ac_energy # load + AC charge + + assert result["Netzbezug_Wh_pro_Stunde"][hour_idx] == pytest.approx( + expected_grid, rel=1e-2 + ) + + def test_discharge_with_dc_to_ac_efficiency(self, simulation_setup): + """dc_to_ac_efficiency affects how much AC energy is delivered from battery.""" + sim, akku, inverter = simulation_setup( + dc_to_ac_efficiency=0.90, battery_initial_soc_pct=80 + ) + + # No PV, no AC charge, discharge only + sim.ac_charge_hours[:] = 0 + sim.dc_charge_hours[:] = 1 + sim.bat_discharge_hours[:] = 1 + + result = sim.simulate(start_hour=0) + + # With dc_to_ac_efficiency=0.90, battery discharge delivers less AC + # This means more grid import compared to efficiency=1.0 + # At hour 0: load=1000, PV=0 + # Shortfall = 1000 + # DC request = 1000 / 0.90 ≈ 1111 Wh + # Battery delivers (limited by capacity and efficiency): + # max raw = min(soc - min_soc, max_charge_power) = min(8000, 5000) = 5000 + # max deliverable DC = 5000 * 0.90 (battery eff) = 4500 + # delivered DC = min(1111, 4500) = 1111 Wh + # delivered AC = 1111 * 0.90 = 1000 Wh → covers full load + # So grid_import should be ≈ 0 for first hours while battery has charge + hour_idx = 0 + assert result["Netzbezug_Wh_pro_Stunde"][hour_idx] == pytest.approx(0.0, abs=5.0) + + # But losses should be higher due to inverter DC→AC conversion + # Inverter loss = 1111 * 0.10 = 111 Wh + # Battery loss = raw_used - delivered = delivered/bat_eff - delivered + # = 1111/0.90 - 1111 ≈ 123.5 Wh + assert result["Verluste_Pro_Stunde"][hour_idx] > 200.0 # Significant losses + + def test_round_trip_efficiency_cost_impact(self, simulation_setup): + """Verify AC charge + discharge round-trip losses increase total cost.""" + # Reference run: no inverter losses + sim_ref, akku_ref, inv_ref = simulation_setup( + ac_to_dc_efficiency=1.0, dc_to_ac_efficiency=1.0 + ) + sim_ref.ac_charge_hours[1] = 0.5 + sim_ref.dc_charge_hours[:] = 0 + sim_ref.bat_discharge_hours[:] = 1 + sim_ref.bat_discharge_hours[1] = 0 # Don't discharge while charging + result_ref = sim_ref.simulate(start_hour=0) + + # Test run: with inverter losses + sim_test, akku_test, inv_test = simulation_setup( + ac_to_dc_efficiency=0.93, dc_to_ac_efficiency=0.93 + ) + sim_test.ac_charge_hours[1] = 0.5 + sim_test.dc_charge_hours[:] = 0 + sim_test.bat_discharge_hours[:] = 1 + sim_test.bat_discharge_hours[1] = 0 + result_test = sim_test.simulate(start_hour=0) + + # With inverter losses, total cost should be HIGHER + assert result_test["Gesamtkosten_Euro"] > result_ref["Gesamtkosten_Euro"] + # And total losses should be HIGHER + assert result_test["Gesamt_Verluste"] > result_ref["Gesamt_Verluste"] + + +# =================================================================== +# 4. Integration with optimizer residual battery value +# =================================================================== + + +class TestResidualBatteryValue: + """Verify that dc_to_ac_efficiency affects residual battery value calculation.""" + + def test_current_energy_content_unaffected(self): + """Battery.current_energy_content() is DC-only; inverter eff applied in optimizer.""" + akku = Genetic0Battery( + Genetic0SolarPanelBatteryParameters( + device_id="bat1", + capacity_wh=10000, + initial_soc_percentage=50, + discharging_efficiency=0.90, + min_soc_percentage=0, + ), + prediction_hours=24, + ) + akku.reset() + + # DC energy content: (5000 - 0) * 0.90 = 4500 + assert akku.current_energy_content() == pytest.approx(4500.0, rel=1e-5) + + +# =================================================================== +# 5. AC charging break-even penalty in GeneticOptimization.evaluate() +# =================================================================== + + +def _make_mock_simulation( + *, + # Inverter properties + ac_to_dc_efficiency: float = 0.93, + dc_to_ac_efficiency: float = 0.95, + # Battery properties + charging_efficiency: float = 0.95, + discharging_efficiency: float = 0.95, + capacity_wh: float = 10_000.0, + initial_soc_percentage: float = 0.0, # fraction of capacity already stored (0 = empty) + min_soc_wh: float = 0.0, + max_charge_power_w: float = 5_000.0, + # Arrays (must be same length) + ac_charge_hours: list | None = None, + elect_price_hourly: list | None = None, + load_energy_array: list | None = None, +): + """Return a mock GeneticSimulation with configurable properties for penalty tests.""" + n = 24 + if ac_charge_hours is None: + ac_charge_hours = [0.0] * n + if elect_price_hourly is None: + elect_price_hourly = [0.0003] * n # 30 ct/kWh flat + if load_energy_array is None: + load_energy_array = [1000.0] * n # 1 kWh constant load + + inv = SimpleNamespace( + ac_to_dc_efficiency=ac_to_dc_efficiency, + dc_to_ac_efficiency=dc_to_ac_efficiency, + ) + bat = SimpleNamespace( + charging_efficiency=charging_efficiency, + discharging_efficiency=discharging_efficiency, + capacity_wh=capacity_wh, + initial_soc_percentage=initial_soc_percentage, + min_soc_wh=min_soc_wh, + max_charge_power_w=max_charge_power_w, + current_energy_content=Mock(return_value=0.0), + ) + + sim = Mock() + sim.battery = bat + sim.inverter = inv + sim.ev = None + sim.ac_charge_hours = np.array(ac_charge_hours, dtype=float) + sim.elect_price_hourly = np.array(elect_price_hourly, dtype=float) + sim.load_energy_array = np.array(load_energy_array, dtype=float) + return sim + + +def _run_evaluate_with_mocked_sim( + config_eos, + mock_sim, + *, + ac_charge_break_even: float = 1.0, + start_hour: int = 0, + base_gesamtbilanz: float = 0.0, +): + """ + Patch a GeneticOptimization so that: + - evaluate_inner() returns a controlled base Gesamtbilanz_Euro + - self.simulation is replaced by mock_sim + Then call evaluate() and return the fitness tuple. + """ + from akkudoktoreos.optimization.genetic0.genetic0 import Genetic0Optimization + + config_eos.merge_settings_from_dict( + { + "prediction": {"hours": 48}, + "optimization": {"hours": 24}, + } + ) + config_eos.optimization.genetic0.penalties = { + "ev_soc_miss": 10, + "ac_charge_break_even": ac_charge_break_even, + } + + optim = Genetic0Optimization.__new__(Genetic0Optimization) + # Minimal __init__ state expected by evaluate() + optim.config = config_eos + optim.optimize_ev = False + optim.verbose = False + optim.opti_param = {"home_appliance": 0} + optim.simulation = mock_sim + + # evaluate_inner() just returns the base balance; we test the *additional* penalty + dummy_result = { + "Gesamtbilanz_Euro": base_gesamtbilanz, + "Gesamt_Verluste": 0.0, + "EAuto_SoC_pro_Stunde": np.zeros(48), + } + + # DEAP individuals are lists that accept attribute assignment; use a trivial subclass + class _Ind(list): # noqa: N801 + pass + + fake_individual = _Ind([0] * 48) + + with patch.object(optim, "evaluate_inner", return_value=dummy_result): + fitness = optim.evaluate( + fake_individual, + parameters=Mock( + ems=Mock(price_per_wh_battery=0.0), + eauto=None, + ), + start_hour=start_hour, + worst_case=False, + ) + return fitness[0] + + +class TestAcChargeBreakEvenPenalty: + """Break-even penalty in GeneticOptimization.evaluate(). + + The penalty adds a positive (bad) contribution to the fitness score whenever + AC grid charging is scheduled at an hour where the round-trip loss means the + stored energy can never be discharged at a price sufficient to recover costs, + taking into account that free PV-charged energy already in the battery covers + the most expensive future hours first. + """ + + # ----------------------------------------------------------------- + # 5a. No AC charging → no penalty + # ----------------------------------------------------------------- + + def test_no_ac_charging_no_penalty(self, config_eos): + """When no AC charging is scheduled, fitness equals the base balance.""" + n = 24 + sim = _make_mock_simulation( + ac_charge_hours=[0.0] * n, + elect_price_hourly=[0.0003] * n, + load_energy_array=[1000.0] * n, + ) + base = 1.5 + fitness = _run_evaluate_with_mocked_sim(config_eos, sim, base_gesamtbilanz=base) + assert fitness == pytest.approx(base, rel=1e-9) + + # ----------------------------------------------------------------- + # 5b. AC charging profitable → no penalty + # ----------------------------------------------------------------- + + def test_profitable_ac_charging_no_penalty(self, config_eos): + """When future discharge price > P_charge / η, charging is justified → no penalty.""" + n = 24 + # Charge at hour 0: 0.0001 €/Wh + # Round-trip: 0.93 * 0.95 * 0.95 * 0.95 ≈ 0.7975 + # break-even price ≈ 0.0001 / 0.7975 ≈ 0.0001254 €/Wh + # Future hour 1 price: 0.0003 > break-even → profitable + prices = [0.0001] + [0.0003] * (n - 1) + ac_charge = [1.0] + [0.0] * (n - 1) + loads = [1000.0] * n + + sim = _make_mock_simulation( + ac_to_dc_efficiency=0.93, + dc_to_ac_efficiency=0.95, + charging_efficiency=0.95, + discharging_efficiency=0.95, + ac_charge_hours=ac_charge, + elect_price_hourly=prices, + load_energy_array=loads, + initial_soc_percentage=0.0, # empty battery → no free PV energy + ) + base = 0.0 + fitness = _run_evaluate_with_mocked_sim(config_eos, sim, base_gesamtbilanz=base) + # penalty should be 0 (or very small due to floating-point rounding) + assert fitness == pytest.approx(base, abs=1e-9) + + # ----------------------------------------------------------------- + # 5c. AC charging unprofitable → penalty fires + # ----------------------------------------------------------------- + + def test_unprofitable_ac_charging_adds_penalty(self, config_eos): + """When future discharge prices are too low to justify AC charging, penalty is added.""" + n = 24 + # Charge at hour 0: 0.0004 €/Wh + # Round-trip: 0.93 * 0.95 * 0.95 * 0.95 ≈ 0.7975 + # break-even price ≈ 0.0004 / 0.7975 ≈ 0.000501 €/Wh + # All future prices: 0.0003 < break-even → unprofitable + prices = [0.0004] + [0.0003] * (n - 1) + ac_charge = [1.0] + [0.0] * (n - 1) + loads = [1000.0] * n + + sim = _make_mock_simulation( + ac_to_dc_efficiency=0.93, + dc_to_ac_efficiency=0.95, + charging_efficiency=0.95, + discharging_efficiency=0.95, + ac_charge_hours=ac_charge, + elect_price_hourly=prices, + load_energy_array=loads, + initial_soc_percentage=0.0, + ) + base = 0.0 + fitness = _run_evaluate_with_mocked_sim(config_eos, sim, base_gesamtbilanz=base) + # Fitness must be worse (higher) than base + assert fitness > base + 1e-6 + + # ----------------------------------------------------------------- + # 5d. Free PV energy covers expensive hours → penalty reduced/eliminated + # ----------------------------------------------------------------- + + def test_free_pv_energy_eliminates_penalty(self, config_eos): + """PV energy covers the best future hour; penalty is larger than without PV energy.""" + n = 24 + # Charge at hour 0: 0.0005 €/Wh + # Round-trip: 0.93*0.95*0.95*0.95 ≈ 0.7974 + # break-even ≈ 0.0005 / 0.7974 ≈ 0.000627 €/Wh + # + # Future: one expensive hour at 0.0006 (< break-even!) and rest at 0.0003 + # → even the best future price 0.0006 < 0.000627 → AC charging is never profitable + # + # Empty battery: best_uncovered = 0.0006 < 0.000627 → penalty fires + # With PV (50% SoC → ~4512 Wh deliverable free AC): covers the 0.0006 hour (1000 Wh) + # → best_uncovered drops to 0.0003 → penalty fires with LARGER excess + prices = [0.0005] + [0.0003] * (n - 2) + [0.0006] # expensive hour at end + ac_charge = [1.0] + [0.0] * (n - 1) + loads = [1000.0] * n + + sim_empty = _make_mock_simulation( + ac_to_dc_efficiency=0.93, + dc_to_ac_efficiency=0.95, + charging_efficiency=0.95, + discharging_efficiency=0.95, + ac_charge_hours=list(ac_charge), + elect_price_hourly=list(prices), + load_energy_array=list(loads), + initial_soc_percentage=0.0, # no free PV energy + ) + sim_with_pv = _make_mock_simulation( + ac_to_dc_efficiency=0.93, + dc_to_ac_efficiency=0.95, + charging_efficiency=0.95, + discharging_efficiency=0.95, + ac_charge_hours=list(ac_charge), + elect_price_hourly=list(prices), + load_energy_array=list(loads), + capacity_wh=10_000.0, + initial_soc_percentage=50.0, # 5000 Wh free PV energy → ~4512 Wh deliverable AC + ) + + fitness_empty = _run_evaluate_with_mocked_sim(config_eos, sim_empty, base_gesamtbilanz=0.0) + fitness_pv = _run_evaluate_with_mocked_sim(config_eos, sim_with_pv, base_gesamtbilanz=0.0) + + # Both are penalised (break-even > max future price) + assert fitness_empty > 1e-6, "Empty battery: best_uncovered=0.0006 < break_even→ penalty" + assert fitness_pv > 1e-6, "With PV: free energy covers 0.0006 hour, best drops to 0.0003" + + # With PV the expensive hour is covered for free → uncovered best price is lower + # → excess_cost_per_wh = break_even - best_uncovered is larger → penalty is BIGGER + assert fitness_pv > fitness_empty, "PV covers expensive hour → uncovered best is cheaper" + + + def test_free_pv_energy_exposes_only_cheap_future_prices(self, config_eos): + """When PV covers ALL expensive hours, best_uncovered_price = 0 → max penalty.""" + n = 5 + capacity_wh = 10_000.0 + # Free PV: initial 80% → (8000 - 0) * 0.95 * 0.95 = 7220 Wh deliverable AC + # Future loads: 2 expensive hours × 1000 Wh = 2000 Wh → all covered by free PV + prices = [0.0010, 0.0008, 0.0008, 0.0002, 0.0002] + ac_charge = [1.0, 0.0, 0.0, 0.0, 0.0] + loads = [1000.0] * n + + sim = _make_mock_simulation( + ac_to_dc_efficiency=0.93, + dc_to_ac_efficiency=0.95, + charging_efficiency=0.95, + discharging_efficiency=0.95, + capacity_wh=capacity_wh, + initial_soc_percentage=80.0, + ac_charge_hours=ac_charge, + elect_price_hourly=prices, + load_energy_array=loads, + ) + + # break_even = 0.001 / (0.93*0.95*0.95*0.95) ≈ 0.001254 + # PV covers both 0.0008 hours → best_uncovered = 0.0002 → penalty fires + fitness = _run_evaluate_with_mocked_sim(config_eos, sim, base_gesamtbilanz=0.0) + assert fitness > 1e-6 + + # ----------------------------------------------------------------- + # 5e. Penalty factor scales the penalty + # ----------------------------------------------------------------- + + def test_penalty_factor_scales_linearly(self, config_eos): + """The ac_charge_break_even factor doubles the penalty when doubled.""" + n = 24 + prices = [0.0004] + [0.0003] * (n - 1) + ac_charge = [1.0] + [0.0] * (n - 1) + loads = [1000.0] * n + + def _fitness(factor): + sim = _make_mock_simulation( + ac_to_dc_efficiency=0.93, + dc_to_ac_efficiency=0.95, + charging_efficiency=0.95, + discharging_efficiency=0.95, + ac_charge_hours=list(ac_charge), + elect_price_hourly=list(prices), + load_energy_array=list(loads), + initial_soc_percentage=0.0, + ) + return _run_evaluate_with_mocked_sim( + config_eos, sim, ac_charge_break_even=factor, base_gesamtbilanz=0.0 + ) + + f1 = _fitness(1.0) + f2 = _fitness(2.0) + + # With factor=2 the penalty should be exactly double + assert f2 == pytest.approx(2.0 * f1, rel=1e-6) + + # ----------------------------------------------------------------- + # 5f. Zero or negative AC charge factor → no penalty contribution + # ----------------------------------------------------------------- + + def test_zero_ac_charge_factor_no_penalty(self, config_eos): + """ac_charge_hours[h] = 0 means no charging, so no penalty.""" + n = 24 + prices = [0.0010] * n # Expensive, but no AC charging + ac_charge = [0.0] * n + loads = [1000.0] * n + + sim = _make_mock_simulation( + ac_charge_hours=ac_charge, + elect_price_hourly=prices, + load_energy_array=loads, + ) + base = 3.0 + fitness = _run_evaluate_with_mocked_sim(config_eos, sim, base_gesamtbilanz=base) + assert fitness == pytest.approx(base, abs=1e-9) + + # ----------------------------------------------------------------- + # 5g. No battery / inverter → penalty skipped entirely + # ----------------------------------------------------------------- + + def test_no_battery_skips_penalty(self, config_eos): + """When no battery is present, the penalty block is skipped.""" + n = 24 + sim = _make_mock_simulation( + ac_charge_hours=[1.0] * n, + elect_price_hourly=[0.001] * n, + load_energy_array=[1000.0] * n, + ) + sim.battery = None # no battery → penalty skipped + + base = 2.5 + fitness = _run_evaluate_with_mocked_sim(config_eos, sim, base_gesamtbilanz=base) + assert fitness == pytest.approx(base, abs=1e-9) + + def test_no_inverter_skips_penalty(self, config_eos): + """When no inverter is present, the penalty block is skipped.""" + n = 24 + sim = _make_mock_simulation( + ac_charge_hours=[1.0] * n, + elect_price_hourly=[0.001] * n, + load_energy_array=[1000.0] * n, + ) + sim.inverter = None # no inverter → penalty skipped + + base = 2.5 + fitness = _run_evaluate_with_mocked_sim(config_eos, sim, base_gesamtbilanz=base) + assert fitness == pytest.approx(base, abs=1e-9) + + # ----------------------------------------------------------------- + # 5h. Unit-level break-even maths (no optimizer setup needed) + # ----------------------------------------------------------------- + + def test_break_even_formula(self): + """Verify the break-even formula: P_break_even = P_charge / η_round_trip.""" + ac_to_dc = 0.93 + bat_charge = 0.95 + bat_discharge = 0.95 + dc_to_ac = 0.95 + + eta_rt = ac_to_dc * bat_charge * bat_discharge * dc_to_ac + p_charge = 0.0004 # 40 ct/kWh + + break_even = p_charge / eta_rt + + # 1 Wh drawn from grid at p_charge → η_rt Wh delivered + # Need discharge price ≥ p_charge / η_rt to break even + assert break_even == pytest.approx(p_charge / eta_rt, rel=1e-9) + assert break_even > p_charge # Always worse due to losses + + def test_free_pv_energy_formula(self): + """Verify free pv energy: (initial_soc - min_soc) × η_bat_dis × η_inv_dis.""" + capacity_wh = 10_000.0 + initial_soc_pct = 60.0 + min_soc_wh = 500.0 + bat_dis = 0.95 + inv_dis = 0.95 + + initial_soc_wh = (initial_soc_pct / 100.0) * capacity_wh # 6000 + free_ac_wh = max(0.0, initial_soc_wh - min_soc_wh) * bat_dis * inv_dis + + # = (6000 - 500) * 0.95 * 0.95 = 5500 * 0.9025 = 4963.75 + expected = 5500.0 * 0.95 * 0.95 + assert free_ac_wh == pytest.approx(expected, rel=1e-9) diff --git a/tests/test_genetic0optimize.py b/tests/test_genetic0optimize.py new file mode 100644 index 0000000..067aa03 --- /dev/null +++ b/tests/test_genetic0optimize.py @@ -0,0 +1,155 @@ +import json +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pytest + +from akkudoktoreos.config.config import ConfigEOS +from akkudoktoreos.core.cache import CacheEnergyManagementStore +from akkudoktoreos.core.coreabc import get_ems +from akkudoktoreos.optimization.genetic0.genetic0 import Genetic0Optimization +from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0OptimizationParameters, +) +from akkudoktoreos.optimization.genetic0.genetic0solution import Genetic0Solution +from akkudoktoreos.utils.datetimeutil import to_datetime +from akkudoktoreos.utils.visualize import ( + prepare_visualize, # Import the new prepare_visualize +) + +ems_eos = get_ems(init=True) # init once + +DIR_TESTDATA = Path(__file__).parent / "testdata" + + +def compare_dict(actual: dict[str, Any], expected: dict[str, Any]): + assert set(actual) == set(expected) + + for key, value in expected.items(): + if isinstance(value, dict): + assert isinstance(actual[key], dict) + compare_dict(actual[key], value) + elif isinstance(value, list): + assert isinstance(actual[key], list) + assert actual[key] == pytest.approx(value) + else: + assert actual[key] == pytest.approx(value) + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "fn_in, fn_out, ngen, break_even", + [ + ("genetic0optimize_input_1.json", "genetic0optimize_result_1.json", 3, 0), + ("genetic0optimize_input_2.json", "genetic0optimize_result_2.json", 3, 0), + ("genetic0optimize_input_2.json", "genetic0optimize_result_2_full.json", 400, 0), + ("genetic0optimize_input_1.json", "genetic0optimize_result_1_be.json", 3, 1), + ("genetic0optimize_input_2.json", "genetic0optimize_result_2_be.json", 3, 1), + ], +) +async def test_optimize( + fn_in: str, + fn_out: str, + ngen: int, + break_even: int, + config_eos: ConfigEOS, + is_finalize: bool, +): + """Test optimize_ems.""" + # Test parameters + fixed_start_hour = 10 + fixed_seed = 42 + + # Assure configuration holds the correct values + config_eos.merge_settings_from_dict( + { + "prediction": { + "hours": 48 + }, + "optimization": { + "algorithm": "GENETIC0", + "genetic0": { + "horizon_hours": 48, + "individuals": 300, + "generations": 10, + "penalties": { + "ev_soc_miss": 10, + "ac_charge_break_even": break_even, + } + } + }, + "devices": { + "max_electric_vehicles": 1, + "electric_vehicles": [ + { + "charge_rates": [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0], + } + ], + } + } + ) + + # Load input and output data + file = DIR_TESTDATA / fn_in + with file.open("r") as f_in: + input_data = Genetic0OptimizationParameters(**json.load(f_in)) + + file = DIR_TESTDATA / fn_out + # In case a new test case is added, we don't want to fail here, so the new output is written + # to disk before + try: + with file.open("r") as f_out: + expected_data = json.load(f_out) + expected_result = Genetic0Solution(**expected_data) + except FileNotFoundError: + pass + + # Fake energy management run start datetime + ems_eos.set_start_datetime(to_datetime().set(hour=fixed_start_hour)) + + # Throw away any cached results of the last energy management run. + CacheEnergyManagementStore().clear() + + genetic0_optimization = Genetic0Optimization(fixed_seed=fixed_seed) + + # Activate with pytest --finalize + if ngen > 10 and not is_finalize: + pytest.skip() + + visualize_filename = str((DIR_TESTDATA / f"new_{fn_out}").with_suffix(".pdf")) + + with patch( + "akkudoktoreos.utils.visualize.prepare_visualize", + side_effect=lambda parameters, results, *args, **kwargs: prepare_visualize( + parameters, results, filename=visualize_filename, **kwargs + ), + ) as prepare_visualize_patch: + # Call the optimization function + genetic0_solution = genetic0_optimization.optimize_ems( + parameters=input_data, start_hour=fixed_start_hour, ngen=ngen + ) + # The function creates a visualization result PDF as a side-effect. + prepare_visualize_patch.assert_called_once() + assert Path(visualize_filename).exists() + + # Write test output to file, so we can take it as new data on intended change + TESTDATA_FILE = DIR_TESTDATA / f"new_{fn_out}" + with TESTDATA_FILE.open("w", encoding="utf-8", newline="\n") as f_out: + f_out.write(genetic0_solution.model_dump_json(indent=4, exclude_unset=True)) + + assert genetic0_solution.result.Gesamtbilanz_Euro == pytest.approx( + expected_result.result.Gesamtbilanz_Euro + ) + + # Assert that the output contains all expected entries. + # This does not assert that the optimization always gives the same result! + # Reproducibility and mathematical accuracy should be tested on the level of individual components. + compare_dict(genetic0_solution.model_dump(), expected_result.model_dump()) + + # Check the correct generic optimization solution is created + optimization_solution = await genetic0_solution.optimization_solution() + # @TODO + + # Check the correct generic energy management plan is created + plan = genetic0_solution.energy_management_plan() + # @TODO diff --git a/tests/test_genetic0simulation.py b/tests/test_genetic0simulation.py new file mode 100644 index 0000000..dd5cb2f --- /dev/null +++ b/tests/test_genetic0simulation.py @@ -0,0 +1,654 @@ +import numpy as np +import pytest + +from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence +from akkudoktoreos.devices.genetic0.genetic0battery import Genetic0Battery +from akkudoktoreos.devices.genetic0.genetic0homeappliance import Genetic0HomeAppliance +from akkudoktoreos.devices.genetic0.genetic0inverter import Genetic0Inverter +from akkudoktoreos.optimization.genetic0.genetic0 import ( + Genetic0Simulation, + Genetic0SimulationResult, +) +from akkudoktoreos.optimization.genetic0.genetic0devices import ( + Genetic0ElectricVehicleParameters, + Genetic0HomeApplianceParameters, + Genetic0InverterParameters, + Genetic0SolarPanelBatteryParameters, +) +from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0EnergyManagementParameters, +) +from akkudoktoreos.utils.datetimeutil import to_duration, to_time + +START_HOUR = 0 + + +# Example initialization of necessary components +@pytest.fixture +def genetic0_simulation(config_eos) -> Genetic0Simulation: + """Fixture to create an GENETIC2 simualtion instance with given test parameters.""" + # Assure configuration holds the correct values + config_eos.merge_settings_from_dict( + { + "prediction": { + "hours": 48 + }, + "optimization": { + "hours": 24 + } + } + ) + assert config_eos.prediction.hours == 48 + assert config_eos.optimization.genetic0.horizon_hours == 24 + + # Initialize the battery and the inverter + akku = Genetic0Battery( + Genetic0SolarPanelBatteryParameters( + device_id="battery1", + capacity_wh=5000, + initial_soc_percentage=80, + min_soc_percentage=10, + ), + prediction_hours = config_eos.prediction.hours, + ) + akku.reset() + + inverter = Genetic0Inverter( + Genetic0InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id), + battery = akku, + ) + + # Household device (currently not used, set to None) + home_appliance = Genetic0HomeAppliance( + Genetic0HomeApplianceParameters( + device_id="dishwasher1", + consumption_wh=2000, + duration_h=2, + time_windows=None, + ), + optimization_hours = config_eos.optimization.genetic0.horizon_hours, + prediction_hours = config_eos.prediction.hours, + ) + + # Example initialization of electric car battery + eauto = Genetic0Battery( + Genetic0ElectricVehicleParameters( + device_id="ev1", capacity_wh=26400, initial_soc_percentage=10, min_soc_percentage=10 + ), + prediction_hours = config_eos.prediction.hours, + ) + eauto.set_charge_per_hour(np.full(config_eos.prediction.hours, 1)) + + # Parameters based on previous example data + pv_prognose_wh = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 8.05, + 352.91, + 728.51, + 930.28, + 1043.25, + 1106.74, + 1161.69, + 6018.82, + 5519.07, + 3969.88, + 3017.96, + 1943.07, + 1007.17, + 319.67, + 7.88, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 5.04, + 335.59, + 705.32, + 1121.12, + 1604.79, + 2157.38, + 1433.25, + 5718.49, + 4553.96, + 3027.55, + 2574.46, + 1720.4, + 963.4, + 383.3, + 0, + 0, + 0, + ] + + strompreis_euro_pro_wh = [ + 0.0003384, + 0.0003318, + 0.0003284, + 0.0003283, + 0.0003289, + 0.0003334, + 0.0003290, + 0.0003302, + 0.0003042, + 0.0002430, + 0.0002280, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.0002270, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.0002780, + 0.0003384, + 0.0003318, + 0.0003284, + 0.0003283, + 0.0003289, + 0.0003334, + 0.0003290, + 0.0003302, + 0.0003042, + 0.0002430, + 0.0002280, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.0002270, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.0002780, + ] + + einspeiseverguetung_euro_pro_wh = 0.00007 + preis_euro_pro_wh_akku = 0.0001 + + gesamtlast = [ + 676.71, + 876.19, + 527.13, + 468.88, + 531.38, + 517.95, + 483.15, + 472.28, + 1011.68, + 995.00, + 1053.07, + 1063.91, + 1320.56, + 1132.03, + 1163.67, + 1176.82, + 1216.22, + 1103.78, + 1129.12, + 1178.71, + 1050.98, + 988.56, + 912.38, + 704.61, + 516.37, + 868.05, + 694.34, + 608.79, + 556.31, + 488.89, + 506.91, + 804.89, + 1141.98, + 1056.97, + 992.46, + 1155.99, + 827.01, + 1257.98, + 1232.67, + 871.26, + 860.88, + 1158.03, + 1222.72, + 1221.04, + 949.99, + 987.01, + 733.99, + 592.97, + ] + + # Initialize the energy management system with the respective parameters + genetic0_simulation = Genetic0Simulation() + genetic0_simulation.prepare( + Genetic0EnergyManagementParameters( + 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, + ), + optimization_hours = config_eos.optimization.genetic0.horizon_hours, + prediction_hours = config_eos.prediction.hours, + inverter=inverter, + ev=eauto, + home_appliance=home_appliance, + ) + + # Init for test + assert genetic0_simulation.ac_charge_hours is not None + assert genetic0_simulation.dc_charge_hours is not None + assert genetic0_simulation.bat_discharge_hours is not None + assert genetic0_simulation.ev_charge_hours is not None + genetic0_simulation.ac_charge_hours[START_HOUR] = 1.0 + genetic0_simulation.dc_charge_hours[START_HOUR] = 1.0 + genetic0_simulation.bat_discharge_hours[START_HOUR] = 1.0 + genetic0_simulation.ev_charge_hours[START_HOUR] = 1.0 + genetic0_simulation.home_appliance_start_hour = 2 + + return genetic0_simulation + +@pytest.fixture +def genetic0_simulation_2(config_eos) -> Genetic0Simulation: + """Fixture to create an EnergyManagement instance with given test parameters.""" + # Assure configuration holds the correct values + config_eos.merge_settings_from_dict( + { + "prediction": { + "hours": 48 + }, + "optimization": { + "hours": 24 + } + } + ) + assert config_eos.prediction.hours == 48 + assert config_eos.optimization.genetic0.horizon_hours == 24 + + # Initialize the battery and the inverter + akku = Genetic0Battery( + Genetic0SolarPanelBatteryParameters( + device_id="battery1", + capacity_wh=5000, + initial_soc_percentage=80, + min_soc_percentage=10, + ), + prediction_hours = config_eos.prediction.hours, + ) + akku.reset() + + inverter = Genetic0Inverter( + Genetic0InverterParameters(device_id="inverter1", max_power_wh=10000, battery_id=akku.parameters.device_id), + battery = akku, + ) + + # Household device (currently not used, set to None) + home_appliance = Genetic0HomeAppliance( + Genetic0HomeApplianceParameters( + device_id="dishwasher1", + consumption_wh=2000, + duration_h=2, + time_windows=None, + ), + optimization_hours = config_eos.optimization.genetic0.horizon_hours, + prediction_hours = config_eos.prediction.hours, + ) + + # Example initialization of electric car battery + eauto = Genetic0Battery( + Genetic0ElectricVehicleParameters( + device_id="ev1", capacity_wh=26400, initial_soc_percentage=10, min_soc_percentage=10 + ), + prediction_hours = config_eos.prediction.hours, + ) + + # Parameters based on previous example data + pv_prognose_wh = [0.0] * config_eos.prediction.hours + pv_prognose_wh[10] = 5000.0 + pv_prognose_wh[11] = 5000.0 + + strompreis_euro_pro_wh = [0.001] * config_eos.prediction.hours + strompreis_euro_pro_wh[0:10] = [0.00001] * 10 + strompreis_euro_pro_wh[11:15] = [0.00005] * 4 + strompreis_euro_pro_wh[20] = 0.00001 + + einspeiseverguetung_euro_pro_wh = [0.00007] * len(strompreis_euro_pro_wh) + preis_euro_pro_wh_akku = 0.0001 + + gesamtlast = [ + 676.71, + 876.19, + 527.13, + 468.88, + 531.38, + 517.95, + 483.15, + 472.28, + 1011.68, + 995.00, + 1053.07, + 1063.91, + 1320.56, + 1132.03, + 1163.67, + 1176.82, + 1216.22, + 1103.78, + 1129.12, + 1178.71, + 1050.98, + 988.56, + 912.38, + 704.61, + 516.37, + 868.05, + 694.34, + 608.79, + 556.31, + 488.89, + 506.91, + 804.89, + 1141.98, + 1056.97, + 992.46, + 1155.99, + 827.01, + 1257.98, + 1232.67, + 871.26, + 860.88, + 1158.03, + 1222.72, + 1221.04, + 949.99, + 987.01, + 733.99, + 592.97, + ] + + # Initialize the energy management system with the respective parameters + simulation = Genetic0Simulation() + simulation.prepare( + Genetic0EnergyManagementParameters( + 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, + ), + optimization_hours = config_eos.optimization.genetic0.horizon_hours, + prediction_hours = config_eos.prediction.hours, + inverter=inverter, + ev=eauto, + home_appliance=home_appliance, + ) + + ac = np.full(config_eos.prediction.hours, 0.0) + ac[20] = 1 + simulation.ac_charge_hours = ac + dc = np.full(config_eos.prediction.hours, 0.0) + dc[11] = 1 + simulation.dc_charge_hours = dc + simulation.home_appliance_start_hour = 2 + + return simulation + + +def test_genetic0simulation(genetic0_simulation): + """Test the EnergyManagement simulation method.""" + simulation = genetic0_simulation + + # Simulate starting from hour 1 (this value can be adjusted) + + result = simulation.simulate(start_hour=START_HOUR) + + # visualisiere_ergebnisse( + # simulation.gesamtlast, + # simulation.pv_prognose_wh, + # simulation.strompreis_euro_pro_wh, + # result, + # simulation.akku.discharge_array+simulation.akku.charge_array, + # None, + # simulation.pv_prognose_wh, + # START_HOUR, + # 48, + # np.full(48, 0.0), + # filename="visualization_results.pdf", + # extra_data=None, + # ) + + # Assertions to validate results + assert result is not None, "Result should not be None" + assert isinstance(result, dict), "Result should be a dictionary" + assert "Last_Wh_pro_Stunde" in result, "Result should contain 'Last_Wh_pro_Stunde'" + + """ + Check the result of the simulation based on expected values. + """ + # Example result returned from the simulation (used for assertions) + assert result is not None, "Result should not be None." + + # Check that the result is a dictionary + assert isinstance(result, dict), "Result should be a dictionary." + assert Genetic0SimulationResult(**result) is not None + + # Check the length of the main arrays + assert len(result["Last_Wh_pro_Stunde"]) == 48, ( + "The length of 'Last_Wh_pro_Stunde' should be 48." + ) + assert len(result["Netzeinspeisung_Wh_pro_Stunde"]) == 48, ( + "The length of 'Netzeinspeisung_Wh_pro_Stunde' should be 48." + ) + assert len(result["Netzbezug_Wh_pro_Stunde"]) == 48, ( + "The length of 'Netzbezug_Wh_pro_Stunde' should be 48." + ) + assert len(result["Kosten_Euro_pro_Stunde"]) == 48, ( + "The length of 'Kosten_Euro_pro_Stunde' should be 48." + ) + assert len(result["akku_soc_pro_stunde"]) == 48, ( + "The length of 'akku_soc_pro_stunde' should be 48." + ) + + # Verify specific values in the 'Last_Wh_pro_Stunde' array + assert result["Last_Wh_pro_Stunde"][1] == 876.19, ( + "The value at index 1 of 'Last_Wh_pro_Stunde' should be 876.19." + ) + assert result["Last_Wh_pro_Stunde"][2] == 1527.13, ( + "The value at index 2 of 'Last_Wh_pro_Stunde' should be 1527.13." + ) + assert result["Last_Wh_pro_Stunde"][12] == 1320.56, ( + "The value at index 12 of 'Last_Wh_pro_Stunde' should be 1320.56." + ) + + # Verify that the value at index 0 is 'None' + # Check that 'Netzeinspeisung_Wh_pro_Stunde' and 'Netzbezug_Wh_pro_Stunde' are consistent + assert result["Netzbezug_Wh_pro_Stunde"][1] == 876.19, ( + "The value at index 1 of 'Netzbezug_Wh_pro_Stunde' should be 876.19." + ) + + # Verify the total balance + assert abs(result["Gesamtbilanz_Euro"] - 6.883546477556756) < 1e-5, ( + "Total balance should be 6.883546477556756." + ) + + # Check total revenue and total costs + assert abs(result["Gesamteinnahmen_Euro"] - 1.964301131937134) < 1e-5, ( + "Total revenue should be 1.964301131937134." + ) + assert abs(result["Gesamtkosten_Euro"] - 8.84784760949389) < 1e-5, ( + "Total costs should be 8.84784760949389." + ) + + # Check the losses + assert abs(result["Gesamt_Verluste"] - 1620.0) < 1e-5, ( + "Total losses should be 1620.0 ." + ) + + # Check the values in 'akku_soc_pro_stunde' + assert result["akku_soc_pro_stunde"][-1] == 98.0, ( + "The value at index -1 of 'akku_soc_pro_stunde' should be 98.0." + ) + assert result["akku_soc_pro_stunde"][1] == 98.0, ( + "The value at index 1 of 'akku_soc_pro_stunde' should be 98.0." + ) + + # Check home appliances + assert sum(simulation.home_appliance.get_load_curve()) == 2000, ( + "The sum of 'simulation.home_appliance.get_load_curve()' should be 2000." + ) + + assert ( + np.nansum( + np.where( + result["Home_appliance_wh_per_hour"] is None, + np.nan, + np.array(result["Home_appliance_wh_per_hour"]), + ) + ) + == 2000 + ), "The sum of 'Home_appliance_wh_per_hour' should be 2000." + + print("All tests passed successfully.") + + + +def test_genetic0simulation_2(genetic0_simulation_2): + """Test the EnergyManagement simulation method.""" + simulation = genetic0_simulation_2 + + # Simulate starting from hour 0 (this value can be adjusted) + result = simulation.simulate(start_hour=START_HOUR) + + # --- Pls do not remove! --- + # visualisiere_ergebnisse( + # simulation.gesamtlast, + # simulation.pv_prognose_wh, + # simulation.strompreis_euro_pro_wh, + # result, + # simulation.akku.discharge_array+simulation.akku.charge_array, + # None, + # simulation.pv_prognose_wh, + # START_HOUR, + # 48, + # np.full(48, 0.0), + # filename="visualization_results.pdf", + # extra_data=None, + # ) + + # Assertions to validate results + assert result is not None, "Result should not be None" + assert isinstance(result, dict), "Result should be a dictionary" + assert Genetic0SimulationResult(**result) is not None + assert "Last_Wh_pro_Stunde" in result, "Result should contain 'Last_Wh_pro_Stunde'" + + """ + Check the result of the simulation based on expected values. + """ + # Example result returned from the simulation (used for assertions) + assert result is not None, "Result should not be None." + + # Check that the result is a dictionary + assert isinstance(result, dict), "Result should be a dictionary." + + # Verify that the expected keys are present in the result + expected_keys = [ + "Last_Wh_pro_Stunde", + "Netzeinspeisung_Wh_pro_Stunde", + "Netzbezug_Wh_pro_Stunde", + "Kosten_Euro_pro_Stunde", + "akku_soc_pro_stunde", + "Einnahmen_Euro_pro_Stunde", + "Gesamtbilanz_Euro", + "EAuto_SoC_pro_Stunde", + "Gesamteinnahmen_Euro", + "Gesamtkosten_Euro", + "Verluste_Pro_Stunde", + "Gesamt_Verluste", + "Home_appliance_wh_per_hour", + ] + + for key in expected_keys: + assert key in result, f"The key '{key}' should be present in the result." + + # Check the length of the main arrays + assert len(result["Last_Wh_pro_Stunde"]) == 48, ( + "The length of 'Last_Wh_pro_Stunde' should be 48." + ) + assert len(result["Netzeinspeisung_Wh_pro_Stunde"]) == 48, ( + "The length of 'Netzeinspeisung_Wh_pro_Stunde' should be 48." + ) + assert len(result["Netzbezug_Wh_pro_Stunde"]) == 48, ( + "The length of 'Netzbezug_Wh_pro_Stunde' should be 48." + ) + assert len(result["Kosten_Euro_pro_Stunde"]) == 48, ( + "The length of 'Kosten_Euro_pro_Stunde' should be 48." + ) + assert len(result["akku_soc_pro_stunde"]) == 48, ( + "The length of 'akku_soc_pro_stunde' should be 48." + ) + + # Verfify DC and AC Charge Bins + assert abs(result["akku_soc_pro_stunde"][2] - 80.0) < 1e-5, ( + "'akku_soc_pro_stunde[2]' should be 80.0." + ) + assert abs(result["akku_soc_pro_stunde"][10] - 80.0) < 1e-5, ( + "'akku_soc_pro_stunde[10]' should be 80." + ) + + assert abs(result["Netzeinspeisung_Wh_pro_Stunde"][10] - 3946.93) < 1e-3, ( + "'Netzeinspeisung_Wh_pro_Stunde[11]' should be 3946.93." + ) + + assert abs(result["Netzeinspeisung_Wh_pro_Stunde"][11] - 2799.7263636361786) < 1e-3, ( + "'Netzeinspeisung_Wh_pro_Stunde[11]' should be 2799.7263636361786." + ) + + assert abs(result["akku_soc_pro_stunde"][20] - 100) < 1e-5, ( + "'akku_soc_pro_stunde[20]' should be 100." + ) + assert abs(result["Last_Wh_pro_Stunde"][20] - 1050.98) < 1e-3, ( + "'Last_Wh_pro_Stunde[20]' should be 1050.98." + ) + + print("All tests passed successfully.") + + +def test_set_parameters(genetic0_simulation_2): + """Test the set_parameters method of EnergyManagement.""" + simulation = genetic0_simulation_2 + + # Check if parameters are set correctly + assert simulation.load_energy_array is not None, "load_energy_array should not be None" + assert simulation.pv_prediction_wh is not None, "pv_prediction_wh should not be None" + assert simulation.elect_price_hourly is not None, "elect_price_hourly should not be None" + assert simulation.elect_revenue_per_hour_arr is not None, ( + "elect_revenue_per_hour_arr should not be None" + ) + + +def test_reset(genetic0_simulation_2): + """Test the reset method of EnergyManagement.""" + simulation = genetic0_simulation_2 + simulation.reset() + assert simulation.ev.current_soc_percentage() == simulation.ev.parameters.initial_soc_percentage, "EV SOC should be reset to initial value" + assert simulation.battery.current_soc_percentage() == simulation.battery.parameters.initial_soc_percentage, ( + "Battery SOC should be reset to initial value" + ) diff --git a/tests/test_translations.py b/tests/test_genetic0translations.py similarity index 84% rename from tests/test_translations.py rename to tests/test_genetic0translations.py index e24d9ce..b90e078 100644 --- a/tests/test_translations.py +++ b/tests/test_genetic0translations.py @@ -3,13 +3,13 @@ import json -from akkudoktoreos.optimization.genetic.geneticparams import ( - GeneticEnergyManagementParameters, +from akkudoktoreos.optimization.genetic0.genetic0 import Genetic0SimulationResult +from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0EnergyManagementParameters, ) -from akkudoktoreos.optimization.genetic.geneticsolution import GeneticSimulationResult -def test_genetic_params_german_input(): +def test_genetic0_params_german_input(): """Test that German field names are accepted as input.""" data_de = { "pv_prognose_wh": [100.0, 200.0], @@ -18,11 +18,11 @@ def test_genetic_params_german_input(): "preis_euro_pro_wh_akku": 0.0001, "gesamtlast": [500.0, 600.0], } - params = GeneticEnergyManagementParameters(**data_de) + params = Genetic0EnergyManagementParameters(**data_de) assert params.pv_forecast_wh == [100.0, 200.0] print("✅ German input accepted") -def test_genetic_params_english_input(): +def test_genetic0_params_english_input(): """Test that English field names are accepted as input.""" data_en = { "pv_forecast_wh": [100.0, 200.0], @@ -31,11 +31,11 @@ def test_genetic_params_english_input(): "price_per_wh_battery": 0.0001, "total_load": [500.0, 600.0], } - params = GeneticEnergyManagementParameters(**data_en) + params = Genetic0EnergyManagementParameters(**data_en) assert params.pv_forecast_wh == [100.0, 200.0] print("✅ English input accepted") -def test_genetic_params_english_output(): +def test_genetic0_params_english_output(): """Test that both English and German field names are in JSON output (backward compatibility).""" data_de = { "pv_prognose_wh": [100.0, 200.0], @@ -44,7 +44,7 @@ def test_genetic_params_english_output(): "preis_euro_pro_wh_akku": 0.0001, "gesamtlast": [500.0, 600.0], } - params = GeneticEnergyManagementParameters(**data_de) + params = Genetic0EnergyManagementParameters(**data_de) json_output = json.loads(params.model_dump_json(by_alias=True)) # English names should be in output @@ -66,7 +66,7 @@ def test_genetic_params_english_output(): assert json_output["electricity_price_per_wh"] == json_output["strompreis_euro_pro_wh"] print("✅ Both English and German output generated") -def test_simulation_result_translations(): +def test_genetic0_simulation_result_translations(): """Test simulation result field translations.""" data_de = { "Last_Wh_pro_Stunde": [100.0, 200.0], @@ -84,7 +84,7 @@ def test_simulation_result_translations(): "akku_soc_pro_stunde": [80.0, 90.0], "Electricity_price": [0.0003, 0.0003], } - result = GeneticSimulationResult(**data_de) + result = Genetic0SimulationResult(**data_de) json_output = json.loads(result.model_dump_json(by_alias=True)) # Check English field names in output @@ -121,16 +121,16 @@ def test_simulation_result_translations(): print("✅ Simulation result translations work") if __name__ == "__main__": - test_genetic_params_german_input() - test_genetic_params_english_input() - test_genetic_params_english_output() - test_simulation_result_translations() + test_genetic0_params_german_input() + test_genetic0_params_english_input() + test_genetic0_params_english_output() + test_genetic0_simulation_result_translations() print("\n✅✅✅ All translation tests passed! ✅✅✅") -def test_optimization_parameters_device_translations(): +def test_genetic0_optimization_parameters_device_translations(): """Test that German device field names are accepted and re-emitted.""" - from akkudoktoreos.optimization.genetic.geneticparams import ( - GeneticOptimizationParameters, + from akkudoktoreos.optimization.genetic0.genetic0params import ( + Genetic0OptimizationParameters, ) ems_de = { @@ -140,7 +140,7 @@ def test_optimization_parameters_device_translations(): "preis_euro_pro_wh_akku": 0.0001, "gesamtlast": [500.0, 600.0], } - params = GeneticOptimizationParameters( + params = Genetic0OptimizationParameters( ems=ems_de, pv_akku={"device_id": "battery1", "capacity_wh": 8000}, inverter=None, @@ -153,7 +153,7 @@ def test_optimization_parameters_device_translations(): assert params.ev.capacity_wh == 60000 # English input names work as well - params_en = GeneticOptimizationParameters( + params_en = Genetic0OptimizationParameters( ems=ems_de, pv_battery={"device_id": "battery1", "capacity_wh": 8000}, inverter=None, diff --git a/tests/test_geneticoptimize.py b/tests/test_geneticoptimize.py index 9668f53..fce2d63 100644 --- a/tests/test_geneticoptimize.py +++ b/tests/test_geneticoptimize.py @@ -67,8 +67,9 @@ async def test_optimize( "hours": 48 }, "optimization": { - "horizon_hours": 48, + "algorithm": "GENETIC", "genetic": { + "horizon_hours": 48, "individuals": 300, "generations": 10, "penalties": { diff --git a/tests/test_geneticsimulation.py b/tests/test_geneticsimulation.py index cc09a08..2b844a3 100644 --- a/tests/test_geneticsimulation.py +++ b/tests/test_geneticsimulation.py @@ -31,7 +31,7 @@ def genetic_simulation(config_eos) -> GeneticSimulation: {"prediction": {"hours": 48}, "optimization": {"hours": 24}} ) assert config_eos.prediction.hours == 48 - assert config_eos.optimization.horizon_hours == 24 + assert config_eos.optimization.genetic.horizon_hours == 24 # Initialize the battery and the inverter akku = Battery( @@ -58,7 +58,7 @@ def genetic_simulation(config_eos) -> GeneticSimulation: duration_h=2, time_windows=None, ), - optimization_hours = config_eos.optimization.horizon_hours, + optimization_hours = config_eos.optimization.genetic.horizon_hours, prediction_hours = config_eos.prediction.hours, ) @@ -238,7 +238,7 @@ def genetic_simulation(config_eos) -> GeneticSimulation: preis_euro_pro_wh_akku=preis_euro_pro_wh_akku, gesamtlast=gesamtlast, ), - optimization_hours = config_eos.optimization.horizon_hours, + optimization_hours = config_eos.optimization.genetic.horizon_hours, prediction_hours = config_eos.prediction.hours, inverter=inverter, ev=eauto, diff --git a/tests/test_geneticsimulation2.py b/tests/test_geneticsimulation2.py index f6c9e9c..9b7a76a 100644 --- a/tests/test_geneticsimulation2.py +++ b/tests/test_geneticsimulation2.py @@ -31,7 +31,7 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation: {"prediction": {"hours": 48}, "optimization": {"hours": 24}} ) assert config_eos.prediction.hours == 48 - assert config_eos.optimization.horizon_hours == 24 + assert config_eos.optimization.genetic.horizon_hours == 24 # Initialize the battery and the inverter akku = Battery( @@ -58,7 +58,7 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation: duration_h=2, time_windows=None, ), - optimization_hours = config_eos.optimization.horizon_hours, + optimization_hours = config_eos.optimization.genetic.horizon_hours, prediction_hours = config_eos.prediction.hours, ) @@ -144,7 +144,7 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation: preis_euro_pro_wh_akku=preis_euro_pro_wh_akku, gesamtlast=gesamtlast, ), - optimization_hours = config_eos.optimization.horizon_hours, + optimization_hours = config_eos.optimization.genetic.horizon_hours, prediction_hours = config_eos.prediction.hours, inverter=inverter, ev=eauto, diff --git a/tests/test_inverter_efficiency.py b/tests/test_inverter_efficiency.py index 582130b..c487a3b 100644 --- a/tests/test_inverter_efficiency.py +++ b/tests/test_inverter_efficiency.py @@ -266,7 +266,7 @@ class TestAcChargingInSimulation: preis_euro_pro_wh_akku=0.0001, gesamtlast=[1000.0] * prediction_hours, # 1 kW constant load ), - optimization_hours=config_eos.optimization.horizon_hours, + optimization_hours=config_eos.optimization.genetic.horizon_hours, prediction_hours=prediction_hours, inverter=inverter, ev=None, diff --git a/tests/testdata/docs/_generated/configexample.md b/tests/testdata/docs/_generated/configexample.md index 521182f..53c340f 100644 --- a/tests/testdata/docs/_generated/configexample.md +++ b/tests/testdata/docs/_generated/configexample.md @@ -177,10 +177,19 @@ ] }, "optimization": { - "horizon_hours": 24, - "interval": 3600, "algorithm": "GENETIC", "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, + "individuals": 400, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + } + }, + "genetic0": { + "horizon_hours": 24, "individuals": 400, "generations": 400, "seed": null, diff --git a/tests/testdata/docs/_generated/configoptimization.md b/tests/testdata/docs/_generated/configoptimization.md index e53d6d6..11c85e7 100644 --- a/tests/testdata/docs/_generated/configoptimization.md +++ b/tests/testdata/docs/_generated/configoptimization.md @@ -8,10 +8,9 @@ | Name | Environment Variable | Type | Read-Only | Default | Description | | ---- | -------------------- | ---- | --------- | ------- | ----------- | | algorithm | `EOS_OPTIMIZATION__ALGORITHM` | `str` | `rw` | `GENETIC` | The optimization algorithm. Defaults to GENETIC | -| genetic | `EOS_OPTIMIZATION__GENETIC` | `GeneticCommonSettings` | `rw` | `required` | Genetic optimization algorithm configuration. | -| horizon | | `int` | `ro` | `N/A` | Number of optimization steps. | -| horizon_hours | `EOS_OPTIMIZATION__HORIZON_HOURS` | `int` | `rw` | `24` | The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours. | -| interval | `EOS_OPTIMIZATION__INTERVAL` | `int` | `rw` | `3600` | The optimization interval [sec]. Defaults to 3600 seconds (1 hour) | +| algorithms | | `list[str]` | `ro` | `N/A` | Available optimization algorithms. | +| genetic | `EOS_OPTIMIZATION__GENETIC` | `GeneticCommonSettings` | `rw` | `required` | GENETIC optimization algorithm configuration. | +| genetic0 | `EOS_OPTIMIZATION__GENETIC0` | `Genetic0CommonSettings` | `rw` | `required` | GENETIC0 optimization algorithm configuration. | | keys | | `list[str]` | `ro` | `N/A` | The keys of the solution. | ::: @@ -24,10 +23,19 @@ ```json { "optimization": { - "horizon_hours": 24, - "interval": 3600, "algorithm": "GENETIC", "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, + "individuals": 400, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + } + }, + "genetic0": { + "horizon_hours": 24, "individuals": 400, "generations": 400, "seed": null, @@ -48,49 +56,68 @@ ```json { "optimization": { - "horizon_hours": 24, - "interval": 3600, "algorithm": "GENETIC", "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, "individuals": 400, "generations": 400, "seed": null, "penalties": { "ev_soc_miss": 10 - } + }, + "horizon": 24 }, - "keys": [], - "horizon": 24 + "genetic0": { + "horizon_hours": 24, + "individuals": 400, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + }, + "interval_sec": 3600, + "horizon": 24 + }, + "algorithms": [ + "GENETIC", + "GENETIC0" + ], + "keys": [] } } ``` -### General Genetic Optimization Algorithm Configuration +### GENETIC0 Optimization Algorithm Configuration -:::{table} optimization::genetic +:::{table} optimization::genetic0 :widths: 10 10 5 5 30 :align: left | Name | Type | Read-Only | Default | Description | | ---- | ---- | --------- | ------- | ----------- | | generations | `int | None` | `rw` | `400` | Number of generations to evolve [>= 10]. Defaults to 400. | +| horizon | `int` | `ro` | `N/A` | Number of optimization steps. | +| horizon_hours | `int` | `rw` | `24` | The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours. | | individuals | `int | None` | `rw` | `300` | Number of individuals (solutions) in the population [>= 10]. Defaults to 300. | +| interval_sec | `int` | `ro` | `N/A` | The optimization interval [sec]. Fixed to 1 hour (3600 seconds). | | penalties | `dict[str, float | int | str]` | `rw` | `required` | Penalty parameters used in fitness evaluation. | | seed | `int | None` | `rw` | `None` | Random seed for reproducibility. None = random. | ::: -**Example Input/Output** +**Example Input** ```json { "optimization": { - "genetic": { + "genetic0": { + "horizon_hours": 24, "individuals": 300, "generations": 400, "seed": null, @@ -102,3 +129,93 @@ } ``` + + +**Example Output** + + + +```json + { + "optimization": { + "genetic0": { + "horizon_hours": 24, + "individuals": 300, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + }, + "interval_sec": 3600, + "horizon": 24 + } + } + } +``` + + +### GENETIC Optimization Algorithm Configuration + + +:::{table} optimization::genetic +:widths: 10 10 5 5 30 +:align: left + +| Name | Type | Read-Only | Default | Description | +| ---- | ---- | --------- | ------- | ----------- | +| generations | `int | None` | `rw` | `400` | Number of generations to evolve [>= 10]. Defaults to 400. | +| horizon | `int` | `ro` | `N/A` | Number of optimization steps. | +| horizon_hours | `int` | `rw` | `24` | The general time window within which the energy optimization goal shall be achieved [h]. Defaults to 24 hours. | +| individuals | `int | None` | `rw` | `300` | Number of individuals (solutions) in the population [>= 10]. Defaults to 300. | +| interval_sec | `int` | `rw` | `3600` | The optimization interval [sec]. Defaults to 3600 seconds (1 hour) | +| penalties | `dict[str, float | int | str]` | `rw` | `required` | Penalty parameters used in fitness evaluation. | +| seed | `int | None` | `rw` | `None` | Random seed for reproducibility. None = random. | +::: + + + +**Example Input** + + + +```json + { + "optimization": { + "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, + "individuals": 300, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + } + } + } + } +``` + + + +**Example Output** + + + +```json + { + "optimization": { + "genetic": { + "interval_sec": 3600, + "horizon_hours": 24, + "individuals": 300, + "generations": 400, + "seed": null, + "penalties": { + "ev_soc_miss": 10 + }, + "horizon": 24 + } + } + } +``` + diff --git a/tests/testdata/eos_config_andreas_now.json b/tests/testdata/eos_config_andreas_now.json index 6068d90..c87cf45 100644 --- a/tests/testdata/eos_config_andreas_now.json +++ b/tests/testdata/eos_config_andreas_now.json @@ -38,7 +38,9 @@ ] }, "optimization": { - "horizon_hours": 48 + "genetic0": { + "horizon_hours": 48 + } }, "elecprice": { "provider": "ElecPriceAkkudoktor", @@ -79,4 +81,4 @@ "verbose": true, "eosdash_host": "0.0.0.0" } -} \ No newline at end of file +} diff --git a/tests/testdata/eos_config_minimal_now.json b/tests/testdata/eos_config_minimal_now.json index 73b2010..478fd41 100644 --- a/tests/testdata/eos_config_minimal_now.json +++ b/tests/testdata/eos_config_minimal_now.json @@ -6,7 +6,9 @@ "longitude": 13.4 }, "optimization": { - "horizon_hours": 48 + "genetic0": { + "horizon_hours": 48 + } }, "elecprice": { "provider": "ElecPriceImport", @@ -16,4 +18,4 @@ "host": "0.0.0.0", "eosdash_host": "0.0.0.0" } -} \ No newline at end of file +} diff --git a/tests/testdata/genetic0optimize_input_1.json b/tests/testdata/genetic0optimize_input_1.json new file mode 100644 index 0000000..86e5d04 --- /dev/null +++ b/tests/testdata/genetic0optimize_input_1.json @@ -0,0 +1,69 @@ +{ + "ems": { + "preis_euro_pro_wh_akku": 0.0001, + "einspeiseverguetung_euro_pro_wh": [ + 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, + 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, + 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, + 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, + 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, 0.00007, + 0.00007, 0.00007, 0.00007 + ], + "gesamtlast": [ + 676.71, 876.19, 527.13, 468.88, 531.38, 517.95, 483.15, 472.28, 1011.68, 995.00, + 1053.07, 1063.91, 1320.56, 1132.03, 1163.67, 1176.82, 1216.22, 1103.78, 1129.12, + 1178.71, 1050.98, 988.56, 912.38, 704.61, 516.37, 868.05, 694.34, 608.79, 556.31, + 488.89, 506.91, 804.89, 1141.98, 1056.97, 992.46, 1155.99, 827.01, 1257.98, 1232.67, + 871.26, 860.88, 1158.03, 1222.72, 1221.04, 949.99, 987.01, 733.99, 592.97 + ], + "pv_prognose_wh": [ + 0, 0, 0, 0, 0, 0, 0, 8.05, 352.91, 728.51, 930.28, 1043.25, 1106.74, 1161.69, + 6018.82, 5519.07, 3969.88, 3017.96, 1943.07, 1007.17, 319.67, 7.88, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 5.04, 335.59, 705.32, 1121.12, 1604.79, 2157.38, 1433.25, 5718.49, + 4553.96, 3027.55, 2574.46, 1720.4, 963.4, 383.3, 0, 0, 0 + ], + "strompreis_euro_pro_wh": [ + 0.0003384, 0.0003318, 0.0003284, 0.0003283, 0.0003289, 0.0003334, 0.0003290, + 0.0003302, 0.0003042, 0.0002430, 0.0002280, 0.0002212, 0.0002093, 0.0001879, + 0.0001838, 0.0002004, 0.0002198, 0.0002270, 0.0002997, 0.0003195, 0.0003081, + 0.0002969, 0.0002921, 0.0002780, 0.0003384, 0.0003318, 0.0003284, 0.0003283, + 0.0003289, 0.0003334, 0.0003290, 0.0003302, 0.0003042, 0.0002430, 0.0002280, + 0.0002212, 0.0002093, 0.0001879, 0.0001838, 0.0002004, 0.0002198, 0.0002270, + 0.0002997, 0.0003195, 0.0003081, 0.0002969, 0.0002921, 0.0002780 + ] + }, + "pv_akku": { + "device_id": "battery1", + "capacity_wh": 26400, + "max_charge_power_w": 5000, + "initial_soc_percentage": 80, + "min_soc_percentage": 15 + }, + "inverter": { + "device_id": "inverter1", + "max_power_wh": 10000, + "battery_id": "battery1" + }, + "eauto": { + "device_id": "ev1", + "capacity_wh": 60000, + "charging_efficiency": 0.95, + "discharging_efficiency": 1.0, + "max_charge_power_w": 11040, + "initial_soc_percentage": 54, + "min_soc_percentage": 0 + }, + "temperature_forecast": [ + 18.3, 17.8, 16.9, 16.2, 15.6, 15.1, 14.6, 14.2, 14.3, 14.8, 15.7, 16.7, 17.4, + 18.0, 18.6, 19.2, 19.1, 18.7, 18.5, 17.7, 16.2, 14.6, 13.6, 13.0, 12.6, 12.2, + 11.7, 11.6, 11.3, 11.0, 10.7, 10.2, 11.4, 14.4, 16.4, 18.3, 19.5, 20.7, 21.9, + 22.7, 23.1, 23.1, 22.8, 21.8, 20.2, 19.1, 18.0, 17.4 + ], + "start_solution": [ + 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, + 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 + ] +} + diff --git a/tests/testdata/genetic0optimize_input_2.json b/tests/testdata/genetic0optimize_input_2.json new file mode 100644 index 0000000..b7cb777 --- /dev/null +++ b/tests/testdata/genetic0optimize_input_2.json @@ -0,0 +1,231 @@ +{ + "ems": { + "preis_euro_pro_wh_akku": 0.0, + "einspeiseverguetung_euro_pro_wh": 0.00007, + "gesamtlast": [ + 676.71, + 876.19, + 527.13, + 468.88, + 531.38, + 517.95, + 483.15, + 472.28, + 1011.68, + 995.0, + 1053.07, + 1063.91, + 1320.56, + 1132.03, + 1163.67, + 1176.82, + 1216.22, + 1103.78, + 1129.12, + 1178.71, + 1050.98, + 988.56, + 912.38, + 704.61, + 516.37, + 868.05, + 694.34, + 608.79, + 556.31, + 488.89, + 506.91, + 804.89, + 1141.98, + 1056.97, + 992.46, + 1155.99, + 827.01, + 1257.98, + 1232.67, + 871.26, + 860.88, + 1158.03, + 1222.72, + 1221.04, + 949.99, + 987.01, + 733.99, + 592.97 + ], + "pv_prognose_wh": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 8.05, + 352.91, + 728.51, + 930.28, + 1043.25, + 1106.74, + 1161.69, + 6018.82, + 5519.07, + 3969.88, + 3017.96, + 1943.07, + 1007.17, + 319.67, + 7.88, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 5.04, + 335.59, + 705.32, + 1121.12, + 1604.79, + 2157.38, + 1433.25, + 5718.49, + 4553.96, + 3027.55, + 2574.46, + 1720.4, + 963.4, + 383.3, + 0, + 0, + 0 + ], + "strompreis_euro_pro_wh": [ + 0.0003384, + 0.0003318, + 0.0003284, + 0.0003283, + 0.0003289, + 0.0003334, + 0.000329, + 0.0003302, + 0.0003042, + 0.000243, + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278, + 0.0003384, + 0.0003318, + 0.0003284, + 0.0003283, + 0.0003289, + 0.0003334, + 0.000329, + 0.0003302, + 0.0003042, + 0.000243, + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278 + ] + }, + "pv_akku": { + "device_id": "battery1", + "capacity_wh": 26400, + "initial_soc_percentage": 80, + "min_soc_percentage": 0 + }, + "inverter": { + "device_id": "inverter1", + "max_power_wh": 10000, + "battery_id": "battery1" + }, + "eauto": { + "device_id": "ev1", + "capacity_wh": 60000, + "charging_efficiency": 0.95, + "max_charge_power_w": 11040, + "initial_soc_percentage": 5, + "min_soc_percentage": 80 + }, + "dishwasher": { + "device_id": "dishwasher1", + "consumption_wh": 5000, + "duration_h": 2 + }, + "temperature_forecast": [ + 18.3, + 17.8, + 16.9, + 16.2, + 15.6, + 15.1, + 14.6, + 14.2, + 14.3, + 14.8, + 15.7, + 16.7, + 17.4, + 18.0, + 18.6, + 19.2, + 19.1, + 18.7, + 18.5, + 17.7, + 16.2, + 14.6, + 13.6, + 13.0, + 12.6, + 12.2, + 11.7, + 11.6, + 11.3, + 11.0, + 10.7, + 10.2, + 11.4, + 14.4, + 16.4, + 18.3, + 19.5, + 20.7, + 21.9, + 22.7, + 23.1, + 23.1, + 22.8, + 21.8, + 20.2, + 19.1, + 18.0, + 17.4 + ], + "start_solution": null +} diff --git a/tests/testdata/genetic0optimize_result_1.json b/tests/testdata/genetic0optimize_result_1.json new file mode 100644 index 0000000..42f7052 --- /dev/null +++ b/tests/testdata/genetic0optimize_result_1.json @@ -0,0 +1,772 @@ +{ + "ac_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "dc_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "discharge_allowed": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + 1, + 0 + ], + "eautocharge_hours_float": null, + "result": { + "Last_Wh_pro_Stunde": [ + 1053.07, + 1063.91, + 1320.56, + 1132.03, + 1163.67, + 1176.82, + 1216.22, + 1103.78, + 1129.12, + 1178.71, + 1050.98, + 988.56, + 912.38, + 704.61, + 516.37, + 868.05, + 694.34, + 608.79, + 556.31, + 488.89, + 506.91, + 804.89, + 1141.98, + 1056.97, + 992.46, + 1155.99, + 827.01, + 1257.98, + 1232.67, + 871.26, + 860.88, + 1158.03, + 1222.72, + 1221.04, + 949.99, + 987.01, + 733.99, + 592.97 + ], + "EAuto_SoC_pro_Stunde": [ + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0 + ], + "Einnahmen_Euro_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.19391086083906173, + 0.18681973047764083, + 0.12880892587597292, + 0.02404700392596282, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.12500582038027028, + 0.14608958812480227, + 0.09047346757070289, + 0.010404817872487553, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Gesamt_Verluste": 2878.660271824896, + "Gesamtbilanz_Euro": 1.053854835771092, + "Gesamteinnahmen_Euro": 0.9055602150669013, + "Gesamtkosten_Euro": 1.9594150508379933, + "Home_appliance_wh_per_hour": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Kosten_Euro_pro_Stunde": [ + 0.0, + 0.004569992000000018, + 0.0, + 0.0, + 0.0, + 4.482711108977355e-14, + 0.0, + 0.016809914659344942, + 0.0, + 0.05480703000000003, + 0.0, + 0.291163892, + 0.0, + 0.0, + 0.0, + 0.0, + 0.22802125600000003, + 0.0, + 0.182970359, + 0.162995926, + 0.0, + 0.26411047, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.010682755832597498, + 0.0, + 0.0003442778967139274, + 0.0, + 0.028137079449292023, + 0.0, + 0.08231598, + 0.174597189, + 0.293043269, + 0.0, + 0.16484566 + ], + "Netzbezug_Wh_pro_Stunde": [ + 0.0, + 20.660000000000082, + 0.0, + 0.0, + 0.0, + 2.236881790906864e-10, + 0.0, + 74.05248748610107, + 0.0, + 171.54000000000008, + 0.0, + 980.68, + 0.0, + 0.0, + 0.0, + 0.0, + 694.34, + 0.0, + 556.31, + 488.89, + 0.0, + 799.85, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 56.853410498124, + 0.0, + 1.7179535764168035, + 0.0, + 123.95189184710142, + 0.0, + 257.64, + 566.69, + 987.01, + 0.0, + 592.97 + ], + "Netzeinspeisung_Wh_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2770.155154843739, + 2668.8532925377262, + 1840.127512513899, + 343.5286275137546, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1785.797434003861, + 2086.994116068604, + 1292.4781081528986, + 148.64025532125078, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Verluste_Pro_Stunde": [ + 16.744090909090914, + 0.0, + 29.157272727272726, + 3.7179773678125034, + 582.6180000000041, + 188.65138141872444, + 10.782457846871594, + 0.0, + 59.810111380126784, + 0.0, + 99.72409090909093, + 0.0, + 124.41545454545451, + 96.08318181818186, + 70.41409090909087, + 118.37045454545455, + 0.0, + 83.01681818181817, + 0.0, + 0.0, + 69.12409090909085, + 0.0, + 109.96227272727276, + 47.952272727272714, + 16.01263877609336, + 55.946263193163475, + 161.62968357967037, + 14.209990740225123, + 538.2984000000038, + 227.42215349036655, + 10.13011689299087, + 0.0, + 44.377460775206174, + 0.0, + 0.0, + 0.0, + 100.08954545454549, + 0.0 + ], + "akku_soc_pro_stunde": [ + 80.0, + 79.4714617768595, + 79.4714617768595, + 78.55109331955923, + 78.57585051614844, + 94.75968384947988, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 96.85214359504131, + 96.85214359504131, + 92.92488808539943, + 89.89195936639118, + 87.6692923553719, + 83.93285123966942, + 83.93285123966942, + 81.31237086776858, + 81.31237086776858, + 81.31237086776858, + 79.13042355371898, + 79.13042355371898, + 75.65939221763084, + 74.14574724517905, + 74.30696088041155, + 74.82732877552169, + 78.33526266026307, + 78.72998462526934, + 93.68271795860093, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 96.84060778236915 + ], + "Electricity_price": [ + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278, + 0.0003384, + 0.0003318, + 0.0003284, + 0.0003283, + 0.0003289, + 0.0003334, + 0.000329, + 0.0003302, + 0.0003042, + 0.000243, + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278 + ] + }, + "eauto_obj": { + "device_id": "ev1", + "hours": 48, + "charge_array": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "discharge_array": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "discharging_efficiency": 1.0, + "capacity_wh": 60000, + "charging_efficiency": 0.95, + "max_charge_power_w": 11040, + "soc_wh": 32400.000000000004, + "initial_soc_percentage": 54 + }, + "start_solution": [ + 1.0, + 1.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 2.0, + 1.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 2.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "washingstart": null +} \ No newline at end of file diff --git a/tests/testdata/genetic0optimize_result_1_be.json b/tests/testdata/genetic0optimize_result_1_be.json new file mode 100644 index 0000000..971025f --- /dev/null +++ b/tests/testdata/genetic0optimize_result_1_be.json @@ -0,0 +1,772 @@ +{ + "ac_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "dc_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "discharge_allowed": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0 + ], + "eautocharge_hours_float": null, + "result": { + "Last_Wh_pro_Stunde": [ + 1053.07, + 1063.91, + 1320.56, + 1132.03, + 1163.67, + 1176.82, + 1216.22, + 1103.78, + 1129.12, + 1178.71, + 1050.98, + 988.56, + 912.38, + 704.61, + 516.37, + 868.05, + 694.34, + 608.79, + 556.31, + 488.89, + 506.91, + 804.89, + 1141.98, + 1056.97, + 992.46, + 1155.99, + 827.01, + 1257.98, + 1232.67, + 871.26, + 860.88, + 1158.03, + 1222.72, + 1221.04, + 949.99, + 987.01, + 733.99, + 592.97 + ], + "EAuto_SoC_pro_Stunde": [ + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0, + 54.0 + ], + "Einnahmen_Euro_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.19478794541504615, + 0.18681973047764083, + 0.12880892587597292, + 0.02404700392596282, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.17104472158211628, + 0.14608958812480227, + 0.09047346757070289, + 0.010404817872487553, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Gesamt_Verluste": 2804.7326610375394, + "Gesamtbilanz_Euro": 0.9004618481798127, + "Gesamteinnahmen_Euro": 0.9524762008447317, + "Gesamtkosten_Euro": 1.8529380490245444, + "Home_appliance_wh_per_hour": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Kosten_Euro_pro_Stunde": [ + 0.0, + 0.004569992000000018, + 0.0, + 0.0018232052307313393, + 0.0, + 4.482711108977355e-14, + 0.0, + 0.016809914659344942, + 0.0, + 0.05480703000000003, + 0.0, + 0.291163892, + 0.0, + 0.19588158, + 0.174739608, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.16677339, + 0.0, + 0.24530383800000005, + 0.08545095, + 0.007989913613567745, + 0.028255713342252034, + 0.0, + 0.010682755832597498, + 0.0, + 0.0003442778967139274, + 0.0, + 0.028137079449292023, + 0.0, + 0.08231598, + 0.0, + 0.293043269, + 0.0, + 0.16484566 + ], + "Netzbezug_Wh_pro_Stunde": [ + 0.0, + 20.660000000000082, + 0.0, + 9.703061366318996, + 0.0, + 2.236881790906864e-10, + 0.0, + 74.05248748610107, + 0.0, + 171.54000000000008, + 0.0, + 980.68, + 0.0, + 704.61, + 516.37, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 506.91, + 0.0, + 806.3900000000001, + 351.65, + 35.04348076126204, + 127.73830624887898, + 0.0, + 56.853410498124, + 0.0, + 1.7179535764168035, + 0.0, + 123.95189184710142, + 0.0, + 257.64, + 0.0, + 987.01, + 0.0, + 592.97 + ], + "Netzeinspeisung_Wh_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2782.6849345006594, + 2668.8532925377262, + 1840.127512513899, + 343.5286275137546, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2443.4960226016615, + 2086.994116068604, + 1292.4781081528986, + 148.64025532125078, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Verluste_Pro_Stunde": [ + 16.744090909090914, + 0.0, + 29.157272727272726, + 2.3948326360417305, + 582.6180000000041, + 187.1478078598941, + 10.782457846871594, + 0.0, + 59.810111380126784, + 0.0, + 99.72409090909093, + 0.0, + 124.41545454545451, + 0.0, + 0.0, + 118.37045454545455, + 94.68272727272722, + 83.01681818181817, + 75.86045454545456, + 66.66681818181814, + 0.0, + 109.0704545454546, + 0.0, + 0.0, + 11.233982308648535, + 38.52740325013451, + 161.62968357967037, + 14.209990740225123, + 538.2984000000038, + 148.49832285863067, + 10.13011689299087, + 0.0, + 44.377460775206174, + 0.0, + 77.27590909090907, + 0.0, + 100.08954545454549, + 0.0 + ], + "akku_soc_pro_stunde": [ + 80.0, + 79.4714617768595, + 79.4714617768595, + 78.55109331955923, + 78.61761644833817, + 94.80144978166962, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 96.85214359504131, + 96.85214359504131, + 92.92488808539943, + 92.92488808539943, + 92.92488808539943, + 89.18844696969695, + 86.19972451790632, + 83.57924414600548, + 81.18465909090907, + 79.08027720385672, + 79.08027720385672, + 75.63739669421484, + 75.63739669421484, + 75.63739669421484, + 75.94945175834397, + 77.01965740418103, + 80.52759128892241, + 80.92231325392866, + 95.87504658726026, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 97.56073519283747, + 97.56073519283747, + 94.40134297520663 + ], + "Electricity_price": [ + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278, + 0.0003384, + 0.0003318, + 0.0003284, + 0.0003283, + 0.0003289, + 0.0003334, + 0.000329, + 0.0003302, + 0.0003042, + 0.000243, + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278 + ] + }, + "eauto_obj": { + "device_id": "ev1", + "hours": 48, + "charge_array": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "discharge_array": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "discharging_efficiency": 1.0, + "capacity_wh": 60000, + "charging_efficiency": 0.95, + "max_charge_power_w": 11040, + "soc_wh": 32400.000000000004, + "initial_soc_percentage": 54 + }, + "start_solution": [ + 1.0, + 1.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "washingstart": null +} \ No newline at end of file diff --git a/tests/testdata/genetic0optimize_result_2.json b/tests/testdata/genetic0optimize_result_2.json new file mode 100644 index 0000000..d00a3d7 --- /dev/null +++ b/tests/testdata/genetic0optimize_result_2.json @@ -0,0 +1,818 @@ +{ + "ac_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 0.0 + ], + "dc_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "discharge_allowed": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1 + ], + "eautocharge_hours_float": [ + 1.0, + 0.5, + 0.375, + 0.375, + 1.0, + 0.75, + 1.0, + 0.75, + 0.5, + 0.875, + 0.0, + 0.875, + 0.75, + 1.0, + 0.625, + 0.375, + 0.75, + 0.875, + 0.625, + 1.0, + 0.75, + 0.375, + 0.75, + 0.5, + 0.5, + 0.625, + 0.875, + 0.5, + 0.0, + 0.0, + 0.75, + 0.875, + 0.0, + 0.0, + 1.0, + 0.375, + 0.375, + 1.0, + 0.0, + 0.875, + 0.5, + 1.0, + 0.625, + 0.75, + 0.875, + 1.0, + 0.5, + 0.5 + ], + "result": { + "Last_Wh_pro_Stunde": [ + 1053.07, + 10240.91, + 14186.56, + 11620.03, + 11218.67, + 7609.82, + 9082.22, + 10280.78, + 2177.92, + 1178.71, + 1050.98, + 1988.56, + 912.38, + 1704.6100000000001, + 516.37, + 868.05, + 694.34, + 608.79, + 556.31, + 488.89, + 506.91, + 804.89, + 1141.98, + 1056.97, + 992.46, + 1155.99, + 827.01, + 1257.98, + 1232.67, + 871.26, + 860.88, + 1158.03, + 1222.72, + 1221.04, + 949.99, + 987.01, + 733.99, + 592.97 + ], + "EAuto_SoC_pro_Stunde": [ + 5.0, + 5.0, + 20.294999999999998, + 33.405, + 50.885000000000005, + 61.809999999999995, + 68.365, + 81.475, + 96.77, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518, + 98.518 + ], + "Einnahmen_Euro_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.010924611164505103, + 0.25751345302450973, + 0.14608958812480227, + 0.07926913850394514, + 0.010404817872487553, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Gesamt_Verluste": 5766.286846118221, + "Gesamtbilanz_Euro": 12.78299149726557, + "Gesamteinnahmen_Euro": 0.5042016086902498, + "Gesamtkosten_Euro": 13.28719310595582, + "Home_appliance_wh_per_hour": [ + 0.0, + 0.0, + 0.0, + 0.0, + 2500.0, + 2500.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Kosten_Euro_pro_Stunde": [ + 0.0, + 2.034522392, + 2.737606326, + 1.9651220859999998, + 0.9557324300000001, + 0.4189863, + 1.1236923319999998, + 1.64866014, + 0.07038454500000005, + 0.05480703000000003, + 0.0, + 0.588063892, + 0.0, + 0.47388158, + 0.174739608, + 0.28801899, + 0.0, + 0.0, + 0.0, + 0.0, + 0.16677339, + 0.0, + 0.0, + 0.0, + 0.007989913613567745, + 0.028255713342252034, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.08231598, + 0.174597189, + 0.293043269, + 0.0, + 0.0 + ], + "Netzbezug_Wh_pro_Stunde": [ + 0.0, + 9197.66, + 13079.82, + 10458.34, + 5199.85, + 2090.75, + 5112.339999999999, + 7262.820000000001, + 234.85000000000014, + 171.54000000000008, + 0.0, + 1980.6799999999998, + 0.0, + 1704.6100000000001, + 516.37, + 868.05, + 0.0, + 0.0, + 0.0, + 0.0, + 506.91, + 0.0, + 0.0, + 0.0, + 35.04348076126204, + 127.73830624887898, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 257.64, + 566.69, + 987.01, + 0.0, + 0.0 + ], + "Netzeinspeisung_Wh_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 156.06587377864435, + 3678.7636146358536, + 2086.994116068604, + 1132.4162643420734, + 148.64025532125078, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Verluste_Pro_Stunde": [ + 16.744090909090914, + 483.0, + 1014.0, + 552.0, + 465.0, + 207.0, + 414.0, + 483.0, + 55.200000000000045, + 0.0, + 99.72409090909093, + 120.0, + 124.41545454545451, + 120.0, + 0.0, + 0.0, + 94.68272727272722, + 83.01681818181817, + 75.86045454545456, + 66.66681818181814, + 0.0, + 109.0704545454546, + 109.96227272727276, + 47.952272727272714, + 11.233982308648535, + 38.52740325013451, + 161.62968357967037, + 21.962728535423857, + 519.5704951465664, + 0.5004782113116364, + 10.13011689299087, + 36.109951963721926, + 44.377460775206174, + 0.0, + 0.0, + 0.0, + 100.08954545454549, + 80.85954545454547 + ], + "akku_soc_pro_stunde": [ + 80.0, + 79.4714617768595, + 79.4714617768595, + 96.13812844352617, + 96.13812844352617, + 99.4714617768595, + 99.4714617768595, + 99.4714617768595, + 99.4714617768595, + 99.4714617768595, + 99.4714617768595, + 96.32360537190083, + 99.65693870523415, + 95.72968319559227, + 99.0630165289256, + 99.0630165289256, + 99.0630165289256, + 96.07429407713497, + 93.45381370523414, + 91.05922865013771, + 88.95484676308537, + 88.95484676308537, + 85.51196625344349, + 82.04093491735533, + 80.52728994490354, + 80.83934500903268, + 81.90955065486975, + 85.41748453961112, + 85.56748624593055, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 100.0, + 96.84060778236915 + ], + "Electricity_price": [ + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278, + 0.0003384, + 0.0003318, + 0.0003284, + 0.0003283, + 0.0003289, + 0.0003334, + 0.000329, + 0.0003302, + 0.0003042, + 0.000243, + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278 + ] + }, + "eauto_obj": { + "device_id": "ev1", + "hours": 48, + "charge_array": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.875, + 0.75, + 1.0, + 0.625, + 0.375, + 0.75, + 0.875, + 0.1, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "discharge_array": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "discharging_efficiency": 1.0, + "capacity_wh": 60000, + "charging_efficiency": 0.95, + "max_charge_power_w": 11040, + "soc_wh": 59110.8, + "initial_soc_percentage": 5 + }, + "start_solution": [ + 0.0, + 0.0, + 2.0, + 0.0, + 1.0, + 1.0, + 0.0, + 2.0, + 1.0, + 1.0, + 1.0, + 0.0, + 2.0, + 0.0, + 2.0, + 0.0, + 2.0, + 2.0, + 0.0, + 2.0, + 1.0, + 2.0, + 1.0, + 2.0, + 2.0, + 2.0, + 1.0, + 1.0, + 1.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 2.0, + 0.0, + 2.0, + 1.0, + 1.0, + 6.0, + 2.0, + 1.0, + 1.0, + 6.0, + 4.0, + 6.0, + 4.0, + 2.0, + 5.0, + 0.0, + 5.0, + 4.0, + 6.0, + 3.0, + 1.0, + 4.0, + 5.0, + 3.0, + 6.0, + 4.0, + 1.0, + 4.0, + 2.0, + 2.0, + 3.0, + 5.0, + 2.0, + 0.0, + 0.0, + 4.0, + 5.0, + 0.0, + 0.0, + 6.0, + 1.0, + 1.0, + 6.0, + 0.0, + 5.0, + 2.0, + 6.0, + 3.0, + 4.0, + 5.0, + 6.0, + 2.0, + 2.0, + 14.0 + ], + "washingstart": 14 +} \ No newline at end of file diff --git a/tests/testdata/genetic0optimize_result_2_be.json b/tests/testdata/genetic0optimize_result_2_be.json new file mode 100644 index 0000000..11781a0 --- /dev/null +++ b/tests/testdata/genetic0optimize_result_2_be.json @@ -0,0 +1,818 @@ +{ + "ac_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "dc_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "discharge_allowed": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + 0, + 1 + ], + "eautocharge_hours_float": [ + 0.625, + 0.375, + 0.5, + 1.0, + 1.0, + 0.75, + 0.5, + 0.375, + 0.375, + 0.625, + 0.75, + 0.875, + 0.625, + 0.625, + 0.625, + 1.0, + 0.375, + 0.625, + 0.875, + 0.0, + 0.5, + 0.0, + 0.0, + 0.5, + 0.875, + 0.625, + 0.75, + 0.5, + 0.375, + 0.375, + 0.75, + 0.625, + 1.0, + 0.375, + 0.625, + 0.625, + 0.0, + 0.5, + 0.875, + 0.375, + 0.5, + 0.875, + 0.5, + 0.875, + 0.75, + 0.625, + 0.75, + 0.0 + ], + "result": { + "Last_Wh_pro_Stunde": [ + 8919.07, + 10240.91, + 7875.5599999999995, + 7687.03, + 7718.67, + 11664.82, + 5149.22, + 6347.78, + 1129.12, + 8678.71, + 3550.98, + 988.56, + 912.38, + 704.61, + 516.37, + 868.05, + 5694.34, + 608.79, + 556.31, + 488.89, + 506.91, + 804.89, + 6141.98, + 1056.97, + 992.46, + 6155.99, + 827.01, + 1257.98, + 1232.67, + 871.26, + 860.88, + 1158.03, + 1222.72, + 1221.04, + 949.99, + 987.01, + 733.99, + 592.97 + ], + "EAuto_SoC_pro_Stunde": [ + 5.0, + 18.11, + 33.405, + 44.330000000000005, + 55.254999999999995, + 66.18, + 83.66, + 90.215, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955 + ], + "Einnahmen_Euro_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Gesamt_Verluste": 10674.660531928814, + "Gesamtbilanz_Euro": 14.366070195145795, + "Gesamteinnahmen_Euro": 0.0, + "Gesamtkosten_Euro": 14.366070195145795, + "Home_appliance_wh_per_hour": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2500.0, + 2500.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Kosten_Euro_pro_Stunde": [ + 0.81824412, + 1.061242392, + 0.49579402599999994, + 0.399351386, + 0.13127915000000007, + 1.2316083, + 0.259218932, + 0.7558691399999999, + 0.061530097476751734, + 2.4510570300000003, + 0.0, + 0.0, + 0.26650619799999997, + 0.19588158, + 0.13029273082161758, + 0.28801899, + 1.870021256, + 0.199865757, + 0.0, + 0.0, + 0.16677339, + 0.0, + 1.7663038380000002, + 0.08545095, + 0.007989913613567745, + 1.134255713342252, + 0.025392879919306634, + 0.010682755832597498, + 4.174095896658514e-14, + 0.0003442778967139274, + 0.0, + 0.0, + 0.04565364324294593, + 0.0, + 0.0, + 0.293043269, + 0.214398479, + 0.0 + ], + "Netzbezug_Wh_pro_Stunde": [ + 3588.79, + 4797.66, + 2368.8199999999997, + 2125.34, + 714.2500000000003, + 6145.75, + 1179.3400000000001, + 3329.8199999999997, + 205.30563055305882, + 7671.54, + 0.0, + 0.0, + 912.38, + 704.61, + 385.0258003002884, + 868.05, + 5694.34, + 608.79, + 0.0, + 0.0, + 506.91, + 0.0, + 5806.39, + 351.65, + 35.04348076126204, + 5127.738306248879, + 121.32288542430308, + 56.853410498124, + 2.270998855635753e-10, + 1.7179535764168035, + 0.0, + 0.0, + 152.3311419517715, + 0.0, + 0.0, + 987.01, + 733.99, + 0.0 + ], + "Netzeinspeisung_Wh_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Verluste_Pro_Stunde": [ + 1014.0, + 1083.0, + 945.0, + 945.0, + 479.4, + 552.0, + 207.0, + 276.0, + 73.03732433363291, + 600.0, + 440.6331818181816, + 133.72909090909081, + 0.0, + 0.0, + 17.910572686324315, + 0.0, + 600.0, + 0.0, + 75.86045454545456, + 66.66681818181814, + 0.0, + 109.0704545454546, + 600.0, + 0.0, + 11.233982308648535, + 638.5274032501345, + 145.08565374908358, + 14.209990740225123, + 538.2983999999728, + 441.7178455708299, + 260.56941082122324, + 171.99990368477063, + 41.441862965787436, + 35.132727272727266, + 77.27590909090907, + 0.0, + 0.0, + 80.85954545454547 + ], + "akku_soc_pro_stunde": [ + 80.0, + 61.06060606060606, + 42.12121212121212, + 23.18181818181818, + 4.242424242424243, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0288145648231377, + 18.695481231489804, + 4.786605542784571, + 0.5653589863107422, + 0.5653589863107422, + 0.5653589863107422, + 0.0, + 0.0, + 16.666666666666664, + 16.666666666666664, + 14.272081611570247, + 12.167699724517906, + 12.167699724517906, + 8.724819214876034, + 25.391485881542703, + 25.391485881542703, + 25.703540945671826, + 43.44041325817556, + 47.47057030676122, + 47.86529227176747, + 62.81802560510005, + 75.08796575984533, + 82.04461281340734, + 85.81933369454761, + 86.97049655470836, + 85.86150895140257, + 83.42224414424004, + 83.42224414424004, + 83.42224414424004 + ], + "Electricity_price": [ + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278, + 0.0003384, + 0.0003318, + 0.0003284, + 0.0003283, + 0.0003289, + 0.0003334, + 0.000329, + 0.0003302, + 0.0003042, + 0.000243, + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278 + ] + }, + "eauto_obj": { + "device_id": "ev1", + "hours": 48, + "charge_array": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.75, + 0.875, + 0.625, + 0.625, + 0.625, + 1.0, + 0.375, + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "discharge_array": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "discharging_efficiency": 1.0, + "capacity_wh": 60000, + "charging_efficiency": 0.95, + "max_charge_power_w": 11040, + "soc_wh": 59373.0, + "initial_soc_percentage": 5 + }, + "start_solution": [ + 2.0, + 2.0, + 0.0, + 0.0, + 2.0, + 0.0, + 0.0, + 2.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 0.0, + 0.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 1.0, + 1.0, + 2.0, + 0.0, + 1.0, + 1.0, + 0.0, + 1.0, + 2.0, + 0.0, + 0.0, + 2.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 0.0, + 1.0, + 1.0, + 0.0, + 0.0, + 1.0, + 3.0, + 1.0, + 2.0, + 6.0, + 6.0, + 4.0, + 2.0, + 1.0, + 1.0, + 3.0, + 4.0, + 5.0, + 3.0, + 3.0, + 3.0, + 6.0, + 1.0, + 3.0, + 5.0, + 0.0, + 2.0, + 0.0, + 0.0, + 2.0, + 5.0, + 3.0, + 4.0, + 2.0, + 1.0, + 1.0, + 4.0, + 3.0, + 6.0, + 1.0, + 3.0, + 3.0, + 0.0, + 2.0, + 5.0, + 1.0, + 2.0, + 5.0, + 2.0, + 5.0, + 4.0, + 3.0, + 4.0, + 0.0, + 19.0 + ], + "washingstart": 19 +} \ No newline at end of file diff --git a/tests/testdata/genetic0optimize_result_2_full.json b/tests/testdata/genetic0optimize_result_2_full.json new file mode 100644 index 0000000..357757c --- /dev/null +++ b/tests/testdata/genetic0optimize_result_2_full.json @@ -0,0 +1,818 @@ +{ + "ac_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "dc_charge": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "discharge_allowed": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ], + "eautocharge_hours_float": [ + 0.875, + 0.75, + 0.5, + 1.0, + 0.625, + 0.625, + 0.875, + 0.625, + 0.875, + 0.875, + 0.0, + 1.0, + 0.5, + 0.625, + 1.0, + 0.75, + 0.5, + 0.625, + 0.375, + 0.5, + 0.625, + 0.625, + 0.5, + 0.625, + 0.625, + 0.0, + 0.625, + 0.5, + 0.5, + 1.0, + 0.375, + 0.625, + 0.875, + 0.5, + 0.5, + 0.75, + 0.75, + 0.75, + 0.0, + 0.875, + 0.75, + 1.0, + 1.0, + 0.75, + 0.625, + 0.875, + 0.5, + 0.875 + ], + "result": { + "Last_Wh_pro_Stunde": [ + 1053.07, + 11551.91, + 6564.5599999999995, + 7687.03, + 14151.67, + 11542.82, + 6460.22, + 7658.78, + 5062.12, + 1178.71, + 1050.98, + 988.56, + 912.38, + 704.61, + 516.37, + 868.05, + 694.34, + 608.79, + 556.31, + 488.89, + 506.91, + 804.89, + 1141.98, + 1056.97, + 992.46, + 1155.99, + 827.01, + 1257.98, + 1232.67, + 871.26, + 860.88, + 1158.03, + 1222.72, + 1221.04, + 949.99, + 987.01, + 733.99, + 592.97 + ], + "EAuto_SoC_pro_Stunde": [ + 5.0, + 5.0, + 22.48, + 31.22, + 42.144999999999996, + 59.62499999999999, + 72.735, + 81.475, + 92.4, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955, + 98.955 + ], + "Einnahmen_Euro_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Gesamt_Verluste": 7647.623819992857, + "Gesamtbilanz_Euro": 7.824605715847156, + "Gesamteinnahmen_Euro": 0.0, + "Gesamtkosten_Euro": 7.824605715847156, + "Home_appliance_wh_per_hour": [ + 0.0, + 0.0, + 0.0, + 0.0, + 2500.0, + 2500.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Kosten_Euro_pro_Stunde": [ + 0.027996119999999992, + 1.351235592, + 1.1423217259999998, + 1.226111386, + 1.4948178300000001, + 1.2071595, + 0.0, + 1.0534661399999998, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.19588158, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01995551999999987, + 0.08545095, + 0.007989913613567745, + 0.012219458233588571, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Netzbezug_Wh_pro_Stunde": [ + 122.78999999999996, + 6108.66, + 5457.82, + 6525.34, + 8132.85, + 6023.75, + 0.0, + 4640.82, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 704.61, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 65.59999999999957, + 351.65, + 35.04348076126204, + 55.24167375040041, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Netzeinspeisung_Wh_pro_Stunde": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "Verluste_Pro_Stunde": [ + 0.0, + 1152.0, + 276.0, + 345.0, + 552.0, + 414.0, + 615.5918181818183, + 345.0, + 632.3249999999998, + 23.391818181818195, + 99.72409090909093, + 133.72909090909081, + 124.41545454545451, + 0.0, + 70.41409090909087, + 118.37045454545455, + 94.68272727272722, + 83.01681818181817, + 75.86045454545456, + 66.66681818181814, + 69.12409090909085, + 109.0704545454546, + 101.01681818181828, + 0.0, + 11.233982308648535, + 48.41330768174522, + 161.62968357967037, + 21.962728535423857, + 538.2984000000038, + 441.95211196761403, + 260.56941082122324, + 171.99990368477063, + 62.214291413756285, + 35.132727272727266, + 77.27590909090907, + 134.59227272727276, + 100.08954545454549, + 80.85954545454547 + ], + "akku_soc_pro_stunde": [ + 80.0, + 80.0, + 61.06060606060606, + 61.06060606060606, + 61.06060606060606, + 61.06060606060606, + 61.06060606060606, + 50.341167355371894, + 50.341167355371894, + 36.91550447658402, + 36.17712637741047, + 33.0292699724518, + 28.808023415977967, + 24.88076790633609, + 24.88076790633609, + 22.658100895316807, + 18.921659779614323, + 15.932937327823693, + 13.312456955922865, + 10.917871900826448, + 8.813490013774107, + 6.63154269972452, + 3.1886621900826473, + 0.0, + 0.0, + 0.3120550641291261, + 1.07020564583707, + 4.578139530578446, + 4.728141236897871, + 19.68087457022947, + 31.94341995234899, + 38.90006700591099, + 42.674787887051245, + 43.17025540478875, + 42.06126780148296, + 39.622002994320425, + 35.373509537020155, + 32.214117319389295 + ], + "Electricity_price": [ + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278, + 0.0003384, + 0.0003318, + 0.0003284, + 0.0003283, + 0.0003289, + 0.0003334, + 0.000329, + 0.0003302, + 0.0003042, + 0.000243, + 0.000228, + 0.0002212, + 0.0002093, + 0.0001879, + 0.0001838, + 0.0002004, + 0.0002198, + 0.000227, + 0.0002997, + 0.0003195, + 0.0003081, + 0.0002969, + 0.0002921, + 0.000278 + ] + }, + "eauto_obj": { + "device_id": "ev1", + "hours": 48, + "charge_array": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.5, + 0.625, + 1.0, + 0.75, + 0.5, + 0.625, + 0.375, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "discharge_array": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "discharging_efficiency": 1.0, + "capacity_wh": 60000, + "charging_efficiency": 0.95, + "max_charge_power_w": 11040, + "soc_wh": 59373.0, + "initial_soc_percentage": 5 + }, + "start_solution": [ + 0.0, + 0.0, + 2.0, + 1.0, + 0.0, + 1.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 5.0, + 4.0, + 2.0, + 6.0, + 3.0, + 3.0, + 5.0, + 3.0, + 5.0, + 5.0, + 0.0, + 6.0, + 2.0, + 3.0, + 6.0, + 4.0, + 2.0, + 3.0, + 1.0, + 2.0, + 3.0, + 3.0, + 2.0, + 3.0, + 3.0, + 0.0, + 3.0, + 2.0, + 2.0, + 6.0, + 1.0, + 3.0, + 5.0, + 2.0, + 2.0, + 4.0, + 4.0, + 4.0, + 0.0, + 5.0, + 4.0, + 6.0, + 6.0, + 4.0, + 3.0, + 5.0, + 2.0, + 5.0, + 14.0 + ], + "washingstart": 14 +} \ No newline at end of file