mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2025-10-11 20:06:18 +00:00
Improve Configuration and Prediction Usability (#220)
* Update utilities in utils submodule. * Add base configuration modules. * Add server base configuration modules. * Add devices base configuration modules. * Add optimization base configuration modules. * Add utils base configuration modules. * Add prediction abstract and base classes plus tests. * Add PV forecast to prediction submodule. The PV forecast modules are adapted from the class_pvforecast module and replace it. * Add weather forecast to prediction submodule. The modules provide classes and methods to retrieve, manage, and process weather forecast data from various sources. Includes are structured representations of weather data and utilities for fetching forecasts for specific locations and time ranges. BrightSky and ClearOutside are currently supported. * Add electricity price forecast to prediction submodule. * Adapt fastapi server to base config and add fasthtml server. * Add ems to core submodule. * Adapt genetic to config. * Adapt visualize to config. * Adapt common test fixtures to config. * Add load forecast to prediction submodule. * Add core abstract and base classes. * Adapt single test optimization to config. * Adapt devices to config. Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com>
This commit is contained in:
@@ -3,8 +3,12 @@ from typing import Any, Optional
|
||||
import numpy as np
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from akkudoktoreos.devices.devicesabc import DeviceBase
|
||||
from akkudoktoreos.utils.logutil import get_logger
|
||||
from akkudoktoreos.utils.utils import NumpyEncoder
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def max_ladeleistung_w_field(default: Optional[float] = None) -> Optional[float]:
|
||||
return Field(
|
||||
@@ -83,31 +87,86 @@ class EAutoResult(BaseModel):
|
||||
return NumpyEncoder.convert_numpy(field)[0]
|
||||
|
||||
|
||||
class PVAkku:
|
||||
def __init__(self, parameters: BaseAkkuParameters, hours: int = 24):
|
||||
# Battery capacity in Wh
|
||||
self.kapazitaet_wh = parameters.kapazitaet_wh
|
||||
# Initial state of charge in Wh
|
||||
self.start_soc_prozent = parameters.start_soc_prozent
|
||||
self.soc_wh = (parameters.start_soc_prozent / 100) * parameters.kapazitaet_wh
|
||||
self.hours = hours
|
||||
class PVAkku(DeviceBase):
|
||||
def __init__(
|
||||
self,
|
||||
parameters: Optional[BaseAkkuParameters] = None,
|
||||
hours: Optional[int] = 24,
|
||||
provider_id: Optional[str] = None,
|
||||
):
|
||||
# Configuration initialisation
|
||||
self.provider_id = provider_id
|
||||
self.prefix = "<invalid>"
|
||||
if self.provider_id == "GenericBattery":
|
||||
self.prefix = "battery"
|
||||
elif self.provider_id == "GenericBEV":
|
||||
self.prefix = "bev"
|
||||
# Parameter initialisiation
|
||||
self.parameters = parameters
|
||||
if hours is None:
|
||||
self.hours = self.total_hours
|
||||
else:
|
||||
self.hours = hours
|
||||
|
||||
self.initialised = False
|
||||
# Run setup if parameters are given, otherwise setup() has to be called later when the config is initialised.
|
||||
if self.parameters is not None:
|
||||
self.setup()
|
||||
|
||||
def setup(self) -> None:
|
||||
if self.initialised:
|
||||
return
|
||||
if self.provider_id is not None:
|
||||
# Setup by configuration
|
||||
# Battery capacity in Wh
|
||||
self.kapazitaet_wh = getattr(self.config, f"{self.prefix}_capacity")
|
||||
# Initial state of charge in Wh
|
||||
self.start_soc_prozent = getattr(self.config, f"{self.prefix}_soc_start")
|
||||
self.hours = self.total_hours
|
||||
# Charge and discharge efficiency
|
||||
self.lade_effizienz = getattr(self.config, f"{self.prefix}_charge_efficiency")
|
||||
self.entlade_effizienz = getattr(self.config, f"{self.prefix}_discharge_efficiency")
|
||||
self.max_ladeleistung_w = getattr(self.config, f"{self.prefix}_charge_power_max")
|
||||
# Only assign for storage battery
|
||||
if self.provider_id == "GenericBattery":
|
||||
self.min_soc_prozent = getattr(self.config, f"{self.prefix}_soc_mint")
|
||||
else:
|
||||
self.min_soc_prozent = 0
|
||||
self.max_soc_prozent = getattr(self.config, f"{self.prefix}_soc_mint")
|
||||
elif self.parameters is not None:
|
||||
# Setup by parameters
|
||||
# Battery capacity in Wh
|
||||
self.kapazitaet_wh = self.parameters.kapazitaet_wh
|
||||
# Initial state of charge in Wh
|
||||
self.start_soc_prozent = self.parameters.start_soc_prozent
|
||||
# Charge and discharge efficiency
|
||||
self.lade_effizienz = self.parameters.lade_effizienz
|
||||
self.entlade_effizienz = self.parameters.entlade_effizienz
|
||||
self.max_ladeleistung_w = self.parameters.max_ladeleistung_w
|
||||
# Only assign for storage battery
|
||||
self.min_soc_prozent = (
|
||||
self.parameters.min_soc_prozent
|
||||
if isinstance(self.parameters, PVAkkuParameters)
|
||||
else 0
|
||||
)
|
||||
self.max_soc_prozent = self.parameters.max_soc_prozent
|
||||
else:
|
||||
error_msg = "Parameters and provider ID missing. Can't instantiate."
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
|
||||
# init
|
||||
if self.max_ladeleistung_w is None:
|
||||
self.max_ladeleistung_w = self.kapazitaet_wh
|
||||
self.discharge_array = np.full(self.hours, 1)
|
||||
self.charge_array = np.full(self.hours, 1)
|
||||
# Charge and discharge efficiency
|
||||
self.lade_effizienz = parameters.lade_effizienz
|
||||
self.entlade_effizienz = parameters.entlade_effizienz
|
||||
self.max_ladeleistung_w = (
|
||||
parameters.max_ladeleistung_w if parameters.max_ladeleistung_w else self.kapazitaet_wh
|
||||
)
|
||||
# Only assign for storage battery
|
||||
self.min_soc_prozent = (
|
||||
parameters.min_soc_prozent if isinstance(parameters, PVAkkuParameters) else 0
|
||||
)
|
||||
self.max_soc_prozent = parameters.max_soc_prozent
|
||||
# Calculate min and max SoC in Wh
|
||||
# Calculate start, min and max SoC in Wh
|
||||
self.soc_wh = (self.start_soc_prozent / 100) * self.kapazitaet_wh
|
||||
self.min_soc_wh = (self.min_soc_prozent / 100) * self.kapazitaet_wh
|
||||
self.max_soc_wh = (self.max_soc_prozent / 100) * self.kapazitaet_wh
|
||||
|
||||
self.initialised = True
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"kapazitaet_wh": self.kapazitaet_wh,
|
||||
|
310
src/akkudoktoreos/devices/devices.py
Normal file
310
src/akkudoktoreos/devices/devices.py
Normal file
@@ -0,0 +1,310 @@
|
||||
from typing import Any, ClassVar, Dict, Optional, Union
|
||||
|
||||
import numpy as np
|
||||
from numpydantic import NDArray, Shape
|
||||
from pydantic import Field, computed_field
|
||||
|
||||
from akkudoktoreos.config.configabc import SettingsBaseModel
|
||||
from akkudoktoreos.core.coreabc import SingletonMixin
|
||||
from akkudoktoreos.devices.battery import PVAkku
|
||||
from akkudoktoreos.devices.devicesabc import DevicesBase
|
||||
from akkudoktoreos.devices.generic import HomeAppliance
|
||||
from akkudoktoreos.devices.inverter import Wechselrichter
|
||||
from akkudoktoreos.utils.datetimeutil import to_duration
|
||||
from akkudoktoreos.utils.logutil import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class DevicesCommonSettings(SettingsBaseModel):
|
||||
"""Base configuration for devices simulation settings."""
|
||||
|
||||
# Battery
|
||||
# -------
|
||||
battery_provider: Optional[str] = Field(
|
||||
default=None, description="Id of Battery simulation provider."
|
||||
)
|
||||
battery_capacity: Optional[int] = Field(default=None, description="Battery capacity [Wh].")
|
||||
battery_soc_start: Optional[int] = Field(
|
||||
default=None, description="Battery initial state of charge [%]."
|
||||
)
|
||||
battery_soc_min: Optional[int] = Field(
|
||||
default=None, description="Battery minimum state of charge [%]."
|
||||
)
|
||||
battery_soc_max: Optional[int] = Field(
|
||||
default=None, description="Battery maximum state of charge [%]."
|
||||
)
|
||||
battery_charge_efficiency: Optional[float] = Field(
|
||||
default=None, description="Battery charging efficiency [%]."
|
||||
)
|
||||
battery_discharge_efficiency: Optional[float] = Field(
|
||||
default=None, description="Battery discharging efficiency [%]."
|
||||
)
|
||||
battery_charge_power_max: Optional[int] = Field(
|
||||
default=None, description="Battery maximum charge power [W]."
|
||||
)
|
||||
|
||||
# Battery Electric Vehicle
|
||||
# ------------------------
|
||||
bev_provider: Optional[str] = Field(
|
||||
default=None, description="Id of Battery Electric Vehicle simulation provider."
|
||||
)
|
||||
bev_capacity: Optional[int] = Field(
|
||||
default=None, description="Battery Electric Vehicle capacity [Wh]."
|
||||
)
|
||||
bev_soc_start: Optional[int] = Field(
|
||||
default=None, description="Battery Electric Vehicle initial state of charge [%]."
|
||||
)
|
||||
bev_soc_max: Optional[int] = Field(
|
||||
default=None, description="Battery Electric Vehicle maximum state of charge [%]."
|
||||
)
|
||||
bev_charge_efficiency: Optional[float] = Field(
|
||||
default=None, description="Battery Electric Vehicle charging efficiency [%]."
|
||||
)
|
||||
bev_discharge_efficiency: Optional[float] = Field(
|
||||
default=None, description="Battery Electric Vehicle discharging efficiency [%]."
|
||||
)
|
||||
bev_charge_power_max: Optional[int] = Field(
|
||||
default=None, description="Battery Electric Vehicle maximum charge power [W]."
|
||||
)
|
||||
|
||||
# Home Appliance - Dish Washer
|
||||
# ----------------------------
|
||||
dishwasher_provider: Optional[str] = Field(
|
||||
default=None, description="Id of Dish Washer simulation provider."
|
||||
)
|
||||
dishwasher_consumption: Optional[int] = Field(
|
||||
default=None, description="Dish Washer energy consumption [Wh]."
|
||||
)
|
||||
dishwasher_duration: Optional[int] = Field(
|
||||
default=None, description="Dish Washer usage duration [h]."
|
||||
)
|
||||
|
||||
# PV Inverter
|
||||
# -----------
|
||||
inverter_provider: Optional[str] = Field(
|
||||
default=None, description="Id of PV Inverter simulation provider."
|
||||
)
|
||||
inverter_power_max: Optional[float] = Field(
|
||||
default=None, description="Inverter maximum power [W]."
|
||||
)
|
||||
|
||||
|
||||
class Devices(SingletonMixin, DevicesBase):
|
||||
# Results of the devices simulation and
|
||||
# insights into various parameters over the entire forecast period.
|
||||
# -----------------------------------------------------------------
|
||||
last_wh_pro_stunde: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, description="The load in watt-hours per hour."
|
||||
)
|
||||
eauto_soc_pro_stunde: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, description="The state of charge of the EV for each hour."
|
||||
)
|
||||
einnahmen_euro_pro_stunde: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None,
|
||||
description="The revenue from grid feed-in or other sources in euros per hour.",
|
||||
)
|
||||
home_appliance_wh_per_hour: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None,
|
||||
description="The energy consumption of a household appliance in watt-hours per hour.",
|
||||
)
|
||||
kosten_euro_pro_stunde: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, description="The costs in euros per hour."
|
||||
)
|
||||
netzbezug_wh_pro_stunde: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, description="The grid energy drawn in watt-hours per hour."
|
||||
)
|
||||
netzeinspeisung_wh_pro_stunde: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, description="The energy fed into the grid in watt-hours per hour."
|
||||
)
|
||||
verluste_wh_pro_stunde: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None, description="The losses in watt-hours per hour."
|
||||
)
|
||||
akku_soc_pro_stunde: Optional[NDArray[Shape["*"], float]] = Field(
|
||||
default=None,
|
||||
description="The state of charge of the battery (not the EV) in percentage per hour.",
|
||||
)
|
||||
|
||||
# Computed fields
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def total_balance_euro(self) -> float:
|
||||
"""The total balance of revenues minus costs in euros."""
|
||||
return self.total_revenues_euro - self.total_costs_euro
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def total_revenues_euro(self) -> float:
|
||||
"""The total revenues in euros."""
|
||||
if self.einnahmen_euro_pro_stunde is None:
|
||||
return 0
|
||||
return np.nansum(self.einnahmen_euro_pro_stunde)
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def total_costs_euro(self) -> float:
|
||||
"""The total costs in euros."""
|
||||
if self.kosten_euro_pro_stunde is None:
|
||||
return 0
|
||||
return np.nansum(self.kosten_euro_pro_stunde)
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def total_losses_wh(self) -> float:
|
||||
"""The total losses in watt-hours over the entire period."""
|
||||
if self.verluste_wh_pro_stunde is None:
|
||||
return 0
|
||||
return np.nansum(self.verluste_wh_pro_stunde)
|
||||
|
||||
# Devices
|
||||
# TODO: Make devices class a container of device simulation providers.
|
||||
# Device simulations to be used are then enabled in the configuration.
|
||||
akku: ClassVar[PVAkku] = PVAkku(provider_id="GenericBattery")
|
||||
eauto: ClassVar[PVAkku] = PVAkku(provider_id="GenericBEV")
|
||||
home_appliance: ClassVar[HomeAppliance] = HomeAppliance(provider_id="GenericDishWasher")
|
||||
wechselrichter: ClassVar[Wechselrichter] = Wechselrichter(
|
||||
akku=akku, provider_id="GenericInverter"
|
||||
)
|
||||
|
||||
def update_data(self) -> None:
|
||||
"""Update device simulation data."""
|
||||
# Assure devices are set up
|
||||
self.akku.setup()
|
||||
self.eauto.setup()
|
||||
self.home_appliance.setup()
|
||||
self.wechselrichter.setup()
|
||||
|
||||
# Pre-allocate arrays for the results, optimized for speed
|
||||
self.last_wh_pro_stunde = np.full((self.total_hours), np.nan)
|
||||
self.netzeinspeisung_wh_pro_stunde = np.full((self.total_hours), np.nan)
|
||||
self.netzbezug_wh_pro_stunde = np.full((self.total_hours), np.nan)
|
||||
self.kosten_euro_pro_stunde = np.full((self.total_hours), np.nan)
|
||||
self.einnahmen_euro_pro_stunde = np.full((self.total_hours), np.nan)
|
||||
self.akku_soc_pro_stunde = np.full((self.total_hours), np.nan)
|
||||
self.eauto_soc_pro_stunde = np.full((self.total_hours), np.nan)
|
||||
self.verluste_wh_pro_stunde = np.full((self.total_hours), np.nan)
|
||||
self.home_appliance_wh_per_hour = np.full((self.total_hours), np.nan)
|
||||
|
||||
# Set initial state
|
||||
simulation_step = to_duration("1 hour")
|
||||
if self.akku:
|
||||
self.akku_soc_pro_stunde[0] = self.akku.ladezustand_in_prozent()
|
||||
if self.eauto:
|
||||
self.eauto_soc_pro_stunde[0] = self.eauto.ladezustand_in_prozent()
|
||||
|
||||
# Get predictions for full device simulation time range
|
||||
# gesamtlast[stunde]
|
||||
load_total_mean = self.prediction.key_to_array(
|
||||
"load_total_mean",
|
||||
start_datetime=self.start_datetime,
|
||||
end_datetime=self.end_datetime,
|
||||
interval=simulation_step,
|
||||
)
|
||||
# pv_prognose_wh[stunde]
|
||||
pvforecast_ac_power = self.prediction.key_to_array(
|
||||
"pvforecast_ac_power",
|
||||
start_datetime=self.start_datetime,
|
||||
end_datetime=self.end_datetime,
|
||||
interval=simulation_step,
|
||||
)
|
||||
# strompreis_euro_pro_wh[stunde]
|
||||
elecprice_marketprice = self.prediction.key_to_array(
|
||||
"elecprice_marketprice",
|
||||
start_datetime=self.start_datetime,
|
||||
end_datetime=self.end_datetime,
|
||||
interval=simulation_step,
|
||||
)
|
||||
# einspeiseverguetung_euro_pro_wh_arr[stunde]
|
||||
# TODO: Create prediction for einspeiseverguetung_euro_pro_wh_arr
|
||||
einspeiseverguetung_euro_pro_wh_arr = np.full((self.total_hours), 0.078)
|
||||
|
||||
for stunde_since_now in range(0, self.total_hours):
|
||||
stunde = self.start_datetime.hour + stunde_since_now
|
||||
|
||||
# Accumulate loads and PV generation
|
||||
verbrauch = load_total_mean[stunde_since_now]
|
||||
self.verluste_wh_pro_stunde[stunde_since_now] = 0.0
|
||||
|
||||
# Home appliances
|
||||
if self.home_appliance:
|
||||
ha_load = self.home_appliance.get_load_for_hour(stunde)
|
||||
verbrauch += ha_load
|
||||
self.home_appliance_wh_per_hour[stunde_since_now] = ha_load
|
||||
|
||||
# E-Auto handling
|
||||
if self.eauto:
|
||||
if self.ev_charge_hours[stunde] > 0:
|
||||
geladene_menge_eauto, verluste_eauto = self.eauto.energie_laden(
|
||||
None, stunde, relative_power=self.ev_charge_hours[stunde]
|
||||
)
|
||||
verbrauch += geladene_menge_eauto
|
||||
self.verluste_wh_pro_stunde[stunde_since_now] += verluste_eauto
|
||||
self.eauto_soc_pro_stunde[stunde_since_now] = self.eauto.ladezustand_in_prozent()
|
||||
|
||||
# Process inverter logic
|
||||
netzeinspeisung, netzbezug, verluste, eigenverbrauch = (0.0, 0.0, 0.0, 0.0)
|
||||
if self.akku:
|
||||
self.akku.set_charge_allowed_for_hour(self.dc_charge_hours[stunde], stunde)
|
||||
if self.wechselrichter:
|
||||
erzeugung = pvforecast_ac_power[stunde]
|
||||
netzeinspeisung, netzbezug, verluste, eigenverbrauch = (
|
||||
self.wechselrichter.energie_verarbeiten(erzeugung, verbrauch, stunde)
|
||||
)
|
||||
|
||||
# AC PV Battery Charge
|
||||
if self.akku and self.ac_charge_hours[stunde] > 0.0:
|
||||
self.akku.set_charge_allowed_for_hour(1, stunde)
|
||||
geladene_menge, verluste_wh = self.akku.energie_laden(
|
||||
None, stunde, relative_power=self.ac_charge_hours[stunde]
|
||||
)
|
||||
# print(stunde, " ", geladene_menge, " ",self.ac_charge_hours[stunde]," ",self.akku.ladezustand_in_prozent())
|
||||
verbrauch += geladene_menge
|
||||
netzbezug += geladene_menge
|
||||
self.verluste_wh_pro_stunde[stunde_since_now] += verluste_wh
|
||||
|
||||
self.netzeinspeisung_wh_pro_stunde[stunde_since_now] = netzeinspeisung
|
||||
self.netzbezug_wh_pro_stunde[stunde_since_now] = netzbezug
|
||||
self.verluste_wh_pro_stunde[stunde_since_now] += verluste
|
||||
self.last_wh_pro_stunde[stunde_since_now] = verbrauch
|
||||
|
||||
# Financial calculations
|
||||
self.kosten_euro_pro_stunde[stunde_since_now] = (
|
||||
netzbezug * self.strompreis_euro_pro_wh[stunde]
|
||||
)
|
||||
self.einnahmen_euro_pro_stunde[stunde_since_now] = (
|
||||
netzeinspeisung * self.einspeiseverguetung_euro_pro_wh_arr[stunde]
|
||||
)
|
||||
|
||||
# Akku SOC tracking
|
||||
if self.akku:
|
||||
self.akku_soc_pro_stunde[stunde_since_now] = self.akku.ladezustand_in_prozent()
|
||||
else:
|
||||
self.akku_soc_pro_stunde[stunde_since_now] = 0.0
|
||||
|
||||
def report_dict(self) -> Dict[str, Any]:
|
||||
"""Provides devices simulation output as a dictionary."""
|
||||
out: Dict[str, Optional[Union[np.ndarray, float]]] = {
|
||||
"Last_Wh_pro_Stunde": self.last_wh_pro_stunde,
|
||||
"Netzeinspeisung_Wh_pro_Stunde": self.netzeinspeisung_wh_pro_stunde,
|
||||
"Netzbezug_Wh_pro_Stunde": self.netzbezug_wh_pro_stunde,
|
||||
"Kosten_Euro_pro_Stunde": self.kosten_euro_pro_stunde,
|
||||
"akku_soc_pro_stunde": self.akku_soc_pro_stunde,
|
||||
"Einnahmen_Euro_pro_Stunde": self.einnahmen_euro_pro_stunde,
|
||||
"Gesamtbilanz_Euro": self.total_balance_euro,
|
||||
"EAuto_SoC_pro_Stunde": self.eauto_soc_pro_stunde,
|
||||
"Gesamteinnahmen_Euro": self.total_revenues_euro,
|
||||
"Gesamtkosten_Euro": self.total_costs_euro,
|
||||
"Verluste_Pro_Stunde": self.verluste_wh_pro_stunde,
|
||||
"Gesamt_Verluste": self.total_losses_wh,
|
||||
"Home_appliance_wh_per_hour": self.home_appliance_wh_per_hour,
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
# Initialize the Devices simulation, it is a singleton.
|
||||
devices = Devices()
|
||||
|
||||
|
||||
def get_devices() -> Devices:
|
||||
"""Gets the EOS Devices simulation."""
|
||||
return devices
|
100
src/akkudoktoreos/devices/devicesabc.py
Normal file
100
src/akkudoktoreos/devices/devicesabc.py
Normal file
@@ -0,0 +1,100 @@
|
||||
"""Abstract and base classes for devices."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pendulum import DateTime
|
||||
from pydantic import ConfigDict, computed_field
|
||||
|
||||
from akkudoktoreos.core.coreabc import (
|
||||
ConfigMixin,
|
||||
EnergyManagementSystemMixin,
|
||||
PredictionMixin,
|
||||
)
|
||||
from akkudoktoreos.core.pydantic import PydanticBaseModel
|
||||
from akkudoktoreos.utils.datetimeutil import to_duration
|
||||
from akkudoktoreos.utils.logutil import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class DevicesStartEndMixin(ConfigMixin, EnergyManagementSystemMixin):
|
||||
"""A mixin to manage start, end datetimes for devices data.
|
||||
|
||||
The starting datetime for devices data generation is provided by the energy management
|
||||
system. Device data cannot be computed if this value is `None`.
|
||||
"""
|
||||
|
||||
# Computed field for end_datetime and keep_datetime
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def end_datetime(self) -> Optional[DateTime]:
|
||||
"""Compute the end datetime based on the `start_datetime` and `prediction_hours`.
|
||||
|
||||
Ajusts the calculated end time if DST transitions occur within the prediction window.
|
||||
|
||||
Returns:
|
||||
Optional[DateTime]: The calculated end datetime, or `None` if inputs are missing.
|
||||
"""
|
||||
if self.ems.start_datetime and self.config.prediction_hours:
|
||||
end_datetime = self.ems.start_datetime + to_duration(
|
||||
f"{self.config.prediction_hours} hours"
|
||||
)
|
||||
dst_change = end_datetime.offset_hours - self.ems.start_datetime.offset_hours
|
||||
logger.debug(
|
||||
f"Pre: {self.ems.start_datetime}..{end_datetime}: DST change: {dst_change}"
|
||||
)
|
||||
if dst_change < 0:
|
||||
end_datetime = end_datetime + to_duration(f"{abs(int(dst_change))} hours")
|
||||
elif dst_change > 0:
|
||||
end_datetime = end_datetime - to_duration(f"{abs(int(dst_change))} hours")
|
||||
logger.debug(
|
||||
f"Pst: {self.ems.start_datetime}..{end_datetime}: DST change: {dst_change}"
|
||||
)
|
||||
return end_datetime
|
||||
return None
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def total_hours(self) -> Optional[int]:
|
||||
"""Compute the hours from `start_datetime` to `end_datetime`.
|
||||
|
||||
Returns:
|
||||
Optional[pendulum.period]: The duration hours, or `None` if either datetime is unavailable.
|
||||
"""
|
||||
end_dt = self.end_datetime
|
||||
if end_dt is None:
|
||||
return None
|
||||
duration = end_dt - self.ems.start_datetime
|
||||
return int(duration.total_hours())
|
||||
|
||||
|
||||
class DeviceBase(DevicesStartEndMixin, PredictionMixin):
|
||||
"""Base class for device simulations.
|
||||
|
||||
Enables access to EOS configuration data (attribute `config`) and EOS prediction data (attribute
|
||||
`prediction`).
|
||||
|
||||
Note:
|
||||
Validation on assignment of the Pydantic model is disabled to speed up simulation runs.
|
||||
"""
|
||||
|
||||
# Disable validation on assignment to speed up simulation runs.
|
||||
model_config = ConfigDict(
|
||||
validate_assignment=False,
|
||||
)
|
||||
|
||||
|
||||
class DevicesBase(DevicesStartEndMixin, PredictionMixin, PydanticBaseModel):
|
||||
"""Base class for handling device data.
|
||||
|
||||
Enables access to EOS configuration data (attribute `config`) and EOS prediction data (attribute
|
||||
`prediction`).
|
||||
|
||||
Note:
|
||||
Validation on assignment of the Pydantic model is disabled to speed up simulation runs.
|
||||
"""
|
||||
|
||||
# Disable validation on assignment to speed up simulation runs.
|
||||
model_config = ConfigDict(
|
||||
validate_assignment=False,
|
||||
)
|
@@ -1,6 +1,13 @@
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from akkudoktoreos.devices.devicesabc import DeviceBase
|
||||
from akkudoktoreos.utils.logutil import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class HomeApplianceParameters(BaseModel):
|
||||
consumption_wh: int = Field(
|
||||
@@ -13,21 +20,57 @@ class HomeApplianceParameters(BaseModel):
|
||||
)
|
||||
|
||||
|
||||
class HomeAppliance:
|
||||
def __init__(self, parameters: HomeApplianceParameters, hours: int = 24):
|
||||
self.hours = hours # Total duration for which the planning is done
|
||||
self.consumption_wh = (
|
||||
parameters.consumption_wh
|
||||
) # Total energy consumption of the device in kWh
|
||||
self.duration_h = parameters.duration_h # Duration of use in hours
|
||||
class HomeAppliance(DeviceBase):
|
||||
def __init__(
|
||||
self,
|
||||
parameters: Optional[HomeApplianceParameters] = None,
|
||||
hours: Optional[int] = 24,
|
||||
provider_id: Optional[str] = None,
|
||||
):
|
||||
# Configuration initialisation
|
||||
self.provider_id = provider_id
|
||||
self.prefix = "<invalid>"
|
||||
if self.provider_id == "GenericDishWasher":
|
||||
self.prefix = "dishwasher"
|
||||
# Parameter initialisiation
|
||||
self.parameters = parameters
|
||||
if hours is None:
|
||||
self.hours = self.total_hours
|
||||
else:
|
||||
self.hours = hours
|
||||
|
||||
self.initialised = False
|
||||
# Run setup if parameters are given, otherwise setup() has to be called later when the config is initialised.
|
||||
if self.parameters is not None:
|
||||
self.setup()
|
||||
|
||||
def setup(self) -> None:
|
||||
if self.initialised:
|
||||
return
|
||||
if self.provider_id is not None:
|
||||
# Setup by configuration
|
||||
self.hours = self.total_hours
|
||||
self.consumption_wh = getattr(self.config, f"{self.prefix}_consumption")
|
||||
self.duration_h = getattr(self.config, f"{self.prefix}_duration")
|
||||
elif self.parameters is not None:
|
||||
# Setup by parameters
|
||||
self.consumption_wh = (
|
||||
self.parameters.consumption_wh
|
||||
) # Total energy consumption of the device in kWh
|
||||
self.duration_h = self.parameters.duration_h # Duration of use in hours
|
||||
else:
|
||||
error_msg = "Parameters and provider ID missing. Can't instantiate."
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
self.load_curve = np.zeros(self.hours) # Initialize the load curve with zeros
|
||||
self.initialised = True
|
||||
|
||||
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.
|
||||
|
||||
:param start_hour: The hour at which the device should start.
|
||||
"""
|
||||
self.reset()
|
||||
self.reset_load_curve()
|
||||
# Check if the duration of use is within the available time frame
|
||||
if start_hour + self.duration_h > self.hours:
|
||||
raise ValueError("The duration of use exceeds the available time frame.")
|
||||
@@ -40,7 +83,7 @@ class HomeAppliance:
|
||||
# Set the power for the duration of use in the load curve array
|
||||
self.load_curve[start_hour : start_hour + self.duration_h] = power_per_hour
|
||||
|
||||
def reset(self) -> None:
|
||||
def reset_load_curve(self) -> None:
|
||||
"""Resets the load curve."""
|
||||
self.load_curve = np.zeros(self.hours)
|
||||
|
||||
|
@@ -1,19 +1,61 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from akkudoktoreos.devices.battery import PVAkku
|
||||
from akkudoktoreos.devices.devicesabc import DeviceBase
|
||||
from akkudoktoreos.utils.logutil import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class WechselrichterParameters(BaseModel):
|
||||
max_leistung_wh: float = Field(default=10000, gt=0)
|
||||
|
||||
|
||||
class Wechselrichter:
|
||||
def __init__(self, parameters: WechselrichterParameters, akku: PVAkku):
|
||||
self.max_leistung_wh = (
|
||||
parameters.max_leistung_wh # Maximum power that the inverter can handle
|
||||
)
|
||||
class Wechselrichter(DeviceBase):
|
||||
def __init__(
|
||||
self,
|
||||
parameters: Optional[WechselrichterParameters] = None,
|
||||
akku: Optional[PVAkku] = None,
|
||||
provider_id: Optional[str] = None,
|
||||
):
|
||||
# Configuration initialisation
|
||||
self.provider_id = provider_id
|
||||
self.prefix = "<invalid>"
|
||||
if self.provider_id == "GenericInverter":
|
||||
self.prefix = "inverter"
|
||||
# Parameter initialisiation
|
||||
self.parameters = parameters
|
||||
if akku is None:
|
||||
# For the moment raise exception
|
||||
# TODO: Make akku configurable by config
|
||||
error_msg = "Battery for PV inverter is mandatory."
|
||||
logger.error(error_msg)
|
||||
raise NotImplementedError(error_msg)
|
||||
self.akku = akku # Connection to a battery object
|
||||
|
||||
self.initialised = False
|
||||
# Run setup if parameters are given, otherwise setup() has to be called later when the config is initialised.
|
||||
if self.parameters is not None:
|
||||
self.setup()
|
||||
|
||||
def setup(self) -> None:
|
||||
if self.initialised:
|
||||
return
|
||||
if self.provider_id is not None:
|
||||
# Setup by configuration
|
||||
self.max_leistung_wh = getattr(self.config, f"{self.prefix}_power_max")
|
||||
elif self.parameters is not None:
|
||||
# Setup by parameters
|
||||
self.max_leistung_wh = (
|
||||
self.parameters.max_leistung_wh # Maximum power that the inverter can handle
|
||||
)
|
||||
else:
|
||||
error_msg = "Parameters and provider ID missing. Can't instantiate."
|
||||
logger.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
|
||||
def energie_verarbeiten(
|
||||
self, erzeugung: float, verbrauch: float, hour: int
|
||||
) -> tuple[float, float, float, float]:
|
||||
|
Reference in New Issue
Block a user