Structure code in logically separated submodules (#188)

This commit is contained in:
Michael Osthege 2024-11-19 21:47:43 +01:00 committed by GitHub
parent a1cc30f33d
commit 22f72e2f13
31 changed files with 75 additions and 84 deletions

View File

@ -4,13 +4,13 @@ import time
import numpy as np import numpy as np
from akkudoktoreos.class_numpy_encoder import NumpyEncoder from akkudoktoreos.config import get_working_dir, load_config
from akkudoktoreos.class_optimize import ( from akkudoktoreos.optimization.genetic import (
OptimizationParameters, OptimizationParameters,
OptimizeResponse, OptimizeResponse,
optimization_problem, optimization_problem,
) )
from akkudoktoreos.config import get_working_dir, load_config from akkudoktoreos.utils import NumpyEncoder
from akkudoktoreos.visualize import visualisiere_ergebnisse from akkudoktoreos.visualize import visualisiere_ergebnisse
start_hour = 0 start_hour = 0

View File

@ -1,24 +0,0 @@
import json
import numpy as np
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist() # Convert NumPy arrays to lists
if isinstance(obj, np.generic):
return obj.item() # Convert NumPy scalars to native Python types
return super(NumpyEncoder, self).default(obj)
@staticmethod
def dumps(data):
"""Static method to serialize a Python object into a JSON string using NumpyEncoder.
Args:
data: The Python object to serialize.
Returns:
str: A JSON string representation of the object.
"""
return json.dumps(data, cls=NumpyEncoder)

View File

View File

@ -1,6 +1,6 @@
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from akkudoktoreos.class_akku import PVAkku from akkudoktoreos.devices.battery import PVAkku
class WechselrichterParameters(BaseModel): class WechselrichterParameters(BaseModel):

View File

@ -6,17 +6,14 @@ from deap import algorithms, base, creator, tools
from pydantic import BaseModel, Field, field_validator, model_validator from pydantic import BaseModel, Field, field_validator, model_validator
from typing_extensions import Self from typing_extensions import Self
from akkudoktoreos.class_akku import EAutoParameters, PVAkku, PVAkkuParameters from akkudoktoreos.config import AppConfig
from akkudoktoreos.class_ems import ( from akkudoktoreos.devices.battery import EAutoParameters, PVAkku, PVAkkuParameters
from akkudoktoreos.devices.generic import Haushaltsgeraet, HaushaltsgeraetParameters
from akkudoktoreos.devices.inverter import Wechselrichter, WechselrichterParameters
from akkudoktoreos.prediction.ems import (
EnergieManagementSystem, EnergieManagementSystem,
EnergieManagementSystemParameters, EnergieManagementSystemParameters,
) )
from akkudoktoreos.class_haushaltsgeraet import (
Haushaltsgeraet,
HaushaltsgeraetParameters,
)
from akkudoktoreos.class_inverter import Wechselrichter, WechselrichterParameters
from akkudoktoreos.config import AppConfig
from akkudoktoreos.visualize import visualisiere_ergebnisse from akkudoktoreos.visualize import visualisiere_ergebnisse

View File

View File

@ -5,10 +5,10 @@ import numpy as np
from pydantic import BaseModel, Field, model_validator from pydantic import BaseModel, Field, model_validator
from typing_extensions import Self from typing_extensions import Self
from akkudoktoreos.class_akku import PVAkku
from akkudoktoreos.class_haushaltsgeraet import Haushaltsgeraet
from akkudoktoreos.class_inverter import Wechselrichter
from akkudoktoreos.config import EOSConfig from akkudoktoreos.config import EOSConfig
from akkudoktoreos.devices.battery import PVAkku
from akkudoktoreos.devices.generic import Haushaltsgeraet
from akkudoktoreos.devices.inverter import Wechselrichter
class EnergieManagementSystemParameters(BaseModel): class EnergieManagementSystemParameters(BaseModel):

View File

@ -43,9 +43,9 @@ import pandas as pd
import requests import requests
from pydantic import BaseModel, ValidationError from pydantic import BaseModel, ValidationError
from akkudoktoreos.cachefilestore import cache_in_file from akkudoktoreos.utils.cachefilestore import cache_in_file
from akkudoktoreos.datetimeutil import to_datetime from akkudoktoreos.utils.datetimeutil import to_datetime
from akkudoktoreos.logutil import get_logger from akkudoktoreos.utils.logutil import get_logger
logger = get_logger(__name__, logging_level="DEBUG") logger = get_logger(__name__, logging_level="DEBUG")

View File

@ -16,22 +16,22 @@ import pandas as pd
from fastapi import FastAPI, Query from fastapi import FastAPI, Query
from fastapi.responses import FileResponse, RedirectResponse from fastapi.responses import FileResponse, RedirectResponse
from akkudoktoreos.class_load import LoadForecast
from akkudoktoreos.class_load_container import Gesamtlast
from akkudoktoreos.class_load_corrector import LoadPredictionAdjuster
from akkudoktoreos.class_optimize import (
OptimizationParameters,
OptimizeResponse,
optimization_problem,
)
from akkudoktoreos.class_pv_forecast import ForecastResponse, PVForecast
from akkudoktoreos.class_strompreis import HourlyElectricityPriceForecast
from akkudoktoreos.config import ( from akkudoktoreos.config import (
SetupIncomplete, SetupIncomplete,
get_start_enddate, get_start_enddate,
get_working_dir, get_working_dir,
load_config, load_config,
) )
from akkudoktoreos.optimization.genetic import (
OptimizationParameters,
OptimizeResponse,
optimization_problem,
)
from akkudoktoreos.prediction.load_container import Gesamtlast
from akkudoktoreos.prediction.load_corrector import LoadPredictionAdjuster
from akkudoktoreos.prediction.load_forecast import LoadForecast
from akkudoktoreos.prediction.price_forecast import HourlyElectricityPriceForecast
from akkudoktoreos.prediction.pv_forecast import ForecastResponse, PVForecast
app = FastAPI( app = FastAPI(
title="Akkudoktor-EOS", title="Akkudoktor-EOS",

View File

View File

@ -34,8 +34,8 @@ import threading
from datetime import date, datetime, time, timedelta from datetime import date, datetime, time, timedelta
from typing import List, Optional, Union from typing import List, Optional, Union
from akkudoktoreos.datetimeutil import to_datetime, to_timedelta from akkudoktoreos.utils.datetimeutil import to_datetime, to_timedelta
from akkudoktoreos.logutil import get_logger from akkudoktoreos.utils.logutil import get_logger
logger = get_logger(__file__) logger = get_logger(__file__)

View File

@ -1,6 +1,9 @@
import datetime import datetime
import json
import zoneinfo import zoneinfo
import numpy as np
# currently unused # currently unused
def ist_dst_wechsel(tag: datetime.datetime, timezone="Europe/Berlin") -> bool: def ist_dst_wechsel(tag: datetime.datetime, timezone="Europe/Berlin") -> bool:
@ -16,6 +19,27 @@ def ist_dst_wechsel(tag: datetime.datetime, timezone="Europe/Berlin") -> bool:
return dst_change return dst_change
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist() # Convert NumPy arrays to lists
if isinstance(obj, np.generic):
return obj.item() # Convert NumPy scalars to native Python types
return super(NumpyEncoder, self).default(obj)
@staticmethod
def dumps(data):
"""Static method to serialize a Python object into a JSON string using NumpyEncoder.
Args:
data: The Python object to serialize.
Returns:
str: A JSON string representation of the object.
"""
return json.dumps(data, cls=NumpyEncoder)
# # Example usage # # Example usage
# start_date = datetime.datetime(2024, 3, 31) # Date of the DST change # start_date = datetime.datetime(2024, 3, 31) # Date of the DST change
# if ist_dst_wechsel(start_date): # if ist_dst_wechsel(start_date):

View File

@ -7,8 +7,8 @@ from time import sleep
import pytest import pytest
from akkudoktoreos.cachefilestore import CacheFileStore, cache_in_file from akkudoktoreos.utils.cachefilestore import CacheFileStore, cache_in_file
from akkudoktoreos.datetimeutil import to_datetime from akkudoktoreos.utils.datetimeutil import to_datetime
# ----------------------------- # -----------------------------
# CacheFileStore # CacheFileStore

View File

@ -1,6 +1,6 @@
import unittest import unittest
from akkudoktoreos.class_akku import PVAkku, PVAkkuParameters from akkudoktoreos.devices.battery import PVAkku, PVAkkuParameters
class TestPVAkku(unittest.TestCase): class TestPVAkku(unittest.TestCase):

View File

@ -1,17 +1,14 @@
import numpy as np import numpy as np
import pytest import pytest
from akkudoktoreos.class_akku import EAutoParameters, PVAkku, PVAkkuParameters from akkudoktoreos.config import AppConfig
from akkudoktoreos.class_ems import ( from akkudoktoreos.devices.battery import EAutoParameters, PVAkku, PVAkkuParameters
from akkudoktoreos.devices.generic import Haushaltsgeraet, HaushaltsgeraetParameters
from akkudoktoreos.devices.inverter import Wechselrichter, WechselrichterParameters
from akkudoktoreos.prediction.ems import (
EnergieManagementSystem, EnergieManagementSystem,
EnergieManagementSystemParameters, EnergieManagementSystemParameters,
) )
from akkudoktoreos.class_haushaltsgeraet import (
Haushaltsgeraet,
HaushaltsgeraetParameters,
)
from akkudoktoreos.class_inverter import Wechselrichter, WechselrichterParameters
from akkudoktoreos.config import AppConfig
prediction_hours = 48 prediction_hours = 48
optimization_hours = 24 optimization_hours = 24

View File

@ -1,17 +1,14 @@
import numpy as np import numpy as np
import pytest import pytest
from akkudoktoreos.class_akku import EAutoParameters, PVAkku, PVAkkuParameters from akkudoktoreos.config import AppConfig
from akkudoktoreos.class_ems import ( from akkudoktoreos.devices.battery import EAutoParameters, PVAkku, PVAkkuParameters
from akkudoktoreos.devices.generic import Haushaltsgeraet, HaushaltsgeraetParameters
from akkudoktoreos.devices.inverter import Wechselrichter, WechselrichterParameters
from akkudoktoreos.prediction.ems import (
EnergieManagementSystem, EnergieManagementSystem,
EnergieManagementSystemParameters, EnergieManagementSystemParameters,
) )
from akkudoktoreos.class_haushaltsgeraet import (
Haushaltsgeraet,
HaushaltsgeraetParameters,
)
from akkudoktoreos.class_inverter import Wechselrichter, WechselrichterParameters
from akkudoktoreos.config import AppConfig
prediction_hours = 48 prediction_hours = 48
optimization_hours = 24 optimization_hours = 24

View File

@ -5,12 +5,12 @@ from unittest.mock import patch
import pytest import pytest
from akkudoktoreos.class_optimize import ( from akkudoktoreos.config import AppConfig
from akkudoktoreos.optimization.genetic import (
OptimizationParameters, OptimizationParameters,
OptimizeResponse, OptimizeResponse,
optimization_problem, optimization_problem,
) )
from akkudoktoreos.config import AppConfig
DIR_TESTDATA = Path(__file__).parent / "testdata" DIR_TESTDATA = Path(__file__).parent / "testdata"
@ -37,7 +37,7 @@ def compare_dict(actual: dict[str, Any], expected: dict[str, Any]):
("optimize_input_2.json", "optimize_result_2_full.json", 400), ("optimize_input_2.json", "optimize_result_2_full.json", 400),
], ],
) )
@patch("akkudoktoreos.class_optimize.visualisiere_ergebnisse") @patch("akkudoktoreos.optimization.genetic.visualisiere_ergebnisse")
def test_optimize( def test_optimize(
visualisiere_ergebnisse_patch, visualisiere_ergebnisse_patch,
fn_in: str, fn_in: str,
@ -65,7 +65,7 @@ def test_optimize(
# Call the optimization function # Call the optimization function
ergebnis = opt_class.optimierung_ems(parameters=input_data, start_hour=start_hour, ngen=ngen) ergebnis = opt_class.optimierung_ems(parameters=input_data, start_hour=start_hour, ngen=ngen)
# with open(f"new_{fn_out}", "w") as f_out: # with open(f"new_{fn_out}", "w") as f_out:
# from akkudoktoreos.class_numpy_encoder import NumpyEncoder # from akkudoktoreos.utils import NumpyEncoder
# json_data_str = NumpyEncoder.dumps(ergebnis) # json_data_str = NumpyEncoder.dumps(ergebnis)
# json.dump(json.loads(json_data_str), f_out, indent=4) # json.dump(json.loads(json_data_str), f_out, indent=4)

View File

@ -5,7 +5,7 @@ from zoneinfo import ZoneInfo
import pytest import pytest
from akkudoktoreos.datetimeutil import to_datetime, to_timedelta, to_timezone from akkudoktoreos.utils.datetimeutil import to_datetime, to_timedelta, to_timezone
# ----------------------------- # -----------------------------
# to_datetime # to_datetime

View File

@ -1,6 +1,6 @@
import pytest import pytest
from akkudoktoreos.heatpump import Heatpump from akkudoktoreos.devices.heatpump import Heatpump
@pytest.fixture(scope="function") @pytest.fixture(scope="function")

View File

@ -6,7 +6,7 @@ from logging.handlers import RotatingFileHandler
import pytest import pytest
from akkudoktoreos.logutil import get_logger from akkudoktoreos.utils.logutil import get_logger
# ----------------------------- # -----------------------------
# get_logger # get_logger

View File

@ -1,7 +1,7 @@
"""Test Module for PV Power Forecasting Module. """Test Module for PV Power Forecasting Module.
This test module is designed to verify the functionality of the `PVForecast` class This test module is designed to verify the functionality of the `PVForecast` class
and its methods in the `class_pv_forecast` module. The tests include validation for and its methods in the `prediction.pv_forecast` module. The tests include validation for
forecast data processing, updating AC power measurements, retrieving forecast data, forecast data processing, updating AC power measurements, retrieving forecast data,
and caching behavior. and caching behavior.
@ -19,7 +19,7 @@ Test Cases:
- test_cache_loading: Tests loading forecast data from a cached file to ensure caching works as expected. - test_cache_loading: Tests loading forecast data from a cached file to ensure caching works as expected.
Usage: Usage:
This test module uses `pytest` and requires the `akkudoktoreos.class_pv_forecast.py` module to be present. This test module uses `pytest` and requires the `akkudoktoreos.prediction.pv_forecast.py` module to be present.
Run the tests using the command: `pytest test_pv_forecast.py`. Run the tests using the command: `pytest test_pv_forecast.py`.
""" """
@ -31,8 +31,8 @@ from pathlib import Path
import pytest import pytest
from akkudoktoreos.class_pv_forecast import PVForecast, validate_pv_forecast_data from akkudoktoreos.prediction.pv_forecast import PVForecast, validate_pv_forecast_data
from akkudoktoreos.datetimeutil import to_datetime from akkudoktoreos.utils.datetimeutil import to_datetime
DIR_TESTDATA = Path(__file__).absolute().parent.joinpath("testdata") DIR_TESTDATA = Path(__file__).absolute().parent.joinpath("testdata")