From 9e20df9edc6b9fbd940eee0850b36e52a348cefe Mon Sep 17 00:00:00 2001 From: Bla Bla Date: Sun, 3 Mar 2024 10:03:32 +0100 Subject: [PATCH] Last Container zum Vereinheitlichen und Bugfixes --- modules/class_ems.py | 11 +++++----- modules/class_heatpump.py | 8 ++++++- modules/class_load.py | 2 +- modules/class_load_container.py | 35 ++++++++++++++++++++++++++++++ modules/class_pv_forecast.py | 29 +++++++++++++++++-------- modules/class_strompreis.py | 2 +- modules/visualize.py | 5 ++++- test.py | 38 ++++++++++++++++++++++++++------- 8 files changed, 103 insertions(+), 27 deletions(-) create mode 100644 modules/class_load_container.py diff --git a/modules/class_ems.py b/modules/class_ems.py index 9c77f64..5abbf72 100644 --- a/modules/class_ems.py +++ b/modules/class_ems.py @@ -1,6 +1,6 @@ from datetime import datetime from pprint import pprint - +from modules.class_generic_load import * class EnergieManagementSystem: @@ -10,11 +10,7 @@ class EnergieManagementSystem: self.pv_prognose_wh = pv_prognose_wh self.strompreis_cent_pro_wh = strompreis_cent_pro_wh # Strompreis in Cent pro Wh self.einspeiseverguetung_cent_pro_wh = einspeiseverguetung_cent_pro_wh # Einspeisevergütung in Cent pro Wh - - # print("\n\nLastprognose:",self.lastkurve_wh.shape) - # print("PV Prognose:",self.pv_prognose_wh.shape) - # print("Preis Prognose:",self.strompreis_cent_pro_wh.shape) - # sys.exit() + def set_akku_discharge_hours(self, ds): self.akku.set_discharge_per_hour(ds) @@ -42,6 +38,9 @@ class EnergieManagementSystem: einnahmen_euro_pro_stunde = [] akku_soc_pro_stunde = [] + #print(gesamtlast_pro_stunde) + #sys.exit() + ende = min( len(self.lastkurve_wh),len(self.pv_prognose_wh), len(self.strompreis_cent_pro_wh)) #print(ende) # Berechnet das Ende basierend auf der Länge der Lastkurve diff --git a/modules/class_heatpump.py b/modules/class_heatpump.py index bb9df46..f037b6f 100644 --- a/modules/class_heatpump.py +++ b/modules/class_heatpump.py @@ -5,8 +5,9 @@ from pprint import pprint # Lade die .npz-Datei beim Start der Anwendung class Waermepumpe: - def __init__(self, max_heizleistung): + def __init__(self, max_heizleistung, prediction_hours): self.max_heizleistung = max_heizleistung + self.prediction_hours = prediction_hours def cop_berechnen(self, aussentemperatur): cop = 3.0 + (aussentemperatur-0) * 0.1 @@ -26,6 +27,11 @@ class Waermepumpe: def simulate_24h(self, temperaturen): leistungsdaten = [] + + # Überprüfen, ob das Temperaturarray die richtige Größe hat + if len(temperaturen) != self.prediction_hours: + raise ValueError("Das Temperaturarray muss genau "+str(self.prediction_hours)+" Einträge enthalten, einen für jede Stunde des Tages.") + for temp in temperaturen: elektrische_leistung = self.elektrische_leistung_berechnen(temp) leistungsdaten.append(elektrische_leistung) diff --git a/modules/class_load.py b/modules/class_load.py index 5b34f1c..8c982a0 100644 --- a/modules/class_load.py +++ b/modules/class_load.py @@ -79,7 +79,7 @@ class LoadForecast: data = np.load(self.filepath) self.data = np.array(list(zip(data["yearly_profiles"],data["yearly_profiles_std"]))) self.data_year_energy = self.data * self.year_energy - pprint(self.data_year_energy) + #pprint(self.data_year_energy) def get_price_data(self): # load_profiles_exp_l = load_profiles_exp*year_energy diff --git a/modules/class_load_container.py b/modules/class_load_container.py new file mode 100644 index 0000000..c6add76 --- /dev/null +++ b/modules/class_load_container.py @@ -0,0 +1,35 @@ +import json +from datetime import datetime, timedelta, timezone +import numpy as np +from pprint import pprint + +class Gesamtlast: + def __init__(self): + self.lasten = {} # Enthält Namen und Lasten-Arrays für verschiedene Quellen + + def hinzufuegen(self, name, last_array): + """ + Fügt ein Array von Lasten für eine bestimmte Quelle hinzu. + + :param name: Name der Lastquelle (z.B. "Haushalt", "Wärmepumpe") + :param last_array: Array von Lasten, wobei jeder Eintrag einer Stunde entspricht + """ + self.lasten[name] = last_array + + def gesamtlast_berechnen(self): + """ + Berechnet die gesamte Last für jede Stunde und gibt ein Array der Gesamtlasten zurück. + + :return: Array der Gesamtlasten, wobei jeder Eintrag einer Stunde entspricht + """ + if not self.lasten: + return [] + + # Annahme: Alle Lasten-Arrays haben die gleiche Länge + stunden = len(next(iter(self.lasten.values()))) + gesamtlast_array = [0] * stunden + for last_array in self.lasten.values(): + + gesamtlast_array = [gesamtlast + stundenlast for gesamtlast, stundenlast in zip(gesamtlast_array, last_array)] + + return np.array(gesamtlast_array) diff --git a/modules/class_pv_forecast.py b/modules/class_pv_forecast.py index 60a1c68..1e6efde 100644 --- a/modules/class_pv_forecast.py +++ b/modules/class_pv_forecast.py @@ -31,16 +31,23 @@ class ForecastData: return self.temperature class PVForecast: - def __init__(self, filepath=None, url=None, cache_dir='cache'): + def __init__(self, filepath=None, url=None, cache_dir='cache', prediction_hours = 48): self.meta = {} self.forecast_data = [] self.cache_dir = cache_dir + self.prediction_hours = prediction_hours + if not os.path.exists(self.cache_dir): os.makedirs(self.cache_dir) if filepath: self.load_data_from_file(filepath) elif url: self.load_data_with_caching(url) + + # Überprüfung nach dem Laden der Daten + if len(self.forecast_data) < self.prediction_hours: + raise ValueError(f"Die Vorhersage muss mindestens {self.prediction_hours} Stunden umfassen, aber es wurden nur {len(self.forecast_data)} Stunden vorhergesagt.") + def process_data(self, data): @@ -72,7 +79,9 @@ class PVForecast: self.load_data_from_url(url) def load_data_with_caching(self, url): - cache_file = os.path.join(self.cache_dir, self.generate_cache_filename(url)) + date = datetime.now().strftime("%Y-%m-%d") + + cache_file = os.path.join(self.cache_dir, self.generate_cache_filename(url,date)) if os.path.exists(cache_file): with open(cache_file, 'r') as file: data = json.load(file) @@ -89,11 +98,11 @@ class PVForecast: return self.process_data(data) - def generate_cache_filename(self, url): + def generate_cache_filename(self, url,date): # Erzeugt einen SHA-256 Hash der URL als Dateinamen - hash_object = hashlib.sha256(url.encode()) - hex_dig = hash_object.hexdigest() - return f"cache_{hex_dig}.json" + cache_key = hashlib.sha256(f"{url}{date}".encode('utf-8')).hexdigest() + #cache_path = os.path.join(self.cache_dir, cache_key) + return f"cache_{cache_key}.json" def get_forecast_data(self): return self.forecast_data @@ -121,15 +130,16 @@ class PVForecast: start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date() end_date = datetime.strptime(end_date_str, "%Y-%m-%d").date() date_range_forecast = [] - + for data in self.forecast_data: data_date = datetime.strptime(data.get_date_time(), "%Y-%m-%dT%H:%M:%S.%f%z").date() + #print(data.get_date_time()) if start_date <= data_date <= end_date: date_range_forecast.append(data) ac_power_forecast = np.array([data.get_ac_power() for data in date_range_forecast]) - return ac_power_forecast + return np.array(ac_power_forecast)[:self.prediction_hours] def get_temperature_for_date_range(self, start_date_str, end_date_str): start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date() @@ -143,7 +153,7 @@ class PVForecast: forecast_data = date_range_forecast temperature_forecast = [data.get_temperature() for data in forecast_data] - return np.array(temperature_forecast) + return np.array(temperature_forecast)[:self.prediction_hours] @@ -154,3 +164,4 @@ if __name__ == '__main__': forecast = PVForecast(r'..\test_data\pvprognose.json') for data in forecast.get_forecast_data(): print(data.get_date_time(), data.get_dc_power(), data.get_ac_power(), data.get_windspeed_10m(), data.get_temperature()) + diff --git a/modules/class_strompreis.py b/modules/class_strompreis.py index c6df994..73fcb90 100644 --- a/modules/class_strompreis.py +++ b/modules/class_strompreis.py @@ -54,7 +54,7 @@ class HourlyElectricityPriceForecast: while start_date <= end_date: date_str = start_date.strftime("%Y-%m-%d") daily_prices = self.get_price_for_date(date_str) - print(len(self.get_price_for_date(date_str))) + #print(len(self.get_price_for_date(date_str))) if daily_prices.size > 0: price_list.extend(daily_prices) start_date += timedelta(days=1) diff --git a/modules/visualize.py b/modules/visualize.py index 4dcf274..99861d0 100644 --- a/modules/visualize.py +++ b/modules/visualize.py @@ -3,8 +3,11 @@ import matplotlib.pyplot as plt def visualisiere_ergebnisse(last,leistung_haushalt,leistung_wp, pv_forecast, strompreise, ergebnisse): - stunden = np.arange(1, len(last)+1) # 1 bis 24 Stunden + + #print(last) + + stunden = np.arange(1, len(last)+1) # 1 bis 24 Stunden # Last und PV-Erzeugung plt.figure(figsize=(14, 10)) diff --git a/test.py b/test.py index ecb4166..664c8ab 100644 --- a/test.py +++ b/test.py @@ -7,6 +7,8 @@ from modules.class_pv_forecast import * from modules.class_akku import * from modules.class_strompreis import * from modules.class_heatpump import * +from modules.class_generic_load import * +from modules.class_load_container import * from pprint import pprint import matplotlib.pyplot as plt from modules.visualize import * @@ -16,8 +18,9 @@ import random import os + prediction_hours = 48 -date = (datetime.now().date() + timedelta(days=1)).strftime("%Y-%m-%d") +date = (datetime.now().date() + timedelta(hours = prediction_hours)).strftime("%Y-%m-%d") date_now = datetime.now().strftime("%Y-%m-%d") akku_size = 30000 # Wh @@ -25,16 +28,28 @@ year_energy = 2000*1000 #Wh einspeiseverguetung_cent_pro_wh = np.full(prediction_hours, 7/(1000.0*100.0)) # € / Wh max_heizleistung = 1000 # 5 kW Heizleistung -wp = Waermepumpe(max_heizleistung) +wp = Waermepumpe(max_heizleistung,prediction_hours) akku = PVAkku(akku_size,prediction_hours) discharge_array = np.full(prediction_hours,1) + +#Gesamtlast +############# +gesamtlast = Gesamtlast() + + # Load Forecast ############### lf = LoadForecast(filepath=r'load_profiles.npz', year_energy=year_energy) #leistung_haushalt = lf.get_daily_stats(date)[0,...] # Datum anpassen leistung_haushalt = lf.get_stats_for_date_range(date_now,date)[0,...].flatten() +gesamtlast.hinzufuegen("Haushalt", leistung_haushalt) + +# Generic Load +############## +# zusatzlast1 = generic_load() +# zusatzlast1.setze_last(24+12, 0.5, 2000) # Startet um 1 Uhr, dauert 0.5 Stunden, mit 2 kW # PV Forecast @@ -42,10 +57,10 @@ leistung_haushalt = lf.get_stats_for_date_range(date_now,date)[0,...].flatten() #PVforecast = PVForecast(filepath=os.path.join(r'test_data', r'pvprognose.json')) PVforecast = PVForecast(url="https://api.akkudoktor.net/forecast?lat=50.8588&lon=7.3747&power=5400&azimuth=-10&tilt=7&powerInvertor=2500&horizont=20,40,30,30&power=4800&azimuth=-90&tilt=7&powerInvertor=2500&horizont=20,40,45,50&power=1480&azimuth=-90&tilt=70&powerInvertor=1120&horizont=60,45,30,70&power=1600&azimuth=5&tilt=60&powerInvertor=1200&horizont=60,45,30,70&past_days=5&cellCoEff=-0.36&inverterEfficiency=0.8&albedo=0.25&timezone=Europe%2FBerlin&hourly=relativehumidity_2m%2Cwindspeed_10m") pv_forecast = PVforecast.get_pv_forecast_for_date_range(date_now,date) #get_forecast_for_date(date) - temperature_forecast = PVforecast.get_temperature_for_date_range(date_now,date) + # Strompreise ############### filepath = os.path.join (r'test_data', r'strompreise_akkudokAPI.json') # Pfad zur JSON-Datei anpassen @@ -54,18 +69,25 @@ price_forecast = HourlyElectricityPriceForecast(source="https://api.akkudoktor.n specific_date_prices = price_forecast.get_price_for_daterange(date_now,date) # WP +############## leistung_wp = wp.simulate_24h(temperature_forecast) +gesamtlast.hinzufuegen("Heatpump", leistung_wp) -# LOAD -load = leistung_haushalt + leistung_wp - +# print(gesamtlast.gesamtlast_berechnen()) +# sys.exit() # EMS / Stromzähler Bilanz -ems = EnergieManagementSystem(akku, load, pv_forecast, specific_date_prices, einspeiseverguetung_cent_pro_wh) +ems = EnergieManagementSystem(akku, gesamtlast.gesamtlast_berechnen(), pv_forecast, specific_date_prices, einspeiseverguetung_cent_pro_wh) + + o = ems.simuliere_ab_jetzt() pprint(o) pprint(o["Gesamtbilanz_Euro"]) -#sys.exit() + +visualisiere_ergebnisse(gesamtlast.gesamtlast_berechnen(),leistung_haushalt,leistung_wp, pv_forecast, specific_date_prices, o) + + +sys.exit() # Optimierung