1 Commits

Author SHA1 Message Date
dependabot[bot]
c614d8878d build(deps): bump markdown-it-py from 3.0.0 to 4.0.0
Bumps [markdown-it-py](https://github.com/executablebooks/markdown-it-py) from 3.0.0 to 4.0.0.
- [Release notes](https://github.com/executablebooks/markdown-it-py/releases)
- [Changelog](https://github.com/executablebooks/markdown-it-py/blob/master/CHANGELOG.md)
- [Commits](https://github.com/executablebooks/markdown-it-py/compare/v3.0.0...v4.0.0)

---
updated-dependencies:
- dependency-name: markdown-it-py
  dependency-version: 4.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-04 23:31:13 +00:00
32 changed files with 1466 additions and 2157 deletions

View File

@@ -5,142 +5,79 @@ All notable changes to the akkudoktoreos project will be documented in this file
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 0.2.0 (2025-11-09) ## 0.1.0+dev (2025-10-26)
The most important new feature is **automatic optimization**. ### feat
EOS can now independently perform optimization at regular intervals. - setup default device configuration for automatic optimization
This is based on the configured system parameters and forecasts, and also uses supplied - allow configuration of genetic algorithm parameters
measurement data, such as the current battery SoC. - allow configuration of home appliance time windows
The result is an energy-management plan as well as the optimization output. - mitigate old config
The existing optimization interface using `POST /optimize` remains available and can still - standardize measurement keys for battery/EV SoC measurements
be used as before. - feed-in tariff prediction support (incl. tests and docs)
- energy management plan generation based on S2 standard instructions
- make measurement keys configurable through EOS configuration
- use pendulum types with pydantic via pydantic_extra_types.pendulum_dt
- add Time, TimeWindow, TimeWindowSequence and to_time to datetimeutil
- extend DataRecord with configurable field-like data
- enrich health endpoints with version and optimization timestamps
- add pydantic merge model tests
- add plan tab to EOSdash
- add predictions tab to EOSdash
- add cache management to EOSdash admin tab
- add about tab to EOSdash
- adapt changelog & documentation for commitizen release flow
- improve install and development documentation
In addition, bugs were fixed and new features were added: ### fix
- automatic optimization (interval execution, locking, new endpoints)
- Automatic optimization creates a **default configuration** if none is provided. - recognize environment variables on EOS server startup
This is intended to make it easier to create a custom configuration by adapting the default. - remove 0.0.0.0 → localhost translation on Windows
- The parameters of the genetic optimization algorithm (number of generations, etc.) are now - allow hostnames as well as IPs
configurable. - access pydantic model fields via class instead of instance
- For home appliances, start windows can now be specified (experimental). - downsampling in key_to_array
- Configuration files from previous versions are converted to the current format on first launch. - /v1/admin/cache/clear now clears all cache files; new /clear-expired endpoint
- There are now measurement keys that are permanently assigned to a specific device simulation. - replace timezonefinder with tzfpy for accurate European timezones
This simplifies providing measurement values for device simulations (e.g. battery SoC). - explicit provider settings in config versus union
- The infrastructure and first applications for **feed-in tariff forecasting**
(currently only fixed tariffs) are now integrated.
- EOSdash has been expanded with new tabs for displaying the **energy-management plan**
and **predictions**.
- The documentation has been updated and expanded in many places.
### Feat
- Energy-management plan generation based on S2 standard instructions
- Feed-in-tariff prediction support (incl. tests & docs)
- `LoadAkkudoktorAdjusted` load prediction variant
- Standardized measurement keys for battery/EV SoC
- Measurement keys configurable via EOS configuration
- Setup default device configuration for automatic optimization
- Health endpoints show version + last optimization timestamps
- Configuration of genetic algorithm parameters
- Configuration options for home-appliance time windows
- Mitigation of legacy configuration
- Config backup enhancements:
- Timestamp-based backup IDs
- API to list backups
- API to revert to a specific backup
- EOSdash Admin tab integration
- Pendulum date types via `pydantic_extra_types.pendulum_dt`
- `Time`, `TimeWindow`, `TimeWindowSequence`, and `to_time` helpers in `datetimeutil`
- Extended `DataRecord` with configurable field-like semantics
- EOSdash: Solution view now displays genetic optimization results and aggregated totals
- EOSdash UI:
- Plan tab
- Predictions tab
- Cache management in Admin tab
- About tab
- Pydantic merge model tests
- Developer profiling entry in Makefile
- Changelog & docs updated for commitizen release flow
- Developer documentation updated
- Improved install & development documentation
### Changed
- Battery simulation
- Performance improvements
- Charge + start times now reflect realistic simulation
- Appliance simulation:
- Time windows may roll over to next day
- Revised load prediction by splitting original `LoadAkkudoktor` into:
- `LoadAkkudoktor`
- `LoadAkkudoktorAdjusted`
### Fixed
- Correct URL/path for Akkudoktor forum in README
- Automatic optimization:
- Reuses previous start solution
- Interval execution + locking + new endpoints
- Properly loads required data
- EV charge-rate migration for proper availability
- Genetic common settings consistently available
- Config markdown generation
- Recognize environment variables on EOS server startup
- Remove `0.0.0.0 → localhost` translation on Windows
- Allow hostnames as well as IPs
- Access Pydantic model fields via class instead of instance
- Down-sampling in `key_to_array`
- `/v1/admin/cache/clear` clears all cache files; added `/clear-expired`
- Use `tzfpy` instead of timezonefinder for more accurate EU timezones
- Explicit provider settings in config instead of union
- ClearOutside weather prediction irradiance calculation - ClearOutside weather prediction irradiance calculation
- Test config file priority without `config_eos` fixture - test config file priority without config_eos fixture
- Complete optimization sample-request documentation - complete optimization sample request documentation
- Replace gitlint with commitizen - replace gitlint with commitizen
- Synchronize pre-commit config with real dependencies - synchronize pre-commit config with real dependencies
- Add missing `babel` to requirements - add missing babel to requirements
- Fix documentation, tests, and implementation around optimization + predictions - fix documentation, tests, and implementation around optimization and predictions
### Chore ### chore
- use memory cache for inverter interpolation
- refactor genetic algorithm modules (split config, remove device singleton)
- rename memory cache to CacheEnergyManagementStore
- use class properties for config/ems/prediction mixins
- skip matplotlib debug logs
- auto-sync Bokeh JS CDN version
- rename hello.py to about.py in EOSdash
- remove demo page from EOSdash
- split server test for system test
- move doc utils to generate_config_md.py
- improve documentation for pydantic merge models
- remove pendulum warning from README
- drop GitHub Discussions from contributing docs
- bump version to 0.1.0+dev
- rename or reorganize files/classes during refactoring
- Use memory cache for inverter interpolation ### build
- Refactor genetic modules (split config, remove device singleton) - bump fastapi[standard] 0.115.14 → 0.117.1 and fix pytest-cov version
- Rename memory cache to `CacheEnergyManagementStore` - bump uvicorn 0.36.0 → 0.37.0
- Use class properties for config/EMS/prediction mixins
- Skip matplotlib debug logs
- Auto-sync Bokeh JS CDN version
- Rename `hello.py``about.py` in EOSdash
- Remove EOSdash demo page
- Split server test from system test
- Move doc utils to `generate_config_md.py`
- Improve documentation for pydantic merge models
- Remove pendulum warning from README
- Drop GitHub Discussions from contributing docs
- Rename or reorganize files / classes during refactors
### BREAKING CHANGES ### BREAKING CHANGE
EOS configuration and v1 API were changed:
EOS configuration + v1 API have changed: - available_charge_rates_percent removed; replaced by new charge_rate config
- optimization param hours renamed to horizon_hours
- `available_charge_rates_percent` removed → replaced by `charge_rate` - device config must now list devices and their properties explicitly
- Optimization parameter `hours` → renamed to `horizon_hours` - specific prediction provider configuration versus union
- Device config must explicitly list devices + properties - measurement keys provided as lists
- Prediction providers now explicit (instead of union) - new feed-in tariff providers must be configured
- Measurement keys provided as lists - /v1/measurement/loadxxx endpoints removed (use generic measurement endpoints)
- Feed-in-tariff providers must be explicitly configured - /v1/admin/cache/clear clears all cache files; use /v1/admin/cache/clear-expired for expired-only clearing
- `/v1/measurement/loadxxx` endpoints removed → use generic measurement endpoints
- `/v1/admin/cache/clear` now clears **all*- cache files;
`/v1/admin/cache/clear-expired` only clears expired entries
## v0.1.0 (2025-09-30) ## v0.1.0 (2025-09-30)

View File

@@ -162,15 +162,7 @@ docker-build:
@docker compose build --pull @docker compose build --pull
# Bump Akkudoktoreos version # Bump Akkudoktoreos version
VERSION ?= 0.2.0
NEW_VERSION ?= $(VERSION)+dev
bump: pip-dev bump: pip-dev
@echo "Bumping akkudoktoreos version from $(VERSION) to $(NEW_VERSION) (dry-run: $(EXTRA_ARGS))" @echo "Bumping akkudoktoreos version to release version"
.venv/bin/python scripts/convert_lightweight_tags.py .venv/bin/python scripts/convert_lightweight_tags.py
.venv/bin/python scripts/bump_version.py $(VERSION) $(NEW_VERSION) $(EXTRA_ARGS) .venv/bin/cz bump
bump-dry: pip-dev
@echo "Bumping akkudoktoreos version from $(VERSION) to $(NEW_VERSION) (dry-run: --dry-run)"
.venv/bin/python scripts/convert_lightweight_tags.py
.venv/bin/python scripts/bump_version.py $(VERSION) $(NEW_VERSION) --dry-run

View File

@@ -1,5 +1,4 @@
![AkkudoktorEOS](./docs/_static/logo.png#gh-light-mode-only) ![AkkudoktorEOS](docs/_static/logo.png)
![AkkudoktorEOS](./docs/_static/logo_dark.png#gh-dark-mode-only)
**Build optimized energy management plans for your home automation** **Build optimized energy management plans for your home automation**

View File

@@ -21,7 +21,7 @@ Properties:
| Name | Environment Variable | Type | Read-Only | Default | Description | | Name | Environment Variable | Type | Read-Only | Default | Description |
| ---- | -------------------- | ---- | --------- | ------- | ----------- | | ---- | -------------------- | ---- | --------- | ------- | ----------- |
| version | `EOS_GENERAL__VERSION` | `str` | `rw` | `0.2.0` | Configuration file version. Used to check compatibility. | | version | `EOS_GENERAL__VERSION` | `str` | `rw` | `0.1.0+dev` | Configuration file version. Used to check compatibility. |
| data_folder_path | `EOS_GENERAL__DATA_FOLDER_PATH` | `Optional[pathlib.Path]` | `rw` | `None` | Path to EOS data directory. | | data_folder_path | `EOS_GENERAL__DATA_FOLDER_PATH` | `Optional[pathlib.Path]` | `rw` | `None` | Path to EOS data directory. |
| data_output_subpath | `EOS_GENERAL__DATA_OUTPUT_SUBPATH` | `Optional[pathlib.Path]` | `rw` | `output` | Sub-path for the EOS output data directory. | | data_output_subpath | `EOS_GENERAL__DATA_OUTPUT_SUBPATH` | `Optional[pathlib.Path]` | `rw` | `output` | Sub-path for the EOS output data directory. |
| latitude | `EOS_GENERAL__LATITUDE` | `Optional[float]` | `rw` | `52.52` | Latitude in decimal degrees, between -90 and 90, north is positive (ISO 19115) (°) | | latitude | `EOS_GENERAL__LATITUDE` | `Optional[float]` | `rw` | `52.52` | Latitude in decimal degrees, between -90 and 90, north is positive (ISO 19115) (°) |
@@ -39,7 +39,7 @@ Properties:
{ {
"general": { "general": {
"version": "0.2.0", "version": "0.1.0+dev",
"data_folder_path": null, "data_folder_path": null,
"data_output_subpath": "output", "data_output_subpath": "output",
"latitude": 52.52, "latitude": 52.52,
@@ -55,7 +55,7 @@ Properties:
{ {
"general": { "general": {
"version": "0.2.0", "version": "0.1.0+dev",
"data_folder_path": null, "data_folder_path": null,
"data_output_subpath": "output", "data_output_subpath": "output",
"latitude": 52.52, "latitude": 52.52,
@@ -195,7 +195,7 @@ Properties:
"levelized_cost_of_storage_kwh": 0.0, "levelized_cost_of_storage_kwh": 0.0,
"max_charge_power_w": 5000, "max_charge_power_w": 5000,
"min_charge_power_w": 50, "min_charge_power_w": 50,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 0, "min_soc_percentage": 0,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "battery1-soc-factor", "measurement_key_soc_factor": "battery1-soc-factor",
@@ -222,7 +222,7 @@ Properties:
"levelized_cost_of_storage_kwh": 0.0, "levelized_cost_of_storage_kwh": 0.0,
"max_charge_power_w": 5000, "max_charge_power_w": 5000,
"min_charge_power_w": 50, "min_charge_power_w": 50,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 0, "min_soc_percentage": 0,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "battery1-soc-factor", "measurement_key_soc_factor": "battery1-soc-factor",
@@ -264,7 +264,7 @@ Properties:
"levelized_cost_of_storage_kwh": 0.0, "levelized_cost_of_storage_kwh": 0.0,
"max_charge_power_w": 5000, "max_charge_power_w": 5000,
"min_charge_power_w": 50, "min_charge_power_w": 50,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 0, "min_soc_percentage": 0,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "battery1-soc-factor", "measurement_key_soc_factor": "battery1-soc-factor",
@@ -291,7 +291,7 @@ Properties:
"levelized_cost_of_storage_kwh": 0.0, "levelized_cost_of_storage_kwh": 0.0,
"max_charge_power_w": 5000, "max_charge_power_w": 5000,
"min_charge_power_w": 50, "min_charge_power_w": 50,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 0, "min_soc_percentage": 0,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "battery1-soc-factor", "measurement_key_soc_factor": "battery1-soc-factor",
@@ -601,7 +601,7 @@ Properties:
| levelized_cost_of_storage_kwh | `float` | `rw` | `0.0` | Levelized cost of storage (LCOS), the average lifetime cost of delivering one kWh [€/kWh]. | | levelized_cost_of_storage_kwh | `float` | `rw` | `0.0` | Levelized cost of storage (LCOS), the average lifetime cost of delivering one kWh [€/kWh]. |
| max_charge_power_w | `Optional[float]` | `rw` | `5000` | Maximum charging power [W]. | | max_charge_power_w | `Optional[float]` | `rw` | `5000` | Maximum charging power [W]. |
| min_charge_power_w | `Optional[float]` | `rw` | `50` | Minimum charging power [W]. | | min_charge_power_w | `Optional[float]` | `rw` | `50` | Minimum charging power [W]. |
| charge_rates | `Optional[numpydantic.vendor.npbase_meta_classes.NDArray]` | `rw` | `[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]` | Charge rates as factor of maximum charging power [0.00 ... 1.00]. None triggers fallback to default charge-rates. | | charge_rates | `Optional[list[float]]` | `rw` | `None` | Charge rates as factor of maximum charging power [0.00 ... 1.00]. None denotes all charge rates are available. |
| min_soc_percentage | `int` | `rw` | `0` | Minimum state of charge (SOC) as percentage of capacity [%]. This is the target SoC for charging | | min_soc_percentage | `int` | `rw` | `0` | Minimum state of charge (SOC) as percentage of capacity [%]. This is the target SoC for charging |
| max_soc_percentage | `int` | `rw` | `100` | Maximum state of charge (SOC) as percentage of capacity [%]. | | max_soc_percentage | `int` | `rw` | `100` | Maximum state of charge (SOC) as percentage of capacity [%]. |
| measurement_key_soc_factor | `str` | `ro` | `N/A` | Measurement key for the battery state of charge (SoC) as factor of total capacity [0.0 ... 1.0]. | | measurement_key_soc_factor | `str` | `ro` | `N/A` | Measurement key for the battery state of charge (SoC) as factor of total capacity [0.0 ... 1.0]. |
@@ -630,7 +630,13 @@ Battery SoC, power. |
"levelized_cost_of_storage_kwh": 0.12, "levelized_cost_of_storage_kwh": 0.12,
"max_charge_power_w": 5000.0, "max_charge_power_w": 5000.0,
"min_charge_power_w": 50.0, "min_charge_power_w": 50.0,
"charge_rates": "[0. 0.25 0.5 0.75 1. ]", "charge_rates": [
0.0,
0.25,
0.5,
0.75,
1.0
],
"min_soc_percentage": 10, "min_soc_percentage": 10,
"max_soc_percentage": 100 "max_soc_percentage": 100
}, },
@@ -642,7 +648,7 @@ Battery SoC, power. |
"levelized_cost_of_storage_kwh": 0.12, "levelized_cost_of_storage_kwh": 0.12,
"max_charge_power_w": 5000.0, "max_charge_power_w": 5000.0,
"min_charge_power_w": 50.0, "min_charge_power_w": 50.0,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 10, "min_soc_percentage": 10,
"max_soc_percentage": 100 "max_soc_percentage": 100
}, },
@@ -654,7 +660,7 @@ Battery SoC, power. |
"levelized_cost_of_storage_kwh": 0.12, "levelized_cost_of_storage_kwh": 0.12,
"max_charge_power_w": 5000.0, "max_charge_power_w": 5000.0,
"min_charge_power_w": 50.0, "min_charge_power_w": 50.0,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 10, "min_soc_percentage": 10,
"max_soc_percentage": 100 "max_soc_percentage": 100
}, },
@@ -666,7 +672,7 @@ Battery SoC, power. |
"levelized_cost_of_storage_kwh": 0.12, "levelized_cost_of_storage_kwh": 0.12,
"max_charge_power_w": 5000.0, "max_charge_power_w": 5000.0,
"min_charge_power_w": 50.0, "min_charge_power_w": 50.0,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 10, "min_soc_percentage": 10,
"max_soc_percentage": 100 "max_soc_percentage": 100
} }
@@ -691,7 +697,13 @@ Battery SoC, power. |
"levelized_cost_of_storage_kwh": 0.12, "levelized_cost_of_storage_kwh": 0.12,
"max_charge_power_w": 5000.0, "max_charge_power_w": 5000.0,
"min_charge_power_w": 50.0, "min_charge_power_w": 50.0,
"charge_rates": "[0. 0.25 0.5 0.75 1. ]", "charge_rates": [
0.0,
0.25,
0.5,
0.75,
1.0
],
"min_soc_percentage": 10, "min_soc_percentage": 10,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "battery1-soc-factor", "measurement_key_soc_factor": "battery1-soc-factor",
@@ -715,7 +727,7 @@ Battery SoC, power. |
"levelized_cost_of_storage_kwh": 0.12, "levelized_cost_of_storage_kwh": 0.12,
"max_charge_power_w": 5000.0, "max_charge_power_w": 5000.0,
"min_charge_power_w": 50.0, "min_charge_power_w": 50.0,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 10, "min_soc_percentage": 10,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "ev1-soc-factor", "measurement_key_soc_factor": "ev1-soc-factor",
@@ -739,7 +751,7 @@ Battery SoC, power. |
"levelized_cost_of_storage_kwh": 0.12, "levelized_cost_of_storage_kwh": 0.12,
"max_charge_power_w": 5000.0, "max_charge_power_w": 5000.0,
"min_charge_power_w": 50.0, "min_charge_power_w": 50.0,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 10, "min_soc_percentage": 10,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "inverter1-soc-factor", "measurement_key_soc_factor": "inverter1-soc-factor",
@@ -763,7 +775,7 @@ Battery SoC, power. |
"levelized_cost_of_storage_kwh": 0.12, "levelized_cost_of_storage_kwh": 0.12,
"max_charge_power_w": 5000.0, "max_charge_power_w": 5000.0,
"min_charge_power_w": 50.0, "min_charge_power_w": 50.0,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 10, "min_soc_percentage": 10,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "dishwasher-soc-factor", "measurement_key_soc_factor": "dishwasher-soc-factor",
@@ -1780,7 +1792,7 @@ Validators:
{ {
"general": { "general": {
"version": "0.2.0", "version": "0.1.0+dev",
"data_folder_path": null, "data_folder_path": null,
"data_output_subpath": "output", "data_output_subpath": "output",
"latitude": 52.52, "latitude": 52.52,
@@ -1809,7 +1821,7 @@ Validators:
"levelized_cost_of_storage_kwh": 0.0, "levelized_cost_of_storage_kwh": 0.0,
"max_charge_power_w": 5000, "max_charge_power_w": 5000,
"min_charge_power_w": 50, "min_charge_power_w": 50,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 0, "min_soc_percentage": 0,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "battery1-soc-factor", "measurement_key_soc_factor": "battery1-soc-factor",
@@ -1836,7 +1848,7 @@ Validators:
"levelized_cost_of_storage_kwh": 0.0, "levelized_cost_of_storage_kwh": 0.0,
"max_charge_power_w": 5000, "max_charge_power_w": 5000,
"min_charge_power_w": 50, "min_charge_power_w": 50,
"charge_rates": "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]", "charge_rates": null,
"min_soc_percentage": 0, "min_soc_percentage": 0,
"max_soc_percentage": 100, "max_soc_percentage": 100,
"measurement_key_soc_factor": "battery1-soc-factor", "measurement_key_soc_factor": "battery1-soc-factor",

View File

@@ -1,6 +1,6 @@
# Akkudoktor-EOS # Akkudoktor-EOS
**Version**: `v0.2.0` **Version**: `v0.1.0+dev`
**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. **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.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

View File

@@ -138,16 +138,16 @@ This method is recommended for users who want a stable, tested version.
### 1) Download the Latest Release (M2) ### 1) Download the Latest Release (M2)
Visit the [Releases page](https://github.com/Akkudoktor-EOS/EOS/tags) and download the latest Visit the [Releases page](https://github.com/Akkudoktor-EOS/EOS/tags) and download the latest
release package (e.g., `akkudoktoreos-v0.2.0.tar.gz` or `akkudoktoreos-v0.2.0.zip`). release package (e.g., `akkudoktoreos-v0.1.0.tar.gz` or `akkudoktoreos-v0.1.0.zip`).
### 2) Extract the Package (M2) ### 2) Extract the Package (M2)
```bash ```bash
tar -xzf akkudoktoreos-v0.2.0.tar.gz # For .tar.gz tar -xzf akkudoktoreos-v0.1.0.tar.gz # For .tar.gz
# or # or
unzip akkudoktoreos-v0.2.0.zip # For .zip unzip akkudoktoreos-v0.1.0.zip # For .zip
cd akkudoktoreos-v0.2.0 cd akkudoktoreos-v0.1.0
``` ```
### 3) Create a virtual environment and run and configure EOS (M2) ### 3) Create a virtual environment and run and configure EOS (M2)

View File

@@ -4,7 +4,7 @@
# Release Process # Release Process
This document describes how to prepare and publish a new release **via a Pull Request from a fork**, This document describes how to prepare and publish a new release **via a Pull Request from a fork**,
and how to set a **development version** after the release. using **Commitizen** to manage versioning and changelogs — and how to set a **development version** after the release.
## ✅ Overview of the Process ## ✅ Overview of the Process
@@ -20,7 +20,7 @@ and how to set a **development version** after the release.
### 1⃣ Contributor: Prepare the Release in Your Fork ### 1⃣ Contributor: Prepare the Release in Your Fork
#### Clone and sync your fork **Clone and sync your fork:**
```bash ```bash
git clone https://github.com/<your-username>/EOS git clone https://github.com/<your-username>/EOS
@@ -32,50 +32,25 @@ git checkout main
git pull eos main git pull eos main
```` ````
#### Create the release branch **Create the release branch:**
```bash ```bash
git checkout -b release/vX.Y.Z git checkout -b release/vX.Y.Z
``` ```
#### Bump the version information **Run Commitizen to bump version and update changelog:**
At least update
- pyproject.toml
- src/akkudoktoreos/core/version.py
- src/akkudoktoreos/data/default.config.json
- Makefile
and the generated documentation:
```bash ```bash
make bump VERSION=0.1.0+dev NEW_VERSION=X.Y.Z make bump
make gen-docs
``` ```
You may check the changes by: > ✅ This updates version files and `CHANGELOG.md` in a single commit.
> 🚫 **Do not push tags** — tags are created by the maintainer via GitHub Releases.
**Push the branch to your fork:**
```bash ```bash
git diff git push origin release/vX.Y.Z
```
#### Create a new CHANGELOG.md entry
Edit CHANGELOG.md
#### Create the new release commit
```bash
git add pyproject.toml src/akkudoktoreos/core/version.py \
src/akkudoktoreos/data/default.config.json Makefile CHANGELOG.md
git commit -s -m "chore(release): Release vX.Y.Z"
```
#### Push the branch to your fork
```bash
git push --set-upstream origin release/vX.Y.Z
``` ```
### 2⃣ Contributor: Open the Release Pull Request ### 2⃣ Contributor: Open the Release Pull Request
@@ -87,7 +62,7 @@ git push --set-upstream origin release/vX.Y.Z
**PR Title:** **PR Title:**
```text ```text
chore(release): release vX.Y.Z Release vX.Y.Z
``` ```
**PR Description Template:** **PR Description Template:**
@@ -98,7 +73,7 @@ chore(release): release vX.Y.Z
This pull request prepares release **vX.Y.Z**. This pull request prepares release **vX.Y.Z**.
### Changes ### Changes
- Version bump - Version bump via Commitizen
- Changelog update - Changelog update
### Changelog Summary ### Changelog Summary
@@ -111,15 +86,15 @@ See `CHANGELOG.md` for full details.
**Review Checklist:** **Review Checklist:**
- ✅ Only version files and `CHANGELOG.md` are modified * ✅ Only version files and `CHANGELOG.md` are modified
- ✅ Version numbers are consistent * ✅ Version numbers are consistent
- ✅ Changelog is complete and properly formatted * ✅ Changelog is complete and properly formatted
- ✅ No unrelated changes are included * ✅ No unrelated changes are included
**Merge Strategy:** **Merge Strategy:**
- Prefer **Merge Commit** (or **Squash Merge**, per project preference) * Prefer **Merge Commit** (or **Squash Merge**, per project preference)
- Use commit message: `chore(release): Release vX.Y.Z` * Use commit message: `Release vX.Y.Z`
### 4⃣ Maintainer: Publish the GitHub Release ### 4⃣ Maintainer: Publish the GitHub Release
@@ -146,21 +121,21 @@ git pull eos main
git checkout -b release/vX.Y.Z_dev git checkout -b release/vX.Y.Z_dev
``` ```
**Set development version marker manually:** **Set development marker manually:**
The following files have to be updated:
* pyproject.toml
* src/akkudoktoreos/core/version.py
* src/data/default.config.json
Example for pyproject.toml
```bash ```bash
make bump VERSION=X.Y.Z NEW_VERSION=X.Y.Z+dev sed -i 's/version = "\(.*\)"/version = "\1+dev"/' pyproject.toml
make gen-docs git add pyproject.toml
``` git commit -m "chore: set development version marker"
git push origin release/vX.Y.Z_dev
```bash
git add pyproject.toml src/akkudoktoreos/core/version.py \
src/akkudoktoreos/data/default.config.json Makefile
git commit -s -m "chore: set development version marker X.Y.Z+dev"
```
```bash
git push --set-upstream origin release/vX.Y.Z_dev
``` ```
### 6⃣ Maintainer (or Contributor): Open the Development Version PR ### 6⃣ Maintainer (or Contributor): Open the Development Version PR
@@ -172,13 +147,13 @@ git push --set-upstream origin release/vX.Y.Z_dev
**PR Title:** **PR Title:**
```text ```text
chore: development version vX.Y.Z+dev Release vX.Y.Z+dev
``` ```
**PR Description Template:** **PR Description Template:**
```markdown ```markdown
## Development version vX.Y.Z+dev ## Release vX.Y.Z_dev
This pull request marks the repository as back in active development. This pull request marks the repository as back in active development.
@@ -192,12 +167,12 @@ No changelog entry is needed.
**Checklist:** **Checklist:**
- ✅ Only version files updated to `+dev` * ✅ Only version files updated to `+dev`
- ✅ No unintended changes * ✅ No unintended changes
**Merge Strategy:** **Merge Strategy:**
- Merge with commit message: `chore: development version vX.Y.Z+dev` * Merge with commit message: `Release vX.Y.Z_dev`
## ✅ Quick Reference ## ✅ Quick Reference

View File

@@ -3,7 +3,7 @@
"info": { "info": {
"title": "Akkudoktor-EOS", "title": "Akkudoktor-EOS",
"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.", "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.",
"version": "v0.2.0" "version": "v0.1.0+dev"
}, },
"paths": { "paths": {
"/v1/admin/cache/clear": { "/v1/admin/cache/clear": {
@@ -2122,7 +2122,7 @@
} }
], ],
"title": "Charge Rates", "title": "Charge Rates",
"description": "Charge rates as factor of maximum charging power [0.00 ... 1.00]. None triggers fallback to default charge-rates.", "description": "Charge rates as factor of maximum charging power [0.00 ... 1.00]. None denotes all charge rates are available.",
"examples": [ "examples": [
[ [
0.0, 0.0,
@@ -2263,7 +2263,7 @@
} }
], ],
"title": "Charge Rates", "title": "Charge Rates",
"description": "Charge rates as factor of maximum charging power [0.00 ... 1.00]. None triggers fallback to default charge-rates.", "description": "Charge rates as factor of maximum charging power [0.00 ... 1.00]. None denotes all charge rates are available.",
"examples": [ "examples": [
[ [
0.0, 0.0,
@@ -2406,7 +2406,7 @@
"general": { "general": {
"$ref": "#/components/schemas/GeneralSettings-Output", "$ref": "#/components/schemas/GeneralSettings-Output",
"default": { "default": {
"version": "0.2.0", "version": "0.1.0+dev",
"data_output_subpath": "output", "data_output_subpath": "output",
"latitude": 52.52, "latitude": 52.52,
"longitude": 13.405, "longitude": 13.405,
@@ -4062,7 +4062,7 @@
"type": "string", "type": "string",
"title": "Version", "title": "Version",
"description": "Configuration file version. Used to check compatibility.", "description": "Configuration file version. Used to check compatibility.",
"default": "0.2.0" "default": "0.1.0+dev"
}, },
"data_folder_path": { "data_folder_path": {
"anyOf": [ "anyOf": [
@@ -4136,7 +4136,7 @@
"type": "string", "type": "string",
"title": "Version", "title": "Version",
"description": "Configuration file version. Used to check compatibility.", "description": "Configuration file version. Used to check compatibility.",
"default": "0.2.0" "default": "0.1.0+dev"
}, },
"data_folder_path": { "data_folder_path": {
"anyOf": [ "anyOf": [
@@ -5921,15 +5921,6 @@
"title": "Total Costs Amt", "title": "Total Costs Amt",
"description": "The total costs [money amount]." "description": "The total costs [money amount]."
}, },
"fitness_score": {
"items": {
"type": "number"
},
"type": "array",
"uniqueItems": true,
"title": "Fitness Score",
"description": "The fitness score as a set of fitness values."
},
"prediction": { "prediction": {
"$ref": "#/components/schemas/PydanticDateTimeDataFrame", "$ref": "#/components/schemas/PydanticDateTimeDataFrame",
"description": "Datetime data frame with time series prediction data per optimization interval:- pv_energy_wh: PV energy prediction (positive) in wh- elec_price_amt_kwh: Electricity price prediction in money per kwh- feed_in_tariff_amt_kwh: Feed in tariff prediction in money per kwh- weather_temp_air_celcius: Temperature in \u00b0C- loadforecast_energy_wh: Load mean 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" "description": "Datetime data frame with time series prediction data per optimization interval:- pv_energy_wh: PV energy prediction (positive) in wh- elec_price_amt_kwh: Electricity price prediction in money per kwh- feed_in_tariff_amt_kwh: Feed in tariff prediction in money per kwh- weather_temp_air_celcius: Temperature in \u00b0C- loadforecast_energy_wh: Load mean 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"
@@ -5946,7 +5937,6 @@
"total_losses_energy_wh", "total_losses_energy_wh",
"total_revenues_amt", "total_revenues_amt",
"total_costs_amt", "total_costs_amt",
"fitness_score",
"prediction", "prediction",
"solution" "solution"
], ],
@@ -7595,31 +7585,6 @@
"title": "Max Soc Percentage", "title": "Max Soc Percentage",
"description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.",
"default": 100 "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, "additionalProperties": false,

View File

@@ -1,6 +1,6 @@
[project] [project]
name = "akkudoktor-eos" name = "akkudoktor-eos"
version = "0.2.0" version = "0.0.1"
authors = [ authors = [
{ name="Andreas Schmitz", email="author@example.com" }, { name="Andreas Schmitz", email="author@example.com" },
] ]
@@ -111,7 +111,7 @@ ignore_missing_imports = true
[tool.commitizen] [tool.commitizen]
name = "cz_conventional_commits" name = "cz_conventional_commits"
version_scheme = "semver" version_scheme = "semver"
version = "0.2.0" # <-- Set your current version heretag_format = "v$version" version = "0.1.0+dev" # <-- Set your current version heretag_format = "v$version"
# Files to automatically update when bumping version # Files to automatically update when bumping version
update_changelog_on_bump = true update_changelog_on_bump = true
@@ -133,5 +133,5 @@ template = "keepachangelog"
version = [ version = [
"pyproject.toml", # Auto-update project version "pyproject.toml", # Auto-update project version
"src/akkudoktoreos/core/version.py", "src/akkudoktoreos/core/version.py",
"src/akkudoktoreos/data/default.config.json" "src/data/default.config.json"
] ]

View File

@@ -25,5 +25,5 @@ myst-parser==4.0.1
# Pytest # Pytest
pytest==8.4.2 pytest==8.4.2
pytest-cov==7.0.0 pytest-cov==7.0.0
coverage==7.11.1 coverage==7.11.0
pytest-xprocess==1.0.2 pytest-xprocess==1.0.2

View File

@@ -10,9 +10,9 @@ fastapi_cli==0.0.14
rich-toolkit==0.15.1 rich-toolkit==0.15.1
python-fasthtml==0.12.33 python-fasthtml==0.12.33
MonsterUI==1.0.32 MonsterUI==1.0.32
markdown-it-py==3.0.0 markdown-it-py==4.0.0
mdit-py-plugins==0.5.0 mdit-py-plugins==0.5.0
bokeh==3.8.1 bokeh==3.8.0
uvicorn==0.38.0 uvicorn==0.38.0
scikit-learn==1.7.2 scikit-learn==1.7.2
tzfpy==1.1.0 tzfpy==1.1.0
@@ -23,7 +23,7 @@ pendulum==3.1.0
platformdirs==4.5.0 platformdirs==4.5.0
psutil==7.1.3 psutil==7.1.3
pvlib==0.13.1 pvlib==0.13.1
pydantic==2.12.4 pydantic==2.12.3
pydantic_extra_types==2.10.6 pydantic_extra_types==2.10.6
statsmodels==0.14.5 statsmodels==0.14.5
pydantic-settings==2.11.0 pydantic-settings==2.11.0

View File

@@ -1,170 +0,0 @@
"""Update version strings in multiple project files only if the old version matches.
This script updates version information in:
- pyproject.toml
- src/akkudoktoreos/core/version.py
- src/akkudoktoreos/data/default.config.json
- Makefile
Supported version formats:
- __version__ = "<version>"
- version = "<version>"
- "version": "<version>"
- VERSION ?: <version>
It will:
- Replace VERSION → NEW_VERSION if the old version is found.
- Report which files were updated.
- Report which files contained mismatched versions.
- Report which files had no version.
Usage:
python bump_version.py VERSION NEW_VERSION
Args:
VERSION (str): Version expected before replacement.
NEW_VERSION (str): Version to write.
"""
#!/usr/bin/env python3
import argparse
import glob
import os
import re
import shutil
from pathlib import Path
from typing import List, Tuple
# Patterns to match version strings
VERSION_PATTERNS = [
re.compile(r'(__version__\s*=\s*")(?P<ver>[^"]+)(")'),
re.compile(r'(version\s*=\s*")(?P<ver>[^"]+)(")'),
re.compile(r'("version"\s*:\s*")(?P<ver>[^"]+)(")'),
re.compile(r'(VERSION\s*\?=\s*)(?P<ver>[^\s]+)'), # For Makefile: VERSION ?= 0.2.0
]
# Default files to process
DEFAULT_FILES = [
"pyproject.toml",
"src/akkudoktoreos/core/version.py",
"src/akkudoktoreos/data/default.config.json",
"Makefile",
]
def backup_file(file_path: str) -> str:
"""Create a backup of the given file with a .bak suffix.
Args:
file_path: Path to the file to backup.
Returns:
Path to the backup file.
"""
backup_path = f"{file_path}.bak"
shutil.copy2(file_path, backup_path)
return backup_path
def replace_version_in_file(
file_path: Path, old_version: str, new_version: str, dry_run: bool = False
) -> Tuple[bool, bool]:
"""
Replace old_version with new_version in the given file if it matches.
Args:
file_path: Path to the file to modify.
old_version: The old version to replace.
new_version: The new version to set.
dry_run: If True, don't actually modify files.
Returns:
Tuple[bool, bool]: (file_would_be_updated, old_version_found)
"""
content = file_path.read_text()
new_content = content
old_version_found = False
file_would_be_updated = False
for pattern in VERSION_PATTERNS:
def repl(match):
nonlocal old_version_found, file_would_be_updated
ver = match.group("ver")
if ver == old_version:
old_version_found = True
file_would_be_updated = True
# Some patterns have 3 groups (like quotes)
if len(match.groups()) == 3:
return f"{match.group(1)}{new_version}{match.group(3)}"
else:
return f"{match.group(1)}{new_version}"
return match.group(0)
new_content = pattern.sub(repl, new_content)
if file_would_be_updated:
if dry_run:
print(f"[DRY-RUN] Would update {file_path}")
else:
backup_path = file_path.with_suffix(file_path.suffix + ".bak")
shutil.copy(file_path, backup_path)
file_path.write_text(new_content)
print(f"Updated {file_path} (backup saved to {backup_path})")
elif not old_version_found:
print(f"[SKIP] {file_path}: old version '{old_version}' not found")
return file_would_be_updated, old_version_found
def main():
parser = argparse.ArgumentParser(description="Bump version across project files.")
parser.add_argument("old_version", help="Old version to replace")
parser.add_argument("new_version", help="New version to set")
parser.add_argument(
"--dry-run", action="store_true", help="Show what would be changed without modifying files"
)
parser.add_argument(
"--glob", nargs="*", help="Optional glob patterns to include additional files"
)
args = parser.parse_args()
updated_files = []
not_found_files = []
# Determine files to update
files_to_update: List[Path] = [Path(f) for f in DEFAULT_FILES]
if args.glob:
for pattern in args.glob:
files_to_update.extend(Path(".").glob(pattern))
files_to_update = list(dict.fromkeys(files_to_update)) # remove duplicates
any_updated = False
for file_path in files_to_update:
if file_path.exists() and file_path.is_file():
updated, _ = replace_version_in_file(
file_path, args.old_version, args.new_version, args.dry_run
)
any_updated |= updated
if updated:
updated_files.append(file_path)
else:
print(f"[SKIP] {file_path}: file does not exist")
not_found_files.append(file_path)
print("\nSummary:")
if updated_files:
print(f"Updated files ({len(updated_files)}):")
for f in updated_files:
print(f" {f}")
else:
print("No files were updated.")
if not_found_files:
print(f"Files where old version was not found ({len(not_found_files)}):")
for f in not_found_files:
print(f" {f}")
if __name__ == "__main__":
main()

View File

@@ -21,7 +21,7 @@ if TYPE_CHECKING:
# - tuple[str, Callable[[Any], Any]] (new path + transform) # - tuple[str, Callable[[Any], Any]] (new path + transform)
# - None (drop) # - None (drop)
MIGRATION_MAP: Dict[str, Union[str, Tuple[str, Callable[[Any], Any]], None]] = { MIGRATION_MAP: Dict[str, Union[str, Tuple[str, Callable[[Any], Any]], None]] = {
# 0.1.0 -> 0.2.0 # 0.1.0 -> now
"devices/batteries/0/initial_soc_percentage": None, "devices/batteries/0/initial_soc_percentage": None,
"devices/electric_vehicles/0/initial_soc_percentage": None, "devices/electric_vehicles/0/initial_soc_percentage": None,
"elecprice/provider_settings/import_file_path": "elecprice/provider_settings/ElecPriceImport/import_file_path", "elecprice/provider_settings/import_file_path": "elecprice/provider_settings/ElecPriceImport/import_file_path",

View File

@@ -2,4 +2,4 @@
# For development add `+dev` to previous release # For development add `+dev` to previous release
# For release omit `+dev`. # For release omit `+dev`.
__version__ = "0.2.0" __version__ = "0.1.0+dev"

View File

@@ -1,5 +1,5 @@
{ {
"general": { "general": {
"version": "0.2.0" "version": "0.1.0+dev"
} }
} }

View File

@@ -1,13 +1,10 @@
"""General configuration settings for simulated devices for optimization.""" """General configuration settings for simulated devices for optimization."""
import json import json
import re
from typing import Any, Optional, TextIO, cast from typing import Any, Optional, TextIO, cast
import numpy as np
from loguru import logger from loguru import logger
from numpydantic import NDArray, Shape from pydantic import Field, computed_field, model_validator
from pydantic import Field, computed_field, field_validator, model_validator
from akkudoktoreos.config.configabc import SettingsBaseModel from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import CacheFileStore from akkudoktoreos.core.cache import CacheFileStore
@@ -17,9 +14,6 @@ from akkudoktoreos.core.pydantic import ConfigDict, PydanticBaseModel
from akkudoktoreos.devices.devicesabc import DevicesBaseSettings from akkudoktoreos.devices.devicesabc import DevicesBaseSettings
from akkudoktoreos.utils.datetimeutil import DateTime, TimeWindowSequence, to_datetime from akkudoktoreos.utils.datetimeutil import DateTime, TimeWindowSequence, to_datetime
# Default charge rates for battery
BATTERY_DEFAULT_CHARGE_RATES = np.linspace(0.0, 1.0, 11) # 0.0, 0.1, ..., 1.0
class BatteriesCommonSettings(DevicesBaseSettings): class BatteriesCommonSettings(DevicesBaseSettings):
"""Battery devices base settings.""" """Battery devices base settings."""
@@ -67,12 +61,9 @@ class BatteriesCommonSettings(DevicesBaseSettings):
examples=[50], examples=[50],
) )
charge_rates: Optional[NDArray[Shape["*"], float]] = Field( charge_rates: Optional[list[float]] = Field(
default=BATTERY_DEFAULT_CHARGE_RATES, default=None,
description=( description="Charge rates as factor of maximum charging power [0.00 ... 1.00]. None denotes all charge rates are available.",
"Charge rates as factor of maximum charging power [0.00 ... 1.00]. "
"None triggers fallback to default charge-rates."
),
examples=[[0.0, 0.25, 0.5, 0.75, 1.0], None], examples=[[0.0, 0.25, 0.5, 0.75, 1.0], None],
) )
@@ -80,10 +71,7 @@ class BatteriesCommonSettings(DevicesBaseSettings):
default=0, default=0,
ge=0, ge=0,
le=100, le=100,
description=( description="Minimum state of charge (SOC) as percentage of capacity [%]. This is the target SoC for charging",
"Minimum state of charge (SOC) as percentage of capacity [%]. "
"This is the target SoC for charging"
),
examples=[10], examples=[10],
) )
@@ -95,36 +83,6 @@ class BatteriesCommonSettings(DevicesBaseSettings):
examples=[100], examples=[100],
) )
@field_validator("charge_rates", mode="before")
def validate_and_sort_charge_rates(cls, v: Any) -> NDArray[Shape["*"], float]:
# None means fallback to default values
if v is None:
return BATTERY_DEFAULT_CHARGE_RATES.copy()
# Convert to numpy array
if isinstance(v, str):
# Remove brackets and split by comma or whitespace
numbers = re.split(r"[,\s]+", v.strip("[]"))
# Filter out any empty strings and convert to floats
arr = np.array([float(x) for x in numbers if x])
else:
arr = np.array(v, dtype=float)
# Must not be empty
if arr.size == 0:
raise ValueError("charge_rates must contain at least one value.")
# Enforce bounds: 0.0 ≤ x ≤ 1.0
if (arr < 0.0).any() or (arr > 1.0).any():
raise ValueError("charge_rates must be within [0.0, 1.0].")
# Remove duplicates + sort
arr = np.unique(arr)
arr.sort()
return arr
@computed_field # type: ignore[prop-decorator] @computed_field # type: ignore[prop-decorator]
@property @property
def measurement_key_soc_factor(self) -> str: def measurement_key_soc_factor(self) -> str:

View File

@@ -1,8 +1,7 @@
from typing import Any, Iterator, Optional from typing import Any, Optional
import numpy as np import numpy as np
from akkudoktoreos.devices.devices import BATTERY_DEFAULT_CHARGE_RATES
from akkudoktoreos.optimization.genetic.geneticdevices import ( from akkudoktoreos.optimization.genetic.geneticdevices import (
BaseBatteryParameters, BaseBatteryParameters,
SolarPanelBatteryParameters, SolarPanelBatteryParameters,
@@ -18,20 +17,12 @@ class Battery:
self._setup() self._setup()
def _setup(self) -> None: def _setup(self) -> None:
"""Sets up the battery parameters based on provided parameters.""" """Sets up the battery parameters based on configuration or provided parameters."""
self.capacity_wh = self.parameters.capacity_wh self.capacity_wh = self.parameters.capacity_wh
self.initial_soc_percentage = self.parameters.initial_soc_percentage self.initial_soc_percentage = self.parameters.initial_soc_percentage
self.charging_efficiency = self.parameters.charging_efficiency self.charging_efficiency = self.parameters.charging_efficiency
self.discharging_efficiency = self.parameters.discharging_efficiency self.discharging_efficiency = self.parameters.discharging_efficiency
# Charge rates, in case of None use default
self.charge_rates = BATTERY_DEFAULT_CHARGE_RATES
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 # Only assign for storage battery
self.min_soc_percentage = ( self.min_soc_percentage = (
self.parameters.min_soc_percentage self.parameters.min_soc_percentage
@@ -45,30 +36,12 @@ class Battery:
self.max_charge_power_w = self.parameters.max_charge_power_w self.max_charge_power_w = self.parameters.max_charge_power_w
else: else:
self.max_charge_power_w = self.capacity_wh # TODO this should not be equal capacity_wh 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.discharge_array = np.full(self.prediction_hours, 1)
self.charge_array = np.full(self.prediction_hours, 0) self.charge_array = np.full(self.prediction_hours, 1)
self.soc_wh = (self.initial_soc_percentage / 100) * self.capacity_wh self.soc_wh = (self.initial_soc_percentage / 100) * self.capacity_wh
self.min_soc_wh = (self.min_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 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]: def to_dict(self) -> dict[str, Any]:
"""Converts the object to a dictionary representation.""" """Converts the object to a dictionary representation."""
return { return {
@@ -88,8 +61,8 @@ class Battery:
"""Resets the battery state to its initial values.""" """Resets the battery state to its initial values."""
self.soc_wh = (self.initial_soc_percentage / 100) * self.capacity_wh self.soc_wh = (self.initial_soc_percentage / 100) * self.capacity_wh
self.soc_wh = min(max(self.soc_wh, self.min_soc_wh), self.max_soc_wh) self.soc_wh = min(max(self.soc_wh, self.min_soc_wh), self.max_soc_wh)
self.discharge_array = np.full(self.prediction_hours, 0) self.discharge_array = np.full(self.prediction_hours, 1)
self.charge_array = np.full(self.prediction_hours, 0) self.charge_array = np.full(self.prediction_hours, 1)
def set_discharge_per_hour(self, discharge_array: np.ndarray) -> None: def set_discharge_per_hour(self, discharge_array: np.ndarray) -> None:
"""Sets the discharge values for each hour.""" """Sets the discharge values for each hour."""
@@ -107,172 +80,70 @@ class Battery:
) )
self.charge_array = np.array(charge_array) self.charge_array = np.array(charge_array)
def set_charge_allowed_for_hour(self, charge: float, hour: int) -> None:
"""Sets the charge for a specific hour."""
if hour >= self.prediction_hours:
raise ValueError(
f"Hour {hour} is out of range. Must be less than {self.prediction_hours}."
)
self.charge_array[hour] = charge
def current_soc_percentage(self) -> float: def current_soc_percentage(self) -> float:
"""Calculates the current state of charge in percentage.""" """Calculates the current state of charge in percentage."""
return (self.soc_wh / self.capacity_wh) * 100 return (self.soc_wh / self.capacity_wh) * 100
def discharge_energy(self, wh: float, hour: int) -> tuple[float, float]: def discharge_energy(self, wh: float, hour: int) -> tuple[float, float]:
"""Discharge energy from the battery. """Discharges 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: if self.discharge_array[hour] == 0:
return 0.0, 0.0 return 0.0, 0.0
# Raw extractable energy above minimum SoC max_possible_discharge_wh = (self.soc_wh - self.min_soc_wh) * self.discharging_efficiency
raw_available_wh = max(self.soc_wh - self.min_soc_wh, 0.0) max_possible_discharge_wh = max(max_possible_discharge_wh, 0.0)
# Maximum raw discharge due to power limit max_possible_discharge_wh = min(
max_raw_wh = self.max_charge_power_w # TODO rename to max_discharge_power_w max_possible_discharge_wh, self.max_charge_power_w
) # TODO make a new cfg variable max_discharge_power_w
# Actual raw withdrawal (internal) actual_discharge_wh = min(wh, max_possible_discharge_wh)
raw_withdrawal_wh = min(raw_available_wh, max_raw_wh) actual_withdrawal_wh = (
actual_discharge_wh / self.discharging_efficiency
if self.discharging_efficiency > 0
else 0.0
)
# Convert raw to delivered self.soc_wh -= actual_withdrawal_wh
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) self.soc_wh = max(self.soc_wh, self.min_soc_wh)
# Losses losses_wh = actual_withdrawal_wh - actual_discharge_wh
losses_wh = raw_used_wh - delivered_wh return actual_discharge_wh, losses_wh
return delivered_wh, losses_wh
def charge_energy( def charge_energy(
self, self, wh: Optional[float], hour: int, relative_power: float = 0.0
wh: Optional[float],
hour: int,
charge_factor: float = 0.0,
) -> tuple[float, float]: ) -> tuple[float, float]:
"""Charge energy into the battery. """Charges 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 hours 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 (01) 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: if hour is not None and self.charge_array[hour] == 0:
return 0.0, 0.0 return 0.0, 0.0 # Charging not allowed in this hour
# Provide fast (3x..5x) local read access (vs. self.xxx) for repetitive read access if relative_power > 0.0:
soc_wh_fast = self.soc_wh wh = self.max_charge_power_w * relative_power
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 wh = wh if wh is not None else self.max_charge_power_w
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_possible_charge_wh = (
max_raw_wh = min(raw_charge_wh, max_charge_power_w_fast) (self.max_soc_wh - self.soc_wh) / self.charging_efficiency
if self.charging_efficiency > 0
else 0.0
)
max_possible_charge_wh = max(max_possible_charge_wh, 0.0)
# Actual raw intake effective_charge_wh = min(wh, max_possible_charge_wh)
raw_input_wh = raw_request_wh if raw_request_wh < max_raw_wh else max_raw_wh charged_wh = effective_charge_wh * self.charging_efficiency
# Apply efficiency self.soc_wh += charged_wh
stored_wh = raw_input_wh * charging_efficiency_fast self.soc_wh = min(self.soc_wh, self.max_soc_wh)
new_soc = soc_wh_fast + stored_wh
if new_soc > self.capacity_wh: losses_wh = effective_charge_wh - charged_wh
raise ValueError( return charged_wh, losses_wh
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: def current_energy_content(self) -> float:
"""Returns the current usable energy in the battery.""" """Returns the current usable energy in the battery."""

View File

@@ -1,3 +1,5 @@
from typing import Optional
import numpy as np import numpy as np
from akkudoktoreos.optimization.genetic.geneticdevices import HomeApplianceParameters from akkudoktoreos.optimization.genetic.geneticdevices import HomeApplianceParameters
@@ -26,6 +28,7 @@ class HomeAppliance:
self.load_curve = np.zeros(self.prediction_hours) # Initialize the load curve with zeros self.load_curve = np.zeros(self.prediction_hours) # Initialize the load curve with zeros
self.duration_h = self.parameters.duration_h self.duration_h = self.parameters.duration_h
self.consumption_wh = self.parameters.consumption_wh self.consumption_wh = self.parameters.consumption_wh
self.appliance_start: Optional[int] = None
# setup possible start times # setup possible start times
if self.parameters.time_windows is None: if self.parameters.time_windows is None:
self.parameters.time_windows = TimeWindowSequence( self.parameters.time_windows = TimeWindowSequence(
@@ -56,32 +59,33 @@ class HomeAppliance:
else: else:
self.start_latest = 23 self.start_latest = 23
def set_starting_time(self, start_hour: int, global_start_hour: int = 0) -> int: def set_starting_time(self, start_hour: int, global_start_hour: int = 0) -> None:
"""Sets the start time of the device and generates the corresponding load curve. """Sets the start time of the device and generates the corresponding load curve.
:param start_hour: The hour at which the device should start. :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() self.reset_load_curve()
# Check if the duration of use is within the available time windows
if not self.start_allowed[start_hour]:
# No available time window to start home appliance
# Use the earliest one
start_hour = self.start_earliest
# Check if it is possibility to start the appliance
if start_hour < global_start_hour:
# Start is before current time
# Use the latest one
start_hour = self.start_latest
# Calculate power per hour based on total consumption and duration # Calculate power per hour based on total consumption and duration
power_per_hour = self.consumption_wh / self.duration_h # Convert to watt-hours 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 # Set the power for the duration of use in the load curve array
if start_hour < len(self.load_curve): self.load_curve[start_hour : start_hour + self.duration_h] = power_per_hour
end_hour = min(start_hour + self.duration_h, self.prediction_hours)
self.load_curve[start_hour:end_hour] = power_per_hour
return start_hour # Set the selected start hour
self.appliance_start = start_hour
def reset_load_curve(self) -> None: def reset_load_curve(self) -> None:
"""Resets the load curve.""" """Resets the load curve."""
@@ -103,3 +107,6 @@ class HomeAppliance:
) )
return self.load_curve[hour] return self.load_curve[hour]
def get_appliance_start(self) -> Optional[int]:
return self.appliance_start

View File

@@ -69,16 +69,7 @@ class GeneticSimulation(PydanticBaseModel):
ac_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(default=None, description="TBD") ac_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(default=None, description="TBD")
dc_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(default=None, description="TBD") dc_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(default=None, description="TBD")
bat_discharge_hours: Optional[NDArray[Shape["*"], float]] = Field(
default=None, description="TBD"
)
ev_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(default=None, description="TBD") ev_charge_hours: Optional[NDArray[Shape["*"], float]] = Field(default=None, description="TBD")
ev_discharge_hours: Optional[NDArray[Shape["*"], float]] = Field(
default=None, description="TBD"
)
home_appliance_start_hour: Optional[int] = Field(
default=None, description="Home appliance start hour - None denotes no start."
)
def prepare( def prepare(
self, self,
@@ -109,11 +100,8 @@ class GeneticSimulation(PydanticBaseModel):
self.home_appliance = home_appliance self.home_appliance = home_appliance
self.inverter = inverter self.inverter = inverter
self.ac_charge_hours = np.full(self.prediction_hours, 0.0) self.ac_charge_hours = np.full(self.prediction_hours, 0.0)
self.dc_charge_hours = np.full(self.prediction_hours, 0.0) self.dc_charge_hours = np.full(self.prediction_hours, 1.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_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
"""Prepare simulation runs.""" """Prepare simulation runs."""
self.load_energy_array = np.array(parameters.gesamtlast, float) self.load_energy_array = np.array(parameters.gesamtlast, float)
self.pv_prediction_wh = np.array(parameters.pv_prognose_wh, float) self.pv_prediction_wh = np.array(parameters.pv_prognose_wh, float)
@@ -126,12 +114,28 @@ class GeneticSimulation(PydanticBaseModel):
) )
) )
def set_akku_discharge_hours(self, ds: np.ndarray) -> None:
if self.battery:
self.battery.set_discharge_per_hour(ds)
def set_akku_ac_charge_hours(self, ds: np.ndarray) -> None:
self.ac_charge_hours = ds
def set_akku_dc_charge_hours(self, ds: np.ndarray) -> None:
self.dc_charge_hours = ds
def set_ev_charge_hours(self, ds: np.ndarray) -> None:
self.ev_charge_hours = ds
def set_home_appliance_start(self, ds: int, global_start_hour: int = 0) -> None:
if self.home_appliance:
self.home_appliance.set_starting_time(ds, global_start_hour=global_start_hour)
def reset(self) -> None: def reset(self) -> None:
if self.ev: if self.ev:
self.ev.reset() self.ev.reset()
if self.battery: if self.battery:
self.battery.reset() self.battery.reset()
self.home_appliance_start_hour = None
def simulate(self, start_hour: int) -> dict[str, Any]: def simulate(self, start_hour: int) -> dict[str, Any]:
"""Simulate energy usage and costs for the given start hour. """Simulate energy usage and costs for the given start hour.
@@ -142,66 +146,45 @@ class GeneticSimulation(PydanticBaseModel):
# Remember start hour # Remember start hour
self.start_hour = start_hour self.start_hour = start_hour
# Provide fast (3x..5x) local read access (vs. self.xxx) for repetitive read access # Check for simulation integrity
load_energy_array_fast = self.load_energy_array required_attrs = [
ev_charge_hours_fast = self.ev_charge_hours "load_energy_array",
ev_discharge_hours_fast = self.ev_discharge_hours "pv_prediction_wh",
ac_charge_hours_fast = self.ac_charge_hours "elect_price_hourly",
dc_charge_hours_fast = self.dc_charge_hours "ev_charge_hours",
bat_discharge_hours_fast = self.bat_discharge_hours "ac_charge_hours",
elect_price_hourly_fast = self.elect_price_hourly "dc_charge_hours",
elect_revenue_per_hour_arr_fast = self.elect_revenue_per_hour_arr "elect_revenue_per_hour_arr",
pv_prediction_wh_fast = self.pv_prediction_wh ]
battery_fast = self.battery missing_data = [
ev_fast = self.ev attr.replace("_", " ").title() for attr in required_attrs if getattr(self, attr) is None
home_appliance_fast = self.home_appliance ]
inverter_fast = self.inverter
# Check for simulation integrity (in a way that mypy understands) if missing_data:
if ( logger.error("Mandatory data missing - %s", ", ".join(missing_data))
load_energy_array_fast is None raise ValueError(f"Mandatory data missing: {', '.join(missing_data)}")
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("Battery 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 ( # Pre-fetch data
len(load_energy_array_fast) load_energy_array = np.array(self.load_energy_array)
== len(pv_prediction_wh_fast) pv_prediction_wh = np.array(self.pv_prediction_wh)
== len(elect_price_hourly_fast) elect_price_hourly = np.array(self.elect_price_hourly)
): ev_charge_hours = np.array(self.ev_charge_hours)
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)}" ac_charge_hours = np.array(self.ac_charge_hours)
dc_charge_hours = np.array(self.dc_charge_hours)
elect_revenue_per_hour_arr = np.array(self.elect_revenue_per_hour_arr)
# Fetch objects
battery = self.battery
ev = self.ev
home_appliance = self.home_appliance
inverter = self.inverter
if not (len(load_energy_array) == len(pv_prediction_wh) == len(elect_price_hourly)):
error_msg = f"Array sizes do not match: Load Curve = {len(load_energy_array)}, PV Forecast = {len(pv_prediction_wh)}, Electricity Price = {len(elect_price_hourly)}"
logger.error(error_msg) logger.error(error_msg)
raise ValueError(error_msg) raise ValueError(error_msg)
end_hour = len(load_energy_array_fast) end_hour = len(load_energy_array)
total_hours = end_hour - start_hour total_hours = end_hour - start_hour
# Pre-allocate arrays for the results, optimized for speed # Pre-allocate arrays for the results, optimized for speed
@@ -217,104 +200,82 @@ class GeneticSimulation(PydanticBaseModel):
electricity_price_per_hour = np.full((total_hours), np.nan) electricity_price_per_hour = np.full((total_hours), np.nan)
# Set initial state # Set initial state
if battery_fast: if battery:
soc_per_hour[0] = battery_fast.current_soc_percentage() soc_per_hour[0] = battery.current_soc_percentage()
# Fill the charge array of the battery if ev:
dc_charge_hours_fast[0:start_hour] = 0 soc_ev_per_hour[0] = ev.current_soc_percentage()
dc_charge_hours_fast[end_hour:] = 0
ac_charge_hours_fast[0:start_hour] = 0
dc_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
if ev_fast:
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
if home_appliance_fast and self.home_appliance_start_hour:
home_appliance_enabled = True
self.home_appliance_start_hour = home_appliance_fast.set_starting_time(
self.home_appliance_start_hour, start_hour
)
else:
home_appliance_enabled = False
for hour in range(start_hour, end_hour): for hour in range(start_hour, end_hour):
hour_idx = hour - start_hour hour_idx = hour - start_hour
# save begin states
if battery:
soc_per_hour[hour_idx] = battery.current_soc_percentage()
if ev:
soc_ev_per_hour[hour_idx] = ev.current_soc_percentage()
# Accumulate loads and PV generation # Accumulate loads and PV generation
consumption = load_energy_array_fast[hour] consumption = load_energy_array[hour]
losses_wh_per_hour[hour_idx] = 0.0 losses_wh_per_hour[hour_idx] = 0.0
# Home appliances # Home appliances
if home_appliance_enabled: if home_appliance:
ha_load = home_appliance_fast.get_load_for_hour(hour) # type: ignore[union-attr] ha_load = home_appliance.get_load_for_hour(hour)
consumption += ha_load consumption += ha_load
home_appliance_wh_per_hour[hour_idx] = ha_load home_appliance_wh_per_hour[hour_idx] = ha_load
# E-Auto handling # E-Auto handling
if ev_fast: if ev and ev_charge_hours[hour] > 0:
soc_ev_per_hour[hour_idx] = ev_fast.current_soc_percentage() # save begin state loaded_energy_ev, verluste_eauto = ev.charge_energy(
if ev_charge_hours_fast[hour] > 0: None, hour, relative_power=ev_charge_hours[hour]
loaded_energy_ev, verluste_eauto = 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] += verluste_eauto
consumption += loaded_energy_ev
losses_wh_per_hour[hour_idx] += verluste_eauto
# Process inverter logic # Process inverter logic
energy_feedin_grid_actual = energy_consumption_grid_actual = losses = eigenverbrauch = ( energy_feedin_grid_actual = energy_consumption_grid_actual = losses = eigenverbrauch = (
0.0 0.0
) )
if inverter_fast: hour_ac_charge = ac_charge_hours[hour]
energy_produced = pv_prediction_wh_fast[hour] hour_dc_charge = dc_charge_hours[hour]
hourly_electricity_price = elect_price_hourly[hour]
hourly_energy_revenue = elect_revenue_per_hour_arr[hour]
if battery:
battery.set_charge_allowed_for_hour(hour_dc_charge, hour)
if inverter:
energy_produced = pv_prediction_wh[hour]
( (
energy_feedin_grid_actual, energy_feedin_grid_actual,
energy_consumption_grid_actual, energy_consumption_grid_actual,
losses, losses,
eigenverbrauch, eigenverbrauch,
) = inverter_fast.process_energy(energy_produced, consumption, hour) ) = inverter.process_energy(energy_produced, consumption, hour)
# AC PV Battery Charge # AC PV Battery Charge
if battery_fast: if battery and hour_ac_charge > 0.0:
soc_per_hour[hour_idx] = battery_fast.current_soc_percentage() # save begin state battery.set_charge_allowed_for_hour(1, hour)
hour_ac_charge = ac_charge_hours_fast[hour] battery_charged_energy_actual, battery_losses_actual = battery.charge_energy(
if hour_ac_charge > 0.0: None, hour, relative_power=hour_ac_charge
battery_charged_energy_actual, battery_losses_actual = ( )
battery_fast.charge_energy(None, hour, charge_factor=hour_ac_charge)
)
total_battery_energy = battery_charged_energy_actual + battery_losses_actual total_battery_energy = battery_charged_energy_actual + battery_losses_actual
consumption += total_battery_energy consumption += total_battery_energy
energy_consumption_grid_actual += total_battery_energy energy_consumption_grid_actual += total_battery_energy
losses_wh_per_hour[hour_idx] += battery_losses_actual losses_wh_per_hour[hour_idx] += battery_losses_actual
# Update hourly arrays # Update hourly arrays
feedin_energy_per_hour[hour_idx] = energy_feedin_grid_actual feedin_energy_per_hour[hour_idx] = energy_feedin_grid_actual
consumption_energy_per_hour[hour_idx] = energy_consumption_grid_actual consumption_energy_per_hour[hour_idx] = energy_consumption_grid_actual
losses_wh_per_hour[hour_idx] += losses losses_wh_per_hour[hour_idx] += losses
loads_energy_per_hour[hour_idx] = consumption loads_energy_per_hour[hour_idx] = consumption
hourly_electricity_price = elect_price_hourly_fast[hour]
electricity_price_per_hour[hour_idx] = hourly_electricity_price electricity_price_per_hour[hour_idx] = hourly_electricity_price
# Financial calculations # Financial calculations
costs_per_hour[hour_idx] = energy_consumption_grid_actual * hourly_electricity_price costs_per_hour[hour_idx] = energy_consumption_grid_actual * hourly_electricity_price
revenue_per_hour[hour_idx] = ( revenue_per_hour[hour_idx] = energy_feedin_grid_actual * hourly_energy_revenue
energy_feedin_grid_actual * elect_revenue_per_hour_arr_fast[hour]
)
total_cost = np.nansum(costs_per_hour) total_cost = np.nansum(costs_per_hour)
total_losses = np.nansum(losses_wh_per_hour) total_losses = np.nansum(losses_wh_per_hour)
@@ -328,7 +289,7 @@ class GeneticSimulation(PydanticBaseModel):
"Kosten_Euro_pro_Stunde": costs_per_hour, "Kosten_Euro_pro_Stunde": costs_per_hour,
"akku_soc_pro_stunde": soc_per_hour, "akku_soc_pro_stunde": soc_per_hour,
"Einnahmen_Euro_pro_Stunde": revenue_per_hour, "Einnahmen_Euro_pro_Stunde": revenue_per_hour,
"Gesamtbilanz_Euro": total_cost - total_revenue, # Fitness score ("FitnessMin") "Gesamtbilanz_Euro": total_cost - total_revenue,
"EAuto_SoC_pro_Stunde": soc_ev_per_hour, "EAuto_SoC_pro_Stunde": soc_ev_per_hour,
"Gesamteinnahmen_Euro": total_revenue, "Gesamteinnahmen_Euro": total_revenue,
"Gesamtkosten_Euro": total_cost, "Gesamtkosten_Euro": total_cost,
@@ -613,33 +574,27 @@ class GeneticOptimization(OptimizationBase):
discharge_hours_bin, eautocharge_hours_index, washingstart_int = self.split_individual( discharge_hours_bin, eautocharge_hours_index, washingstart_int = self.split_individual(
individual individual
) )
if self.opti_param.get("home_appliance", 0) > 0 and washingstart_int: if self.opti_param.get("home_appliance", 0) > 0 and washingstart_int:
# Set start hour for appliance self.simulation.set_home_appliance_start(
self.simulation.home_appliance_start_hour = washingstart_int washingstart_int, global_start_hour=self.ems.start_datetime.hour
)
ac_charge_hours, dc_charge_hours, discharge = self.decode_charge_discharge( ac, dc, discharge = self.decode_charge_discharge(discharge_hours_bin)
discharge_hours_bin
)
self.simulation.bat_discharge_hours = discharge self.simulation.set_akku_discharge_hours(discharge)
# Set DC charge hours only if DC optimization is enabled # Set DC charge hours only if DC optimization is enabled
if self.optimize_dc_charge: if self.optimize_dc_charge:
self.simulation.dc_charge_hours = dc_charge_hours self.simulation.set_akku_dc_charge_hours(dc)
else: self.simulation.set_akku_ac_charge_hours(ac)
self.simulation.dc_charge_hours = np.full(self.config.prediction.hours, 1)
self.simulation.ac_charge_hours = ac_charge_hours
if eautocharge_hours_index is not None: if eautocharge_hours_index is not None:
eautocharge_hours_float = np.array( eautocharge_hours_float = np.array(
[self.ev_possible_charge_values[i] for i in eautocharge_hours_index], [self.ev_possible_charge_values[i] for i in eautocharge_hours_index],
float, float,
) )
# discharge is set to 0 by default self.simulation.set_ev_charge_hours(eautocharge_hours_float)
self.simulation.ev_charge_hours = eautocharge_hours_float
else: else:
# discharge is set to 0 by default self.simulation.set_ev_charge_hours(np.full(self.config.prediction.hours, 0))
self.simulation.ev_charge_hours = np.full(self.config.prediction.hours, 0)
# Do the simulation and return result. # Do the simulation and return result.
return self.simulation.simulate(self.ems.start_datetime.hour) return self.simulation.simulate(self.ems.start_datetime.hour)
@@ -651,57 +606,21 @@ class GeneticOptimization(OptimizationBase):
start_hour: int, start_hour: int,
worst_case: bool, worst_case: bool,
) -> tuple[float]: ) -> tuple[float]:
"""Evaluate the fitness score of a single individual in the DEAP genetic algorithm. """Evaluate the fitness of an individual solution based on the simulation results."""
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 (GeneticOptimizationParameters):
Optimization parameters that influence simulation behavior,
constraints, and scoring logic.
start_hour (int):
The simulation start hour (023 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: try:
simulation_result = self.evaluate_inner(individual) o = self.evaluate_inner(individual)
except Exception as e: except Exception as e:
# Return bad fitness score ("FitnessMin") in case of an exception return (100000.0,) # Return a high penalty in case of an exception
return (100000.0,)
gesamtbilanz = simulation_result["Gesamtbilanz_Euro"] * (-1.0 if worst_case else 1.0) gesamtbilanz = o["Gesamtbilanz_Euro"] * (-1.0 if worst_case else 1.0)
discharge_hours_bin, eautocharge_hours_index, washingstart_int = self.split_individual(
individual
)
# EV 100% & charge not allowed # EV 100% & charge not allowed
if self.optimize_ev: if self.optimize_ev:
discharge_hours_bin, eautocharge_hours_index, washingstart_int = self.split_individual( eauto_soc_per_hour = np.array(o.get("EAuto_SoC_pro_Stunde", [])) # Beispielkey
individual
)
eauto_soc_per_hour = np.array(
simulation_result.get("EAuto_SoC_pro_Stunde", [])
) # Beispielkey
if eauto_soc_per_hour is None or eautocharge_hours_index is None: if eauto_soc_per_hour is None or eautocharge_hours_index is None:
raise ValueError("eauto_soc_per_hour or eautocharge_hours_index is None") raise ValueError("eauto_soc_per_hour or eautocharge_hours_index is None")
@@ -767,8 +686,8 @@ class GeneticOptimization(OptimizationBase):
# More metrics # More metrics
individual.extra_data = ( # type: ignore[attr-defined] individual.extra_data = ( # type: ignore[attr-defined]
simulation_result["Gesamtbilanz_Euro"], o["Gesamtbilanz_Euro"],
simulation_result["Gesamt_Verluste"], o["Gesamt_Verluste"],
parameters.eauto.min_soc_percentage - self.simulation.ev.current_soc_percentage() parameters.eauto.min_soc_percentage - self.simulation.ev.current_soc_percentage()
if parameters.eauto and self.simulation.ev if parameters.eauto and self.simulation.ev
else 0, else 0,
@@ -782,7 +701,7 @@ class GeneticOptimization(OptimizationBase):
) )
gesamtbilanz += -restwert_akku gesamtbilanz += -restwert_akku
if self.optimize_ev and parameters.eauto and self.simulation.ev: if self.optimize_ev:
try: try:
penalty = self.config.optimization.genetic.penalties["ev_soc_miss"] penalty = self.config.optimization.genetic.penalties["ev_soc_miss"]
except: except:
@@ -791,14 +710,16 @@ class GeneticOptimization(OptimizationBase):
logger.error( logger.error(
"Penalty function parameter `ev_soc_miss` not configured, using {}.", penalty "Penalty function parameter `ev_soc_miss` not configured, using {}.", penalty
) )
ev_soc_percentage = self.simulation.ev.current_soc_percentage() gesamtbilanz += max(
if ( 0,
ev_soc_percentage < parameters.eauto.min_soc_percentage (
or ev_soc_percentage > parameters.eauto.max_soc_percentage parameters.eauto.min_soc_percentage
): - self.simulation.ev.current_soc_percentage()
gesamtbilanz += ( if parameters.eauto and self.simulation.ev
abs(parameters.eauto.min_soc_percentage - ev_soc_percentage) * penalty else 0
) )
* penalty,
)
return (gesamtbilanz,) return (gesamtbilanz,)
@@ -904,7 +825,7 @@ class GeneticOptimization(OptimizationBase):
parameters.pv_akku, parameters.pv_akku,
prediction_hours=self.config.prediction.hours, prediction_hours=self.config.prediction.hours,
) )
akku.set_charge_per_hour(np.full(self.config.prediction.hours, 0)) akku.set_charge_per_hour(np.full(self.config.prediction.hours, 1))
eauto: Optional[Battery] = None eauto: Optional[Battery] = None
if parameters.eauto: if parameters.eauto:
@@ -996,7 +917,7 @@ class GeneticOptimization(OptimizationBase):
) )
# home appliance may have choosen a different appliance start hour # home appliance may have choosen a different appliance start hour
if self.simulation.home_appliance: if self.simulation.home_appliance:
washingstart_int = self.simulation.home_appliance_start_hour washingstart_int = self.simulation.home_appliance.get_appliance_start()
eautocharge_hours_float = ( eautocharge_hours_float = (
[self.ev_possible_charge_values[i] for i in eautocharge_hours_index] [self.ev_possible_charge_values[i] for i in eautocharge_hours_index]
@@ -1004,28 +925,12 @@ class GeneticOptimization(OptimizationBase):
else None else None
) )
# Simulation may have changed something, use simulation values ac_charge, dc_charge, discharge = self.decode_charge_discharge(discharge_hours_bin)
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 # Visualize the results
visualize = { visualize = {
"ac_charge": ac_charge_hours, "ac_charge": ac_charge.tolist(),
"dc_charge": dc_charge_hours, "dc_charge": dc_charge.tolist(),
"discharge_allowed": discharge, "discharge_allowed": discharge.tolist(),
"eautocharge_hours_float": eautocharge_hours_float, "eautocharge_hours_float": eautocharge_hours_float,
"result": simulation_result, "result": simulation_result,
"eauto_obj": self.simulation.ev.to_dict() if self.simulation.ev else None, "eauto_obj": self.simulation.ev.to_dict() if self.simulation.ev else None,
@@ -1041,8 +946,8 @@ class GeneticOptimization(OptimizationBase):
return GeneticSolution( return GeneticSolution(
**{ **{
"ac_charge": ac_charge_hours, "ac_charge": ac_charge,
"dc_charge": dc_charge_hours, "dc_charge": dc_charge,
"discharge_allowed": discharge, "discharge_allowed": discharge,
"eautocharge_hours_float": eautocharge_hours_float, "eautocharge_hours_float": eautocharge_hours_float,
"result": GeneticSimulationResult(**simulation_result), "result": GeneticSimulationResult(**simulation_result),

View File

@@ -74,11 +74,6 @@ class BaseBatteryParameters(DeviceParameters):
le=100, le=100,
description="An integer representing the maximum state of charge (SOC) of the battery in percentage.", description="An integer representing the maximum state of charge (SOC) of the battery in percentage.",
) )
charge_rates: Optional[list[float]] = Field(
default=None,
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 SolarPanelBatteryParameters(BaseBatteryParameters): class SolarPanelBatteryParameters(BaseBatteryParameters):
@@ -95,6 +90,11 @@ class ElectricVehicleParameters(BaseBatteryParameters):
initial_soc_percentage: int = initial_soc_percentage_field( initial_soc_percentage: int = initial_soc_percentage_field(
"An integer representing the current state of charge (SOC) of the battery in percentage." "An integer representing the current state of charge (SOC) of the battery in percentage."
) )
charge_rates: Optional[list[float]] = Field(
default=None,
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 HomeApplianceParameters(DeviceParameters): class HomeApplianceParameters(DeviceParameters):

View File

@@ -457,7 +457,7 @@ class GeneticOptimizationParameters(
{ {
"device_id": "ev11", "device_id": "ev11",
"capacity_wh": 50000, "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], "charge_rates": [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0],
"min_soc_percentage": 70, "min_soc_percentage": 70,
} }
] ]
@@ -483,7 +483,7 @@ class GeneticOptimizationParameters(
{ {
"device_id": "ev12", "device_id": "ev12",
"capacity_wh": 50000, "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], "charge_rates": [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0],
"min_soc_percentage": 70, "min_soc_percentage": 70,
} }
] ]

View File

@@ -6,9 +6,7 @@ import pandas as pd
from loguru import logger from loguru import logger
from pydantic import Field, field_validator from pydantic import Field, field_validator
from akkudoktoreos.core.coreabc import ( from akkudoktoreos.config.config import get_config
ConfigMixin,
)
from akkudoktoreos.core.emplan import ( from akkudoktoreos.core.emplan import (
DDBCInstruction, DDBCInstruction,
EnergyManagementPlan, EnergyManagementPlan,
@@ -111,7 +109,7 @@ class GeneticSimulationResult(GeneticParametersBaseModel):
return NumpyEncoder.convert_numpy(field)[0] return NumpyEncoder.convert_numpy(field)[0]
class GeneticSolution(ConfigMixin, GeneticParametersBaseModel): class GeneticSolution(GeneticParametersBaseModel):
"""**Note**: The first value of "Last_Wh_per_hour", "Netzeinspeisung_Wh_per_hour", and "Netzbezug_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.""" """**Note**: The first value of "Last_Wh_per_hour", "Netzeinspeisung_Wh_per_hour", and "Netzbezug_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."""
ac_charge: list[float] = Field( ac_charge: list[float] = Field(
@@ -230,20 +228,18 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
""" """
from akkudoktoreos.core.ems import get_ems from akkudoktoreos.core.ems import get_ems
config = get_config()
start_datetime = get_ems().start_datetime start_datetime = get_ems().start_datetime
start_day_hour = start_datetime.in_timezone(self.config.general.timezone).hour
interval_hours = 1 interval_hours = 1
power_to_energy_per_interval_factor = 1.0 power_to_energy_per_interval_factor = 1.0
# --- Create index based on list length and interval --- # --- Create index based on list length and interval ---
# Ensure we only use the minimum of results and commands if differing n_points = len(self.result.Kosten_Euro_pro_Stunde)
periods = min(len(self.result.Kosten_Euro_pro_Stunde), len(self.ac_charge) - start_day_hour)
time_index = pd.date_range( time_index = pd.date_range(
start=start_datetime, start=start_datetime,
periods=periods, periods=n_points,
freq=f"{interval_hours}h", freq=f"{interval_hours}h",
) )
n_points = len(time_index)
end_datetime = start_datetime.add(hours=n_points) end_datetime = start_datetime.add(hours=n_points)
# Fill solution into dataframe with correct column names # Fill solution into dataframe with correct column names
@@ -260,42 +256,26 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
solution = pd.DataFrame( solution = pd.DataFrame(
{ {
"date_time": time_index, "date_time": time_index,
# result starts at start_day_hour "load_energy_wh": self.result.Last_Wh_pro_Stunde,
"load_energy_wh": self.result.Last_Wh_pro_Stunde[:n_points], "grid_feedin_energy_wh": self.result.Netzeinspeisung_Wh_pro_Stunde,
"grid_feedin_energy_wh": self.result.Netzeinspeisung_Wh_pro_Stunde[:n_points], "grid_consumption_energy_wh": self.result.Netzbezug_Wh_pro_Stunde,
"grid_consumption_energy_wh": self.result.Netzbezug_Wh_pro_Stunde[:n_points], "elec_price_prediction_amt_kwh": [v * 1000 for v in self.result.Electricity_price],
"costs_amt": self.result.Kosten_Euro_pro_Stunde[:n_points], "costs_amt": self.result.Kosten_Euro_pro_Stunde,
"revenue_amt": self.result.Einnahmen_Euro_pro_Stunde[:n_points], "revenue_amt": self.result.Einnahmen_Euro_pro_Stunde,
"losses_energy_wh": self.result.Verluste_Pro_Stunde[:n_points], "losses_energy_wh": self.result.Verluste_Pro_Stunde,
}, },
index=time_index, index=time_index,
) )
# Add battery data # Add battery data
solution["battery1_soc_factor"] = [ solution["battery1_soc_factor"] = [v / 100 for v in self.result.akku_soc_pro_stunde]
v / 100 operation: dict[str, list[float]] = {}
for v in self.result.akku_soc_pro_stunde[:n_points] # result starts at start_day_hour for hour, rate in enumerate(self.ac_charge):
] if hour >= n_points:
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 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])
operation_mode, operation_mode_factor = self._battery_operation_from_solution( operation_mode, operation_mode_factor = self._battery_operation_from_solution(
ac_charge_hour, dc_charge_hour, discharge_allowed_hour self.ac_charge[hour], self.dc_charge[hour], bool(self.discharge_allowed[hour])
) )
operation["genetic_ac_charge_factor"].append(ac_charge_hour)
operation["genetic_dc_charge_factor"].append(dc_charge_hour)
operation["genetic_discharge_allowed_factor"].append(discharge_allowed_hour)
for mode in BatteryOperationMode: for mode in BatteryOperationMode:
mode_key = f"battery1_{mode.lower()}_op_mode" mode_key = f"battery1_{mode.lower()}_op_mode"
factor_key = f"battery1_{mode.lower()}_op_factor" factor_key = f"battery1_{mode.lower()}_op_factor"
@@ -309,22 +289,15 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
operation[mode_key].append(0.0) operation[mode_key].append(0.0)
operation[factor_key].append(0.0) operation[factor_key].append(0.0)
for key in operation.keys(): 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] solution[key] = operation[key]
# Add EV battery solution # Add EV battery solution
# eautocharge_hours_float start at hour 0 of start day
# result.EAuto_SoC_pro_Stunde start at start_datetime.hour
if self.eauto_obj: if self.eauto_obj:
if self.eautocharge_hours_float is None: if self.eautocharge_hours_float is None:
# Electric vehicle is full enough. No load times. # Electric vehicle is full enough. No load times.
solution[f"{self.eauto_obj.device_id}_soc_factor"] = [ solution[f"{self.eauto_obj.device_id}_soc_factor"] = [
self.eauto_obj.initial_soc_percentage / 100.0 self.eauto_obj.initial_soc_percentage / 100.0
] * n_points ] * n_points
solution["genetic_ev_charge_factor"] = [0.0] * n_points
# operation modes # operation modes
operation_mode = BatteryOperationMode.IDLE operation_mode = BatteryOperationMode.IDLE
for mode in BatteryOperationMode: for mode in BatteryOperationMode:
@@ -338,17 +311,12 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
solution[factor_key] = [0.0] * n_points solution[factor_key] = [0.0] * n_points
else: else:
solution[f"{self.eauto_obj.device_id}_soc_factor"] = [ solution[f"{self.eauto_obj.device_id}_soc_factor"] = [
v / 100 for v in self.result.EAuto_SoC_pro_Stunde[:n_points] v / 100 for v in self.result.EAuto_SoC_pro_Stunde
] ]
operation = { operation = {}
"genetic_ev_charge_factor": [], for hour, rate in enumerate(self.eautocharge_hours_float):
} if hour >= n_points:
for hour_idx, rate in enumerate(self.eautocharge_hours_float):
if hour_idx < start_day_hour:
continue
if hour_idx >= start_day_hour + n_points:
break break
operation["genetic_ev_charge_factor"].append(rate)
operation_mode, operation_mode_factor = self._battery_operation_from_solution( operation_mode, operation_mode_factor = self._battery_operation_from_solution(
rate, 0.0, False rate, 0.0, False
) )
@@ -365,16 +333,11 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
operation[mode_key].append(0.0) operation[mode_key].append(0.0)
operation[factor_key].append(0.0) operation[factor_key].append(0.0)
for key in operation.keys(): 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] solution[key] = operation[key]
# Add home appliance data # Add home appliance data
if self.washingstart: if self.washingstart:
# result starts at start_day_hour solution["homeappliance1_energy_wh"] = self.result.Home_appliance_wh_per_hour
solution["homeappliance1_energy_wh"] = self.result.Home_appliance_wh_per_hour[:n_points]
# Fill prediction into dataframe with correct column names # Fill prediction into dataframe with correct column names
# - pvforecast_ac_energy_wh_energy_wh: PV energy prediction (positive) in wh # - pvforecast_ac_energy_wh_energy_wh: PV energy prediction (positive) in wh
@@ -482,13 +445,10 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
generated_at=to_datetime(), generated_at=to_datetime(),
comment="Optimization solution derived from GeneticSolution.", comment="Optimization solution derived from GeneticSolution.",
valid_from=start_datetime, valid_from=start_datetime,
valid_until=start_datetime.add(hours=self.config.optimization.horizon_hours), valid_until=start_datetime.add(hours=config.optimization.horizon_hours),
total_losses_energy_wh=self.result.Gesamt_Verluste, total_losses_energy_wh=self.result.Gesamt_Verluste,
total_revenues_amt=self.result.Gesamteinnahmen_Euro, total_revenues_amt=self.result.Gesamteinnahmen_Euro,
total_costs_amt=self.result.Gesamtkosten_Euro, total_costs_amt=self.result.Gesamtkosten_Euro,
fitness_score={
self.result.Gesamtkosten_Euro,
},
prediction=PydanticDateTimeDataFrame.from_dataframe(prediction), prediction=PydanticDateTimeDataFrame.from_dataframe(prediction),
solution=PydanticDateTimeDataFrame.from_dataframe(solution), solution=PydanticDateTimeDataFrame.from_dataframe(solution),
) )
@@ -500,7 +460,6 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
from akkudoktoreos.core.ems import get_ems from akkudoktoreos.core.ems import get_ems
start_datetime = get_ems().start_datetime start_datetime = get_ems().start_datetime
start_day_hour = start_datetime.in_timezone(self.config.general.timezone).hour
plan = EnergyManagementPlan( plan = EnergyManagementPlan(
id=f"plan-genetic@{to_datetime(as_string=True)}", id=f"plan-genetic@{to_datetime(as_string=True)}",
generated_at=to_datetime(), generated_at=to_datetime(),
@@ -512,15 +471,10 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
last_operation_mode: Optional[str] = None last_operation_mode: Optional[str] = None
last_operation_mode_factor: Optional[float] = None last_operation_mode_factor: Optional[float] = None
resource_id = "battery1" resource_id = "battery1"
# ac_charge, dc_charge, discharge_allowed start at hour 0 of start day logger.debug("BAT: {} - {}", resource_id, self.ac_charge)
logger.debug("BAT: {} - {}", resource_id, self.ac_charge[start_day_hour:]) for hour, rate in enumerate(self.ac_charge):
for hour_idx, rate in enumerate(self.ac_charge):
if hour_idx < start_day_hour:
continue
operation_mode, operation_mode_factor = self._battery_operation_from_solution( operation_mode, operation_mode_factor = self._battery_operation_from_solution(
self.ac_charge[hour_idx], self.ac_charge[hour], self.dc_charge[hour], bool(self.discharge_allowed[hour])
self.dc_charge[hour_idx],
bool(self.discharge_allowed[hour_idx]),
) )
if ( if (
operation_mode == last_operation_mode operation_mode == last_operation_mode
@@ -530,7 +484,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
continue continue
last_operation_mode = operation_mode last_operation_mode = operation_mode
last_operation_mode_factor = operation_mode_factor last_operation_mode_factor = operation_mode_factor
execution_time = start_datetime.add(hours=hour_idx - start_day_hour) execution_time = start_datetime.add(hours=hour)
plan.add_instruction( plan.add_instruction(
FRBCInstruction( FRBCInstruction(
resource_id=resource_id, resource_id=resource_id,
@@ -542,7 +496,6 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
) )
# Add EV battery instructions (fill rate based control) # Add EV battery instructions (fill rate based control)
# eautocharge_hours_float start at hour 0 of start day
if self.eauto_obj: if self.eauto_obj:
resource_id = self.eauto_obj.device_id resource_id = self.eauto_obj.device_id
if self.eautocharge_hours_float is None: if self.eautocharge_hours_float is None:
@@ -560,12 +513,8 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
else: else:
last_operation_mode = None last_operation_mode = None
last_operation_mode_factor = None last_operation_mode_factor = None
logger.debug( logger.debug("EV: {} - {}", resource_id, self.eauto_obj.charge_array)
"EV: {} - {}", resource_id, self.eautocharge_hours_float[start_day_hour:] for hour, rate in enumerate(self.eautocharge_hours_float):
)
for hour_idx, rate in enumerate(self.eautocharge_hours_float):
if hour_idx < start_day_hour:
continue
operation_mode, operation_mode_factor = self._battery_operation_from_solution( operation_mode, operation_mode_factor = self._battery_operation_from_solution(
rate, 0.0, False rate, 0.0, False
) )
@@ -577,7 +526,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
continue continue
last_operation_mode = operation_mode last_operation_mode = operation_mode
last_operation_mode_factor = operation_mode_factor last_operation_mode_factor = operation_mode_factor
execution_time = start_datetime.add(hours=hour_idx - start_day_hour) execution_time = start_datetime.add(hours=hour)
plan.add_instruction( plan.add_instruction(
FRBCInstruction( FRBCInstruction(
resource_id=resource_id, resource_id=resource_id,
@@ -593,7 +542,7 @@ class GeneticSolution(ConfigMixin, GeneticParametersBaseModel):
resource_id = "homeappliance1" resource_id = "homeappliance1"
operation_mode = ApplianceOperationMode.RUN # type: ignore[assignment] operation_mode = ApplianceOperationMode.RUN # type: ignore[assignment]
operation_mode_factor = 1.0 operation_mode_factor = 1.0
execution_time = start_datetime.add(hours=self.washingstart - start_day_hour) execution_time = start_datetime.add(hours=self.washingstart)
plan.add_instruction( plan.add_instruction(
DDBCInstruction( DDBCInstruction(
resource_id=resource_id, resource_id=resource_id,

View File

@@ -110,8 +110,6 @@ class OptimizationSolution(PydanticBaseModel):
total_costs_amt: float = Field(description="The total costs [money amount].") total_costs_amt: float = Field(description="The total costs [money amount].")
fitness_score: set[float] = Field(description="The fitness score as a set of fitness values.")
prediction: PydanticDateTimeDataFrame = Field( prediction: PydanticDateTimeDataFrame = Field(
description=( description=(
"Datetime data frame with time series prediction data per optimization interval:" "Datetime data frame with time series prediction data per optimization interval:"

View File

@@ -54,21 +54,8 @@ color_palette = {
"pink-500": "#EC4899", # pink-500 "pink-500": "#EC4899", # pink-500
"rose-500": "#F43F5E", # rose-500 "rose-500": "#F43F5E", # rose-500
} }
# Color names
colors = list(color_palette.keys()) colors = list(color_palette.keys())
# Colums that are exclude from the the solution card display
# They are currently not used or are covered by others
solution_excludes = [
"date_time",
"_op_mode",
"_fault_",
"_outage_supply_",
"_reserve_backup_",
"_ramp_rate_control_",
"_frequency_regulation_",
]
# Current state of solution displayed # Current state of solution displayed
solution_visible: dict[str, bool] = { solution_visible: dict[str, bool] = {
"pv_energy_wh": True, "pv_energy_wh": True,
@@ -135,9 +122,7 @@ def SolutionCard(solution: OptimizationSolution, config: SettingsEOS, data: Opti
instruction_columns = [ instruction_columns = [
instruction instruction
for instruction in solution_columns for instruction in solution_columns
if instruction.endswith("op_mode") if instruction.endswith("op_mode") or instruction.endswith("op_factor")
or instruction.endswith("op_factor")
or instruction.startswith("genetic_")
] ]
solution_columns = [x for x in solution_columns if x not in instruction_columns] solution_columns = [x for x in solution_columns if x not in instruction_columns]
@@ -155,26 +140,13 @@ def SolutionCard(solution: OptimizationSolution, config: SettingsEOS, data: Opti
prediction_columns_to_join = prediction_df.columns.difference(df.columns) prediction_columns_to_join = prediction_df.columns.difference(df.columns)
df = df.join(prediction_df[prediction_columns_to_join], how="inner") df = df.join(prediction_df[prediction_columns_to_join], how="inner")
# Exclude columns that currently do not have a value # Remove time offset from UTC to get naive local time and make bokey plot in local time
excludes = solution_excludes
for instruction in instruction_columns:
if instruction.endswith("op_mode") and df[instruction].eq(0).all():
# Exclude op_mode and op_factor if all op_mode is 0
excludes.append(instruction)
excludes.append(f"{instruction[:-4]}factor")
# Make bokey plot in local time at location
# Determine daylight saving time change
dst_offsets = df.index.map(lambda x: x.dst().total_seconds() / 3600) dst_offsets = df.index.map(lambda x: x.dst().total_seconds() / 3600)
# Determine desired timezone
if config.general is None or config.general.timezone is None: if config.general is None or config.general.timezone is None:
date_time_tz = "Europe/Berlin" date_time_tz = "Europe/Berlin"
else: else:
date_time_tz = config.general.timezone date_time_tz = config.general.timezone
# Ensure original date_time is parsed as UTC and convert to local time df["date_time"] = pd.to_datetime(df["date_time"], utc=True).dt.tz_convert(date_time_tz)
df["date_time_local"] = (
pd.to_datetime(df["date_time"], utc=True).dt.tz_convert(date_time_tz).dt.tz_localize(None)
)
# There is a special case if we have daylight saving time change in the time series # There is a special case if we have daylight saving time change in the time series
if dst_offsets.nunique() > 1: if dst_offsets.nunique() > 1:
@@ -269,12 +241,21 @@ def SolutionCard(solution: OptimizationSolution, config: SettingsEOS, data: Opti
# Create line renderers for each column # Create line renderers for each column
renderers = {} renderers = {}
# Have an index for the colors of predictions, solutions and instructions.
prediction_color_idx = 0
solution_color_idx = int(len(colors) * 0.33) + 1
instruction_color_idx = int(len(colors) * 0.66) + 1
for i, col in enumerate(sorted(df.columns)): for i, col in enumerate(sorted(df.columns)):
# Exclude some columns that are currently not used or are covered by others # Exclude some columns that are currently not used or are covered by others
excludes = [
"date_time",
"_op_mode",
"_fault_",
"_forced_discharge_",
"_outage_supply_",
"_reserve_backup_",
"_ramp_rate_control_",
"_frequency_regulation_",
"_grid_support_export_",
"_peak_shaving_",
]
# excludes = ["date_time"]
if any(exclude in col for exclude in excludes): if any(exclude in col for exclude in excludes):
continue continue
if col in solution_visible: if col in solution_visible:
@@ -284,85 +265,73 @@ def SolutionCard(solution: OptimizationSolution, config: SettingsEOS, data: Opti
solution_visible[col] = visible solution_visible[col] = visible
if col in solution_color: if col in solution_color:
color = solution_color[col] color = solution_color[col]
else: elif col == "pv_energy_wh":
if col in prediction_columns: color = "yellow-500"
color = colors[prediction_color_idx % len(colors)] solution_color[col] = color
prediction_color_idx += 3 elif col == "elec_price_amt_kwh":
elif col in solution_columns: color = "red-500"
color = colors[solution_color_idx % len(colors)]
solution_color_idx += 3
else:
color = colors[instruction_color_idx % len(colors)]
instruction_color_idx += 3
# Remember the color of this column
solution_color[col] = color solution_color[col] = color
if col in prediction_columns:
line_dash = "dotted"
else: else:
line_dash = "solid" color = colors[i % len(colors)]
solution_color[col] = color
if visible: if visible:
if col.endswith("energy_wh"): if col == "pv_energy_wh":
r = plot.step( r = plot.vbar(
x="date_time_local", x="date_time",
y=col, top=col,
mode="after",
source=source, source=source,
width=BAR_WIDTH_1HOUR * 0.8,
legend_label=col, legend_label=col,
color=color_palette[color], color=color_palette[color],
line_dash=line_dash, level="underlay",
) )
elif col.endswith("soc_factor"): elif col.endswith("energy_wh"):
r = plot.line( r = plot.step(
x="date_time_local", x="date_time",
y=col, y=col,
mode="before",
source=source, source=source,
legend_label=col, legend_label=col,
color=color_palette[color], color=color_palette[color],
line_dash=line_dash,
y_range_name="factor",
) )
elif col.endswith("factor"): elif col.endswith("factor"):
r = plot.step( r = plot.step(
x="date_time_local", x="date_time",
y=col, y=col,
mode="after", mode="before",
source=source, source=source,
legend_label=col, legend_label=col,
color=color_palette[color], color=color_palette[color],
line_dash=line_dash,
y_range_name="factor", y_range_name="factor",
) )
elif col.endswith("mode"): elif col.endswith("mode"):
r = plot.step( r = plot.step(
x="date_time_local", x="date_time",
y=col, y=col,
mode="after", mode="before",
source=source, source=source,
legend_label=col, legend_label=col,
color=color_palette[color], color=color_palette[color],
line_dash=line_dash,
y_range_name="factor", y_range_name="factor",
) )
elif col.endswith("amt_kwh"): elif col.endswith("amt_kwh"):
r = plot.step( r = plot.step(
x="date_time_local", x="date_time",
y=col, y=col,
mode="after", mode="before",
source=source, source=source,
legend_label=col, legend_label=col,
color=color_palette[color], color=color_palette[color],
line_dash=line_dash,
y_range_name="amt_kwh", y_range_name="amt_kwh",
) )
elif col.endswith("amt"): elif col.endswith("amt"):
r = plot.step( r = plot.step(
x="date_time_local", x="date_time",
y=col, y=col,
mode="after", mode="before",
source=source, source=source,
legend_label=col, legend_label=col,
color=color_palette[color], color=color_palette[color],
line_dash=line_dash,
y_range_name="amt", y_range_name="amt",
) )
else: else:
@@ -461,16 +430,7 @@ def SolutionCard(solution: OptimizationSolution, config: SettingsEOS, data: Opti
) )
return Grid( return Grid(
Grid( Bokeh(plot),
Bokeh(plot),
Card(
P(f"Total revenues: {solution.total_revenues_amt}"),
P(f"Total costs: {solution.total_costs_amt}"),
P(f"Total losses: {solution.total_losses_energy_wh / 1000} kWh"),
P(f"Fitness score: {solution.fitness_score}"),
),
cols=1,
),
Checkbox, Checkbox,
cls="w-full space-y-3 space-x-3", cls="w-full space-y-3 space-x-3",
) )

View File

@@ -6,53 +6,20 @@ from akkudoktoreos.devices.genetic.battery import Battery, SolarPanelBatteryPara
@pytest.fixture @pytest.fixture
def setup_pv_battery(): 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 = SolarPanelBatteryParameters( params = SolarPanelBatteryParameters(
device_id=device_id, device_id="battery1",
capacity_wh=capacity_wh, capacity_wh=10000,
initial_soc_percentage=initial_soc_percentage, initial_soc_percentage=50,
charging_efficiency=charging_efficiency, min_soc_percentage=20,
discharging_efficiency=discharging_efficiency, max_soc_percentage=80,
min_soc_percentage=min_soc_percentage, max_charge_power_w=8000,
max_soc_percentage=max_soc_percentage, hours=24,
max_charge_power_w=max_charge_power_w,
hours=hours,
) )
battery = Battery( battery = Battery(
params, params,
prediction_hours=48, prediction_hours=48,
) )
battery.reset() 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 return battery
@@ -197,47 +164,17 @@ def test_charge_energy_not_allowed_hour(setup_pv_battery):
), "SOC should remain unchanged" ), "SOC should remain unchanged"
@pytest.mark.parametrize( def test_charge_energy_relative_power(setup_pv_battery):
"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 battery = setup_pv_battery
hour = 4
if wh is not None and charge_factor == 0.0: # mode 1 relative_power = 0.5 # 50% of max charge power
raw_request_wh = wh charged_wh, losses_wh = battery.charge_energy(wh=None, hour=4, relative_power=relative_power)
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: assert charged_wh > 0, "Charging should occur with relative power"
# Should raise assert losses_wh >= 0, "Losses should not be negative"
with pytest.raises(ValueError): assert charged_wh <= battery.max_charge_power_w * relative_power, (
battery.charge_energy( "Charging should respect relative power limit"
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" assert battery.soc_wh > 0, "SOC should increase after charging"
@@ -261,13 +198,6 @@ def setup_car_battery():
prediction_hours=48, prediction_hours=48,
) )
battery.reset() 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 return battery

View File

@@ -3,24 +3,11 @@ from pathlib import Path
from typing import Any, Optional, Union from typing import Any, Optional, Union
from unittest.mock import patch from unittest.mock import patch
import numpy as np
import pytest import pytest
from loguru import logger from loguru import logger
from pydantic import IPvAnyAddress, ValidationError from pydantic import IPvAnyAddress, ValidationError
from akkudoktoreos.config.config import ConfigEOS, GeneralSettings from akkudoktoreos.config.config import ConfigEOS, GeneralSettings
from akkudoktoreos.devices.devices import BATTERY_DEFAULT_CHARGE_RATES
def assert_values_equal(actual, expected):
"""Compare values, handling lists and numpy arrays."""
if isinstance(actual, (list, np.ndarray)) or isinstance(expected, (list, np.ndarray)):
# Convert both to numpy arrays for comparison
actual_arr = np.array(actual)
expected_arr = np.array(expected)
assert np.array_equal(actual_arr, expected_arr), f"Expected {expected_arr}, but got {actual_arr}"
else:
assert actual == expected, f"Expected {expected}, but got {actual}"
# overwrite config_mixin fixture from conftest # overwrite config_mixin fixture from conftest
@@ -365,7 +352,7 @@ def test_config_common_settings_timezone_none_when_coordinates_missing():
[ [
( (
"devices.electric_vehicles[0].charge_rates", "devices.electric_vehicles[0].charge_rates",
BATTERY_DEFAULT_CHARGE_RATES, [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0],
) )
], ],
ValueError, ValueError,
@@ -377,10 +364,10 @@ def test_config_common_settings_timezone_none_when_coordinates_missing():
[ [
( (
"devices.electric_vehicles[0].charge_rates", "devices.electric_vehicles[0].charge_rates",
BATTERY_DEFAULT_CHARGE_RATES, [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0],
) )
], ],
KeyError, TypeError,
), ),
# Invalid index (no number) # Invalid index (no number)
( (
@@ -389,10 +376,10 @@ def test_config_common_settings_timezone_none_when_coordinates_missing():
[ [
( (
"devices.electric_vehicles[0].charge_rates", "devices.electric_vehicles[0].charge_rates",
BATTERY_DEFAULT_CHARGE_RATES, [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0],
) )
], ],
KeyError, IndexError,
), ),
# Unset value (set None) # Unset value (set None)
( (
@@ -401,7 +388,7 @@ def test_config_common_settings_timezone_none_when_coordinates_missing():
[ [
( (
"devices.electric_vehicles[0].charge_rates", "devices.electric_vehicles[0].charge_rates",
BATTERY_DEFAULT_CHARGE_RATES, None,
) )
], ],
None, None,
@@ -413,13 +400,17 @@ def test_set_nested_key(path, value, expected, exception, config_eos):
config_eos.set_nested_value(path, value) config_eos.set_nested_value(path, value)
for expected_path, expected_value in expected: for expected_path, expected_value in expected:
actual_value = eval(f"config_eos.{expected_path}") actual_value = eval(f"config_eos.{expected_path}")
assert_values_equal(actual_value, expected_value) assert actual_value == expected_value, (
f"Expected {expected_value} at {expected_path}, but got {actual_value}"
)
else: else:
try: try:
config_eos.set_nested_value(path, value) config_eos.set_nested_value(path, value)
for expected_path, expected_value in expected: for expected_path, expected_value in expected:
actual_value = eval(f"config_eos.{expected_path}") actual_value = eval(f"config_eos.{expected_path}")
assert_values_equal(actual_value, expected_value) assert actual_value == expected_value, (
f"Expected {expected_value} at {expected_path}, but got {actual_value}"
)
pytest.fail( pytest.fail(
f"Expected exception {exception} but none was raised. Set '{expected_path}' to '{actual_value}'" f"Expected exception {exception} but none was raised. Set '{expected_path}' to '{actual_value}'"
) )
@@ -517,19 +508,19 @@ def test_merge_settings_partial(config_eos):
config_eos.merge_settings_from_dict(partial_settings) config_eos.merge_settings_from_dict(partial_settings)
assert config_eos.devices.max_electric_vehicles == 1 assert config_eos.devices.max_electric_vehicles == 1
assert len(config_eos.devices.electric_vehicles) == 1 assert len(config_eos.devices.electric_vehicles) == 1
assert_values_equal(config_eos.devices.electric_vehicles[0].charge_rates, [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]) assert config_eos.devices.electric_vehicles[0].charge_rates == [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]
# Assure re-apply generates the same config # Assure re-apply generates the same config
config_eos.merge_settings_from_dict(partial_settings) config_eos.merge_settings_from_dict(partial_settings)
assert config_eos.devices.max_electric_vehicles == 1 assert config_eos.devices.max_electric_vehicles == 1
assert len(config_eos.devices.electric_vehicles) == 1 assert len(config_eos.devices.electric_vehicles) == 1
assert_values_equal(config_eos.devices.electric_vehicles[0].charge_rates, [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]) assert config_eos.devices.electric_vehicles[0].charge_rates == [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]
# Assure update keeps same values # Assure update keeps same values
config_eos.update() config_eos.update()
assert config_eos.devices.max_electric_vehicles == 1 assert config_eos.devices.max_electric_vehicles == 1
assert len(config_eos.devices.electric_vehicles) == 1 assert len(config_eos.devices.electric_vehicles) == 1
assert_values_equal(config_eos.devices.electric_vehicles[0].charge_rates, [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]) assert config_eos.devices.electric_vehicles[0].charge_rates == [0.0, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0]
def test_merge_settings_empty(config_eos): def test_merge_settings_empty(config_eos):

View File

@@ -65,6 +65,7 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
optimization_hours = config_eos.optimization.horizon_hours, optimization_hours = config_eos.optimization.horizon_hours,
prediction_hours = config_eos.prediction.hours, prediction_hours = config_eos.prediction.hours,
) )
home_appliance.set_starting_time(2)
# Example initialization of electric car battery # Example initialization of electric car battery
eauto = Battery( eauto = Battery(
@@ -249,17 +250,6 @@ def genetic_simulation(config_eos) -> GeneticSimulation:
home_appliance=home_appliance, home_appliance=home_appliance,
) )
# Init for test
assert simulation.ac_charge_hours is not None
assert simulation.dc_charge_hours is not None
assert simulation.bat_discharge_hours is not None
assert simulation.ev_charge_hours is not None
simulation.ac_charge_hours[start_hour] = 1.0
simulation.dc_charge_hours[start_hour] = 1.0
simulation.bat_discharge_hours[start_hour] = 1.0
simulation.ev_charge_hours[start_hour] = 1.0
simulation.home_appliance_start_hour = 2
return simulation return simulation
@@ -331,34 +321,34 @@ def test_simulation(genetic_simulation):
# Verify that the value at index 0 is 'None' # Verify that the value at index 0 is 'None'
# Check that 'Netzeinspeisung_Wh_pro_Stunde' and 'Netzbezug_Wh_pro_Stunde' are consistent # Check that 'Netzeinspeisung_Wh_pro_Stunde' and 'Netzbezug_Wh_pro_Stunde' are consistent
assert result["Netzbezug_Wh_pro_Stunde"][1] == 1527.13, ( assert result["Netzbezug_Wh_pro_Stunde"][1] == 0, (
"The value at index 1 of 'Netzbezug_Wh_pro_Stunde' should be 1527.13." "The value at index 1 of 'Netzbezug_Wh_pro_Stunde' should be 0."
) )
# Verify the total balance # Verify the total balance
assert abs(result["Gesamtbilanz_Euro"] - 6.612835813556755) < 1e-5, ( assert abs(result["Gesamtbilanz_Euro"] - 1.958185274567674) < 1e-5, (
"Total balance should be 6.612835813556755." "Total balance should be 1.958185274567674."
) )
# Check total revenue and total costs # Check total revenue and total costs
assert abs(result["Gesamteinnahmen_Euro"] - 1.964301131937134) < 1e-5, ( assert abs(result["Gesamteinnahmen_Euro"] - 1.168863124510214) < 1e-5, (
"Total revenue should be 1.964301131937134." "Total revenue should be 1.168863124510214."
) )
assert abs(result["Gesamtkosten_Euro"] - 8.577136945493889) < 1e-5, ( assert abs(result["Gesamtkosten_Euro"] - 3.127048399077888) < 1e-5, (
"Total costs should be 8.577136945493889 ." "Total costs should be 3.127048399077888 ."
) )
# Check the losses # Check the losses
assert abs(result["Gesamt_Verluste"] - 1620.0) < 1e-5, ( assert abs(result["Gesamt_Verluste"] - 2871.5330639359036) < 1e-5, (
"Total losses should be 1620.0 ." "Total losses should be 2871.5330639359036 ."
) )
# Check the values in 'akku_soc_pro_stunde' # Check the values in 'akku_soc_pro_stunde'
assert result["akku_soc_pro_stunde"][-1] == 98.0, ( assert result["akku_soc_pro_stunde"][-1] == 42.151590909090906, (
"The value at index -1 of 'akku_soc_pro_stunde' should be 98.0." "The value at index -1 of 'akku_soc_pro_stunde' should be 42.151590909090906."
) )
assert result["akku_soc_pro_stunde"][1] == 98.0, ( assert result["akku_soc_pro_stunde"][1] == 60.08659090909091, (
"The value at index 1 of 'akku_soc_pro_stunde' should be 98.0." "The value at index 1 of 'akku_soc_pro_stunde' should be 60.08659090909091."
) )
# Check home appliances # Check home appliances

View File

@@ -65,6 +65,7 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation:
optimization_hours = config_eos.optimization.horizon_hours, optimization_hours = config_eos.optimization.horizon_hours,
prediction_hours = config_eos.prediction.hours, prediction_hours = config_eos.prediction.hours,
) )
home_appliance.set_starting_time(2)
# Example initialization of electric car battery # Example initialization of electric car battery
eauto = Battery( eauto = Battery(
@@ -157,11 +158,10 @@ def genetic_simulation_2(config_eos) -> GeneticSimulation:
ac = np.full(config_eos.prediction.hours, 0.0) ac = np.full(config_eos.prediction.hours, 0.0)
ac[20] = 1 ac[20] = 1
simulation.ac_charge_hours = ac simulation.set_akku_ac_charge_hours(ac)
dc = np.full(config_eos.prediction.hours, 0.0) dc = np.full(config_eos.prediction.hours, 0.0)
dc[11] = 1 dc[11] = 1
simulation.dc_charge_hours = dc simulation.set_akku_dc_charge_hours(dc)
simulation.home_appliance_start_hour = 2
return simulation return simulation
@@ -242,26 +242,26 @@ def test_simulation(genetic_simulation_2):
) )
# Verfify DC and AC Charge Bins # Verfify DC and AC Charge Bins
assert abs(result["akku_soc_pro_stunde"][2] - 80.0) < 1e-5, ( assert abs(result["akku_soc_pro_stunde"][2] - 44.70681818181818) < 1e-5, (
"'akku_soc_pro_stunde[2]' should be 80.0." "'akku_soc_pro_stunde[2]' should be 44.70681818181818."
) )
assert abs(result["akku_soc_pro_stunde"][10] - 80.0) < 1e-5, ( assert abs(result["akku_soc_pro_stunde"][10] - 10.0) < 1e-5, (
"'akku_soc_pro_stunde[10]' should be 80." "'akku_soc_pro_stunde[10]' should be 10."
) )
assert abs(result["Netzeinspeisung_Wh_pro_Stunde"][10] - 3946.93) < 1e-3, ( assert abs(result["Netzeinspeisung_Wh_pro_Stunde"][10] - 3946.93) < 1e-3, (
"'Netzeinspeisung_Wh_pro_Stunde[11]' should be 3946.93." "'Netzeinspeisung_Wh_pro_Stunde[11]' should be 3946.93."
) )
assert abs(result["Netzeinspeisung_Wh_pro_Stunde"][11] - 2799.7263636361786) < 1e-3, ( assert abs(result["Netzeinspeisung_Wh_pro_Stunde"][11] - 0.0) < 1e-3, (
"'Netzeinspeisung_Wh_pro_Stunde[11]' should be 2799.7263636361786." "'Netzeinspeisung_Wh_pro_Stunde[11]' should be 0.0."
) )
assert abs(result["akku_soc_pro_stunde"][20] - 100) < 1e-5, ( assert abs(result["akku_soc_pro_stunde"][20] - 10) < 1e-5, (
"'akku_soc_pro_stunde[20]' should be 100." "'akku_soc_pro_stunde[20]' should be 10."
) )
assert abs(result["Last_Wh_pro_Stunde"][20] - 1050.98) < 1e-3, ( assert abs(result["Last_Wh_pro_Stunde"][20] - 6050.98) < 1e-3, (
"'Last_Wh_pro_Stunde[20]' should be 1050.98." "'Last_Wh_pro_Stunde[20]' should be 6050.98."
) )
print("All tests passed successfully.") print("All tests passed successfully.")
@@ -280,6 +280,46 @@ def test_set_parameters(genetic_simulation_2):
) )
def test_set_akku_discharge_hours(genetic_simulation_2):
"""Test the set_akku_discharge_hours method of EnergyManagement."""
simulation = genetic_simulation_2
discharge_hours = np.full(simulation.prediction_hours, 1.0)
simulation.set_akku_discharge_hours(discharge_hours)
assert np.array_equal(simulation.battery.discharge_array, discharge_hours), (
"Discharge hours should be set correctly"
)
def test_set_akku_ac_charge_hours(genetic_simulation_2):
"""Test the set_akku_ac_charge_hours method of EnergyManagement."""
simulation = genetic_simulation_2
ac_charge_hours = np.full(simulation.prediction_hours, 1.0)
simulation.set_akku_ac_charge_hours(ac_charge_hours)
assert np.array_equal(simulation.ac_charge_hours, ac_charge_hours), (
"AC charge hours should be set correctly"
)
def test_set_akku_dc_charge_hours(genetic_simulation_2):
"""Test the set_akku_dc_charge_hours method of EnergyManagement."""
simulation = genetic_simulation_2
dc_charge_hours = np.full(simulation.prediction_hours, 1.0)
simulation.set_akku_dc_charge_hours(dc_charge_hours)
assert np.array_equal(simulation.dc_charge_hours, dc_charge_hours), (
"DC charge hours should be set correctly"
)
def test_set_ev_charge_hours(genetic_simulation_2):
"""Test the set_ev_charge_hours method of EnergyManagement."""
simulation = genetic_simulation_2
ev_charge_hours = np.full(simulation.prediction_hours, 1.0)
simulation.set_ev_charge_hours(ev_charge_hours)
assert np.array_equal(simulation.ev_charge_hours, ev_charge_hours), (
"EV charge hours should be set correctly"
)
def test_reset(genetic_simulation_2): def test_reset(genetic_simulation_2):
"""Test the reset method of EnergyManagement.""" """Test the reset method of EnergyManagement."""
simulation = genetic_simulation_2 simulation = genetic_simulation_2

View File

@@ -2,14 +2,14 @@
"ac_charge": [ "ac_charge": [
0.0, 0.0,
0.0, 0.0,
0.875,
0.0, 0.0,
0.875,
0.0, 0.0,
0.625,
0.75,
0.0, 0.0,
0.0, 0.375,
0.0,
0.0,
0.0,
0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
@@ -50,16 +50,16 @@
0.0 0.0
], ],
"dc_charge": [ "dc_charge": [
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,
@@ -103,9 +103,9 @@
0, 0,
0, 0,
0, 0,
1,
0, 0,
0, 1,
0,
0, 0,
0, 0,
0, 0,
@@ -476,6 +476,7 @@
0.0 0.0
], ],
"akku_soc_pro_stunde": [ "akku_soc_pro_stunde": [
80.0,
80.0, 80.0,
79.91107093663912, 79.91107093663912,
79.91107093663912, 79.91107093663912,
@@ -503,7 +504,7 @@
76.64231728537023, 76.64231728537023,
77.71252293120729, 77.71252293120729,
81.22045681594867, 81.22045681594867,
81.61517878095492, 87.86517878095492,
100.0, 100.0,
100.0, 100.0,
100.0, 100.0,
@@ -512,7 +513,6 @@
100.0, 100.0,
100.0, 100.0,
100.0, 100.0,
96.84060778236915,
96.84060778236915 96.84060778236915
], ],
"Electricity_price": [ "Electricity_price": [
@@ -558,108 +558,108 @@
}, },
"eauto_obj": { "eauto_obj": {
"device_id": "ev1", "device_id": "ev1",
"hours": 48,
"charge_array": [ "charge_array": [
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,
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,
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
], ],
"discharge_array": [ "discharge_array": [
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, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0 1
], ],
"discharging_efficiency": 1.0, "discharging_efficiency": 1.0,
"hours": 48,
"capacity_wh": 60000, "capacity_wh": 60000,
"charging_efficiency": 0.95, "charging_efficiency": 0.95,
"max_charge_power_w": 11040, "max_charge_power_w": 11040,

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,13 @@
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
1.0,
1.0,
0.75,
0.0,
0.0,
0.0,
0.5,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
@@ -11,14 +18,7 @@
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 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,
@@ -50,16 +50,16 @@
0.0 0.0
], ],
"dc_charge": [ "dc_charge": [
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,
@@ -101,9 +101,7 @@
], ],
"discharge_allowed": [ "discharge_allowed": [
0, 0,
0, 1,
0,
0,
0, 0,
0, 0,
0, 0,
@@ -111,13 +109,18 @@
0, 0,
0, 0,
1, 1,
0,
1,
1,
1, 1,
0, 0,
0, 0,
0, 0,
0, 1,
1, 1,
0, 0,
1,
1,
0, 0,
1, 1,
1, 1,
@@ -125,22 +128,19 @@
1, 1,
1, 1,
1, 1,
0,
1,
1,
0,
1,
1,
0,
1, 1,
1, 1,
1, 1,
1, 1,
1, 0,
1, 0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1, 1,
1, 1,
1, 1,
@@ -151,65 +151,65 @@
], ],
"eautocharge_hours_float": [ "eautocharge_hours_float": [
0.5, 0.5,
1.0,
0.625,
0.0,
1.0,
0.375, 0.375,
0.375,
0.875,
0.0,
0.0,
0.375,
0.625,
0.375,
0.875,
1.0,
0.875,
0.375,
0.75,
1.0,
0.625,
0.625, 0.625,
0.75, 0.75,
0.375,
1.0,
0.375,
0.375,
1.0,
1.0,
0.0,
0.0,
0.375,
0.625, 0.625,
0.375, 0.5,
1.0, 0.5,
0.875,
0.625,
0.625,
0.0,
0.0,
0.75,
0.375,
0.75, 0.75,
0.0,
0.5,
0.375, 0.375,
0.0, 0.0,
1.0, 0.0,
0.5,
0.5,
0.625, 0.625,
0.875, 0.5,
1.0 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.375,
0.0,
0.0,
0.0,
0.375,
0.0,
0.0,
0.625,
0.0,
0.0,
0.0,
0.0,
0.0
], ],
"result": { "result": {
"Last_Wh_pro_Stunde": [ "Last_Wh_pro_Stunde": [
4986.07, 4986.07,
7618.91, 1063.91,
5253.5599999999995, 1320.56,
12809.029999999999, 8876.029999999999,
14151.67, 8907.67,
10353.82, 7731.82,
5149.22, 6460.22,
8969.78, 6347.78,
2177.92, 3629.12,
1178.71, 1178.71,
1050.98, 1050.98,
988.56, 988.56,
@@ -226,14 +226,14 @@
1141.98, 1141.98,
1056.97, 1056.97,
992.46, 992.46,
1155.99, 5088.99,
827.01, 827.01,
1257.98, 1257.98,
1232.67, 1232.67,
871.26, 4804.26,
860.88, 860.88,
1158.03, 1158.03,
1222.72, 7777.72,
1221.04, 1221.04,
949.99, 949.99,
987.01, 987.01,
@@ -243,42 +243,42 @@
"EAuto_SoC_pro_Stunde": [ "EAuto_SoC_pro_Stunde": [
5.0, 5.0,
11.555, 11.555,
22.48, 11.555,
11.555,
20.294999999999998,
29.035, 29.035,
44.330000000000005, 39.96,
61.809999999999995, 48.699999999999996,
77.105, 57.440000000000005,
83.66, 57.440000000000005,
96.77, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 57.440000000000005,
98.518, 63.995000000000005,
98.518, 63.995000000000005,
98.518, 63.995000000000005,
98.518, 63.995000000000005,
98.518, 70.55,
98.518, 70.55,
98.518, 70.55,
98.518, 81.475,
98.518, 81.475,
98.518, 81.475,
98.518, 81.475,
98.518, 81.475
98.518,
98.518
], ],
"Einnahmen_Euro_pro_Stunde": [ "Einnahmen_Euro_pro_Stunde": [
0.0, 0.0,
@@ -320,10 +320,10 @@
0.0, 0.0,
0.0 0.0
], ],
"Gesamt_Verluste": 7633.823819992856, "Gesamt_Verluste": 7755.845910804702,
"Gesamtbilanz_Euro": 7.648978330847156, "Gesamtbilanz_Euro": 4.690157296412734,
"Gesamteinnahmen_Euro": 0.0, "Gesamteinnahmen_Euro": 0.0,
"Gesamtkosten_Euro": 7.648978330847156, "Gesamtkosten_Euro": 4.690157296412734,
"Home_appliance_wh_per_hour": [ "Home_appliance_wh_per_hour": [
0.0, 0.0,
0.0, 0.0,
@@ -366,83 +366,83 @@
], ],
"Kosten_Euro_pro_Stunde": [ "Kosten_Euro_pro_Stunde": [
0.0, 0.0,
0.48125599199999997,
0.8679294259999999,
2.1885351859999997,
1.4948178300000001,
0.9688838999999999,
0.0, 0.0,
1.3510631400000002, 0.0,
0.07038454500000005, 1.4495244859999996,
0.53097063,
0.44343509999999997,
0.0,
0.0,
0.8107800974767518,
0.0,
0.0,
0.291163892,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.182970359,
0.0, 0.0,
0.0, 0.0,
0.26411047,
0.0, 0.0,
0.0, 0.0,
0.0,
0.0,
0.0,
0.12044799000000005,
0.08545095,
0.007989913613567745, 0.007989913613567745,
0.012219458233588571, 0.0,
0.002459704740224363,
0.0,
0.0,
0.05016012000000004,
0.0076430797975209205,
0.0,
0.31687880399999996,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 0.16722497978466921,
0.0, 0.16484566
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0
], ],
"Netzbezug_Wh_pro_Stunde": [ "Netzbezug_Wh_pro_Stunde": [
0.0, 0.0,
2175.66,
4146.82,
11647.339999999998,
8132.85,
4834.75,
0.0, 0.0,
5951.820000000001, 0.0,
234.85000000000014, 7714.339999999998,
2888.8500000000004,
2212.75,
0.0,
0.0,
2705.305630553059,
0.0,
0.0,
980.68,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
556.31,
0.0, 0.0,
0.0, 0.0,
799.85,
0.0, 0.0,
0.0, 0.0,
0.0,
0.0,
0.0,
395.9500000000001,
351.65,
35.04348076126204, 35.04348076126204,
55.24167375040041, 0.0,
11.752053226107805,
0.0,
0.0,
250.30000000000018,
34.77288351920346,
0.0,
1057.3199999999997,
0.0, 0.0,
0.0, 0.0,
0.0, 0.0,
0.0, 572.4922279516235,
0.0, 592.97
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0
], ],
"Netzeinspeisung_Wh_pro_Stunde": [ "Netzeinspeisung_Wh_pro_Stunde": [
0.0, 0.0,
@@ -486,83 +486,83 @@
], ],
"Verluste_Pro_Stunde": [ "Verluste_Pro_Stunde": [
760.062272727273, 760.062272727273,
945.0, 2.817272727272737,
207.0, 29.157272727272726,
483.0, 276.0,
552.0, 276.0,
483.0, 345.0,
367.81909090909085, 615.5918181818183,
414.0, 730.0663636363638,
55.200000000000045, 373.0373243336329,
23.391818181818195, 23.391818181818195,
99.72409090909093, 99.72409090909093,
133.72909090909081, 0.0,
124.41545454545451, 124.41545454545451,
96.08318181818186, 96.08318181818186,
70.41409090909087, 70.41409090909087,
118.37045454545455, 118.37045454545455,
94.68272727272722, 94.68272727272722,
83.01681818181817, 83.01681818181817,
75.86045454545456, 0.0,
66.66681818181814, 66.66681818181814,
69.12409090909085, 69.12409090909085,
109.0704545454546,
55.96909090909088,
0.0, 0.0,
109.96227272727276,
47.952272727272714,
11.233982308648535, 11.233982308648535,
48.41330768174522, 682.1181818181817,
161.62968357967037, 160.0271308670193,
21.962728535423857, 21.962728535423857,
538.2984000000038, 538.2984000000038,
441.95211196761403, 207.0,
260.56941082122324, 255.8276539776955,
171.99990368477063, 171.99990368477063,
62.214291413756285, 1026.818181818182,
35.132727272727266, 35.132727272727266,
77.27590909090907, 77.27590909090907,
134.59227272727276, 134.59227272727276,
100.08954545454549, 22.022423461142267,
80.85954545454547 0.0
], ],
"akku_soc_pro_stunde": [ "akku_soc_pro_stunde": [
80.0,
62.54222623966943, 62.54222623966943,
43.60283230027549, 62.45329717630854,
43.60283230027549, 61.532928719008275,
43.60283230027549, 61.532928719008275,
43.60283230027549, 61.532928719008275,
43.60283230027549, 61.532928719008275,
38.52647210743802, 50.81349001377411,
38.52647210743802, 36.480587121212125,
38.52647210743802, 46.842735019368604,
37.78809400826446, 46.10435692019505,
34.64023760330579, 42.95650051523637,
30.418991046831955, 42.95650051523637,
26.49173553719008, 39.029245005594504,
23.458806818181817, 35.996316286586236,
21.236139807162534, 33.77364927556696,
17.499698691460054, 30.03720815986448,
14.510976239669422, 27.048485708073848,
11.890495867768596, 24.428005336173022,
9.495910812672175, 24.428005336173022,
7.391528925619835, 22.32362344912068,
5.209581611570248, 20.141676135071094,
1.7667011019283745, 20.141676135071094,
0.0, 16.670644798982938,
0.0, 15.156999826531148,
0.3120550641291261, 15.469054890660274,
1.07020564583707, 0.471637535288375,
4.578139530578446, 4.030157048585656,
4.728141236897871, 4.180158754905081,
19.68087457022947, 19.132892088236673,
31.94341995234899, 19.132892088236673,
38.90006700591099, 26.239215809839333,
42.674787887051245, 30.01393669097958,
43.17025540478875, 8.49189812348647,
42.06126780148296, 7.382910520180684,
39.622002994320425, 4.9436457130181495,
35.373509537020155, 0.6951522557178741,
32.214117319389295, 0.0
29.661732677516017
], ],
"Electricity_price": [ "Electricity_price": [
0.000228, 0.000228,
@@ -607,211 +607,211 @@
}, },
"eauto_obj": { "eauto_obj": {
"device_id": "ev1", "device_id": "ev1",
"hours": 48,
"charge_array": [ "charge_array": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.375,
0.625,
0.375,
0.875,
1.0, 1.0,
0.875, 1.0,
0.375, 1.0,
0.75, 1.0,
0.1, 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,
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
], ],
"discharge_array": [ "discharge_array": [
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, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0, 1,
0 1
], ],
"discharging_efficiency": 1.0, "discharging_efficiency": 1.0,
"hours": 48,
"capacity_wh": 60000, "capacity_wh": 60000,
"charging_efficiency": 0.95, "charging_efficiency": 0.95,
"max_charge_power_w": 11040, "max_charge_power_w": 11040,
"soc_wh": 59110.8, "soc_wh": 48885.0,
"initial_soc_percentage": 5 "initial_soc_percentage": 5
}, },
"start_solution": [ "start_solution": [
19.0, 14.0,
18.0, 13.0,
18.0, 0.0,
7.0,
5.0,
20.0, 20.0,
17.0, 20.0,
15.0, 18.0,
4.0, 5.0,
3.0,
9.0,
16.0,
12.0, 12.0,
13.0, 13.0,
8.0, 8.0,
5.0,
1.0,
1.0,
4.0, 4.0,
0.0,
14.0,
11.0,
9.0, 9.0,
16.0,
8.0,
9.0,
5.0,
10.0,
13.0,
13.0,
8.0,
8.0,
9.0,
5.0,
10.0,
7.0,
2.0, 2.0,
5.0,
8.0, 8.0,
10.0,
12.0,
10.0,
9.0,
13.0,
7.0,
8.0,
7.0,
9.0,
13.0,
7.0,
10.0,
8.0,
8.0,
12.0,
12.0,
7.0,
10.0,
13.0,
11.0,
11.0,
10.0,
11.0,
10.0,
13.0,
10.0,
10.0,
12.0, 12.0,
2.0, 2.0,
6.0, 9.0,
3.0, 11.0,
0.0, 10.0,
10.0,
6.0, 6.0,
1.0, 1.0,
12.0,
9.0,
12.0,
13.0,
10.0,
13.0,
11.0,
2.0,
1.0, 1.0,
5.0,
0.0,
0.0,
1.0,
3.0,
1.0,
5.0,
6.0,
5.0,
1.0,
4.0,
6.0,
3.0,
3.0, 3.0,
4.0, 4.0,
1.0,
6.0,
1.0,
1.0,
6.0,
6.0,
0.0,
0.0,
1.0,
3.0, 3.0,
1.0, 2.0,
6.0, 2.0,
5.0,
3.0,
3.0,
0.0,
0.0,
4.0,
1.0,
4.0, 4.0,
0.0,
2.0,
1.0, 1.0,
0.0, 0.0,
6.0, 0.0,
2.0,
2.0,
3.0, 3.0,
5.0, 2.0,
6.0, 2.0,
0.0,
0.0,
0.0,
0.0,
0.0,
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,
1.0,
0.0,
0.0,
3.0,
0.0,
0.0,
0.0,
0.0,
0.0,
13.0 13.0
], ],
"washingstart": 13 "washingstart": 13