Files
EOS/docs/akkudoktoreos/resource.md
Bobby Noelte b397b5d43e fix: automatic optimization (#596)
This fix implements the long term goal to have the EOS server run optimization (or
energy management) on regular intervals automatically. Thus clients can request
the current energy management plan at any time and it is updated on regular
intervals without interaction by the client.

This fix started out to "only" make automatic optimization (or energy management)
runs working. It turned out there are several endpoints that in some way
update predictions or run the optimization. To lock against such concurrent attempts
the code had to be refactored to allow control of execution. During refactoring it
became clear that some classes and files are named without a proper reference
to their usage. Thus not only refactoring but also renaming became necessary.
The names are still not the best, but I hope they are more intuitive.

The fix includes several bug fixes that are not directly related to the automatic optimization
but are necessary to keep EOS running properly to do the automatic optimization and
to test and document the changes.

This is a breaking change as the configuration structure changed once again and
the server API was also enhanced and streamlined. The server API that is used by
Andreas and Jörg in their videos has not changed.

* fix: automatic optimization

  Allow optimization to automatically run on configured intervals gathering all
  optimization parameters from configuration and predictions. The automatic run
  can be configured to only run prediction updates skipping the optimization.
  Extend documentaion to also cover automatic optimization. Lock automatic runs
  against runs initiated by the /optimize or other endpoints. Provide new
  endpoints to retrieve the energy management plan and the genetic solution
  of the latest automatic optimization run. Offload energy management to thread
  pool executor to keep the app more responsive during the CPU heavy optimization
  run.

* fix: EOS servers recognize environment variables on startup

  Force initialisation of EOS configuration on server startup to assure
  all sources of EOS configuration are properly set up and read. Adapt
  server tests and configuration tests to also test for environment
  variable configuration.

* fix: Remove 0.0.0.0 to localhost translation under Windows

  EOS imposed a 0.0.0.0 to localhost translation under Windows for
  convenience. This caused some trouble in user configurations. Now, as the
  default IP address configuration is 127.0.0.1, the user is responsible
  for to set up the correct Windows compliant IP address.

* fix: allow names for hosts additional to IP addresses

* fix: access pydantic model fields by class

  Access by instance is deprecated.

* fix: down sampling key_to_array

* fix: make cache clear endpoint clear all cache files

  Make /v1/admin/cache/clear clear all cache files. Before it only cleared
  expired cache files by default. Add new endpoint /v1/admin/clear-expired
  to only clear expired cache files.

* fix: timezonefinder returns Europe/Paris instead of Europe/Berlin

  timezonefinder 8.10 got more inaccurate for timezones in europe as there is
  a common timezone. Use new package tzfpy instead which is still returning
  Europe/Berlin if you are in Germany. tzfpy also claims to be faster than
  timezonefinder.

* fix: provider settings configuration

  Provider configuration used to be a union holding the settings for several
  providers. Pydantic union handling does not always find the correct type
  for a provider setting. This led to exceptions in specific configurations.
  Now provider settings are explicit comfiguration items for each possible
  provider. This is a breaking change as the configuration structure was
  changed.

* fix: ClearOutside weather prediction irradiance calculation

  Pvlib needs a pandas time index. Convert time index.

* fix: test config file priority

  Do not use config_eos fixture as this fixture already creates a config file.

* fix: optimization sample request documentation

  Provide all data in documentation of optimization sample request.

* fix: gitlint blocking pip dependency resolution

  Replace gitlint by commitizen. Gitlint is not actively maintained anymore.
  Gitlint dependencies blocked pip from dependency resolution.

* fix: sync pre-commit config to actual dependency requirements

  .pre-commit-config.yaml was out of sync, also requirements-dev.txt.

* fix: missing babel in requirements.txt

  Add babel to requirements.txt

* feat: setup default device configuration for automatic optimization

  In case the parameters for automatic optimization are not fully defined a
  default configuration is setup to allow the automatic energy management
  run. The default configuration may help the user to correctly define
  the device configuration.

* feat: allow configuration of genetic algorithm parameters

  The genetic algorithm parameters for number of individuals, number of
  generations, the seed and penalty function parameters are now avaliable
  as configuration options.

* feat: allow configuration of home appliance time windows

  The time windows a home appliance is allowed to run are now configurable
  by the configuration (for /v1 API) and also by the home appliance parameters
  (for the classic /optimize API). If there is no such configuration the
  time window defaults to optimization hours, which was the standard before
  the change. Documentation on how to configure time windows is added.

* feat: standardize mesaurement keys for battery/ ev SoC measurements

  The standardized measurement keys to report battery SoC to the device
  simulations can now be retrieved from the device configuration as a
  read-only config option.

* feat: feed in tariff prediction

  Add feed in tarif predictions needed for automatic optimization. The feed in
  tariff can be retrieved as fixed feed in tarif or can be imported. Also add
  tests for the different feed in tariff providers. Extend documentation to
  cover the feed in tariff providers.

* feat: add energy management plan based on S2 standard instructions

  EOS can generate an energy management plan as a list of simple instructions.
  May be retrieved by the /v1/energy-management/plan endpoint. The instructions
  loosely follow the S2 energy management standard.

* feat: make measurement keys configurable by EOS configuration.

  The fixed measurement keys are replaced by configurable measurement keys.

* feat: make pendulum DateTime, Date, Duration types usable for pydantic models

  Use pydantic_extra_types.pendulum_dt to get pydantic pendulum types. Types are
  added to the datetimeutil utility. Remove custom made pendulum adaptations
  from EOS pydantic module. Make EOS modules use the pydantic pendulum types
  managed by the datetimeutil module instead of the core pendulum types.

* feat: Add Time, TimeWindow, TimeWindowSequence and to_time to datetimeutil.

  The time windows are are added to support home appliance time window
  configuration. All time classes are also pydantic models. Time is the base
  class for time definition derived from pendulum.Time.

* feat: Extend DataRecord by configurable field like data.

  Configurable field like data was added to support the configuration of
  measurement records.

* feat: Add additional information to health information

  Version information is added to the health endpoints of eos and eosDash.
  The start time of the last optimization and the latest run time of the energy
  management is added to the EOS health information.

* feat: add pydantic merge model tests

* feat: add plan tab to EOSdash

  The plan tab displays the current energy management instructions.

* feat: add predictions tab to EOSdash

  The predictions tab displays the current predictions.

* feat: add cache management to EOSdash admin tab

  The admin tab is extended by a section for cache management. It allows to
  clear the cache.

* feat: add about tab to EOSdash

  The about tab resembles the former hello tab and provides extra information.

* feat: Adapt changelog and prepare for release management

  Release management using commitizen is added. The changelog file is adapted and
  teh changelog and a description for release management is added in the
  documentation.

* feat(doc): Improve install and devlopment documentation

  Provide a more concise installation description in Readme.md and add extra
  installation page and development page to documentation.

* chore: Use memory cache for interpolation instead of dict in inverter

  Decorate calculate_self_consumption() with @cachemethod_until_update to cache
  results in memory during an energy management/ optimization run. Replacement
  of dict type caching in inverter is now possible because all optimization
  runs are properly locked and the memory cache CacheUntilUpdateStore is properly
  cleared at the start of any energy management/ optimization operation.

* chore: refactor genetic

  Refactor the genetic algorithm modules for enhanced module structure and better
  readability. Removed unnecessary and overcomplex devices singleton. Also
  split devices configuration from genetic algorithm parameters to allow further
  development independently from genetic algorithm parameter format. Move
  charge rates configuration for electric vehicles from optimization to devices
  configuration to allow to have different charge rates for different cars in
  the future.

* chore: Rename memory cache to CacheEnergyManagementStore

  The name better resembles the task of the cache to chache function and method
  results for an energy management run. Also the decorator functions are renamed
  accordingly: cachemethod_energy_management, cache_energy_management

* chore: use class properties for config/ems/prediction mixin classes

* chore: skip debug logs from mathplotlib

  Mathplotlib is very noisy in debug mode.

* chore: automatically sync bokeh js to bokeh python package

  bokeh was updated to 3.8.0, make JS CDN automatically follow the package version.

* chore: rename hello.py to about.py

  Make hello.py the adapted EOSdash about page.

* chore: remove demo page from EOSdash

  As no the plan and prediction pages are working without configuration, the demo
  page is no longer necessary

* chore: split test_server.py for system test

  Split test_server.py to create explicit test_system.py for system tests.

* chore: move doc utils to generate_config_md.py

  The doc utils are only used in scripts/generate_config_md.py. Move it there to
  attribute for strong cohesion.

* chore: improve pydantic merge model documentation

* chore: remove pendulum warning from readme

* chore: remove GitHub discussions from contributing documentation

  Github discussions is to be replaced by Akkudoktor.net.

* chore(release): bump version to 0.1.0+dev for development

* build(deps): bump fastapi[standard] from 0.115.14 to 0.117.1

  bump fastapi and make coverage version (for pytest-cov) explicit to avoid pip break.

* build(deps): bump uvicorn from 0.36.0 to 0.37.0

BREAKING CHANGE: EOS configuration changed. V1 API changed.

  - The available_charge_rates_percent configuration is removed from optimization.
    Use the new charge_rate configuration for the electric vehicle
  - Optimization configuration parameter hours renamed to horizon_hours
  - Device configuration now has to provide the number of devices and device
    properties per device.
  - Specific prediction provider configuration to be provided by explicit
    configuration item (no union for all providers).
  - Measurement keys to be provided as a list.
  - New feed in tariff providers have to be configured.
  - /v1/measurement/loadxxx endpoints are removed. Use generic mesaurement endpoints.
  - /v1/admin/cache/clear now clears all cache files. Use
    /v1/admin/cache/clear-expired to only clear all expired cache files.

Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
2025-10-28 02:50:31 +01:00

259 lines
11 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

% SPDX-License-Identifier: Apache-2.0
(resource-page)=
# Resources (Device Simulations)
## Concepts
The simulations for resources are leaning on general concepts of the [S2 standard].
### Control Types
The control of resources and such what a resource simulation will simulate follows three
basic control principles:
- Operation Mode Based Control (OMBC)
- Fill Rate Based Control (FRBC)
- Demand Driven Based Control (DDBC)
Although these control principles differ enough to separate them into three distinct control types,
there are some common aspects that make them similar:
- Operation Modes
- Transitions and
- Timers.
The objective for a control type is under which circumstances what things can be adjusted, and what
the constraints are for these adjustments. The three control types model a virtual, abstract resource
for simulation.
The abstract resource ignores all details of pyhsical device that are not relevant to energy
management. In addition, physical devices have an enormous variety in parameters, sensors, control
strategies, concerns, safeguards, and so on. It would be practically impossible to develop a
simulation that can
understand all the parameters of all the physical devices on the market. By making the resource more
abstract, its concepts can be translated to all sorts of physical devices, even though internally
they function very differently. As a consequence, it not always possible to make a 100% accurate
description of all the behaviors and constraints in these abstractions. But the abstractions used
in the control types are quite powerful, and should allow you to come pretty close.
The control types basically define how the simulated resource can be described. The user in the end
selects the proper desciption of a physical device using the configuration options provided for
resource simulations. The configuration sets how the simulated resource functions, what it can do and
what kind of constraints it has.
### Resource Simulation
Based on the description of this virtual resource, the resource simulation can make predictions of
what the physical device will do in certain situations, and when it is allowed to execute
instructions generated by the optimization as part of the energy management plan evaluation.
### Resource Status
Once the physical device has changed it's behavior, the resource simulation should be informed
to make the simulation change it's state accordingly.
The actual state of a pyhsical device may be reported to the resource simulation by the
**PUT** `/v1/resource/status` API endpoint.
## Battery
There is a wealth of possible battery operation modes:
<!-- pyml disable line-length -->
| Mode | Purpose / Behavior | Typical Trigger / Context |
| ------------------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| **IDLE** | Battery neither charges nor discharges (SOC stable). | No active control objective or power imbalance below thresholds. |
| **SELF_CONSUMPTION** | Charge from PV surplus and discharge to cover local load. | PV generation > load (charge) or load > PV (discharge). |
| **NON_EXPORT** | Charge from on-site or local surplus with the goal of minimizing or preventing energy export to the external grid. Discharging to the grid is not allowed. | Export limit reached and SOC < SOC_max. |
| **PEAK_SHAVING** | Discharge to keep grid import below a target threshold. | Predicted or measured site load exceeds peak limit. |
| **GRID_SUPPORT_EXPORT** | Discharge energy to grid for revenue (V2G, wholesale market, flexibility service). | Market or signal permits profitable export. |
| **GRID_SUPPORT_IMPORT** | Charge from grid to absorb surplus or provide up-regulation service. | Low-price or grid-support signal detected. |
| **FREQUENCY_REGULATION** | Rapid charge/discharge response to grid frequency deviations. | Active participation in frequency control. |
| **RAMP_RATE_CONTROL** | Smooth site-level power ramp rates by buffering fluctuations. | Sudden PV/load change exceeding ramp limit. |
| **RESERVE_BACKUP** | Maintain SOC reserve threshold to ensure backup capacity. | Resilience mode active, grid operational. |
| **OUTAGE_SUPPLY** | Islanded operation: power local loads using stored energy (and PV if available). | Grid failure detected. |
| **FORCED_CHARGE** | Manual or external control command to charge (e.g., pre-event, maintenance). No discharge. | Operator or optimizer command. |
| **FORCED_DISCHARGE** | Manual or external control command to discharge. No charge. | Operator or optimizer command. |
| **FAULT** | Battery unavailable due to fault, safety, or protection state. | Fault detected (thermal, voltage, comms, etc.). |
<!-- pyml enable line-length -->
The optimization algorithm, the device simulation and the configuration properties only support the
most important of these modes.
### Battery Simulation
The battery simulation assumes an idealized battery model. Under this model, the battery can be
operated in three discrete operation modes with fill rate based control (FRBC):
| **Operation Mode ID** | **Description** |
| ------------------------ | --------------------------------------------------------------------- |
| **SELF_CONSUMPTION** | Charge from local surplus and discharge to cover local load. |
| **NON_EXPORT** | Charge from local surplus and do not discharge. |
| **FORCED_CHARGE** | Charge. |
The **operation mode factor** (0.01.0) specifies the normalized power rate relative to the
battery's nominal maximum charge or discharge power. A value of 1.0 corresponds to full-rate
charging or discharging, while 0.0 indicates no power transfer. Intermediate values scale the power
proportionally.
The **fill level** (0.01.0) specifies the normalized fill level relative to the
battery's nominal maximum charge. A value of 1.0 corresponds to full while 0.0 indicates empty.
Intermediate values scale the fill level proportionally.
### Battery Configuration
### Battery Stati
To keep the battery simulation in synchonization with the actual stati of the battery the following
resource stati may be reported to EOS by the **PUT** `/v1/resource/status` API endpoint.
#### Battery FRBCActuatorStatus
The operation mode the battery is currently operated.
```json
{
"type": "FRBCActuatorStatus",
"active_operation_mode_id": "GRID_SUPPORT_IMPORT",
"operation_mode_factor": "0.375",
"previous_operation_mode_id": "SELF_CONSUMPTION",
"transistion_timestamp": "20250725T12:00:12"
}
```
#### Battery FRBCStorageStatus
The current battery state of charge (SoC).
```json
{
"type": "FRBCStorageStatus",
"present_fill_level": "0.88"
}
```
#### Battery PowerMeasurement
The current power that the battery is charged or discharged with \[W\].
```json
{
"type": "PowerMeasurement",
"measurement_timestamp": "20250725T12:00:12",
"values": [
{
"commodity_quantity": "ELECTRIC.POWER.L1",
"value": "887.5"
},
{
"commodity_quantity": "ELECTRIC.POWER.L2",
"value": "905.5"
},
{
"commodity_quantity": "ELECTRIC.POWER.L2",
"value": "1100.7"
},
]
}
```
For symmetric (or unknown) power distribution:
```json
{
"type": "PowerMeasurement",
"measurement_timestamp": "20250725T12:00:12",
"values": [
{
"commodity_quantity": "ELECTRIC.POWER.3_PHASE_SYM",
"value": "1000"
}
]
}
```
## Electric Vehicle
The electric vehicle is basically a battery with a reduced set of operation modes.
### Electric Vehicle Instructions
The electric vehicle control instructions assume an idealized EV battery model. Under this model,
the EV battery can be operated in two operation modes:
| **Operation Mode ID** | **Description** |
| --------------------- | ----------------------------------------------------------------------- |
| **IDLE** | Battery neither charges nor discharges; holds its state of charge. |
| **FORCED_CHARGE** | Charge at a specified power rate up to the allowable maximum. |
The **operation mode factor** (0.01.0) specifies the normalized power rate relative to the
battery's nominal maximum charge power. A value of 1.0 corresponds to full-rate charging, while 0.0
indicates no power transfer. Intermediate values scale the power proportionally.
## Home Appliance
The optimization algorithm supports one start of the home appliance within the optimization
horizon.
### Home Appliance Simulation
### Home Appliance Configuration
Home appliance to run within the optimization horizon.
```json
[
{
"device_id": "dishwasher1",
"consumption_wh": 2000,
"duration_h": 3
}
]
```
Home appliance to run within a time window of 5 hours starting at 8:00 every day and another time
window of 3 hours starting at 15:00 every day. See
[Time Window Sequence Configuration](configtimewindow-page) for more information.
```json
[
{
"device_id": "dishwasher1",
"consumption_wh": 2000,
"duration_h": 3,
"time_windows": {
"windows": [
{
"start_time": "08:00",
"duration": "5 hours"
},
{
"start_time": "15:00",
"duration": "3 hours"
}
]
}
}
]
```
:::{admonition} Note
:class: note
The optimization algorithm always restricts to one start within the optimization horizon per
energy management run.
:::
### Home Appliance Instructions
The home appliance instructions assume an idealized home appliance model. Under this model,
the home appliance can be operated in two operation modes:
| **Operation Mode ID** | **Description** |
|-----------------------|-------------------------------------------------------------------------|
| **RUN** | The home appliance is started and runs until the end of it's power |
| | sequence. |
| **IDLE** | The home appliance does not run. |
The **operation mode factor** (0.01.0) is ignored.