From 167b056defe1473dcc83048c9408b0848ec0a03b Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 19 Jul 2024 15:22:50 +0200 Subject: [PATCH 01/58] remove obsolete rural/urban COPs and rename cop_..._total to cop_..._individual_heating --- rules/build_sector.smk | 20 ++++---------------- scripts/build_cop_profiles.py | 11 +++++------ scripts/prepare_sector_network.py | 4 ++-- 3 files changed, 11 insertions(+), 24 deletions(-) diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 6614b163a..9986bcebf 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -220,18 +220,10 @@ rule build_cop_profiles: heat_pump_sink_T=config_provider("sector", "heat_pump_sink_T"), input: temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), - temp_soil_rural=resources("temp_soil_rural_elec_s{simpl}_{clusters}.nc"), - temp_soil_urban=resources("temp_soil_urban_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), - temp_air_rural=resources("temp_air_rural_elec_s{simpl}_{clusters}.nc"), - temp_air_urban=resources("temp_air_urban_elec_s{simpl}_{clusters}.nc"), output: - cop_soil_total=resources("cop_soil_total_elec_s{simpl}_{clusters}.nc"), - cop_soil_rural=resources("cop_soil_rural_elec_s{simpl}_{clusters}.nc"), - cop_soil_urban=resources("cop_soil_urban_elec_s{simpl}_{clusters}.nc"), - cop_air_total=resources("cop_air_total_elec_s{simpl}_{clusters}.nc"), - cop_air_rural=resources("cop_air_rural_elec_s{simpl}_{clusters}.nc"), - cop_air_urban=resources("cop_air_urban_elec_s{simpl}_{clusters}.nc"), + cop_soil_individual_heating=resources("cop_soil_individual_heating_elec_s{simpl}_{clusters}.nc"), + cop_air_individual_heating=resources("cop_air_individual_heating_elec_s{simpl}_{clusters}.nc"), resources: mem_mb=20000, log: @@ -1029,12 +1021,8 @@ rule prepare_sector_network: temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), temp_air_rural=resources("temp_air_rural_elec_s{simpl}_{clusters}.nc"), temp_air_urban=resources("temp_air_urban_elec_s{simpl}_{clusters}.nc"), - cop_soil_total=resources("cop_soil_total_elec_s{simpl}_{clusters}.nc"), - cop_soil_rural=resources("cop_soil_rural_elec_s{simpl}_{clusters}.nc"), - cop_soil_urban=resources("cop_soil_urban_elec_s{simpl}_{clusters}.nc"), - cop_air_total=resources("cop_air_total_elec_s{simpl}_{clusters}.nc"), - cop_air_rural=resources("cop_air_rural_elec_s{simpl}_{clusters}.nc"), - cop_air_urban=resources("cop_air_urban_elec_s{simpl}_{clusters}.nc"), + cop_soil_individual_heating=resources("cop_soil_individual_heating_elec_s{simpl}_{clusters}.nc"), + cop_air_individual_heating=resources("cop_air_individual_heating_elec_s{simpl}_{clusters}.nc"), solar_thermal_total=lambda w: ( resources("solar_thermal_total_elec_s{simpl}_{clusters}.nc") if config_provider("sector", "solar_thermal")(w) diff --git a/scripts/build_cop_profiles.py b/scripts/build_cop_profiles.py index 2a47198b2..104737b85 100644 --- a/scripts/build_cop_profiles.py +++ b/scripts/build_cop_profiles.py @@ -67,12 +67,11 @@ def coefficient_of_performance(delta_T, source="air"): set_scenario_config(snakemake) - for area in ["total", "urban", "rural"]: - for source in ["air", "soil"]: - source_T = xr.open_dataarray(snakemake.input[f"temp_{source}_{area}"]) + for source in ["air", "soil"]: + source_T = xr.open_dataarray(snakemake.input[f"temp_{source}_total"]) - delta_T = snakemake.params.heat_pump_sink_T - source_T + delta_T = snakemake.params.heat_pump_sink_T - source_T - cop = coefficient_of_performance(delta_T, source) + cop = coefficient_of_performance(delta_T, source) - cop.to_netcdf(snakemake.output[f"cop_{source}_{area}"]) + cop.to_netcdf(snakemake.output[f"cop_{source}_individual_heating"]) diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index 53b811aa9..1967bf443 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1824,10 +1824,10 @@ def add_heat(n, costs): ] cop = { - "air": xr.open_dataarray(snakemake.input.cop_air_total) + "air": xr.open_dataarray(snakemake.input.cop_air_individual_heating) .to_pandas() .reindex(index=n.snapshots), - "ground": xr.open_dataarray(snakemake.input.cop_soil_total) + "ground": xr.open_dataarray(snakemake.input.cop_soil_individual_heating) .to_pandas() .reindex(index=n.snapshots), } From f3c898f43dd6a5a878bfc26c47344a2af7c1bc6f Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 19 Jul 2024 15:39:16 +0200 Subject: [PATCH 02/58] build district heating heat pump COPs using approximation from Jensen et al. and values from Pieper et al. --- config/config.default.yaml | 11 +- rules/build_sector.smk | 10 +- scripts/build_cop_profiles.py | 316 +++++++++++++++++++++++++++++++++- 3 files changed, 331 insertions(+), 6 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index 0af347341..c9ee439b0 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -418,6 +418,15 @@ sector: 2045: 0.8 2050: 1.0 district_heating_loss: 0.15 + # check these numbers! + forward_temperature: 90 #C + return_temperature: 60 #C + heat_source_cooling: 6 #K + heat_pump_cop_approximation: + refrigerant: ammonia + heat_exchanger_pinch_point_temperature_difference: 5 #K + isentropic_compressor_efficiency: 0.8 + heat_loss: 0.0 cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 @@ -500,7 +509,7 @@ sector: aviation_demand_factor: 1. HVC_demand_factor: 1. time_dep_hp_cop: true - heat_pump_sink_T: 55. + heat_pump_sink_T_individual_heating: 55. reduce_space_heat_exogenously: true reduce_space_heat_exogenously_factor: 2020: 0.10 # this results in a space heat demand reduction of 10% diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 9986bcebf..41c857b34 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -217,13 +217,19 @@ rule build_temperature_profiles: rule build_cop_profiles: params: - heat_pump_sink_T=config_provider("sector", "heat_pump_sink_T"), + heat_pump_sink_T_individual_heating=config_provider("sector", "heat_pump_sink_T_individual_heating"), + forward_temperature_district_heating=config_provider("sector", "district_heating", "forward_temperature"), + return_temperature_district_heating=config_provider("sector", "district_heating", "return_temperature"), + heat_source_cooling_district_heating=config_provider("sector", "district_heating", "heat_source_cooling"), + heat_pump_cop_approximation=config_provider("sector", "district_heating", "heat_pump_cop_approximation"), input: temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), output: cop_soil_individual_heating=resources("cop_soil_individual_heating_elec_s{simpl}_{clusters}.nc"), cop_air_individual_heating=resources("cop_air_individual_heating_elec_s{simpl}_{clusters}.nc"), + cop_air_district_heating=resources("cop_air_district_heating_elec_s{simpl}_{clusters}.nc"), + cop_soil_district_heating=resources("cop_soil_district_heating_elec_s{simpl}_{clusters}.nc"), resources: mem_mb=20000, log: @@ -1023,6 +1029,8 @@ rule prepare_sector_network: temp_air_urban=resources("temp_air_urban_elec_s{simpl}_{clusters}.nc"), cop_soil_individual_heating=resources("cop_soil_individual_heating_elec_s{simpl}_{clusters}.nc"), cop_air_individual_heating=resources("cop_air_individual_heating_elec_s{simpl}_{clusters}.nc"), + cop_air_district_heating=resources("cop_air_district_heating_elec_s{simpl}_{clusters}.nc"), + cop_soil_district_heating=resources("cop_soil_district_heating_elec_s{simpl}_{clusters}.nc"), solar_thermal_total=lambda w: ( resources("solar_thermal_total_elec_s{simpl}_{clusters}.nc") if config_provider("sector", "solar_thermal")(w) diff --git a/scripts/build_cop_profiles.py b/scripts/build_cop_profiles.py index 104737b85..6d7050baf 100644 --- a/scripts/build_cop_profiles.py +++ b/scripts/build_cop_profiles.py @@ -42,11 +42,14 @@ [1] Staffell et al., Energy & Environmental Science 11 (2012): A review of domestic heat pumps, https://doi.org/10.1039/C2EE22653G. """ +from typing import Union +from enum import Enum import xarray as xr +import numpy as np from _helpers import set_scenario_config -def coefficient_of_performance(delta_T, source="air"): +def coefficient_of_performance_individual_heating(delta_T, source="air"): if source == "air": return 6.81 - 0.121 * delta_T + 0.000630 * delta_T**2 elif source == "soil": @@ -55,6 +58,301 @@ def coefficient_of_performance(delta_T, source="air"): raise NotImplementedError("'source' must be one of ['air', 'soil']") +def celsius_to_kelvin(t_celsius: Union[float, xr.DataArray, np.array]) -> Union[float, xr.DataArray, np.array]: + if (np.asarray(t_celsius) > 200).any(): + raise ValueError("t_celsius > 200. Are you sure you are using the right units?") + return t_celsius + 273.15 + + +def logarithmic_mean(t_hot: Union[float, xr.DataArray, np.ndarray], t_cold: Union[float, xr.DataArray, np.ndarray]) -> Union[float, xr.DataArray, np.ndarray]: + if (np.asarray(t_hot <= t_cold)).any(): + raise ValueError("t_hot must be greater than t_cold") + return (t_hot - t_cold) / np.log(t_hot / t_cold) + +class CopDistrictHeating: + + def __init__( + self, + forward_temperature_celsius: Union[xr.DataArray, np.array], + source_inlet_temperature_celsius: Union[xr.DataArray, np.array], + return_temperature_celsius: Union[xr.DataArray, np.array], + source_outlet_temperature_celsius: Union[xr.DataArray, np.array], + delta_t_pinch_point: float = 5, + isentropic_compressor_efficiency: float = 0.8, + heat_loss: float = 0.0, + ) -> None: + """ + Initialize the COPProfileBuilder object. + + Parameters: + ---------- + forward_temperature_celsius : Union[xr.DataArray, np.array] + The forward temperature in Celsius. + return_temperature_celsius : Union[xr.DataArray, np.array] + The return temperature in Celsius. + source_inlet_temperature_celsius : Union[xr.DataArray, np.array] + The source inlet temperature in Celsius. + source_outlet_temperature_celsius : Union[xr.DataArray, np.array] + The source outlet temperature in Celsius. + delta_t_pinch_point : float, optional + The pinch point temperature difference, by default 5. + isentropic_compressor_efficiency : float, optional + The isentropic compressor efficiency, by default 0.8. + heat_loss : float, optional + The heat loss, by default 0.0. + """ + self.t_source_in = celsius_to_kelvin(source_inlet_temperature_celsius) + self.t_sink_out = celsius_to_kelvin(forward_temperature_celsius) + + self.t_sink_in = celsius_to_kelvin(return_temperature_celsius) + self.t_source_out = celsius_to_kelvin(source_outlet_temperature_celsius) + + self.isentropic_efficiency_compressor = isentropic_compressor_efficiency + self.heat_loss = heat_loss + self.delta_t_pinch = delta_t_pinch_point + + def cop(self) -> Union[xr.DataArray, np.array]: + """ + Calculate the coefficient of performance (COP) for the system. + + Returns: + Union[xr.DataArray, np.array]: The calculated COP values. + """ + return ( + self.ideal_lorenz_cop + * ( + ( + 1 + + (self.delta_t_refrigerant_sink + self.delta_t_pinch) + / self.t_sink_mean + ) + / ( + 1 + + ( + self.delta_t_refrigerant_sink + + self.delta_t_refrigerant_source + + 2 * self.delta_t_pinch + ) + / self.delta_t_lift + ) + ) + * self.isentropic_efficiency_compressor + * (1 - self.ratio_evaporation_compression_work) + + 1 + - self.isentropic_efficiency_compressor + - self.heat_loss + ) + + @property + def t_sink_mean(self) -> Union[xr.DataArray, np.array]: + """ + Calculate the logarithmic mean temperature difference between the cold and hot sinks. + + Returns + ------- + Union[xr.DataArray, np.array] + The mean temperature difference. + """ + return logarithmic_mean(t_cold=self.t_sink_in, t_hot=self.t_sink_out) + + @property + def t_source_mean(self) -> Union[xr.DataArray, np.array]: + """ + Calculate the logarithmic mean temperature of the heat source. + + Returns + ------- + Union[xr.DataArray, np.array] + The mean temperature of the heat source. + """ + return logarithmic_mean(t_hot=self.t_source_in, t_cold=self.t_source_out) + + @property + def delta_t_lift(self) -> Union[xr.DataArray, np.array]: + """ + Calculate the temperature lift as the difference between the logarithmic sink and source temperatures. + + Returns + ------- + Union[xr.DataArray, np.array] + The temperature difference between the sink and source. + """ + return self.t_sink_mean - self.t_source_mean + + @property + def ideal_lorenz_cop(self) -> Union[xr.DataArray, np.array]: + """ + Ideal Lorenz coefficient of performance (COP). + + The ideal Lorenz COP is calculated as the ratio of the mean sink temperature + to the lift temperature difference. + + Returns + ------- + np.array + The ideal Lorenz COP. + + """ + return self.t_sink_mean / self.delta_t_lift + + @property + def delta_t_refrigerant_source(self) -> Union[xr.DataArray, np.array]: + """ + Calculate the temperature difference between the refrigerant source inlet and outlet. + + Returns + ------- + Union[xr.DataArray, np.array] + The temperature difference between the refrigerant source inlet and outlet. + """ + return self._approximate_delta_t_refrigerant_source( + delta_t_source=self.t_source_in - self.t_source_out + ) + + @property + def delta_t_refrigerant_sink(self) -> Union[xr.DataArray, np.array]: + """ + Temperature difference between the refrigerant and the sink based on approximation. + + Returns + ------- + Union[xr.DataArray, np.array] + The temperature difference between the refrigerant and the sink. + """ + return self._approximate_delta_t_refrigerant_sink() + + @property + def ratio_evaporation_compression_work(self) -> Union[xr.DataArray, np.array]: + """ + Calculate the ratio of evaporation to compression work based on approximation. + + Returns + ------- + Union[xr.DataArray, np.array] + The calculated ratio of evaporation to compression work. + """ + return self._ratio_evaporation_compression_work_approximation() + + @property + def delta_t_sink(self) -> Union[xr.DataArray, np.array]: + """ + Calculate the temperature difference at the sink. + + Returns + ------- + Union[xr.DataArray, np.array] + The temperature difference at the sink. + """ + return self.t_sink_out - self.t_sink_in + + def _approximate_delta_t_refrigerant_source( + self, delta_t_source: Union[xr.DataArray, np.array] + ) -> Union[xr.DataArray, np.array]: + """ + Approximates the temperature difference between the refrigerant and the source. + + Parameters + ---------- + delta_t_source : Union[xr.DataArray, np.array] + The temperature difference for the refrigerant source. + + Returns + ------- + Union[xr.DataArray, np.array] + The approximate temperature difference for the refrigerant source. + """ + return delta_t_source / 2 + + def _approximate_delta_t_refrigerant_sink( + self, + refrigerant: str = "ammonia", + a: float = {"ammonia": 0.2, "isobutane": -0.0011}, + b: float = {"ammonia": 0.2, "isobutane": 0.3}, + c: float = {"ammonia": 0.016, "isobutane": 2.4}, + ) -> Union[xr.DataArray, np.array]: + """ + Approximates the temperature difference at the refrigerant sink. + + Parameters: + ---------- + refrigerant : str, optional + The refrigerant used in the system. Either 'isobutane' or 'ammonia. Default is 'ammonia'. + a : float, optional + Coefficient for the temperature difference between the sink and source, default is 0.2. + b : float, optional + Coefficient for the temperature difference at the sink, default is 0.2. + c : float, optional + Constant term, default is 0.016. + + Returns: + ------- + Union[xr.DataArray, np.array] + The approximate temperature difference at the refrigerant sink. + + Notes: + ------ + This function assumes ammonia as the refrigerant. + + The approximate temperature difference at the refrigerant sink is calculated using the following formula: + a * (t_sink_out - t_source_out + 2 * delta_t_pinch) + b * delta_t_sink + c + + """ + if refrigerant not in a.keys(): + raise ValueError( + f"Invalid refrigerant '{refrigerant}'. Must be one of {a.keys()}" + ) + return ( + a[refrigerant] + * (self.t_sink_out - self.t_source_out + 2 * self.delta_t_pinch) + + b[refrigerant] * self.delta_t_sink + + c[refrigerant] + ) + + def _ratio_evaporation_compression_work_approximation( + self, + refrigerant: str = "ammonia", + a: float = {"ammonia": 0.0014, "isobutane": 0.0035}, + b: float = {"ammonia": -0.0015, "isobutane": -0.0033}, + c: float = {"ammonia": 0.039, "isobutane": 0.053}, + ) -> Union[xr.DataArray, np.array]: + """ + Calculate the ratio of evaporation to compression work approximation. + + Parameters: + ---------- + refrigerant : str, optional + The refrigerant used in the system. Either 'isobutane' or 'ammonia. Default is 'ammonia'. + a : float, optional + Coefficient 'a' in the approximation equation. Default is 0.0014. + b : float, optional + Coefficient 'b' in the approximation equation. Default is -0.0015. + c : float, optional + Coefficient 'c' in the approximation equation. Default is 0.039. + + Returns: + ------- + Union[xr.DataArray, np.array] + The calculated ratio of evaporation to compression work. + + Notes: + ------ + This function assumes ammonia as the refrigerant. + + The approximation equation used is: + ratio = a * (t_sink_out - t_source_out + 2 * delta_t_pinch) + b * delta_t_sink + c + """ + if refrigerant not in a.keys(): + raise ValueError( + f"Invalid refrigerant '{refrigerant}'. Must be one of {a.keys()}" + ) + return ( + a[refrigerant] + * (self.t_sink_out - self.t_source_out + 2 * self.delta_t_pinch) + + b[refrigerant] * self.delta_t_sink + + c[refrigerant] + ) + + if __name__ == "__main__": if "snakemake" not in globals(): from _helpers import mock_snakemake @@ -70,8 +368,18 @@ def coefficient_of_performance(delta_T, source="air"): for source in ["air", "soil"]: source_T = xr.open_dataarray(snakemake.input[f"temp_{source}_total"]) - delta_T = snakemake.params.heat_pump_sink_T - source_T + delta_T = snakemake.params.heat_pump_sink_T_individual_heating - source_T + + cop_individual_heating = coefficient_of_performance_individual_heating(delta_T, source) + cop_individual_heating.to_netcdf(snakemake.output[f"cop_{source}_individual_heating"]) - cop = coefficient_of_performance(delta_T, source) + cop_district_heating = CopDistrictHeating( + forward_temperature_celsius=snakemake.params.forward_temperature_district_heating, + return_temperature_celsius=snakemake.params.return_temperature_district_heating, + source_inlet_temperature_celsius=source_T, + source_outlet_temperature_celsius=source_T - snakemake.params.heat_source_cooling_district_heating, + ).cop() - cop.to_netcdf(snakemake.output[f"cop_{source}_individual_heating"]) + cop_district_heating.to_netcdf(snakemake.output[f"cop_{source}_district_heating"]) + + From 052394fa88dc550b781f21fd020219f69b0e081d Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 19 Jul 2024 15:57:53 +0200 Subject: [PATCH 03/58] change naming from individual/district heating to denctral/central heating --- rules/build_sector.smk | 26 +++++++++++++------------- scripts/build_cop_profiles.py | 4 ++-- scripts/prepare_sector_network.py | 4 ++-- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 41c857b34..995eb9e2a 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -217,19 +217,19 @@ rule build_temperature_profiles: rule build_cop_profiles: params: - heat_pump_sink_T_individual_heating=config_provider("sector", "heat_pump_sink_T_individual_heating"), - forward_temperature_district_heating=config_provider("sector", "district_heating", "forward_temperature"), - return_temperature_district_heating=config_provider("sector", "district_heating", "return_temperature"), - heat_source_cooling_district_heating=config_provider("sector", "district_heating", "heat_source_cooling"), - heat_pump_cop_approximation=config_provider("sector", "district_heating", "heat_pump_cop_approximation"), + heat_pump_sink_T_decentral_heating=config_provider("sector", "heat_pump_sink_T_individual_heating"), + forward_temperature_central_heating=config_provider("sector", "district_heating", "forward_temperature"), + return_temperature_central_heating=config_provider("sector", "district_heating", "return_temperature"), + heat_source_cooling_central_heating=config_provider("sector", "district_heating", "heat_source_cooling"), + heat_pump_cop_approximation_central_heating=config_provider("sector", "district_heating", "heat_pump_cop_approximation"), input: temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), output: - cop_soil_individual_heating=resources("cop_soil_individual_heating_elec_s{simpl}_{clusters}.nc"), - cop_air_individual_heating=resources("cop_air_individual_heating_elec_s{simpl}_{clusters}.nc"), - cop_air_district_heating=resources("cop_air_district_heating_elec_s{simpl}_{clusters}.nc"), - cop_soil_district_heating=resources("cop_soil_district_heating_elec_s{simpl}_{clusters}.nc"), + cop_air_decentral_heating=resources("cop_air_decentral_elec_s{simpl}_{clusters}.nc"), + cop_soil_decentral_heating=resources("cop_soil_decentral_elec_s{simpl}_{clusters}.nc"), + cop_air_central_heating=resources("cop_air_central_heating_elec_s{simpl}_{clusters}.nc"), + cop_soil_central_heating=resources("cop_soil_central_heating_elec_s{simpl}_{clusters}.nc"), resources: mem_mb=20000, log: @@ -1027,10 +1027,10 @@ rule prepare_sector_network: temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), temp_air_rural=resources("temp_air_rural_elec_s{simpl}_{clusters}.nc"), temp_air_urban=resources("temp_air_urban_elec_s{simpl}_{clusters}.nc"), - cop_soil_individual_heating=resources("cop_soil_individual_heating_elec_s{simpl}_{clusters}.nc"), - cop_air_individual_heating=resources("cop_air_individual_heating_elec_s{simpl}_{clusters}.nc"), - cop_air_district_heating=resources("cop_air_district_heating_elec_s{simpl}_{clusters}.nc"), - cop_soil_district_heating=resources("cop_soil_district_heating_elec_s{simpl}_{clusters}.nc"), + cop_soil_decentral_heating=resources("cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc"), + cop_air_decentral_heating=resources("cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc"), + cop_air_central_heating=resources("cop_air_central_heating_elec_s{simpl}_{clusters}.nc"), + cop_soil_central_heating=resources("cop_soil_central_heating_elec_s{simpl}_{clusters}.nc"), solar_thermal_total=lambda w: ( resources("solar_thermal_total_elec_s{simpl}_{clusters}.nc") if config_provider("sector", "solar_thermal")(w) diff --git a/scripts/build_cop_profiles.py b/scripts/build_cop_profiles.py index 6d7050baf..15c796509 100644 --- a/scripts/build_cop_profiles.py +++ b/scripts/build_cop_profiles.py @@ -371,7 +371,7 @@ def _ratio_evaporation_compression_work_approximation( delta_T = snakemake.params.heat_pump_sink_T_individual_heating - source_T cop_individual_heating = coefficient_of_performance_individual_heating(delta_T, source) - cop_individual_heating.to_netcdf(snakemake.output[f"cop_{source}_individual_heating"]) + cop_individual_heating.to_netcdf(snakemake.output[f"cop_{source}_decentral_heating"]) cop_district_heating = CopDistrictHeating( forward_temperature_celsius=snakemake.params.forward_temperature_district_heating, @@ -380,6 +380,6 @@ def _ratio_evaporation_compression_work_approximation( source_outlet_temperature_celsius=source_T - snakemake.params.heat_source_cooling_district_heating, ).cop() - cop_district_heating.to_netcdf(snakemake.output[f"cop_{source}_district_heating"]) + cop_district_heating.to_netcdf(snakemake.output[f"cop_{source}_central_heating"]) diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index 1967bf443..4cec75304 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1824,10 +1824,10 @@ def add_heat(n, costs): ] cop = { - "air": xr.open_dataarray(snakemake.input.cop_air_individual_heating) + "air": xr.open_dataarray(snakemake.input.cop_air_decentral_heating) .to_pandas() .reindex(index=n.snapshots), - "ground": xr.open_dataarray(snakemake.input.cop_soil_individual_heating) + "ground": xr.open_dataarray(snakemake.input.cop_soil_decentral_heating) .to_pandas() .reindex(index=n.snapshots), } From 0c7e7cb46b5806879ebd480647b61af2de2824ea Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 19 Jul 2024 18:54:19 +0200 Subject: [PATCH 04/58] fix naming, udpate docs --- rules/build_sector.smk | 12 ++++++------ scripts/build_cop_profiles.py | 22 +++++++++------------- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 995eb9e2a..8b4608600 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -218,16 +218,16 @@ rule build_temperature_profiles: rule build_cop_profiles: params: heat_pump_sink_T_decentral_heating=config_provider("sector", "heat_pump_sink_T_individual_heating"), - forward_temperature_central_heating=config_provider("sector", "district_heating", "forward_temperature"), - return_temperature_central_heating=config_provider("sector", "district_heating", "return_temperature"), - heat_source_cooling_central_heating=config_provider("sector", "district_heating", "heat_source_cooling"), - heat_pump_cop_approximation_central_heating=config_provider("sector", "district_heating", "heat_pump_cop_approximation"), + forward_temperature_district_heating=config_provider("sector", "district_heating", "forward_temperature"), + return_temperature_district_heating=config_provider("sector", "district_heating", "return_temperature"), + heat_source_cooling_district_heating=config_provider("sector", "district_heating", "heat_source_cooling"), + heat_pump_cop_approximation_district_heating=config_provider("sector", "district_heating", "heat_pump_cop_approximation"), input: temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), output: - cop_air_decentral_heating=resources("cop_air_decentral_elec_s{simpl}_{clusters}.nc"), - cop_soil_decentral_heating=resources("cop_soil_decentral_elec_s{simpl}_{clusters}.nc"), + cop_air_decentral_heating=resources("cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc"), + cop_soil_decentral_heating=resources("cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc"), cop_air_central_heating=resources("cop_air_central_heating_elec_s{simpl}_{clusters}.nc"), cop_soil_central_heating=resources("cop_soil_central_heating_elec_s{simpl}_{clusters}.nc"), resources: diff --git a/scripts/build_cop_profiles.py b/scripts/build_cop_profiles.py index 15c796509..77caa1a6b 100644 --- a/scripts/build_cop_profiles.py +++ b/scripts/build_cop_profiles.py @@ -6,8 +6,8 @@ Build coefficient of performance (COP) time series for air- or ground-sourced heat pumps. -The COP is approximated as a quatratic function of the temperature difference between source and -sink, based on Staffell et al. 2012. +For individual (decentral) heat pumps, the COP is approximated as a quatratic function of the temperature difference between source and sink, based on Staffell et al. 2012. +For district (central) heating, the COP is approximated based on Jensen et al. 2018 and parameters from Pieper et al. 2020. This rule is executed in ``build_sector.smk``. @@ -21,25 +21,21 @@ Inputs: ------- - ``resources//temp_soil_total_elec_s_.nc``: Soil temperature (total) time series. -- ``resources//temp_soil_rural_elec_s_.nc``: Soil temperature (rural) time series. -- ``resources//temp_soil_urban_elec_s_.nc``: Soil temperature (urban) time series. - ``resources//temp_air_total_elec_s_.nc``: Ambient air temperature (total) time series. -- ``resources//temp_air_rural_elec_s_.nc``: Ambient air temperature (rural) time series. -- ``resources//temp_air_urban_elec_s_.nc``: Ambient air temperature (urban) time series. Outputs: -------- -- ``resources/cop_soil_total_elec_s_.nc``: COP (ground-sourced) time series (total). -- ``resources/cop_soil_rural_elec_s_.nc``: COP (ground-sourced) time series (rural). -- ``resources/cop_soil_urban_elec_s_.nc``: COP (ground-sourced) time series (urban). -- ``resources/cop_air_total_elec_s_.nc``: COP (air-sourced) time series (total). -- ``resources/cop_air_rural_elec_s_.nc``: COP (air-sourced) time series (rural). -- ``resources/cop_air_urban_elec_s_.nc``: COP (air-sourced) time series (urban). +- ``resources/cop_air_decentral_heating_elec_s_.nc``: COP (air-sourced) time series (decentral heating). +- ``resources/cop_soil_decentral_heating_elec_s_.nc``: COP (ground-sourced) time series (decentral heating). +- ``resources/cop_air_central_heating_elec_s_.nc``: COP (air-sourced) time series (central heating). +- ``resources/cop_soil_central_heating_elec_s_.nc``: COP (ground-sourced) time series (central heating). References ---------- [1] Staffell et al., Energy & Environmental Science 11 (2012): A review of domestic heat pumps, https://doi.org/10.1039/C2EE22653G. +[2] Jensen et al., Proceedings of the13th IIR-Gustav Lorentzen Conference on Natural Refrigerants (2018): Heat pump COP, part 2: Generalized COP estimation of heat pump processes, https://doi.org/10.18462/iir.gl.2018.1386 +[3] Pieper et al., Energy 205 (2020): Comparison of COP estimation methods for large-scale heat pumps used in energy planning, https://doi.org/10.1016/j.energy.2020.117994 """ from typing import Union @@ -368,7 +364,7 @@ def _ratio_evaporation_compression_work_approximation( for source in ["air", "soil"]: source_T = xr.open_dataarray(snakemake.input[f"temp_{source}_total"]) - delta_T = snakemake.params.heat_pump_sink_T_individual_heating - source_T + delta_T = snakemake.params.heat_pump_sink_T_decentral_heating - source_T cop_individual_heating = coefficient_of_performance_individual_heating(delta_T, source) cop_individual_heating.to_netcdf(snakemake.output[f"cop_{source}_decentral_heating"]) From 560373a864e1695806a8556a0e726cfd4de4a13a Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 19 Jul 2024 18:54:30 +0200 Subject: [PATCH 05/58] add DH cops to network --- scripts/prepare_sector_network.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index 4cec75304..66b5085da 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1824,10 +1824,16 @@ def add_heat(n, costs): ] cop = { - "air": xr.open_dataarray(snakemake.input.cop_air_decentral_heating) + "air decentral": xr.open_dataarray(snakemake.input.cop_air_decentral_heating) .to_pandas() .reindex(index=n.snapshots), - "ground": xr.open_dataarray(snakemake.input.cop_soil_decentral_heating) + "ground decentral": xr.open_dataarray(snakemake.input.cop_soil_decentral_heating) + .to_pandas() + .reindex(index=n.snapshots), + "air central": xr.open_dataarray(snakemake.input.cop_air_central_heating) + .to_pandas() + .reindex(index=n.snapshots), + "ground central": xr.open_dataarray(snakemake.input.cop_soil_central_heating) .to_pandas() .reindex(index=n.snapshots), } @@ -1922,7 +1928,7 @@ def add_heat(n, costs): for heat_pump_type in heat_pump_types: costs_name = f"{name_type} {heat_pump_type}-sourced heat pump" efficiency = ( - cop[heat_pump_type][nodes] + cop[f"{heat_pump_type} {name_type}"][nodes] if options["time_dep_hp_cop"] else costs.at[costs_name, "efficiency"] ) From 5361facbb7a3f480442bbea6e5792085b28ddeec Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 22 Jul 2024 13:39:04 +0000 Subject: [PATCH 06/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- rules/build_sector.smk | 52 +++++++++++++++++++++-------- scripts/build_cop_profiles.py | 54 ++++++++++++++++++++----------- scripts/prepare_sector_network.py | 4 ++- 3 files changed, 77 insertions(+), 33 deletions(-) diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 8b4608600..510af7c04 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -217,19 +217,37 @@ rule build_temperature_profiles: rule build_cop_profiles: params: - heat_pump_sink_T_decentral_heating=config_provider("sector", "heat_pump_sink_T_individual_heating"), - forward_temperature_district_heating=config_provider("sector", "district_heating", "forward_temperature"), - return_temperature_district_heating=config_provider("sector", "district_heating", "return_temperature"), - heat_source_cooling_district_heating=config_provider("sector", "district_heating", "heat_source_cooling"), - heat_pump_cop_approximation_district_heating=config_provider("sector", "district_heating", "heat_pump_cop_approximation"), + heat_pump_sink_T_decentral_heating=config_provider( + "sector", "heat_pump_sink_T_individual_heating" + ), + forward_temperature_district_heating=config_provider( + "sector", "district_heating", "forward_temperature" + ), + return_temperature_district_heating=config_provider( + "sector", "district_heating", "return_temperature" + ), + heat_source_cooling_district_heating=config_provider( + "sector", "district_heating", "heat_source_cooling" + ), + heat_pump_cop_approximation_district_heating=config_provider( + "sector", "district_heating", "heat_pump_cop_approximation" + ), input: temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), output: - cop_air_decentral_heating=resources("cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc"), - cop_soil_decentral_heating=resources("cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc"), - cop_air_central_heating=resources("cop_air_central_heating_elec_s{simpl}_{clusters}.nc"), - cop_soil_central_heating=resources("cop_soil_central_heating_elec_s{simpl}_{clusters}.nc"), + cop_air_decentral_heating=resources( + "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_soil_decentral_heating=resources( + "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_air_central_heating=resources( + "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_soil_central_heating=resources( + "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" + ), resources: mem_mb=20000, log: @@ -1027,10 +1045,18 @@ rule prepare_sector_network: temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), temp_air_rural=resources("temp_air_rural_elec_s{simpl}_{clusters}.nc"), temp_air_urban=resources("temp_air_urban_elec_s{simpl}_{clusters}.nc"), - cop_soil_decentral_heating=resources("cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc"), - cop_air_decentral_heating=resources("cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc"), - cop_air_central_heating=resources("cop_air_central_heating_elec_s{simpl}_{clusters}.nc"), - cop_soil_central_heating=resources("cop_soil_central_heating_elec_s{simpl}_{clusters}.nc"), + cop_soil_decentral_heating=resources( + "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_air_decentral_heating=resources( + "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_air_central_heating=resources( + "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_soil_central_heating=resources( + "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" + ), solar_thermal_total=lambda w: ( resources("solar_thermal_total_elec_s{simpl}_{clusters}.nc") if config_provider("sector", "solar_thermal")(w) diff --git a/scripts/build_cop_profiles.py b/scripts/build_cop_profiles.py index 77caa1a6b..89eeb9b68 100644 --- a/scripts/build_cop_profiles.py +++ b/scripts/build_cop_profiles.py @@ -38,10 +38,11 @@ [3] Pieper et al., Energy 205 (2020): Comparison of COP estimation methods for large-scale heat pumps used in energy planning, https://doi.org/10.1016/j.energy.2020.117994 """ -from typing import Union from enum import Enum -import xarray as xr +from typing import Union + import numpy as np +import xarray as xr from _helpers import set_scenario_config @@ -54,17 +55,23 @@ def coefficient_of_performance_individual_heating(delta_T, source="air"): raise NotImplementedError("'source' must be one of ['air', 'soil']") -def celsius_to_kelvin(t_celsius: Union[float, xr.DataArray, np.array]) -> Union[float, xr.DataArray, np.array]: +def celsius_to_kelvin( + t_celsius: Union[float, xr.DataArray, np.array] +) -> Union[float, xr.DataArray, np.array]: if (np.asarray(t_celsius) > 200).any(): raise ValueError("t_celsius > 200. Are you sure you are using the right units?") return t_celsius + 273.15 -def logarithmic_mean(t_hot: Union[float, xr.DataArray, np.ndarray], t_cold: Union[float, xr.DataArray, np.ndarray]) -> Union[float, xr.DataArray, np.ndarray]: +def logarithmic_mean( + t_hot: Union[float, xr.DataArray, np.ndarray], + t_cold: Union[float, xr.DataArray, np.ndarray], +) -> Union[float, xr.DataArray, np.ndarray]: if (np.asarray(t_hot <= t_cold)).any(): raise ValueError("t_hot must be greater than t_cold") return (t_hot - t_cold) / np.log(t_hot / t_cold) + class CopDistrictHeating: def __init__( @@ -142,7 +149,8 @@ def cop(self) -> Union[xr.DataArray, np.array]: @property def t_sink_mean(self) -> Union[xr.DataArray, np.array]: """ - Calculate the logarithmic mean temperature difference between the cold and hot sinks. + Calculate the logarithmic mean temperature difference between the cold + and hot sinks. Returns ------- @@ -166,7 +174,8 @@ def t_source_mean(self) -> Union[xr.DataArray, np.array]: @property def delta_t_lift(self) -> Union[xr.DataArray, np.array]: """ - Calculate the temperature lift as the difference between the logarithmic sink and source temperatures. + Calculate the temperature lift as the difference between the + logarithmic sink and source temperatures. Returns ------- @@ -187,14 +196,14 @@ def ideal_lorenz_cop(self) -> Union[xr.DataArray, np.array]: ------- np.array The ideal Lorenz COP. - """ return self.t_sink_mean / self.delta_t_lift @property def delta_t_refrigerant_source(self) -> Union[xr.DataArray, np.array]: """ - Calculate the temperature difference between the refrigerant source inlet and outlet. + Calculate the temperature difference between the refrigerant source + inlet and outlet. Returns ------- @@ -208,7 +217,8 @@ def delta_t_refrigerant_source(self) -> Union[xr.DataArray, np.array]: @property def delta_t_refrigerant_sink(self) -> Union[xr.DataArray, np.array]: """ - Temperature difference between the refrigerant and the sink based on approximation. + Temperature difference between the refrigerant and the sink based on + approximation. Returns ------- @@ -220,7 +230,8 @@ def delta_t_refrigerant_sink(self) -> Union[xr.DataArray, np.array]: @property def ratio_evaporation_compression_work(self) -> Union[xr.DataArray, np.array]: """ - Calculate the ratio of evaporation to compression work based on approximation. + Calculate the ratio of evaporation to compression work based on + approximation. Returns ------- @@ -228,7 +239,7 @@ def ratio_evaporation_compression_work(self) -> Union[xr.DataArray, np.array]: The calculated ratio of evaporation to compression work. """ return self._ratio_evaporation_compression_work_approximation() - + @property def delta_t_sink(self) -> Union[xr.DataArray, np.array]: """ @@ -245,7 +256,8 @@ def _approximate_delta_t_refrigerant_source( self, delta_t_source: Union[xr.DataArray, np.array] ) -> Union[xr.DataArray, np.array]: """ - Approximates the temperature difference between the refrigerant and the source. + Approximates the temperature difference between the refrigerant and the + source. Parameters ---------- @@ -291,7 +303,6 @@ def _approximate_delta_t_refrigerant_sink( The approximate temperature difference at the refrigerant sink is calculated using the following formula: a * (t_sink_out - t_source_out + 2 * delta_t_pinch) + b * delta_t_sink + c - """ if refrigerant not in a.keys(): raise ValueError( @@ -366,16 +377,21 @@ def _ratio_evaporation_compression_work_approximation( delta_T = snakemake.params.heat_pump_sink_T_decentral_heating - source_T - cop_individual_heating = coefficient_of_performance_individual_heating(delta_T, source) - cop_individual_heating.to_netcdf(snakemake.output[f"cop_{source}_decentral_heating"]) + cop_individual_heating = coefficient_of_performance_individual_heating( + delta_T, source + ) + cop_individual_heating.to_netcdf( + snakemake.output[f"cop_{source}_decentral_heating"] + ) cop_district_heating = CopDistrictHeating( forward_temperature_celsius=snakemake.params.forward_temperature_district_heating, return_temperature_celsius=snakemake.params.return_temperature_district_heating, source_inlet_temperature_celsius=source_T, - source_outlet_temperature_celsius=source_T - snakemake.params.heat_source_cooling_district_heating, + source_outlet_temperature_celsius=source_T + - snakemake.params.heat_source_cooling_district_heating, ).cop() - cop_district_heating.to_netcdf(snakemake.output[f"cop_{source}_central_heating"]) - - + cop_district_heating.to_netcdf( + snakemake.output[f"cop_{source}_central_heating"] + ) diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index 66b5085da..1916c62ec 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1827,7 +1827,9 @@ def add_heat(n, costs): "air decentral": xr.open_dataarray(snakemake.input.cop_air_decentral_heating) .to_pandas() .reindex(index=n.snapshots), - "ground decentral": xr.open_dataarray(snakemake.input.cop_soil_decentral_heating) + "ground decentral": xr.open_dataarray( + snakemake.input.cop_soil_decentral_heating + ) .to_pandas() .reindex(index=n.snapshots), "air central": xr.open_dataarray(snakemake.input.cop_air_central_heating) From 0e6a7377ea48241701b9e91518ed649084f49bc6 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 24 Jul 2024 15:03:14 +0200 Subject: [PATCH 07/58] update configtables --- doc/configtables/sector.csv | 70 +++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 31 deletions(-) diff --git a/doc/configtables/sector.csv b/doc/configtables/sector.csv index 5045cecdc..bb74035ee 100644 --- a/doc/configtables/sector.csv +++ b/doc/configtables/sector.csv @@ -5,9 +5,17 @@ biomass,--,"{true, false}",Flag to include biomass sector. industry,--,"{true, false}",Flag to include industry sector. agriculture,--,"{true, false}",Flag to include agriculture sector. district_heating,--,,`prepare_sector_network.py `_ --- potential,--,float,maximum fraction of urban demand which can be supplied by district heating. Ignored where below current fraction. --- progress,--,Dictionary with planning horizons as keys., Increase of today's district heating demand to potential maximum district heating share. Progress = 0 means today's district heating share. Progress = 1 means maximum fraction of urban demand is supplied by district heating --- district_heating_loss,--,float,Share increase in district heat demand in urban central due to heat losses +#NAME?,--,float,maximum fraction of urban demand which can be supplied by district heating. Ignored where below current fraction. +#NAME?,--,Dictionary with planning horizons as keys., Increase of today's district heating demand to potential maximum district heating share. Progress = 0 means today's district heating share. Progress = 1 means maximum fraction of urban demand is supplied by district heating +#NAME?,--,float,Share increase in district heat demand in urban central due to heat losses +#NAME?,°C,float,Forward temperature in district heating +#NAME?,°C,float,Return temperature in district heating. Must be lower than forward temperature +#NAME?,K,float,Cooling of heat source for heat pumps +#NAME?,,, +#NAME?,--,"{ammonia, isobutane}",Heat pump refrigerant assumed for COP approximation +#NAME?,K,float,Heat pump pinch point temperature difference in heat exchangers assumed for approximation. +#NAME?,--,float,Isentropic efficiency of heat pump compressor assumed for approximation. Must be between 0 and 1. +#NAME?,--,float,Heat pump heat loss assumed for approximation. Must be between 0 and 1. cluster_heat_buses,--,"{true, false}",Cluster residential and service heat buses in `prepare_sector_network.py `_ to one to save memory. ,,, bev_dsm_restriction _value,--,float,Adds a lower state of charge (SOC) limit for battery electric vehicles (BEV) to manage its own energy demand (DSM). Located in `build_transport_demand.py `_. Set to 0 for no restriction on BEV DSM @@ -57,21 +65,21 @@ heat_pump_sink_T,°C,float,The temperature heat sink used in heat pumps based on reduce_space_heat _exogenously,--,"{true, false}",Influence on space heating demand by a certain factor (applied before losses in district heating). reduce_space_heat _exogenously_factor,--,Dictionary with planning horizons as keys.,"A positive factor can mean renovation or demolition of a building. If the factor is negative, it can mean an increase in floor area, increased thermal comfort, population growth. The default factors are determined by the `Eurocalc Homes and buildings decarbonization scenario `_" retrofitting,,, --- retro_endogen,--,"{true, false}",Add retrofitting as an endogenous system which co-optimise space heat savings. --- cost_factor,--,float,Weight costs for building renovation --- interest_rate,--,float,The interest rate for investment in building components --- annualise_cost,--,"{true, false}",Annualise the investment costs of retrofitting --- tax_weighting,--,"{true, false}",Weight the costs of retrofitting depending on taxes in countries --- construction_index,--,"{true, false}",Weight the costs of retrofitting depending on labour/material costs per country +#NAME?,--,"{true, false}",Add retrofitting as an endogenous system which co-optimise space heat savings. +#NAME?,--,float,Weight costs for building renovation +#NAME?,--,float,The interest rate for investment in building components +#NAME?,--,"{true, false}",Annualise the investment costs of retrofitting +#NAME?,--,"{true, false}",Weight the costs of retrofitting depending on taxes in countries +#NAME?,--,"{true, false}",Weight the costs of retrofitting depending on labour/material costs per country tes,--,"{true, false}",Add option for storing thermal energy in large water pits associated with district heating systems and individual thermal energy storage (TES) tes_tau,,,The time constant used to calculate the decay of thermal energy in thermal energy storage (TES): 1- :math:`e^{-1/24τ}`. --- decentral,days,float,The time constant in decentralized thermal energy storage (TES) --- central,days,float,The time constant in centralized thermal energy storage (TES) +#NAME?,days,float,The time constant in decentralized thermal energy storage (TES) +#NAME?,days,float,The time constant in centralized thermal energy storage (TES) boilers,--,"{true, false}",Add option for transforming gas into heat using gas boilers resistive_heaters,--,"{true, false}",Add option for transforming electricity into heat using resistive heaters (independently from gas boilers) oil_boilers,--,"{true, false}",Add option for transforming oil into heat using boilers biomass_boiler,--,"{true, false}",Add option for transforming biomass into heat using boilers -overdimension_individual_heating,--,"float",Add option for overdimensioning individual heating systems by a certain factor. This allows them to cover heat demand peaks e.g. 10% higher than those in the data with a setting of 1.1. +overdimension_individual_heating,--,float,Add option for overdimensioning individual heating systems by a certain factor. This allows them to cover heat demand peaks e.g. 10% higher than those in the data with a setting of 1.1. chp,--,"{true, false}",Add option for using Combined Heat and Power (CHP) micro_chp,--,"{true, false}",Add option for using Combined Heat and Power (CHP) for decentral areas. solar_thermal,--,"{true, false}",Add option for using solar thermal to generate heat. @@ -89,12 +97,12 @@ SMR CC,--,"{true, false}",Add option for transforming natural gas into hydrogen regional_methanol_demand,--,"{true, false}",Spatially resolve methanol demand. Set to true if regional CO2 constraints needed. regional_oil_demand,--,"{true, false}",Spatially resolve oil demand. Set to true if regional CO2 constraints needed. regional_co2 _sequestration_potential,,, --- enable,--,"{true, false}",Add option for regionally-resolved geological carbon dioxide sequestration potentials based on `CO2StoP `_. --- attribute,--,string or list,Name (or list of names) of the attribute(s) for the sequestration potential --- include_onshore,--,"{true, false}",Add options for including onshore sequestration potentials --- min_size,Gt ,float,Any sites with lower potential than this value will be excluded --- max_size,Gt ,float,The maximum sequestration potential for any one site. --- years_of_storage,years,float,The years until potential exhausted at optimised annual rate +#NAME?,--,"{true, false}",Add option for regionally-resolved geological carbon dioxide sequestration potentials based on `CO2StoP `_. +#NAME?,--,string or list,Name (or list of names) of the attribute(s) for the sequestration potential +#NAME?,--,"{true, false}",Add options for including onshore sequestration potentials +#NAME?,Gt ,float,Any sites with lower potential than this value will be excluded +#NAME?,Gt ,float,The maximum sequestration potential for any one site. +#NAME?,years,float,The years until potential exhausted at optimised annual rate co2_sequestration_potential,MtCO2/a,float,The potential of sequestering CO2 in Europe per year co2_sequestration_cost,currency/tCO2,float,The cost of sequestering a ton of CO2 co2_sequestration_lifetime,years,int,The lifetime of a CO2 sequestration site @@ -121,9 +129,9 @@ electricity_distribution _grid_cost_factor,,,Multiplies the investment cost of t electricity_grid _connection,--,"{true, false}",Add the cost of electricity grid connection for onshore wind and solar transmission_efficiency,,,Section to specify transmission losses or compression energy demands of bidirectional links. Splits them into two capacity-linked unidirectional links. -- {carrier},--,str,The carrier of the link. --- -- efficiency_static,p.u.,float,Length-independent transmission efficiency. --- -- efficiency_per_1000km,p.u. per 1000 km,float,Length-dependent transmission efficiency ($\eta^{\text{length}}$) --- -- compression_per_1000km,p.u. per 1000 km,float,Length-dependent electricity demand for compression ($\eta \cdot \text{length}$) implemented as multi-link to local electricity bus. +#NAME?,p.u.,float,Length-independent transmission efficiency. +#NAME?,p.u. per 1000 km,float,Length-dependent transmission efficiency ($\eta^{\text{length}}$) +#NAME?,p.u. per 1000 km,float,Length-dependent electricity demand for compression ($\eta \cdot \text{length}$) implemented as multi-link to local electricity bus. H2_network,--,"{true, false}",Add option for new hydrogen pipelines gas_network,--,"{true, false}","Add existing natural gas infrastructure, incl. LNG terminals, production and entry-points. The existing gas network is added with a lossless transport model. A length-weighted `k-edge augmentation algorithm `_ can be run to add new candidate gas pipelines such that all regions of the model can be connected to the gas network. When activated, all the gas demands are regionally disaggregated as well." H2_retrofit,--,"{true, false}",Add option for retrofiting existing pipelines to transport hydrogen. @@ -139,17 +147,17 @@ conventional_generation,,,Add a more detailed description of conventional carrie biomass_to_liquid,--,"{true, false}",Add option for transforming solid biomass into liquid fuel with the same properties as oil biosng,--,"{true, false}",Add option for transforming solid biomass into synthesis gas with the same properties as natural gas limit_max_growth,,, --- enable,--,"{true, false}",Add option to limit the maximum growth of a carrier --- factor,p.u.,float,The maximum growth factor of a carrier (e.g. 1.3 allows 30% larger than max historic growth) --- max_growth,,, +#NAME?,--,"{true, false}",Add option to limit the maximum growth of a carrier +#NAME?,p.u.,float,The maximum growth factor of a carrier (e.g. 1.3 allows 30% larger than max historic growth) +#NAME?,,, -- -- {carrier},GW,float,The historic maximum growth of a carrier --- max_relative_growth,,, +#NAME?,,, -- -- {carrier},p.u.,float,The historic maximum relative growth of a carrier ,,, enhanced_geothermal,,, --- enable,--,"{true, false}",Add option to include Enhanced Geothermal Systems --- flexible,--,"{true, false}",Add option for flexible operation (see Ricks et al. 2024) --- max_hours,--,int,The maximum hours the reservoir can be charged under flexible operation --- max_boost,--,float,The maximum boost in power output under flexible operation --- var_cf,--,"{true, false}",Add option for variable capacity factor (see Ricks et al. 2024) --- sustainability_factor,--,float,Share of sourced heat that is replenished by the earth's core (see details in `build_egs_potentials.py `_) +#NAME?,--,"{true, false}",Add option to include Enhanced Geothermal Systems +#NAME?,--,"{true, false}",Add option for flexible operation (see Ricks et al. 2024) +#NAME?,--,int,The maximum hours the reservoir can be charged under flexible operation +#NAME?,--,float,The maximum boost in power output under flexible operation +#NAME?,--,"{true, false}",Add option for variable capacity factor (see Ricks et al. 2024) +#NAME?,--,float,Share of sourced heat that is replenished by the earth's core (see details in `build_egs_potentials.py `_) \ No newline at end of file From 3fac27ff27317246bd613652802477d4652bbc95 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 24 Jul 2024 15:03:44 +0200 Subject: [PATCH 08/58] use module structure --- rules/build_sector.smk | 10 +- .../build_cop_profiles/BaseCopApproximator.py | 61 ++++++ .../CentralHeatingCopApproximator.py} | 184 ++++-------------- .../DecentralHeatingCopApproximator.py | 79 ++++++++ scripts/build_cop_profiles/__main__.py | 42 ++++ 5 files changed, 228 insertions(+), 148 deletions(-) create mode 100644 scripts/build_cop_profiles/BaseCopApproximator.py rename scripts/{build_cop_profiles.py => build_cop_profiles/CentralHeatingCopApproximator.py} (58%) create mode 100644 scripts/build_cop_profiles/DecentralHeatingCopApproximator.py create mode 100644 scripts/build_cop_profiles/__main__.py diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 510af7c04..278bff48e 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -220,16 +220,16 @@ rule build_cop_profiles: heat_pump_sink_T_decentral_heating=config_provider( "sector", "heat_pump_sink_T_individual_heating" ), - forward_temperature_district_heating=config_provider( + forward_temperature_central_heating=config_provider( "sector", "district_heating", "forward_temperature" ), - return_temperature_district_heating=config_provider( + return_temperature_central_heating=config_provider( "sector", "district_heating", "return_temperature" ), - heat_source_cooling_district_heating=config_provider( + heat_source_cooling_central_heating=config_provider( "sector", "district_heating", "heat_source_cooling" ), - heat_pump_cop_approximation_district_heating=config_provider( + heat_pump_cop_approximation_central_heating=config_provider( "sector", "district_heating", "heat_pump_cop_approximation" ), input: @@ -257,7 +257,7 @@ rule build_cop_profiles: conda: "../envs/environment.yaml" script: - "../scripts/build_cop_profiles.py" + "../scripts/build_cop_profiles/__main__.py" def solar_thermal_cutout(wildcards): diff --git a/scripts/build_cop_profiles/BaseCopApproximator.py b/scripts/build_cop_profiles/BaseCopApproximator.py new file mode 100644 index 000000000..87343d368 --- /dev/null +++ b/scripts/build_cop_profiles/BaseCopApproximator.py @@ -0,0 +1,61 @@ + +from abc import ABC, abstractmethod +from typing import Union +import xarray as xr +import numpy as np + +class BaseCopApproximator(ABC): + """ + Abstract class for approximating the coefficient of performance (COP) of a heat pump.""" + def __init__( + self, + forward_temperature_celsius: Union[xr.DataArray, np.array], + source_inlet_temperature_celsius: Union[xr.DataArray, np.array], + ): + """ + Initialize CopApproximator. + + Parameters: + ---------- + forward_temperature_celsius : Union[xr.DataArray, np.array] + The forward temperature in Celsius. + return_temperature_celsius : Union[xr.DataArray, np.array] + The return temperature in Celsius. + """ + pass + + @abstractmethod + def approximate_cop(self) -> Union[xr.DataArray, np.array]: + """Approximate heat pump coefficient of performance (COP). + + Returns: + ------- + Union[xr.DataArray, np.array] + The calculated COP values. + """ + pass + + def celsius_to_kelvin(t_celsius: Union[float, xr.DataArray, np.array]) -> Union[float, xr.DataArray, np.array]: + if (np.asarray(t_celsius) > 200).any(): + raise ValueError("t_celsius > 200. Are you sure you are using the right units?") + return t_celsius + 273.15 + + + def logarithmic_mean(t_hot: Union[float, xr.DataArray, np.ndarray], t_cold: Union[float, xr.DataArray, np.ndarray]) -> Union[float, xr.DataArray, np.ndarray]: + if (np.asarray(t_hot <= t_cold)).any(): + raise ValueError("t_hot must be greater than t_cold") + return (t_hot - t_cold) / np.log(t_hot / t_cold) + + @staticmethod + def celsius_to_kelvin(t_celsius: Union[float, xr.DataArray, np.array]) -> Union[float, xr.DataArray, np.array]: + if (np.asarray(t_celsius) > 200).any(): + raise ValueError("t_celsius > 200. Are you sure you are using the right units?") + return t_celsius + 273.15 + + @staticmethod + def logarithmic_mean(t_hot: Union[float, xr.DataArray, np.ndarray], t_cold: Union[float, xr.DataArray, np.ndarray]) -> Union[float, xr.DataArray, np.ndarray]: + if (np.asarray(t_hot <= t_cold)).any(): + raise ValueError("t_hot must be greater than t_cold") + return (t_hot - t_cold) / np.log(t_hot / t_cold) + + diff --git a/scripts/build_cop_profiles.py b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py similarity index 58% rename from scripts/build_cop_profiles.py rename to scripts/build_cop_profiles/CentralHeatingCopApproximator.py index 89eeb9b68..9b4454264 100644 --- a/scripts/build_cop_profiles.py +++ b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py @@ -1,78 +1,17 @@ -# -*- coding: utf-8 -*- -# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors -# -# SPDX-License-Identifier: MIT -""" -Build coefficient of performance (COP) time series for air- or ground-sourced -heat pumps. -For individual (decentral) heat pumps, the COP is approximated as a quatratic function of the temperature difference between source and sink, based on Staffell et al. 2012. -For district (central) heating, the COP is approximated based on Jensen et al. 2018 and parameters from Pieper et al. 2020. - -This rule is executed in ``build_sector.smk``. - -Relevant Settings ------------------ - -.. code:: yaml - heat_pump_sink_T: - - -Inputs: -------- -- ``resources//temp_soil_total_elec_s_.nc``: Soil temperature (total) time series. -- ``resources//temp_air_total_elec_s_.nc``: Ambient air temperature (total) time series. - -Outputs: --------- -- ``resources/cop_air_decentral_heating_elec_s_.nc``: COP (air-sourced) time series (decentral heating). -- ``resources/cop_soil_decentral_heating_elec_s_.nc``: COP (ground-sourced) time series (decentral heating). -- ``resources/cop_air_central_heating_elec_s_.nc``: COP (air-sourced) time series (central heating). -- ``resources/cop_soil_central_heating_elec_s_.nc``: COP (ground-sourced) time series (central heating). - - -References ----------- -[1] Staffell et al., Energy & Environmental Science 11 (2012): A review of domestic heat pumps, https://doi.org/10.1039/C2EE22653G. -[2] Jensen et al., Proceedings of the13th IIR-Gustav Lorentzen Conference on Natural Refrigerants (2018): Heat pump COP, part 2: Generalized COP estimation of heat pump processes, https://doi.org/10.18462/iir.gl.2018.1386 -[3] Pieper et al., Energy 205 (2020): Comparison of COP estimation methods for large-scale heat pumps used in energy planning, https://doi.org/10.1016/j.energy.2020.117994 -""" - -from enum import Enum from typing import Union - -import numpy as np import xarray as xr -from _helpers import set_scenario_config - - -def coefficient_of_performance_individual_heating(delta_T, source="air"): - if source == "air": - return 6.81 - 0.121 * delta_T + 0.000630 * delta_T**2 - elif source == "soil": - return 8.77 - 0.150 * delta_T + 0.000734 * delta_T**2 - else: - raise NotImplementedError("'source' must be one of ['air', 'soil']") - - -def celsius_to_kelvin( - t_celsius: Union[float, xr.DataArray, np.array] -) -> Union[float, xr.DataArray, np.array]: - if (np.asarray(t_celsius) > 200).any(): - raise ValueError("t_celsius > 200. Are you sure you are using the right units?") - return t_celsius + 273.15 - - -def logarithmic_mean( - t_hot: Union[float, xr.DataArray, np.ndarray], - t_cold: Union[float, xr.DataArray, np.ndarray], -) -> Union[float, xr.DataArray, np.ndarray]: - if (np.asarray(t_hot <= t_cold)).any(): - raise ValueError("t_hot must be greater than t_cold") - return (t_hot - t_cold) / np.log(t_hot / t_cold) +import numpy as np +from BaseCopApproximator import BaseCopApproximator -class CopDistrictHeating: +class CentralHeatingCopApproximator(BaseCopApproximator): + """ + Approximate the coefficient of performance (COP) for a heat pump in a central heating system (district heating). + + Uses an approximation method proposed by Jensen et al. (2018) and default parameters from Pieper et al. (2020). + The method is based on a thermodynamic heat pump model with some hard-to-know parameters being approximated. + """ def __init__( self, @@ -85,7 +24,6 @@ def __init__( heat_loss: float = 0.0, ) -> None: """ - Initialize the COPProfileBuilder object. Parameters: ---------- @@ -104,17 +42,17 @@ def __init__( heat_loss : float, optional The heat loss, by default 0.0. """ - self.t_source_in = celsius_to_kelvin(source_inlet_temperature_celsius) - self.t_sink_out = celsius_to_kelvin(forward_temperature_celsius) + self.t_source_in_kelvin = BaseCopApproximator.celsius_to_kelvin(source_inlet_temperature_celsius) + self.t_sink_out_kelvin = BaseCopApproximator.celsius_to_kelvin(forward_temperature_celsius) - self.t_sink_in = celsius_to_kelvin(return_temperature_celsius) - self.t_source_out = celsius_to_kelvin(source_outlet_temperature_celsius) + self.t_sink_in_kelvin = BaseCopApproximator.celsius_to_kelvin(return_temperature_celsius) + self.t_source_out = BaseCopApproximator.celsius_to_kelvin(source_outlet_temperature_celsius) - self.isentropic_efficiency_compressor = isentropic_compressor_efficiency + self.isentropic_efficiency_compressor_kelvin = isentropic_compressor_efficiency self.heat_loss = heat_loss self.delta_t_pinch = delta_t_pinch_point - def cop(self) -> Union[xr.DataArray, np.array]: + def approximate_cop(self) -> Union[xr.DataArray, np.array]: """ Calculate the coefficient of performance (COP) for the system. @@ -127,7 +65,7 @@ def cop(self) -> Union[xr.DataArray, np.array]: ( 1 + (self.delta_t_refrigerant_sink + self.delta_t_pinch) - / self.t_sink_mean + / self.t_sink_mean_kelvin ) / ( 1 @@ -139,28 +77,27 @@ def cop(self) -> Union[xr.DataArray, np.array]: / self.delta_t_lift ) ) - * self.isentropic_efficiency_compressor + * self.isentropic_efficiency_compressor_kelvin * (1 - self.ratio_evaporation_compression_work) + 1 - - self.isentropic_efficiency_compressor + - self.isentropic_efficiency_compressor_kelvin - self.heat_loss ) @property - def t_sink_mean(self) -> Union[xr.DataArray, np.array]: + def t_sink_mean_kelvin(self) -> Union[xr.DataArray, np.array]: """ - Calculate the logarithmic mean temperature difference between the cold - and hot sinks. + Calculate the logarithmic mean temperature difference between the cold and hot sinks. Returns ------- Union[xr.DataArray, np.array] The mean temperature difference. """ - return logarithmic_mean(t_cold=self.t_sink_in, t_hot=self.t_sink_out) + return BaseCopApproximator.logarithmic_mean(t_cold=self.t_sink_in_kelvin, t_hot=self.t_sink_out_kelvin) @property - def t_source_mean(self) -> Union[xr.DataArray, np.array]: + def t_source_mean_kelvin(self) -> Union[xr.DataArray, np.array]: """ Calculate the logarithmic mean temperature of the heat source. @@ -169,20 +106,19 @@ def t_source_mean(self) -> Union[xr.DataArray, np.array]: Union[xr.DataArray, np.array] The mean temperature of the heat source. """ - return logarithmic_mean(t_hot=self.t_source_in, t_cold=self.t_source_out) + return BaseCopApproximator.logarithmic_mean(t_hot=self.t_source_in_kelvin, t_cold=self.t_source_out) @property def delta_t_lift(self) -> Union[xr.DataArray, np.array]: """ - Calculate the temperature lift as the difference between the - logarithmic sink and source temperatures. + Calculate the temperature lift as the difference between the logarithmic sink and source temperatures. Returns ------- Union[xr.DataArray, np.array] The temperature difference between the sink and source. """ - return self.t_sink_mean - self.t_source_mean + return self.t_sink_mean_kelvin - self.t_source_mean_kelvin @property def ideal_lorenz_cop(self) -> Union[xr.DataArray, np.array]: @@ -196,14 +132,14 @@ def ideal_lorenz_cop(self) -> Union[xr.DataArray, np.array]: ------- np.array The ideal Lorenz COP. + """ - return self.t_sink_mean / self.delta_t_lift + return self.t_sink_mean_kelvin / self.delta_t_lift @property def delta_t_refrigerant_source(self) -> Union[xr.DataArray, np.array]: """ - Calculate the temperature difference between the refrigerant source - inlet and outlet. + Calculate the temperature difference between the refrigerant source inlet and outlet. Returns ------- @@ -211,14 +147,13 @@ def delta_t_refrigerant_source(self) -> Union[xr.DataArray, np.array]: The temperature difference between the refrigerant source inlet and outlet. """ return self._approximate_delta_t_refrigerant_source( - delta_t_source=self.t_source_in - self.t_source_out + delta_t_source=self.t_source_in_kelvin - self.t_source_out ) @property def delta_t_refrigerant_sink(self) -> Union[xr.DataArray, np.array]: """ - Temperature difference between the refrigerant and the sink based on - approximation. + Temperature difference between the refrigerant and the sink based on approximation. Returns ------- @@ -230,8 +165,7 @@ def delta_t_refrigerant_sink(self) -> Union[xr.DataArray, np.array]: @property def ratio_evaporation_compression_work(self) -> Union[xr.DataArray, np.array]: """ - Calculate the ratio of evaporation to compression work based on - approximation. + Calculate the ratio of evaporation to compression work based on approximation. Returns ------- @@ -239,7 +173,7 @@ def ratio_evaporation_compression_work(self) -> Union[xr.DataArray, np.array]: The calculated ratio of evaporation to compression work. """ return self._ratio_evaporation_compression_work_approximation() - + @property def delta_t_sink(self) -> Union[xr.DataArray, np.array]: """ @@ -250,14 +184,13 @@ def delta_t_sink(self) -> Union[xr.DataArray, np.array]: Union[xr.DataArray, np.array] The temperature difference at the sink. """ - return self.t_sink_out - self.t_sink_in + return self.t_sink_out_kelvin - self.t_sink_in_kelvin def _approximate_delta_t_refrigerant_source( self, delta_t_source: Union[xr.DataArray, np.array] ) -> Union[xr.DataArray, np.array]: """ - Approximates the temperature difference between the refrigerant and the - source. + Approximates the temperature difference between the refrigerant and the source. Parameters ---------- @@ -267,7 +200,7 @@ def _approximate_delta_t_refrigerant_source( Returns ------- Union[xr.DataArray, np.array] - The approximate temperature difference for the refrigerant source. + The approximate temperature difference between the refrigerant and heat source. """ return delta_t_source / 2 @@ -279,7 +212,7 @@ def _approximate_delta_t_refrigerant_sink( c: float = {"ammonia": 0.016, "isobutane": 2.4}, ) -> Union[xr.DataArray, np.array]: """ - Approximates the temperature difference at the refrigerant sink. + Approximates the temperature difference between the refrigerant and heat sink. Parameters: ---------- @@ -295,7 +228,7 @@ def _approximate_delta_t_refrigerant_sink( Returns: ------- Union[xr.DataArray, np.array] - The approximate temperature difference at the refrigerant sink. + The approximate temperature difference between the refrigerant and heat sink. Notes: ------ @@ -303,6 +236,7 @@ def _approximate_delta_t_refrigerant_sink( The approximate temperature difference at the refrigerant sink is calculated using the following formula: a * (t_sink_out - t_source_out + 2 * delta_t_pinch) + b * delta_t_sink + c + """ if refrigerant not in a.keys(): raise ValueError( @@ -310,7 +244,7 @@ def _approximate_delta_t_refrigerant_sink( ) return ( a[refrigerant] - * (self.t_sink_out - self.t_source_out + 2 * self.delta_t_pinch) + * (self.t_sink_out_kelvin - self.t_source_out + 2 * self.delta_t_pinch) + b[refrigerant] * self.delta_t_sink + c[refrigerant] ) @@ -339,7 +273,7 @@ def _ratio_evaporation_compression_work_approximation( Returns: ------- Union[xr.DataArray, np.array] - The calculated ratio of evaporation to compression work. + The approximated ratio of evaporation to compression work. Notes: ------ @@ -354,44 +288,8 @@ def _ratio_evaporation_compression_work_approximation( ) return ( a[refrigerant] - * (self.t_sink_out - self.t_source_out + 2 * self.delta_t_pinch) + * (self.t_sink_out_kelvin - self.t_source_out + 2 * self.delta_t_pinch) + b[refrigerant] * self.delta_t_sink + c[refrigerant] ) - -if __name__ == "__main__": - if "snakemake" not in globals(): - from _helpers import mock_snakemake - - snakemake = mock_snakemake( - "build_cop_profiles", - simpl="", - clusters=48, - ) - - set_scenario_config(snakemake) - - for source in ["air", "soil"]: - source_T = xr.open_dataarray(snakemake.input[f"temp_{source}_total"]) - - delta_T = snakemake.params.heat_pump_sink_T_decentral_heating - source_T - - cop_individual_heating = coefficient_of_performance_individual_heating( - delta_T, source - ) - cop_individual_heating.to_netcdf( - snakemake.output[f"cop_{source}_decentral_heating"] - ) - - cop_district_heating = CopDistrictHeating( - forward_temperature_celsius=snakemake.params.forward_temperature_district_heating, - return_temperature_celsius=snakemake.params.return_temperature_district_heating, - source_inlet_temperature_celsius=source_T, - source_outlet_temperature_celsius=source_T - - snakemake.params.heat_source_cooling_district_heating, - ).cop() - - cop_district_heating.to_netcdf( - snakemake.output[f"cop_{source}_central_heating"] - ) diff --git a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py new file mode 100644 index 000000000..03ca63fea --- /dev/null +++ b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py @@ -0,0 +1,79 @@ + + + +from typing import Union +import xarray as xr +import numpy as np + +from BaseCopApproximator import BaseCopApproximator + +class DecentralHeatingCopApproximator(BaseCopApproximator): + """ + Approximate the coefficient of performance (COP) for a heat pump in a decentral heating system (individual/household heating). + + Uses a quadratic regression on the temperature difference between the source and sink based on empirical data proposed by Staffell et al. 2012 . + + References + ---------- + [1] Staffell et al., Energy & Environmental Science 11 (2012): A review of domestic heat pumps, https://doi.org/10.1039/C2EE22653G. + """ + + def __init__( + self, + forward_temperature_celsius: Union[xr.DataArray, np.array], + source_inlet_temperature_celsius: Union[xr.DataArray, np.array], + source_type: str + ): + """ + Initialize the COPProfileBuilder object. + + Parameters: + ---------- + forward_temperature_celsius : Union[xr.DataArray, np.array] + The forward temperature in Celsius. + return_temperature_celsius : Union[xr.DataArray, np.array] + The return temperature in Celsius. + source: str + The source of the heat pump. Must be either 'air' or 'soil' + """ + + self.delta_t = forward_temperature_celsius - source_inlet_temperature_celsius + if source_type not in ["air", "soil"]: + raise ValueError("'source' must be one of ['air', 'soil']") + else: + self.source_type = source_type + + def approximate_cop(self) -> Union[xr.DataArray, np.array]: + """ + Compute output of quadratic regression for air-/ground-source heat pumps. + + Calls the appropriate method depending on `source`.""" + if self.source_type == "air": + return self._approximate_cop_air_source() + elif self.source_type == "soil": + return self._approximate_cop_ground_source() + + def _approximate_cop_air_source(self) -> Union[xr.DataArray, np.array]: + """ + Evaluate quadratic regression for an air-sourced heat pump. + + COP = 6.81 - 0.121 * delta_T + 0.000630 * delta_T^2 + + Returns + ------- + Union[xr.DataArray, np.array] + The calculated COP values.""" + return 6.81 - 0.121 * self.delta_t + 0.000630 * self.delta_t**2 + + def _approximate_cop_ground_source(self) -> Union[xr.DataArray, np.array]: + """ + Evaluate quadratic regression for a ground-sourced heat pump. + + COP = 8.77 - 0.150 * delta_T + 0.000734 * delta_T^2 + + Returns + ------- + Union[xr.DataArray, np.array] + The calculated COP values.""" + return 8.77 - 0.150 * self.delta_t + 0.000734 * self.delta_t**2 + \ No newline at end of file diff --git a/scripts/build_cop_profiles/__main__.py b/scripts/build_cop_profiles/__main__.py new file mode 100644 index 000000000..2568476fc --- /dev/null +++ b/scripts/build_cop_profiles/__main__.py @@ -0,0 +1,42 @@ + + +import xarray as xr +import numpy as np +from CentralHeatingCopApproximator import CentralHeatingCopApproximator +from DecentralHeatingCopApproximator import DecentralHeatingCopApproximator +from _helpers import set_scenario_config + +if __name__ == "__main__": + if "snakemake" not in globals(): + from _helpers import mock_snakemake + + snakemake = mock_snakemake( + "build_cop_profiles", + simpl="", + clusters=48, + ) + + set_scenario_config(snakemake) + + for source_type in ["air", "soil"]: + # source inlet temperature (air/soil) is based on weather data + source_inlet_temperature_celsius = xr.open_dataarray(snakemake.input[f"temp_{source_type}_total"]) + + # Approximate COP for decentral (individual) heating + cop_individual_heating = DecentralHeatingCopApproximator( + forward_temperature_celsius=snakemake.params.heat_pump_sink_T_decentral_heating, + source_inlet_temperature_celsius=source_inlet_temperature_celsius, + source_type=source_type + ).approximate_cop() + cop_individual_heating.to_netcdf(snakemake.output[f"cop_{source_type}_decentral_heating"]) + + # Approximate COP for central (district) heating + cop_central_heating = CentralHeatingCopApproximator( + forward_temperature_celsius=snakemake.params.forward_temperature_central_heating, + return_temperature_celsius=snakemake.params.return_temperature_central_heating, + source_inlet_temperature_celsius=source_inlet_temperature_celsius, + source_outlet_temperature_celsius=source_inlet_temperature_celsius - snakemake.params.heat_source_cooling_central_heating, + ).approximate_cop() + cop_central_heating.to_netcdf(snakemake.output[f"cop_{source_type}_central_heating"]) + + From a9f4c6375dc5cd10fcdc3a71912cc7b5288d7516 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 24 Jul 2024 15:04:14 +0200 Subject: [PATCH 09/58] change default DH return temperature to 50C --- config/config.default.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index 7e2f7077a..cace1f4c4 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -420,7 +420,7 @@ sector: district_heating_loss: 0.15 # check these numbers! forward_temperature: 90 #C - return_temperature: 60 #C + return_temperature: 50 #C heat_source_cooling: 6 #K heat_pump_cop_approximation: refrigerant: ammonia From eb2911cb9300cfaeba3fa5e579f7f6513481af60 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 24 Jul 2024 15:31:48 +0200 Subject: [PATCH 10/58] rename __main__ to run --- scripts/build_cop_profiles/{__main__.py => run.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename scripts/build_cop_profiles/{__main__.py => run.py} (100%) diff --git a/scripts/build_cop_profiles/__main__.py b/scripts/build_cop_profiles/run.py similarity index 100% rename from scripts/build_cop_profiles/__main__.py rename to scripts/build_cop_profiles/run.py From a4847a10ce9fb3246e3cff1d2225c3911971910f Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 24 Jul 2024 15:40:21 +0200 Subject: [PATCH 11/58] update build_sector.smk --- rules/build_sector.smk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 278bff48e..662773f7b 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -257,7 +257,7 @@ rule build_cop_profiles: conda: "../envs/environment.yaml" script: - "../scripts/build_cop_profiles/__main__.py" + "../scripts/build_cop_profiles/run.py" def solar_thermal_cutout(wildcards): From 8d6feb6a66860b861aec2183b221e30aff185d3e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 24 Jul 2024 15:04:58 +0000 Subject: [PATCH 12/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- doc/configtables/sector.csv | 2 +- .../build_cop_profiles/BaseCopApproximator.py | 76 ++++++++++++------- .../CentralHeatingCopApproximator.py | 67 ++++++++++------ .../DecentralHeatingCopApproximator.py | 43 ++++++----- scripts/build_cop_profiles/run.py | 26 ++++--- 5 files changed, 132 insertions(+), 82 deletions(-) diff --git a/doc/configtables/sector.csv b/doc/configtables/sector.csv index bb74035ee..de2873edd 100644 --- a/doc/configtables/sector.csv +++ b/doc/configtables/sector.csv @@ -160,4 +160,4 @@ enhanced_geothermal,,, #NAME?,--,int,The maximum hours the reservoir can be charged under flexible operation #NAME?,--,float,The maximum boost in power output under flexible operation #NAME?,--,"{true, false}",Add option for variable capacity factor (see Ricks et al. 2024) -#NAME?,--,float,Share of sourced heat that is replenished by the earth's core (see details in `build_egs_potentials.py `_) \ No newline at end of file +#NAME?,--,float,Share of sourced heat that is replenished by the earth's core (see details in `build_egs_potentials.py `_) diff --git a/scripts/build_cop_profiles/BaseCopApproximator.py b/scripts/build_cop_profiles/BaseCopApproximator.py index 87343d368..247ff0fea 100644 --- a/scripts/build_cop_profiles/BaseCopApproximator.py +++ b/scripts/build_cop_profiles/BaseCopApproximator.py @@ -1,32 +1,39 @@ +# -*- coding: utf-8 -*- from abc import ABC, abstractmethod from typing import Union -import xarray as xr + import numpy as np +import xarray as xr + class BaseCopApproximator(ABC): """ - Abstract class for approximating the coefficient of performance (COP) of a heat pump.""" + Abstract class for approximating the coefficient of performance (COP) of a + heat pump. + """ + def __init__( - self, - forward_temperature_celsius: Union[xr.DataArray, np.array], - source_inlet_temperature_celsius: Union[xr.DataArray, np.array], - ): - """ - Initialize CopApproximator. - - Parameters: - ---------- - forward_temperature_celsius : Union[xr.DataArray, np.array] - The forward temperature in Celsius. - return_temperature_celsius : Union[xr.DataArray, np.array] - The return temperature in Celsius. - """ - pass - + self, + forward_temperature_celsius: Union[xr.DataArray, np.array], + source_inlet_temperature_celsius: Union[xr.DataArray, np.array], + ): + """ + Initialize CopApproximator. + + Parameters: + ---------- + forward_temperature_celsius : Union[xr.DataArray, np.array] + The forward temperature in Celsius. + return_temperature_celsius : Union[xr.DataArray, np.array] + The return temperature in Celsius. + """ + pass + @abstractmethod def approximate_cop(self) -> Union[xr.DataArray, np.array]: - """Approximate heat pump coefficient of performance (COP). + """ + Approximate heat pump coefficient of performance (COP). Returns: ------- @@ -34,28 +41,39 @@ def approximate_cop(self) -> Union[xr.DataArray, np.array]: The calculated COP values. """ pass - - def celsius_to_kelvin(t_celsius: Union[float, xr.DataArray, np.array]) -> Union[float, xr.DataArray, np.array]: + + def celsius_to_kelvin( + t_celsius: Union[float, xr.DataArray, np.array] + ) -> Union[float, xr.DataArray, np.array]: if (np.asarray(t_celsius) > 200).any(): - raise ValueError("t_celsius > 200. Are you sure you are using the right units?") + raise ValueError( + "t_celsius > 200. Are you sure you are using the right units?" + ) return t_celsius + 273.15 - - def logarithmic_mean(t_hot: Union[float, xr.DataArray, np.ndarray], t_cold: Union[float, xr.DataArray, np.ndarray]) -> Union[float, xr.DataArray, np.ndarray]: + def logarithmic_mean( + t_hot: Union[float, xr.DataArray, np.ndarray], + t_cold: Union[float, xr.DataArray, np.ndarray], + ) -> Union[float, xr.DataArray, np.ndarray]: if (np.asarray(t_hot <= t_cold)).any(): raise ValueError("t_hot must be greater than t_cold") return (t_hot - t_cold) / np.log(t_hot / t_cold) @staticmethod - def celsius_to_kelvin(t_celsius: Union[float, xr.DataArray, np.array]) -> Union[float, xr.DataArray, np.array]: + def celsius_to_kelvin( + t_celsius: Union[float, xr.DataArray, np.array] + ) -> Union[float, xr.DataArray, np.array]: if (np.asarray(t_celsius) > 200).any(): - raise ValueError("t_celsius > 200. Are you sure you are using the right units?") + raise ValueError( + "t_celsius > 200. Are you sure you are using the right units?" + ) return t_celsius + 273.15 @staticmethod - def logarithmic_mean(t_hot: Union[float, xr.DataArray, np.ndarray], t_cold: Union[float, xr.DataArray, np.ndarray]) -> Union[float, xr.DataArray, np.ndarray]: + def logarithmic_mean( + t_hot: Union[float, xr.DataArray, np.ndarray], + t_cold: Union[float, xr.DataArray, np.ndarray], + ) -> Union[float, xr.DataArray, np.ndarray]: if (np.asarray(t_hot <= t_cold)).any(): raise ValueError("t_hot must be greater than t_cold") return (t_hot - t_cold) / np.log(t_hot / t_cold) - - diff --git a/scripts/build_cop_profiles/CentralHeatingCopApproximator.py b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py index 9b4454264..f2b8d80c1 100644 --- a/scripts/build_cop_profiles/CentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py @@ -1,16 +1,21 @@ +# -*- coding: utf-8 -*- from typing import Union -import xarray as xr -import numpy as np +import numpy as np +import xarray as xr from BaseCopApproximator import BaseCopApproximator + class CentralHeatingCopApproximator(BaseCopApproximator): """ - Approximate the coefficient of performance (COP) for a heat pump in a central heating system (district heating). - - Uses an approximation method proposed by Jensen et al. (2018) and default parameters from Pieper et al. (2020). - The method is based on a thermodynamic heat pump model with some hard-to-know parameters being approximated. + Approximate the coefficient of performance (COP) for a heat pump in a + central heating system (district heating). + + Uses an approximation method proposed by Jensen et al. (2018) and + default parameters from Pieper et al. (2020). The method is based on + a thermodynamic heat pump model with some hard-to-know parameters + being approximated. """ def __init__( @@ -42,11 +47,19 @@ def __init__( heat_loss : float, optional The heat loss, by default 0.0. """ - self.t_source_in_kelvin = BaseCopApproximator.celsius_to_kelvin(source_inlet_temperature_celsius) - self.t_sink_out_kelvin = BaseCopApproximator.celsius_to_kelvin(forward_temperature_celsius) + self.t_source_in_kelvin = BaseCopApproximator.celsius_to_kelvin( + source_inlet_temperature_celsius + ) + self.t_sink_out_kelvin = BaseCopApproximator.celsius_to_kelvin( + forward_temperature_celsius + ) - self.t_sink_in_kelvin = BaseCopApproximator.celsius_to_kelvin(return_temperature_celsius) - self.t_source_out = BaseCopApproximator.celsius_to_kelvin(source_outlet_temperature_celsius) + self.t_sink_in_kelvin = BaseCopApproximator.celsius_to_kelvin( + return_temperature_celsius + ) + self.t_source_out = BaseCopApproximator.celsius_to_kelvin( + source_outlet_temperature_celsius + ) self.isentropic_efficiency_compressor_kelvin = isentropic_compressor_efficiency self.heat_loss = heat_loss @@ -87,14 +100,17 @@ def approximate_cop(self) -> Union[xr.DataArray, np.array]: @property def t_sink_mean_kelvin(self) -> Union[xr.DataArray, np.array]: """ - Calculate the logarithmic mean temperature difference between the cold and hot sinks. + Calculate the logarithmic mean temperature difference between the cold + and hot sinks. Returns ------- Union[xr.DataArray, np.array] The mean temperature difference. """ - return BaseCopApproximator.logarithmic_mean(t_cold=self.t_sink_in_kelvin, t_hot=self.t_sink_out_kelvin) + return BaseCopApproximator.logarithmic_mean( + t_cold=self.t_sink_in_kelvin, t_hot=self.t_sink_out_kelvin + ) @property def t_source_mean_kelvin(self) -> Union[xr.DataArray, np.array]: @@ -106,12 +122,15 @@ def t_source_mean_kelvin(self) -> Union[xr.DataArray, np.array]: Union[xr.DataArray, np.array] The mean temperature of the heat source. """ - return BaseCopApproximator.logarithmic_mean(t_hot=self.t_source_in_kelvin, t_cold=self.t_source_out) + return BaseCopApproximator.logarithmic_mean( + t_hot=self.t_source_in_kelvin, t_cold=self.t_source_out + ) @property def delta_t_lift(self) -> Union[xr.DataArray, np.array]: """ - Calculate the temperature lift as the difference between the logarithmic sink and source temperatures. + Calculate the temperature lift as the difference between the + logarithmic sink and source temperatures. Returns ------- @@ -132,14 +151,14 @@ def ideal_lorenz_cop(self) -> Union[xr.DataArray, np.array]: ------- np.array The ideal Lorenz COP. - """ return self.t_sink_mean_kelvin / self.delta_t_lift @property def delta_t_refrigerant_source(self) -> Union[xr.DataArray, np.array]: """ - Calculate the temperature difference between the refrigerant source inlet and outlet. + Calculate the temperature difference between the refrigerant source + inlet and outlet. Returns ------- @@ -153,7 +172,8 @@ def delta_t_refrigerant_source(self) -> Union[xr.DataArray, np.array]: @property def delta_t_refrigerant_sink(self) -> Union[xr.DataArray, np.array]: """ - Temperature difference between the refrigerant and the sink based on approximation. + Temperature difference between the refrigerant and the sink based on + approximation. Returns ------- @@ -165,7 +185,8 @@ def delta_t_refrigerant_sink(self) -> Union[xr.DataArray, np.array]: @property def ratio_evaporation_compression_work(self) -> Union[xr.DataArray, np.array]: """ - Calculate the ratio of evaporation to compression work based on approximation. + Calculate the ratio of evaporation to compression work based on + approximation. Returns ------- @@ -173,7 +194,7 @@ def ratio_evaporation_compression_work(self) -> Union[xr.DataArray, np.array]: The calculated ratio of evaporation to compression work. """ return self._ratio_evaporation_compression_work_approximation() - + @property def delta_t_sink(self) -> Union[xr.DataArray, np.array]: """ @@ -190,7 +211,8 @@ def _approximate_delta_t_refrigerant_source( self, delta_t_source: Union[xr.DataArray, np.array] ) -> Union[xr.DataArray, np.array]: """ - Approximates the temperature difference between the refrigerant and the source. + Approximates the temperature difference between the refrigerant and the + source. Parameters ---------- @@ -212,7 +234,8 @@ def _approximate_delta_t_refrigerant_sink( c: float = {"ammonia": 0.016, "isobutane": 2.4}, ) -> Union[xr.DataArray, np.array]: """ - Approximates the temperature difference between the refrigerant and heat sink. + Approximates the temperature difference between the refrigerant and + heat sink. Parameters: ---------- @@ -236,7 +259,6 @@ def _approximate_delta_t_refrigerant_sink( The approximate temperature difference at the refrigerant sink is calculated using the following formula: a * (t_sink_out - t_source_out + 2 * delta_t_pinch) + b * delta_t_sink + c - """ if refrigerant not in a.keys(): raise ValueError( @@ -292,4 +314,3 @@ def _ratio_evaporation_compression_work_approximation( + b[refrigerant] * self.delta_t_sink + c[refrigerant] ) - diff --git a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py index 03ca63fea..b49be54c0 100644 --- a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py @@ -1,16 +1,18 @@ - +# -*- coding: utf-8 -*- from typing import Union -import xarray as xr -import numpy as np +import numpy as np +import xarray as xr from BaseCopApproximator import BaseCopApproximator + class DecentralHeatingCopApproximator(BaseCopApproximator): """ - Approximate the coefficient of performance (COP) for a heat pump in a decentral heating system (individual/household heating). - + Approximate the coefficient of performance (COP) for a heat pump in a + decentral heating system (individual/household heating). + Uses a quadratic regression on the temperature difference between the source and sink based on empirical data proposed by Staffell et al. 2012 . References @@ -22,7 +24,7 @@ def __init__( self, forward_temperature_celsius: Union[xr.DataArray, np.array], source_inlet_temperature_celsius: Union[xr.DataArray, np.array], - source_type: str + source_type: str, ): """ Initialize the COPProfileBuilder object. @@ -36,18 +38,20 @@ def __init__( source: str The source of the heat pump. Must be either 'air' or 'soil' """ - + self.delta_t = forward_temperature_celsius - source_inlet_temperature_celsius if source_type not in ["air", "soil"]: raise ValueError("'source' must be one of ['air', 'soil']") else: self.source_type = source_type - + def approximate_cop(self) -> Union[xr.DataArray, np.array]: """ - Compute output of quadratic regression for air-/ground-source heat pumps. - - Calls the appropriate method depending on `source`.""" + Compute output of quadratic regression for air-/ground-source heat + pumps. + + Calls the appropriate method depending on `source`. + """ if self.source_type == "air": return self._approximate_cop_air_source() elif self.source_type == "soil": @@ -56,24 +60,25 @@ def approximate_cop(self) -> Union[xr.DataArray, np.array]: def _approximate_cop_air_source(self) -> Union[xr.DataArray, np.array]: """ Evaluate quadratic regression for an air-sourced heat pump. - + COP = 6.81 - 0.121 * delta_T + 0.000630 * delta_T^2 - + Returns ------- Union[xr.DataArray, np.array] - The calculated COP values.""" + The calculated COP values. + """ return 6.81 - 0.121 * self.delta_t + 0.000630 * self.delta_t**2 - + def _approximate_cop_ground_source(self) -> Union[xr.DataArray, np.array]: """ Evaluate quadratic regression for a ground-sourced heat pump. - + COP = 8.77 - 0.150 * delta_T + 0.000734 * delta_T^2 - + Returns ------- Union[xr.DataArray, np.array] - The calculated COP values.""" + The calculated COP values. + """ return 8.77 - 0.150 * self.delta_t + 0.000734 * self.delta_t**2 - \ No newline at end of file diff --git a/scripts/build_cop_profiles/run.py b/scripts/build_cop_profiles/run.py index 2568476fc..c25b80a3f 100644 --- a/scripts/build_cop_profiles/run.py +++ b/scripts/build_cop_profiles/run.py @@ -1,10 +1,11 @@ +# -*- coding: utf-8 -*- -import xarray as xr import numpy as np +import xarray as xr +from _helpers import set_scenario_config from CentralHeatingCopApproximator import CentralHeatingCopApproximator from DecentralHeatingCopApproximator import DecentralHeatingCopApproximator -from _helpers import set_scenario_config if __name__ == "__main__": if "snakemake" not in globals(): @@ -19,24 +20,29 @@ set_scenario_config(snakemake) for source_type in ["air", "soil"]: - # source inlet temperature (air/soil) is based on weather data - source_inlet_temperature_celsius = xr.open_dataarray(snakemake.input[f"temp_{source_type}_total"]) + # source inlet temperature (air/soil) is based on weather data + source_inlet_temperature_celsius = xr.open_dataarray( + snakemake.input[f"temp_{source_type}_total"] + ) # Approximate COP for decentral (individual) heating cop_individual_heating = DecentralHeatingCopApproximator( forward_temperature_celsius=snakemake.params.heat_pump_sink_T_decentral_heating, source_inlet_temperature_celsius=source_inlet_temperature_celsius, - source_type=source_type + source_type=source_type, ).approximate_cop() - cop_individual_heating.to_netcdf(snakemake.output[f"cop_{source_type}_decentral_heating"]) + cop_individual_heating.to_netcdf( + snakemake.output[f"cop_{source_type}_decentral_heating"] + ) # Approximate COP for central (district) heating cop_central_heating = CentralHeatingCopApproximator( forward_temperature_celsius=snakemake.params.forward_temperature_central_heating, return_temperature_celsius=snakemake.params.return_temperature_central_heating, source_inlet_temperature_celsius=source_inlet_temperature_celsius, - source_outlet_temperature_celsius=source_inlet_temperature_celsius - snakemake.params.heat_source_cooling_central_heating, + source_outlet_temperature_celsius=source_inlet_temperature_celsius + - snakemake.params.heat_source_cooling_central_heating, ).approximate_cop() - cop_central_heating.to_netcdf(snakemake.output[f"cop_{source_type}_central_heating"]) - - + cop_central_heating.to_netcdf( + snakemake.output[f"cop_{source_type}_central_heating"] + ) From 0c2f9b5daa197c425b1fca4c3df901fb1b407259 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 24 Jul 2024 17:05:04 +0200 Subject: [PATCH 13/58] remove rural/urban temperature --- rules/build_sector.smk | 2 -- 1 file changed, 2 deletions(-) diff --git a/rules/build_sector.smk b/rules/build_sector.smk index a5ecbd6de..790ebc7ce 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -1041,8 +1041,6 @@ rule prepare_sector_network: ), temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), - temp_air_rural=resources("temp_air_rural_elec_s{simpl}_{clusters}.nc"), - temp_air_urban=resources("temp_air_urban_elec_s{simpl}_{clusters}.nc"), cop_soil_decentral_heating=resources( "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" ), From 368971f2a6c9e47d3685f7adc8bcfcc236d2cab7 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 24 Jul 2024 17:19:42 +0200 Subject: [PATCH 14/58] remove cop_total input from prepare_sector_network --- rules/build_sector.smk | 2 -- 1 file changed, 2 deletions(-) diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 790ebc7ce..5f8d58176 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -1053,8 +1053,6 @@ rule prepare_sector_network: cop_soil_central_heating=resources( "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" ), - cop_soil_total=resources("cop_soil_total_elec_s{simpl}_{clusters}.nc"), - cop_air_total=resources("cop_air_total_elec_s{simpl}_{clusters}.nc"), solar_thermal_total=lambda w: ( resources("solar_thermal_total_elec_s{simpl}_{clusters}.nc") if config_provider("sector", "solar_thermal")(w) From b80bb7bb7a05c3024b4b4d123be3cdffe6ffcf4b Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Thu, 25 Jul 2024 14:33:14 +0200 Subject: [PATCH 15/58] update base year COPs --- scripts/add_existing_baseyear.py | 83 ++++++++++++++++++-------------- 1 file changed, 48 insertions(+), 35 deletions(-) diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index d53336756..3d4debea9 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -419,11 +419,11 @@ def add_heating_capacities_installed_before_baseyear( n, baseyear, grouping_years, - ashp_cop, - gshp_cop, - time_dep_hp_cop, + cop: dict, + time_dep_hp_cop: bool, costs, default_lifetime, + existing_heating: pd.DataFrame ): """ Parameters @@ -435,13 +435,13 @@ def add_heating_capacities_installed_before_baseyear( currently assumed heating capacities split between residential and services proportional to heating load in both 50% capacities in rural buses 50% in urban buses + cop: dict + Dictionary with time-dependent coefficients of perforamnce (COPs) for air and ground heat pumps as values and keys "air decentral", "ground decentral", "air central", "ground central" + time_dep_hp_cop: bool + If True, time-dependent (dynamic) COPs are used for heat pumps """ logger.debug(f"Adding heating capacities installed before {baseyear}") - existing_heating = pd.read_csv( - snakemake.input.existing_heating_distribution, header=[0, 1], index_col=0 - ) - for name in existing_heating.columns.get_level_values(0).unique(): name_type = "central" if name == "urban central" else "decentral" @@ -457,12 +457,11 @@ def add_heating_capacities_installed_before_baseyear( # Add heat pumps costs_name = f"decentral {heat_pump_type}-sourced heat pump" - cop = {"air": ashp_cop, "ground": gshp_cop} - - if time_dep_hp_cop: - efficiency = cop[heat_pump_type][nodes] - else: - efficiency = costs.at[costs_name, "efficiency"] + efficiency = ( + cop[f"{heat_pump_type} {name_type}"][nodes] + if options["time_dep_hp_cop"] + else costs.at[costs_name, "efficiency"] + ) too_large_grouping_years = [gy for gy in grouping_years if gy >= int(baseyear)] if too_large_grouping_years: @@ -639,29 +638,43 @@ def add_heating_capacities_installed_before_baseyear( ) if options["heating"]: - time_dep_hp_cop = options["time_dep_hp_cop"] - ashp_cop = ( - xr.open_dataarray(snakemake.input.cop_air_total) - .to_pandas() - .reindex(index=n.snapshots) - ) - gshp_cop = ( - xr.open_dataarray(snakemake.input.cop_soil_total) - .to_pandas() - .reindex(index=n.snapshots) - ) - default_lifetime = snakemake.params.existing_capacities[ - "default_heating_lifetime" - ] + add_heating_capacities_installed_before_baseyear( - n, - baseyear, - grouping_years_heat, - ashp_cop, - gshp_cop, - time_dep_hp_cop, - costs, - default_lifetime, + n=n, + baseyear=baseyear, + grouping_years=grouping_years_heat, + cop={ + "air decentral": xr.open_dataarray( + snakemake.input.cop_air_decentral_heating + ) + .to_pandas() + .reindex(index=n.snapshots), + "ground decentral": xr.open_dataarray( + snakemake.input.cop_soil_decentral_heating + ) + .to_pandas() + .reindex(index=n.snapshots), + "air central": xr.open_dataarray( + snakemake.input.cop_air_central_heating + ) + .to_pandas() + .reindex(index=n.snapshots), + "ground central": xr.open_dataarray( + snakemake.input.cop_soil_central_heating + ) + .to_pandas() + .reindex(index=n.snapshots), + }, + time_dep_hp_cop=options["time_dep_hp_cop"], + costs=costs, + default_lifetime=snakemake.params.existing_capacities[ + "default_heating_lifetime" + ], + existing_heating=pd.read_csv( + snakemake.input.existing_heating_distribution, + header=[0, 1], + index_col=0, + ), ) if options.get("cluster_heat_buses", False): From 744aaf71decd17eb9f5c985103966c0c6afd247f Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 25 Jul 2024 12:33:37 +0000 Subject: [PATCH 16/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- scripts/add_existing_baseyear.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index 3d4debea9..cc82295da 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -423,7 +423,7 @@ def add_heating_capacities_installed_before_baseyear( time_dep_hp_cop: bool, costs, default_lifetime, - existing_heating: pd.DataFrame + existing_heating: pd.DataFrame, ): """ Parameters @@ -458,10 +458,10 @@ def add_heating_capacities_installed_before_baseyear( costs_name = f"decentral {heat_pump_type}-sourced heat pump" efficiency = ( - cop[f"{heat_pump_type} {name_type}"][nodes] - if options["time_dep_hp_cop"] - else costs.at[costs_name, "efficiency"] - ) + cop[f"{heat_pump_type} {name_type}"][nodes] + if options["time_dep_hp_cop"] + else costs.at[costs_name, "efficiency"] + ) too_large_grouping_years = [gy for gy in grouping_years if gy >= int(baseyear)] if too_large_grouping_years: From d297f84ea7e3ff9f19d4a2da627c0d3f25192d34 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Thu, 25 Jul 2024 14:50:27 +0200 Subject: [PATCH 17/58] update inputs for add_existing_baseyear --- rules/solve_myopic.smk | 14 ++++++++++++-- rules/solve_perfect.smk | 14 ++++++++++++-- scripts/add_existing_baseyear.py | 4 ++-- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/rules/solve_myopic.smk b/rules/solve_myopic.smk index 21fb7169b..8d3230ada 100644 --- a/rules/solve_myopic.smk +++ b/rules/solve_myopic.smk @@ -21,8 +21,18 @@ rule add_existing_baseyear: config_provider("scenario", "planning_horizons", 0)(w) ) ), - cop_soil_total=resources("cop_soil_total_elec_s{simpl}_{clusters}.nc"), - cop_air_total=resources("cop_air_total_elec_s{simpl}_{clusters}.nc"), + cop_soil_decentral_heating=resources( + "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_air_decentral_heating=resources( + "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_air_central_heating=resources( + "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_soil_central_heating=resources( + "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" + ), existing_heating_distribution=resources( "existing_heating_distribution_elec_s{simpl}_{clusters}_{planning_horizons}.csv" ), diff --git a/rules/solve_perfect.smk b/rules/solve_perfect.smk index 51cb39207..d2ea1a16a 100644 --- a/rules/solve_perfect.smk +++ b/rules/solve_perfect.smk @@ -19,8 +19,18 @@ rule add_existing_baseyear: config_provider("scenario", "planning_horizons", 0)(w) ) ), - cop_soil_total=resources("cop_soil_total_elec_s{simpl}_{clusters}.nc"), - cop_air_total=resources("cop_air_total_elec_s{simpl}_{clusters}.nc"), + cop_soil_decentral_heating=resources( + "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_air_decentral_heating=resources( + "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_air_central_heating=resources( + "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_soil_central_heating=resources( + "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" + ), existing_heating_distribution=resources( "existing_heating_distribution_elec_s{simpl}_{clusters}_{planning_horizons}.csv" ), diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index cc82295da..9770e6ce5 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -436,7 +436,7 @@ def add_heating_capacities_installed_before_baseyear( services proportional to heating load in both 50% capacities in rural buses 50% in urban buses cop: dict - Dictionary with time-dependent coefficients of perforamnce (COPs) for air and ground heat pumps as values and keys "air decentral", "ground decentral", "air central", "ground central" + Dictionary with time-dependent coefficients of performance (COPs) for air and ground heat pumps as values and keys "air decentral", "ground decentral", "air central", "ground central" time_dep_hp_cop: bool If True, time-dependent (dynamic) COPs are used for heat pumps """ @@ -459,7 +459,7 @@ def add_heating_capacities_installed_before_baseyear( efficiency = ( cop[f"{heat_pump_type} {name_type}"][nodes] - if options["time_dep_hp_cop"] + if time_dep_hp_cop else costs.at[costs_name, "efficiency"] ) From da201e1b9ac49f7987193d066065c84b7c0d1d45 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Thu, 25 Jul 2024 15:08:42 +0200 Subject: [PATCH 18/58] udpate add_brownfield COPs --- rules/solve_myopic.smk | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/rules/solve_myopic.smk b/rules/solve_myopic.smk index 8d3230ada..bf952d4d9 100644 --- a/rules/solve_myopic.smk +++ b/rules/solve_myopic.smk @@ -87,8 +87,18 @@ rule add_brownfield: + "prenetworks/elec_s{simpl}_{clusters}_l{ll}_{opts}_{sector_opts}_{planning_horizons}.nc", network_p=solved_previous_horizon, #solved network at previous time step costs=resources("costs_{planning_horizons}.csv"), - cop_soil_total=resources("cop_soil_total_elec_s{simpl}_{clusters}.nc"), - cop_air_total=resources("cop_air_total_elec_s{simpl}_{clusters}.nc"), + cop_soil_decentral_heating=resources( + "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_air_decentral_heating=resources( + "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_air_central_heating=resources( + "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" + ), + cop_soil_central_heating=resources( + "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" + ), output: RESULTS + "prenetworks-brownfield/elec_s{simpl}_{clusters}_l{ll}_{opts}_{sector_opts}_{planning_horizons}.nc", From 8875ab6c38c4cc90341ec3058f0667ba831b2135 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Thu, 25 Jul 2024 15:10:45 +0200 Subject: [PATCH 19/58] add licensing info --- scripts/build_cop_profiles/BaseCopApproximator.py | 3 +++ scripts/build_cop_profiles/CentralHeatingCopApproximator.py | 4 ++++ scripts/build_cop_profiles/DecentralHeatingCopApproximator.py | 4 ++++ scripts/build_cop_profiles/run.py | 4 +++- 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/scripts/build_cop_profiles/BaseCopApproximator.py b/scripts/build_cop_profiles/BaseCopApproximator.py index 247ff0fea..ad537a74b 100644 --- a/scripts/build_cop_profiles/BaseCopApproximator.py +++ b/scripts/build_cop_profiles/BaseCopApproximator.py @@ -1,4 +1,7 @@ # -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# +# SPDX-License-Identifier: MIT from abc import ABC, abstractmethod from typing import Union diff --git a/scripts/build_cop_profiles/CentralHeatingCopApproximator.py b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py index f2b8d80c1..a29dab592 100644 --- a/scripts/build_cop_profiles/CentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# +# SPDX-License-Identifier: MIT + from typing import Union diff --git a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py index b49be54c0..dfcbdfb34 100644 --- a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py @@ -1,4 +1,8 @@ # -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# +# SPDX-License-Identifier: MIT + from typing import Union diff --git a/scripts/build_cop_profiles/run.py b/scripts/build_cop_profiles/run.py index c25b80a3f..12d012bb3 100644 --- a/scripts/build_cop_profiles/run.py +++ b/scripts/build_cop_profiles/run.py @@ -1,5 +1,7 @@ # -*- coding: utf-8 -*- - +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# +# SPDX-License-Identifier: MIT import numpy as np import xarray as xr From 64d0f291d59d3b7a5a1b1b4f14fdd817ae36c754 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 25 Jul 2024 13:11:05 +0000 Subject: [PATCH 20/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- scripts/build_cop_profiles/DecentralHeatingCopApproximator.py | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py index dfcbdfb34..d8526c396 100644 --- a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py @@ -4,7 +4,6 @@ # SPDX-License-Identifier: MIT - from typing import Union import numpy as np From 3c5b11e4ea583f12eca3d5edfb6c13d28262df68 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Thu, 25 Jul 2024 15:28:31 +0200 Subject: [PATCH 21/58] update release notes --- doc/release_notes.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc/release_notes.rst b/doc/release_notes.rst index fa0473fc3..8b60381b8 100644 --- a/doc/release_notes.rst +++ b/doc/release_notes.rst @@ -10,6 +10,8 @@ Release Notes Upcoming Release ================ +* Changed heat pump COP approximation for central heating to be based on Jensen et al. 2018 and a default forward temperature of 90C. This is more realistic for district heating than the previously used approximation method. + * Changed default assumptions about waste heat usage from PtX and fuel cells in district heating. The default value for the link efficiency scaling factor was changed from 100% to 25%. It can be set to other values in the configuration ``sector: use_TECHNOLOGY_waste_heat``. From 6c14d2072636302a33e7afcc71e20909ca304573 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 29 Jul 2024 10:26:47 +0200 Subject: [PATCH 22/58] checkout sector configtable from master --- doc/configtables/sector.csv | 70 ++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 39 deletions(-) diff --git a/doc/configtables/sector.csv b/doc/configtables/sector.csv index de2873edd..5045cecdc 100644 --- a/doc/configtables/sector.csv +++ b/doc/configtables/sector.csv @@ -5,17 +5,9 @@ biomass,--,"{true, false}",Flag to include biomass sector. industry,--,"{true, false}",Flag to include industry sector. agriculture,--,"{true, false}",Flag to include agriculture sector. district_heating,--,,`prepare_sector_network.py `_ -#NAME?,--,float,maximum fraction of urban demand which can be supplied by district heating. Ignored where below current fraction. -#NAME?,--,Dictionary with planning horizons as keys., Increase of today's district heating demand to potential maximum district heating share. Progress = 0 means today's district heating share. Progress = 1 means maximum fraction of urban demand is supplied by district heating -#NAME?,--,float,Share increase in district heat demand in urban central due to heat losses -#NAME?,°C,float,Forward temperature in district heating -#NAME?,°C,float,Return temperature in district heating. Must be lower than forward temperature -#NAME?,K,float,Cooling of heat source for heat pumps -#NAME?,,, -#NAME?,--,"{ammonia, isobutane}",Heat pump refrigerant assumed for COP approximation -#NAME?,K,float,Heat pump pinch point temperature difference in heat exchangers assumed for approximation. -#NAME?,--,float,Isentropic efficiency of heat pump compressor assumed for approximation. Must be between 0 and 1. -#NAME?,--,float,Heat pump heat loss assumed for approximation. Must be between 0 and 1. +-- potential,--,float,maximum fraction of urban demand which can be supplied by district heating. Ignored where below current fraction. +-- progress,--,Dictionary with planning horizons as keys., Increase of today's district heating demand to potential maximum district heating share. Progress = 0 means today's district heating share. Progress = 1 means maximum fraction of urban demand is supplied by district heating +-- district_heating_loss,--,float,Share increase in district heat demand in urban central due to heat losses cluster_heat_buses,--,"{true, false}",Cluster residential and service heat buses in `prepare_sector_network.py `_ to one to save memory. ,,, bev_dsm_restriction _value,--,float,Adds a lower state of charge (SOC) limit for battery electric vehicles (BEV) to manage its own energy demand (DSM). Located in `build_transport_demand.py `_. Set to 0 for no restriction on BEV DSM @@ -65,21 +57,21 @@ heat_pump_sink_T,°C,float,The temperature heat sink used in heat pumps based on reduce_space_heat _exogenously,--,"{true, false}",Influence on space heating demand by a certain factor (applied before losses in district heating). reduce_space_heat _exogenously_factor,--,Dictionary with planning horizons as keys.,"A positive factor can mean renovation or demolition of a building. If the factor is negative, it can mean an increase in floor area, increased thermal comfort, population growth. The default factors are determined by the `Eurocalc Homes and buildings decarbonization scenario `_" retrofitting,,, -#NAME?,--,"{true, false}",Add retrofitting as an endogenous system which co-optimise space heat savings. -#NAME?,--,float,Weight costs for building renovation -#NAME?,--,float,The interest rate for investment in building components -#NAME?,--,"{true, false}",Annualise the investment costs of retrofitting -#NAME?,--,"{true, false}",Weight the costs of retrofitting depending on taxes in countries -#NAME?,--,"{true, false}",Weight the costs of retrofitting depending on labour/material costs per country +-- retro_endogen,--,"{true, false}",Add retrofitting as an endogenous system which co-optimise space heat savings. +-- cost_factor,--,float,Weight costs for building renovation +-- interest_rate,--,float,The interest rate for investment in building components +-- annualise_cost,--,"{true, false}",Annualise the investment costs of retrofitting +-- tax_weighting,--,"{true, false}",Weight the costs of retrofitting depending on taxes in countries +-- construction_index,--,"{true, false}",Weight the costs of retrofitting depending on labour/material costs per country tes,--,"{true, false}",Add option for storing thermal energy in large water pits associated with district heating systems and individual thermal energy storage (TES) tes_tau,,,The time constant used to calculate the decay of thermal energy in thermal energy storage (TES): 1- :math:`e^{-1/24τ}`. -#NAME?,days,float,The time constant in decentralized thermal energy storage (TES) -#NAME?,days,float,The time constant in centralized thermal energy storage (TES) +-- decentral,days,float,The time constant in decentralized thermal energy storage (TES) +-- central,days,float,The time constant in centralized thermal energy storage (TES) boilers,--,"{true, false}",Add option for transforming gas into heat using gas boilers resistive_heaters,--,"{true, false}",Add option for transforming electricity into heat using resistive heaters (independently from gas boilers) oil_boilers,--,"{true, false}",Add option for transforming oil into heat using boilers biomass_boiler,--,"{true, false}",Add option for transforming biomass into heat using boilers -overdimension_individual_heating,--,float,Add option for overdimensioning individual heating systems by a certain factor. This allows them to cover heat demand peaks e.g. 10% higher than those in the data with a setting of 1.1. +overdimension_individual_heating,--,"float",Add option for overdimensioning individual heating systems by a certain factor. This allows them to cover heat demand peaks e.g. 10% higher than those in the data with a setting of 1.1. chp,--,"{true, false}",Add option for using Combined Heat and Power (CHP) micro_chp,--,"{true, false}",Add option for using Combined Heat and Power (CHP) for decentral areas. solar_thermal,--,"{true, false}",Add option for using solar thermal to generate heat. @@ -97,12 +89,12 @@ SMR CC,--,"{true, false}",Add option for transforming natural gas into hydrogen regional_methanol_demand,--,"{true, false}",Spatially resolve methanol demand. Set to true if regional CO2 constraints needed. regional_oil_demand,--,"{true, false}",Spatially resolve oil demand. Set to true if regional CO2 constraints needed. regional_co2 _sequestration_potential,,, -#NAME?,--,"{true, false}",Add option for regionally-resolved geological carbon dioxide sequestration potentials based on `CO2StoP `_. -#NAME?,--,string or list,Name (or list of names) of the attribute(s) for the sequestration potential -#NAME?,--,"{true, false}",Add options for including onshore sequestration potentials -#NAME?,Gt ,float,Any sites with lower potential than this value will be excluded -#NAME?,Gt ,float,The maximum sequestration potential for any one site. -#NAME?,years,float,The years until potential exhausted at optimised annual rate +-- enable,--,"{true, false}",Add option for regionally-resolved geological carbon dioxide sequestration potentials based on `CO2StoP `_. +-- attribute,--,string or list,Name (or list of names) of the attribute(s) for the sequestration potential +-- include_onshore,--,"{true, false}",Add options for including onshore sequestration potentials +-- min_size,Gt ,float,Any sites with lower potential than this value will be excluded +-- max_size,Gt ,float,The maximum sequestration potential for any one site. +-- years_of_storage,years,float,The years until potential exhausted at optimised annual rate co2_sequestration_potential,MtCO2/a,float,The potential of sequestering CO2 in Europe per year co2_sequestration_cost,currency/tCO2,float,The cost of sequestering a ton of CO2 co2_sequestration_lifetime,years,int,The lifetime of a CO2 sequestration site @@ -129,9 +121,9 @@ electricity_distribution _grid_cost_factor,,,Multiplies the investment cost of t electricity_grid _connection,--,"{true, false}",Add the cost of electricity grid connection for onshore wind and solar transmission_efficiency,,,Section to specify transmission losses or compression energy demands of bidirectional links. Splits them into two capacity-linked unidirectional links. -- {carrier},--,str,The carrier of the link. -#NAME?,p.u.,float,Length-independent transmission efficiency. -#NAME?,p.u. per 1000 km,float,Length-dependent transmission efficiency ($\eta^{\text{length}}$) -#NAME?,p.u. per 1000 km,float,Length-dependent electricity demand for compression ($\eta \cdot \text{length}$) implemented as multi-link to local electricity bus. +-- -- efficiency_static,p.u.,float,Length-independent transmission efficiency. +-- -- efficiency_per_1000km,p.u. per 1000 km,float,Length-dependent transmission efficiency ($\eta^{\text{length}}$) +-- -- compression_per_1000km,p.u. per 1000 km,float,Length-dependent electricity demand for compression ($\eta \cdot \text{length}$) implemented as multi-link to local electricity bus. H2_network,--,"{true, false}",Add option for new hydrogen pipelines gas_network,--,"{true, false}","Add existing natural gas infrastructure, incl. LNG terminals, production and entry-points. The existing gas network is added with a lossless transport model. A length-weighted `k-edge augmentation algorithm `_ can be run to add new candidate gas pipelines such that all regions of the model can be connected to the gas network. When activated, all the gas demands are regionally disaggregated as well." H2_retrofit,--,"{true, false}",Add option for retrofiting existing pipelines to transport hydrogen. @@ -147,17 +139,17 @@ conventional_generation,,,Add a more detailed description of conventional carrie biomass_to_liquid,--,"{true, false}",Add option for transforming solid biomass into liquid fuel with the same properties as oil biosng,--,"{true, false}",Add option for transforming solid biomass into synthesis gas with the same properties as natural gas limit_max_growth,,, -#NAME?,--,"{true, false}",Add option to limit the maximum growth of a carrier -#NAME?,p.u.,float,The maximum growth factor of a carrier (e.g. 1.3 allows 30% larger than max historic growth) -#NAME?,,, +-- enable,--,"{true, false}",Add option to limit the maximum growth of a carrier +-- factor,p.u.,float,The maximum growth factor of a carrier (e.g. 1.3 allows 30% larger than max historic growth) +-- max_growth,,, -- -- {carrier},GW,float,The historic maximum growth of a carrier -#NAME?,,, +-- max_relative_growth,,, -- -- {carrier},p.u.,float,The historic maximum relative growth of a carrier ,,, enhanced_geothermal,,, -#NAME?,--,"{true, false}",Add option to include Enhanced Geothermal Systems -#NAME?,--,"{true, false}",Add option for flexible operation (see Ricks et al. 2024) -#NAME?,--,int,The maximum hours the reservoir can be charged under flexible operation -#NAME?,--,float,The maximum boost in power output under flexible operation -#NAME?,--,"{true, false}",Add option for variable capacity factor (see Ricks et al. 2024) -#NAME?,--,float,Share of sourced heat that is replenished by the earth's core (see details in `build_egs_potentials.py `_) +-- enable,--,"{true, false}",Add option to include Enhanced Geothermal Systems +-- flexible,--,"{true, false}",Add option for flexible operation (see Ricks et al. 2024) +-- max_hours,--,int,The maximum hours the reservoir can be charged under flexible operation +-- max_boost,--,float,The maximum boost in power output under flexible operation +-- var_cf,--,"{true, false}",Add option for variable capacity factor (see Ricks et al. 2024) +-- sustainability_factor,--,float,Share of sourced heat that is replenished by the earth's core (see details in `build_egs_potentials.py `_) From 9183846c6eee1b1df85459eb1189655e4d485faf Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 29 Jul 2024 10:30:23 +0200 Subject: [PATCH 23/58] update sector configtable --- doc/configtables/sector.csv | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/doc/configtables/sector.csv b/doc/configtables/sector.csv index 5045cecdc..17dae5e06 100644 --- a/doc/configtables/sector.csv +++ b/doc/configtables/sector.csv @@ -6,6 +6,14 @@ industry,--,"{true, false}",Flag to include industry sector. agriculture,--,"{true, false}",Flag to include agriculture sector. district_heating,--,,`prepare_sector_network.py `_ -- potential,--,float,maximum fraction of urban demand which can be supplied by district heating. Ignored where below current fraction. +-- forward_temperature,°C,float,Forward temperature in district heating +-- return_temperature,°C,float,Return temperature in district heating. Must be lower than forward temperature +-- heat_source_cooling,K,float,Cooling of heat source for heat pumps +-- heat_pump_cop_approximation,,, +-- refrigerant,--,"{ammonia, isobutane}",Heat pump refrigerant assumed for COP approximation +-- heat_exchanger_pinch_point_temperature_difference,K,float,Heat pump pinch point temperature difference in heat exchangers assumed for approximation. +-- isentropic_compressor_efficiency,--,float,Isentropic efficiency of heat pump compressor assumed for approximation. Must be between 0 and 1. +-- heat_loss,--,float,Heat pump heat loss assumed for approximation. Must be between 0 and 1. -- progress,--,Dictionary with planning horizons as keys., Increase of today's district heating demand to potential maximum district heating share. Progress = 0 means today's district heating share. Progress = 1 means maximum fraction of urban demand is supplied by district heating -- district_heating_loss,--,float,Share increase in district heat demand in urban central due to heat losses cluster_heat_buses,--,"{true, false}",Cluster residential and service heat buses in `prepare_sector_network.py `_ to one to save memory. From 160cb011ccd4a63762d4798585803fd1d440ea5f Mon Sep 17 00:00:00 2001 From: Amos Schledorn <60692940+amosschle@users.noreply.github.com> Date: Mon, 29 Jul 2024 11:30:44 +0200 Subject: [PATCH 24/58] Update doc/configtables/sector.csv Co-authored-by: Fabian Neumann --- doc/configtables/sector.csv | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/configtables/sector.csv b/doc/configtables/sector.csv index 17dae5e06..e14da5573 100644 --- a/doc/configtables/sector.csv +++ b/doc/configtables/sector.csv @@ -10,10 +10,10 @@ district_heating,--,,`prepare_sector_network.py `_ to one to save memory. From 69b01e670fce9b43e2b2b7dd99a3b0bd2d965d2e Mon Sep 17 00:00:00 2001 From: Amos Schledorn <60692940+amosschle@users.noreply.github.com> Date: Mon, 29 Jul 2024 11:33:28 +0200 Subject: [PATCH 25/58] Update config/config.default.yaml Co-authored-by: Fabian Neumann --- config/config.default.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index fbaa965be..5827bffb7 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -408,7 +408,6 @@ sector: 2045: 0.8 2050: 1.0 district_heating_loss: 0.15 - # check these numbers! forward_temperature: 90 #C return_temperature: 50 #C heat_source_cooling: 6 #K From 1d3e39979a79a27ed738d718373074b3506d2ac9 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 29 Jul 2024 11:36:46 +0200 Subject: [PATCH 26/58] remove duplicate staticmethods --- .../build_cop_profiles/BaseCopApproximator.py | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/scripts/build_cop_profiles/BaseCopApproximator.py b/scripts/build_cop_profiles/BaseCopApproximator.py index ad537a74b..891182847 100644 --- a/scripts/build_cop_profiles/BaseCopApproximator.py +++ b/scripts/build_cop_profiles/BaseCopApproximator.py @@ -45,23 +45,6 @@ def approximate_cop(self) -> Union[xr.DataArray, np.array]: """ pass - def celsius_to_kelvin( - t_celsius: Union[float, xr.DataArray, np.array] - ) -> Union[float, xr.DataArray, np.array]: - if (np.asarray(t_celsius) > 200).any(): - raise ValueError( - "t_celsius > 200. Are you sure you are using the right units?" - ) - return t_celsius + 273.15 - - def logarithmic_mean( - t_hot: Union[float, xr.DataArray, np.ndarray], - t_cold: Union[float, xr.DataArray, np.ndarray], - ) -> Union[float, xr.DataArray, np.ndarray]: - if (np.asarray(t_hot <= t_cold)).any(): - raise ValueError("t_hot must be greater than t_cold") - return (t_hot - t_cold) / np.log(t_hot / t_cold) - @staticmethod def celsius_to_kelvin( t_celsius: Union[float, xr.DataArray, np.array] From 9073e49085d08af194aa75a273f77c9ef018425f Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 29 Jul 2024 11:43:53 +0200 Subject: [PATCH 27/58] add link to paper in release notes --- doc/release_notes.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/release_notes.rst b/doc/release_notes.rst index ad204b53d..32eb73344 100644 --- a/doc/release_notes.rst +++ b/doc/release_notes.rst @@ -10,7 +10,7 @@ Release Notes Upcoming Release ================ -* Changed heat pump COP approximation for central heating to be based on Jensen et al. 2018 and a default forward temperature of 90C. This is more realistic for district heating than the previously used approximation method. +* Changed heat pump COP approximation for central heating to be based on `Jensen et al. (2018) `__ and a default forward temperature of 90C. This is more realistic for district heating than the previously used approximation method. * Renamed the carrier of batteries in BEVs from `battery storage` to `EV battery` and the corresponding bus carrier from `Li ion` to `EV battery`. This is to avoid confusion with stationary battery storage. From 0edf566e3fd0bc9f1dbb0cc6db29a94362efa3e3 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 29 Jul 2024 14:36:30 +0200 Subject: [PATCH 28/58] attempt to handle heat_pump_sources dynamically --- config/config.default.yaml | 6 ++++++ rules/build_sector.smk | 28 ++++++++++++++++------------ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index 5827bffb7..f68ff9607 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -416,6 +416,12 @@ sector: heat_exchanger_pinch_point_temperature_difference: 5 #K isentropic_compressor_efficiency: 0.8 heat_loss: 0.0 + heat_pump_sources: + central_heating: + - air + decentral_heating: + - air + - ground cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 5f8d58176..d6f959f3f 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -232,22 +232,26 @@ rule build_cop_profiles: heat_pump_cop_approximation_central_heating=config_provider( "sector", "district_heating", "heat_pump_cop_approximation" ), + heat_pump_sources=config_provider("sector", "heat_pump_sources"), input: temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), output: - cop_air_decentral_heating=resources( - "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_soil_decentral_heating=resources( - "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_air_central_heating=resources( - "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_soil_central_heating=resources( - "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" - ), + **{f"cop_{source}_{sink}": resources( + "cop_" + source + "_" + {sink} + "_" + "elec_s{simpl}_{clusters}.nc" + ) for sink, source in config_provider("sector", "heat_pump_sources").items()}, + # cop_air_decentral_heating=resources( + # "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" + # ), + # cop_soil_decentral_heating=resources( + # "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" + # ), + # cop_air_central_heating=resources( + # "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" + # ), + # cop_soil_central_heating=resources( + # "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" + # ), resources: mem_mb=20000, log: From 51f42b4a36c046534fc50363b77e9d0546d3bbd8 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 29 Jul 2024 12:36:58 +0000 Subject: [PATCH 29/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- config/config.default.yaml | 6 +++--- rules/build_sector.smk | 9 ++++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index f68ff9607..5e204a956 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -418,10 +418,10 @@ sector: heat_loss: 0.0 heat_pump_sources: central_heating: - - air + - air decentral_heating: - - air - - ground + - air + - ground cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 diff --git a/rules/build_sector.smk b/rules/build_sector.smk index d6f959f3f..dbba8805c 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -237,9 +237,12 @@ rule build_cop_profiles: temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), output: - **{f"cop_{source}_{sink}": resources( - "cop_" + source + "_" + {sink} + "_" + "elec_s{simpl}_{clusters}.nc" - ) for sink, source in config_provider("sector", "heat_pump_sources").items()}, + **{ + f"cop_{source}_{sink}": resources( + "cop_" + source + "_" + {sink} + "_" + "elec_s{simpl}_{clusters}.nc" + ) + for sink, source in config_provider("sector", "heat_pump_sources").items() + }, # cop_air_decentral_heating=resources( # "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" # ), From 29479c50d0150bf768d02cca7a242b867b5b564d Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 29 Jul 2024 18:29:27 +0200 Subject: [PATCH 30/58] pass heat source/system type to prepare_sector_network and add_existing_baseyear --- config/config.default.yaml | 4 +- rules/build_sector.smk | 37 ++-- rules/solve_myopic.smk | 14 +- scripts/add_existing_baseyear.py | 72 ++++---- .../DecentralHeatingCopApproximator.py | 8 +- scripts/build_cop_profiles/run.py | 74 +++++--- scripts/prepare_sector_network.py | 163 ++++++++---------- 7 files changed, 176 insertions(+), 196 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index f68ff9607..9f5954010 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -417,9 +417,9 @@ sector: isentropic_compressor_efficiency: 0.8 heat_loss: 0.0 heat_pump_sources: - central_heating: + central: - air - decentral_heating: + decentral: - air - ground cluster_heat_buses: true diff --git a/rules/build_sector.smk b/rules/build_sector.smk index d6f959f3f..9b2bfde65 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -214,6 +214,13 @@ rule build_temperature_profiles: script: "../scripts/build_temperature_profiles.py" +# def output_cop(wildcards): +# return { +# f"cop_{source}_{sink}": resources( +# "cop_" + source + "_" + sink + "_" + "elec_s{simpl}_{clusters}.nc" +# ) +# for sink, source in config["sector"]["heat_pump_sources"].items() +# } rule build_cop_profiles: params: @@ -237,21 +244,7 @@ rule build_cop_profiles: temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), output: - **{f"cop_{source}_{sink}": resources( - "cop_" + source + "_" + {sink} + "_" + "elec_s{simpl}_{clusters}.nc" - ) for sink, source in config_provider("sector", "heat_pump_sources").items()}, - # cop_air_decentral_heating=resources( - # "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" - # ), - # cop_soil_decentral_heating=resources( - # "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" - # ), - # cop_air_central_heating=resources( - # "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" - # ), - # cop_soil_central_heating=resources( - # "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" - # ), + cop_profiles=resources("cop_profiles_elec_s{simpl}_{clusters}.nc"), resources: mem_mb=20000, log: @@ -969,6 +962,7 @@ rule prepare_sector_network: adjustments=config_provider("adjustments", "sector"), emissions_scope=config_provider("energy", "emissions"), RDIR=RDIR, + heat_pump_sources=config_provider("sector", "heat_pump_sources"), input: unpack(input_profile_offwind), **rules.cluster_gas_network.output, @@ -1045,18 +1039,7 @@ rule prepare_sector_network: ), temp_soil_total=resources("temp_soil_total_elec_s{simpl}_{clusters}.nc"), temp_air_total=resources("temp_air_total_elec_s{simpl}_{clusters}.nc"), - cop_soil_decentral_heating=resources( - "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_air_decentral_heating=resources( - "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_air_central_heating=resources( - "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_soil_central_heating=resources( - "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" - ), + cop_profiles=resources("cop_profiles_elec_s{simpl}_{clusters}.nc"), solar_thermal_total=lambda w: ( resources("solar_thermal_total_elec_s{simpl}_{clusters}.nc") if config_provider("sector", "solar_thermal")(w) diff --git a/rules/solve_myopic.smk b/rules/solve_myopic.smk index bf952d4d9..09f25b241 100644 --- a/rules/solve_myopic.smk +++ b/rules/solve_myopic.smk @@ -9,6 +9,7 @@ rule add_existing_baseyear: sector=config_provider("sector"), existing_capacities=config_provider("existing_capacities"), costs=config_provider("costs"), + heat_pump_sources=config_provider("sector", "heat_pump_sources"), input: network=RESULTS + "prenetworks/elec_s{simpl}_{clusters}_l{ll}_{opts}_{sector_opts}_{planning_horizons}.nc", @@ -21,18 +22,7 @@ rule add_existing_baseyear: config_provider("scenario", "planning_horizons", 0)(w) ) ), - cop_soil_decentral_heating=resources( - "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_air_decentral_heating=resources( - "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_air_central_heating=resources( - "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_soil_central_heating=resources( - "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" - ), + cop_profiles=resources("cop_profiles_elec_s{simpl}_{clusters}.nc"), existing_heating_distribution=resources( "existing_heating_distribution_elec_s{simpl}_{clusters}_{planning_horizons}.csv" ), diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index 9770e6ce5..00b5eeb7e 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -442,27 +442,27 @@ def add_heating_capacities_installed_before_baseyear( """ logger.debug(f"Adding heating capacities installed before {baseyear}") - for name in existing_heating.columns.get_level_values(0).unique(): - name_type = "central" if name == "urban central" else "decentral" + for heat_system in existing_heating.columns.get_level_values(0).unique(): + system_type = "central" if heat_system == "urban central" else "decentral" - nodes = pd.Index(n.buses.location[n.buses.index.str.contains(f"{name} heat")]) + nodes = pd.Index(n.buses.location[n.buses.index.str.contains(f"{heat_system} heat")]) - if (name_type != "central") and options["electricity_distribution_grid"]: + if (system_type != "central") and options["electricity_distribution_grid"]: nodes_elec = nodes + " low voltage" else: nodes_elec = nodes - heat_pump_type = "air" if "urban" in name else "ground" - # Add heat pumps - costs_name = f"decentral {heat_pump_type}-sourced heat pump" + heat_source = snakemake.params.heat_pump_sources[system_type] + costs_name = f"{system_type} {heat_source}-sourced heat pump" efficiency = ( - cop[f"{heat_pump_type} {name_type}"][nodes] - if time_dep_hp_cop + cop.sel(heat_system=system_type, heat_source=heat_source, name=nodes).to_pandas().reindex(index=n.snapshots) + if options["time_dep_hp_cop"] else costs.at[costs_name, "efficiency"] ) + too_large_grouping_years = [gy for gy in grouping_years if gy >= int(baseyear)] if too_large_grouping_years: logger.warning( @@ -491,14 +491,14 @@ def add_heating_capacities_installed_before_baseyear( n.madd( "Link", nodes, - suffix=f" {name} {heat_pump_type} heat pump-{grouping_year}", + suffix=f" {heat_system} {heat_source} heat pump-{grouping_year}", bus0=nodes_elec, - bus1=nodes + " " + name + " heat", - carrier=f"{name} {heat_pump_type} heat pump", + bus1=nodes + " " + heat_system + " heat", + carrier=f"{heat_system} {heat_source} heat pump", efficiency=efficiency, capital_cost=costs.at[costs_name, "efficiency"] * costs.at[costs_name, "fixed"], - p_nom=existing_heating.loc[nodes, (name, f"{heat_pump_type} heat pump")] + p_nom=existing_heating.loc[nodes, (heat_system, f"{heat_source} heat pump")] * ratio / costs.at[costs_name, "efficiency"], build_year=int(grouping_year), @@ -509,66 +509,66 @@ def add_heating_capacities_installed_before_baseyear( n.madd( "Link", nodes, - suffix=f" {name} resistive heater-{grouping_year}", + suffix=f" {heat_system} resistive heater-{grouping_year}", bus0=nodes_elec, - bus1=nodes + " " + name + " heat", - carrier=name + " resistive heater", - efficiency=costs.at[f"{name_type} resistive heater", "efficiency"], + bus1=nodes + " " + heat_system + " heat", + carrier=heat_system + " resistive heater", + efficiency=costs.at[f"{system_type} resistive heater", "efficiency"], capital_cost=( - costs.at[f"{name_type} resistive heater", "efficiency"] - * costs.at[f"{name_type} resistive heater", "fixed"] + costs.at[f"{system_type} resistive heater", "efficiency"] + * costs.at[f"{system_type} resistive heater", "fixed"] ), p_nom=( - existing_heating.loc[nodes, (name, "resistive heater")] + existing_heating.loc[nodes, (heat_system, "resistive heater")] * ratio - / costs.at[f"{name_type} resistive heater", "efficiency"] + / costs.at[f"{system_type} resistive heater", "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{name_type} resistive heater", "lifetime"], + lifetime=costs.at[f"{system_type} resistive heater", "lifetime"], ) n.madd( "Link", nodes, - suffix=f" {name} gas boiler-{grouping_year}", + suffix=f" {heat_system} gas boiler-{grouping_year}", bus0="EU gas" if "EU gas" in spatial.gas.nodes else nodes + " gas", - bus1=nodes + " " + name + " heat", + bus1=nodes + " " + heat_system + " heat", bus2="co2 atmosphere", - carrier=name + " gas boiler", - efficiency=costs.at[f"{name_type} gas boiler", "efficiency"], + carrier=heat_system + " gas boiler", + efficiency=costs.at[f"{system_type} gas boiler", "efficiency"], efficiency2=costs.at["gas", "CO2 intensity"], capital_cost=( - costs.at[f"{name_type} gas boiler", "efficiency"] - * costs.at[f"{name_type} gas boiler", "fixed"] + costs.at[f"{system_type} gas boiler", "efficiency"] + * costs.at[f"{system_type} gas boiler", "fixed"] ), p_nom=( - existing_heating.loc[nodes, (name, "gas boiler")] + existing_heating.loc[nodes, (heat_system, "gas boiler")] * ratio - / costs.at[f"{name_type} gas boiler", "efficiency"] + / costs.at[f"{system_type} gas boiler", "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{name_type} gas boiler", "lifetime"], + lifetime=costs.at[f"{system_type} gas boiler", "lifetime"], ) n.madd( "Link", nodes, - suffix=f" {name} oil boiler-{grouping_year}", + suffix=f" {heat_system} oil boiler-{grouping_year}", bus0=spatial.oil.nodes, - bus1=nodes + " " + name + " heat", + bus1=nodes + " " + heat_system + " heat", bus2="co2 atmosphere", - carrier=name + " oil boiler", + carrier=heat_system + " oil boiler", efficiency=costs.at["decentral oil boiler", "efficiency"], efficiency2=costs.at["oil", "CO2 intensity"], capital_cost=costs.at["decentral oil boiler", "efficiency"] * costs.at["decentral oil boiler", "fixed"], p_nom=( - existing_heating.loc[nodes, (name, "oil boiler")] + existing_heating.loc[nodes, (heat_system, "oil boiler")] * ratio / costs.at["decentral oil boiler", "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{name_type} gas boiler", "lifetime"], + lifetime=costs.at[f"{system_type} gas boiler", "lifetime"], ) # delete links with p_nom=nan corresponding to extra nodes in country diff --git a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py index d8526c396..11be7407f 100644 --- a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py @@ -39,12 +39,12 @@ def __init__( return_temperature_celsius : Union[xr.DataArray, np.array] The return temperature in Celsius. source: str - The source of the heat pump. Must be either 'air' or 'soil' + The source of the heat pump. Must be either 'air' or 'ground' """ self.delta_t = forward_temperature_celsius - source_inlet_temperature_celsius - if source_type not in ["air", "soil"]: - raise ValueError("'source' must be one of ['air', 'soil']") + if source_type not in ["air", "ground"]: + raise ValueError("'source' must be one of ['air', 'ground']") else: self.source_type = source_type @@ -57,7 +57,7 @@ def approximate_cop(self) -> Union[xr.DataArray, np.array]: """ if self.source_type == "air": return self._approximate_cop_air_source() - elif self.source_type == "soil": + elif self.source_type == "ground": return self._approximate_cop_ground_source() def _approximate_cop_air_source(self) -> Union[xr.DataArray, np.array]: diff --git a/scripts/build_cop_profiles/run.py b/scripts/build_cop_profiles/run.py index 12d012bb3..5178483a8 100644 --- a/scripts/build_cop_profiles/run.py +++ b/scripts/build_cop_profiles/run.py @@ -4,11 +4,39 @@ # SPDX-License-Identifier: MIT import numpy as np +import pandas as pd import xarray as xr from _helpers import set_scenario_config from CentralHeatingCopApproximator import CentralHeatingCopApproximator from DecentralHeatingCopApproximator import DecentralHeatingCopApproximator + +def get_cop( + heat_system_type: str, + heat_source: str, + source_inlet_temperature_celsius: xr.DataArray, +) -> xr.DataArray: + if heat_system_type == "decentral": + return DecentralHeatingCopApproximator( + forward_temperature_celsius=snakemake.params.heat_pump_sink_T_decentral_heating, + source_inlet_temperature_celsius=source_inlet_temperature_celsius, + source_type=heat_source, + ).approximate_cop() + + elif heat_system_type == "central": + return CentralHeatingCopApproximator( + forward_temperature_celsius=snakemake.params.forward_temperature_central_heating, + return_temperature_celsius=snakemake.params.return_temperature_central_heating, + source_inlet_temperature_celsius=source_inlet_temperature_celsius, + source_outlet_temperature_celsius=source_inlet_temperature_celsius + - snakemake.params.heat_source_cooling_central_heating, + ).approximate_cop() + else: + raise ValueError( + f"Invalid heat system type '{heat_system_type}'. Must be one of ['decentral', 'central']" + ) + + if __name__ == "__main__": if "snakemake" not in globals(): from _helpers import mock_snakemake @@ -21,30 +49,28 @@ set_scenario_config(snakemake) - for source_type in ["air", "soil"]: - # source inlet temperature (air/soil) is based on weather data - source_inlet_temperature_celsius = xr.open_dataarray( - snakemake.input[f"temp_{source_type}_total"] + cop_all_system_types = [] + for heat_system_type, heat_sources in snakemake.params.heat_pump_sources.items(): + cop_this_system_type = [] + for heat_source in heat_sources: + source_inlet_temperature_celsius = xr.open_dataarray( + snakemake.input[f"temp_{heat_source.replace('ground', 'soil')}_total"] + ) + cop_da = get_cop( + heat_system_type=heat_system_type, + heat_source=heat_source, + source_inlet_temperature_celsius=source_inlet_temperature_celsius, + ) + cop_this_system_type.append(cop_da) + cop_all_system_types.append( + xr.concat( + cop_this_system_type, dim=pd.Index(heat_sources, name="heat_source") + ) ) - # Approximate COP for decentral (individual) heating - cop_individual_heating = DecentralHeatingCopApproximator( - forward_temperature_celsius=snakemake.params.heat_pump_sink_T_decentral_heating, - source_inlet_temperature_celsius=source_inlet_temperature_celsius, - source_type=source_type, - ).approximate_cop() - cop_individual_heating.to_netcdf( - snakemake.output[f"cop_{source_type}_decentral_heating"] - ) + cop_dataarray = xr.concat( + cop_all_system_types, + dim=pd.Index(snakemake.params.heat_pump_sources.keys(), name="heat_system"), + ) - # Approximate COP for central (district) heating - cop_central_heating = CentralHeatingCopApproximator( - forward_temperature_celsius=snakemake.params.forward_temperature_central_heating, - return_temperature_celsius=snakemake.params.return_temperature_central_heating, - source_inlet_temperature_celsius=source_inlet_temperature_celsius, - source_outlet_temperature_celsius=source_inlet_temperature_celsius - - snakemake.params.heat_source_cooling_central_heating, - ).approximate_cop() - cop_central_heating.to_netcdf( - snakemake.output[f"cop_{source_type}_central_heating"] - ) + cop_dataarray.to_netcdf(snakemake.output.cop_profiles) diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index d5b892adf..e59984d3b 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1825,23 +1825,6 @@ def add_heat(n, costs): "urban central", ] - cop = { - "air decentral": xr.open_dataarray(snakemake.input.cop_air_decentral_heating) - .to_pandas() - .reindex(index=n.snapshots), - "ground decentral": xr.open_dataarray( - snakemake.input.cop_soil_decentral_heating - ) - .to_pandas() - .reindex(index=n.snapshots), - "air central": xr.open_dataarray(snakemake.input.cop_air_central_heating) - .to_pandas() - .reindex(index=n.snapshots), - "ground central": xr.open_dataarray(snakemake.input.cop_soil_central_heating) - .to_pandas() - .reindex(index=n.snapshots), - } - if options["solar_thermal"]: solar_thermal = ( xr.open_dataarray(snakemake.input.solar_thermal_total) @@ -1851,31 +1834,32 @@ def add_heat(n, costs): # 1e3 converts from W/m^2 to MW/(1000m^2) = kW/m^2 solar_thermal = options["solar_cf_correction"] * solar_thermal / 1e3 - for name in heat_systems: - name_type = "central" if name == "urban central" else "decentral" + cop = xr.open_dataarray(snakemake.input.cop_profiles) + for heat_system in heat_systems: + system_type = "central" if heat_system == "urban central" else "decentral" - if name == "urban central": + if heat_system == "urban central": nodes = dist_fraction.index[dist_fraction > 0] else: nodes = pop_layout.index - n.add("Carrier", name + " heat") + n.add("Carrier", heat_system + " heat") n.madd( "Bus", - nodes + f" {name} heat", + nodes + f" {heat_system} heat", location=nodes, - carrier=name + " heat", + carrier=heat_system + " heat", unit="MWh_th", ) - if name == "urban central" and options.get("central_heat_vent"): + if heat_system == "urban central" and options.get("central_heat_vent"): n.madd( "Generator", - nodes + f" {name} heat vent", - bus=nodes + f" {name} heat", + nodes + f" {heat_system} heat vent", + bus=nodes + f" {heat_system} heat", location=nodes, - carrier=name + " heat vent", + carrier=heat_system + " heat vent", p_nom_extendable=True, p_max_pu=0, p_min_pu=-1, @@ -1886,18 +1870,18 @@ def add_heat(n, costs): for sector in sectors: # heat demand weighting - if "rural" in name: + if "rural" in heat_system: factor = 1 - urban_fraction[nodes] - elif "urban central" in name: + elif "urban central" in heat_system: factor = dist_fraction[nodes] - elif "urban decentral" in name: + elif "urban decentral" in heat_system: factor = urban_fraction[nodes] - dist_fraction[nodes] else: raise NotImplementedError( - f" {name} not in " f"heat systems: {heat_systems}" + f" {heat_system} not in " f"heat systems: {heat_systems}" ) - if sector in name: + if sector in heat_system: heat_load = ( heat_demand[[sector + " water", sector + " space"]] .T.groupby(level=1) @@ -1906,7 +1890,7 @@ def add_heat(n, costs): .multiply(factor) ) - if name == "urban central": + if heat_system == "urban central": heat_load = ( heat_demand.T.groupby(level=1) .sum() @@ -1919,20 +1903,17 @@ def add_heat(n, costs): n.madd( "Load", nodes, - suffix=f" {name} heat", - bus=nodes + f" {name} heat", - carrier=name + " heat", + suffix=f" {heat_system} heat", + bus=nodes + f" {heat_system} heat", + carrier=heat_system + " heat", p_set=heat_load, ) ## Add heat pumps - - heat_pump_types = ["air"] if "urban" in name else ["ground", "air"] - - for heat_pump_type in heat_pump_types: - costs_name = f"{name_type} {heat_pump_type}-sourced heat pump" + for heat_source in snakemake.params.heat_pump_sources[system_type]: + costs_name = f"{system_type} {heat_source}-sourced heat pump" efficiency = ( - cop[f"{heat_pump_type} {name_type}"][nodes] + cop.sel(heat_system=system_type, heat_source=heat_source, name=nodes).to_pandas().reindex(index=n.snapshots) if options["time_dep_hp_cop"] else costs.at[costs_name, "efficiency"] ) @@ -1940,10 +1921,10 @@ def add_heat(n, costs): n.madd( "Link", nodes, - suffix=f" {name} {heat_pump_type} heat pump", + suffix=f" {heat_system} {heat_source} heat pump", bus0=nodes, - bus1=nodes + f" {name} heat", - carrier=f"{name} {heat_pump_type} heat pump", + bus1=nodes + f" {heat_system} heat", + carrier=f"{heat_system} {heat_source} heat pump", efficiency=efficiency, capital_cost=costs.at[costs_name, "efficiency"] * costs.at[costs_name, "fixed"] @@ -1953,59 +1934,59 @@ def add_heat(n, costs): ) if options["tes"]: - n.add("Carrier", name + " water tanks") + n.add("Carrier", heat_system + " water tanks") n.madd( "Bus", - nodes + f" {name} water tanks", + nodes + f" {heat_system} water tanks", location=nodes, - carrier=name + " water tanks", + carrier=heat_system + " water tanks", unit="MWh_th", ) n.madd( "Link", - nodes + f" {name} water tanks charger", - bus0=nodes + f" {name} heat", - bus1=nodes + f" {name} water tanks", + nodes + f" {heat_system} water tanks charger", + bus0=nodes + f" {heat_system} heat", + bus1=nodes + f" {heat_system} water tanks", efficiency=costs.at["water tank charger", "efficiency"], - carrier=name + " water tanks charger", + carrier=heat_system + " water tanks charger", p_nom_extendable=True, ) n.madd( "Link", - nodes + f" {name} water tanks discharger", - bus0=nodes + f" {name} water tanks", - bus1=nodes + f" {name} heat", - carrier=name + " water tanks discharger", + nodes + f" {heat_system} water tanks discharger", + bus0=nodes + f" {heat_system} water tanks", + bus1=nodes + f" {heat_system} heat", + carrier=heat_system + " water tanks discharger", efficiency=costs.at["water tank discharger", "efficiency"], p_nom_extendable=True, ) - tes_time_constant_days = options["tes_tau"][name_type] + tes_time_constant_days = options["tes_tau"][system_type] n.madd( "Store", - nodes + f" {name} water tanks", - bus=nodes + f" {name} water tanks", + nodes + f" {heat_system} water tanks", + bus=nodes + f" {heat_system} water tanks", e_cyclic=True, e_nom_extendable=True, - carrier=name + " water tanks", + carrier=heat_system + " water tanks", standing_loss=1 - np.exp(-1 / 24 / tes_time_constant_days), - capital_cost=costs.at[name_type + " water tank storage", "fixed"], - lifetime=costs.at[name_type + " water tank storage", "lifetime"], + capital_cost=costs.at[system_type + " water tank storage", "fixed"], + lifetime=costs.at[system_type + " water tank storage", "lifetime"], ) if options["resistive_heaters"]: - key = f"{name_type} resistive heater" + key = f"{system_type} resistive heater" n.madd( "Link", - nodes + f" {name} resistive heater", + nodes + f" {heat_system} resistive heater", bus0=nodes, - bus1=nodes + f" {name} heat", - carrier=name + " resistive heater", + bus1=nodes + f" {heat_system} heat", + carrier=heat_system + " resistive heater", efficiency=costs.at[key, "efficiency"], capital_cost=costs.at[key, "efficiency"] * costs.at[key, "fixed"] @@ -2015,16 +1996,16 @@ def add_heat(n, costs): ) if options["boilers"]: - key = f"{name_type} gas boiler" + key = f"{system_type} gas boiler" n.madd( "Link", - nodes + f" {name} gas boiler", + nodes + f" {heat_system} gas boiler", p_nom_extendable=True, bus0=spatial.gas.df.loc[nodes, "nodes"].values, - bus1=nodes + f" {name} heat", + bus1=nodes + f" {heat_system} heat", bus2="co2 atmosphere", - carrier=name + " gas boiler", + carrier=heat_system + " gas boiler", efficiency=costs.at[key, "efficiency"], efficiency2=costs.at["gas", "CO2 intensity"], capital_cost=costs.at[key, "efficiency"] @@ -2034,22 +2015,22 @@ def add_heat(n, costs): ) if options["solar_thermal"]: - n.add("Carrier", name + " solar thermal") + n.add("Carrier", heat_system + " solar thermal") n.madd( "Generator", nodes, - suffix=f" {name} solar thermal collector", - bus=nodes + f" {name} heat", - carrier=name + " solar thermal", + suffix=f" {heat_system} solar thermal collector", + bus=nodes + f" {heat_system} heat", + carrier=heat_system + " solar thermal", p_nom_extendable=True, - capital_cost=costs.at[name_type + " solar thermal", "fixed"] + capital_cost=costs.at[system_type + " solar thermal", "fixed"] * overdim_factor, p_max_pu=solar_thermal[nodes], - lifetime=costs.at[name_type + " solar thermal", "lifetime"], + lifetime=costs.at[system_type + " solar thermal", "lifetime"], ) - if options["chp"] and name == "urban central": + if options["chp"] and heat_system == "urban central": # add gas CHP; biomass CHP is added in biomass section n.madd( "Link", @@ -2106,16 +2087,16 @@ def add_heat(n, costs): lifetime=costs.at["central gas CHP", "lifetime"], ) - if options["chp"] and options["micro_chp"] and name != "urban central": + if options["chp"] and options["micro_chp"] and heat_system != "urban central": n.madd( "Link", - nodes + f" {name} micro gas CHP", + nodes + f" {heat_system} micro gas CHP", p_nom_extendable=True, bus0=spatial.gas.df.loc[nodes, "nodes"].values, bus1=nodes, - bus2=nodes + f" {name} heat", + bus2=nodes + f" {heat_system} heat", bus3="co2 atmosphere", - carrier=name + " micro gas CHP", + carrier=heat_system + " micro gas CHP", efficiency=costs.at["micro CHP", "efficiency"], efficiency2=costs.at["micro CHP", "efficiency-heat"], efficiency3=costs.at["gas", "CO2 intensity"], @@ -2150,27 +2131,27 @@ def add_heat(n, costs): heat_demand["services space"] + heat_demand["residential space"] ) / heat_demand.T.groupby(level=[1]).sum().T - for name in n.loads[ + for heat_system in n.loads[ n.loads.carrier.isin([x + " heat" for x in heat_systems]) ].index: - node = n.buses.loc[name, "location"] + node = n.buses.loc[heat_system, "location"] ct = pop_layout.loc[node, "ct"] # weighting 'f' depending on the size of the population at the node - if "urban central" in name: + if "urban central" in heat_system: f = dist_fraction[node] - elif "urban decentral" in name: + elif "urban decentral" in heat_system: f = urban_fraction[node] - dist_fraction[node] else: f = 1 - urban_fraction[node] if f == 0: continue # get sector name ("residential"/"services"/or both "tot" for urban central) - if "urban central" in name: + if "urban central" in heat_system: sec = "tot" - if "residential" in name: + if "residential" in heat_system: sec = "residential" - if "services" in name: + if "services" in heat_system: sec = "services" # get floor aread at node and region (urban/rural) in m^2 @@ -2178,7 +2159,7 @@ def add_heat(n, costs): pop_layout.loc[node].fraction * floor_area.loc[ct, "value"] * 10**6 ).loc[sec] * f # total heat demand at node [MWh] - demand = n.loads_t.p_set[name] + demand = n.loads_t.p_set[heat_system] # space heat demand at node [MWh] space_heat_demand = demand * w_space[sec][node] @@ -2219,12 +2200,12 @@ def add_heat(n, costs): # add for each retrofitting strength a generator with heat generation profile following the profile of the heat demand for strength in strengths: - node_name = " ".join(name.split(" ")[2::]) + node_name = " ".join(heat_system.split(" ")[2::]) n.madd( "Generator", [node], suffix=" retrofitting " + strength + " " + node_name, - bus=name, + bus=heat_system, carrier="retrofitting", p_nom_extendable=True, p_nom_max=dE_diff[strength] From 1fe54513cd8f33961263d21a693dd4f8cf0c595f Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 29 Jul 2024 16:33:49 +0000 Subject: [PATCH 31/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- config/config.default.yaml | 6 +++--- rules/build_sector.smk | 2 ++ scripts/add_existing_baseyear.py | 13 +++++++++---- scripts/prepare_sector_network.py | 4 +++- 4 files changed, 17 insertions(+), 8 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index 9f5954010..794b2baea 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -418,10 +418,10 @@ sector: heat_loss: 0.0 heat_pump_sources: central: - - air + - air decentral: - - air - - ground + - air + - ground cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 9b2bfde65..b7d916ea4 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -214,6 +214,7 @@ rule build_temperature_profiles: script: "../scripts/build_temperature_profiles.py" + # def output_cop(wildcards): # return { # f"cop_{source}_{sink}": resources( @@ -222,6 +223,7 @@ rule build_temperature_profiles: # for sink, source in config["sector"]["heat_pump_sources"].items() # } + rule build_cop_profiles: params: heat_pump_sink_T_decentral_heating=config_provider( diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index 00b5eeb7e..610523e99 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -445,7 +445,9 @@ def add_heating_capacities_installed_before_baseyear( for heat_system in existing_heating.columns.get_level_values(0).unique(): system_type = "central" if heat_system == "urban central" else "decentral" - nodes = pd.Index(n.buses.location[n.buses.index.str.contains(f"{heat_system} heat")]) + nodes = pd.Index( + n.buses.location[n.buses.index.str.contains(f"{heat_system} heat")] + ) if (system_type != "central") and options["electricity_distribution_grid"]: nodes_elec = nodes + " low voltage" @@ -457,12 +459,13 @@ def add_heating_capacities_installed_before_baseyear( costs_name = f"{system_type} {heat_source}-sourced heat pump" efficiency = ( - cop.sel(heat_system=system_type, heat_source=heat_source, name=nodes).to_pandas().reindex(index=n.snapshots) + cop.sel(heat_system=system_type, heat_source=heat_source, name=nodes) + .to_pandas() + .reindex(index=n.snapshots) if options["time_dep_hp_cop"] else costs.at[costs_name, "efficiency"] ) - too_large_grouping_years = [gy for gy in grouping_years if gy >= int(baseyear)] if too_large_grouping_years: logger.warning( @@ -498,7 +501,9 @@ def add_heating_capacities_installed_before_baseyear( efficiency=efficiency, capital_cost=costs.at[costs_name, "efficiency"] * costs.at[costs_name, "fixed"], - p_nom=existing_heating.loc[nodes, (heat_system, f"{heat_source} heat pump")] + p_nom=existing_heating.loc[ + nodes, (heat_system, f"{heat_source} heat pump") + ] * ratio / costs.at[costs_name, "efficiency"], build_year=int(grouping_year), diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index e59984d3b..f71dd5f58 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1913,7 +1913,9 @@ def add_heat(n, costs): for heat_source in snakemake.params.heat_pump_sources[system_type]: costs_name = f"{system_type} {heat_source}-sourced heat pump" efficiency = ( - cop.sel(heat_system=system_type, heat_source=heat_source, name=nodes).to_pandas().reindex(index=n.snapshots) + cop.sel(heat_system=system_type, heat_source=heat_source, name=nodes) + .to_pandas() + .reindex(index=n.snapshots) if options["time_dep_hp_cop"] else costs.at[costs_name, "efficiency"] ) From 5e73dae3a7b5a5d39c36d47f6f7220b417f2ca46 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Tue, 30 Jul 2024 18:21:10 +0200 Subject: [PATCH 32/58] add heat_pump_sources to config and docs --- config/config.default.yaml | 6 +++--- doc/configtables/sector.csv | 10 +++++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index 794b2baea..9f5954010 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -418,10 +418,10 @@ sector: heat_loss: 0.0 heat_pump_sources: central: - - air + - air decentral: - - air - - ground + - air + - ground cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 diff --git a/doc/configtables/sector.csv b/doc/configtables/sector.csv index e14da5573..17435a28b 100644 --- a/doc/configtables/sector.csv +++ b/doc/configtables/sector.csv @@ -6,6 +6,9 @@ industry,--,"{true, false}",Flag to include industry sector. agriculture,--,"{true, false}",Flag to include agriculture sector. district_heating,--,,`prepare_sector_network.py `_ -- potential,--,float,maximum fraction of urban demand which can be supplied by district heating. Ignored where below current fraction. +-- progress,--,Dictionary with planning horizons as keys., Increase of today's district heating demand to potential maximum district heating share. Progress = 0 means today's district heating share. Progress = 1 means maximum fraction of urban demand is supplied by district heating +-- district_heating_loss,--,float,Share increase in district heat demand in urban central due to heat losses +cluster_heat_buses,--,"{true, false}",Cluster residential and service heat buses in `prepare_sector_network.py `_ to one to save memory. -- forward_temperature,°C,float,Forward temperature in district heating -- return_temperature,°C,float,Return temperature in district heating. Must be lower than forward temperature -- heat_source_cooling,K,float,Cooling of heat source for heat pumps @@ -14,9 +17,10 @@ district_heating,--,,`prepare_sector_network.py `_ to one to save memory. +-- heat_pump_sources,,, +-- -- central,--,"Any subset of {ground, air}", Heat pump sources for central heating heat pumps +-- -- decentral,--,"Any subset of {ground, air}", Heat pump sources for decentral heating heat pumps + ,,, bev_dsm_restriction _value,--,float,Adds a lower state of charge (SOC) limit for battery electric vehicles (BEV) to manage its own energy demand (DSM). Located in `build_transport_demand.py `_. Set to 0 for no restriction on BEV DSM bev_dsm_restriction _time,--,float,Time at which SOC of BEV has to be dsm_restriction_value From a2c0311ae7c6ece7003a4cdeeeb3566fbfa856dc Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 30 Jul 2024 16:23:58 +0000 Subject: [PATCH 33/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- config/config.default.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index 9f5954010..794b2baea 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -418,10 +418,10 @@ sector: heat_loss: 0.0 heat_pump_sources: central: - - air + - air decentral: - - air - - ground + - air + - ground cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 From 4362300dced326c92523aeb5581d798c720aeb76 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 31 Jul 2024 16:54:46 +0200 Subject: [PATCH 34/58] update configtables and docs --- config/config.default.yaml | 6 +++--- doc/configtables/sector.csv | 10 +++------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index 794b2baea..9f5954010 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -418,10 +418,10 @@ sector: heat_loss: 0.0 heat_pump_sources: central: - - air + - air decentral: - - air - - ground + - air + - ground cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 diff --git a/doc/configtables/sector.csv b/doc/configtables/sector.csv index 17435a28b..e14da5573 100644 --- a/doc/configtables/sector.csv +++ b/doc/configtables/sector.csv @@ -6,9 +6,6 @@ industry,--,"{true, false}",Flag to include industry sector. agriculture,--,"{true, false}",Flag to include agriculture sector. district_heating,--,,`prepare_sector_network.py `_ -- potential,--,float,maximum fraction of urban demand which can be supplied by district heating. Ignored where below current fraction. --- progress,--,Dictionary with planning horizons as keys., Increase of today's district heating demand to potential maximum district heating share. Progress = 0 means today's district heating share. Progress = 1 means maximum fraction of urban demand is supplied by district heating --- district_heating_loss,--,float,Share increase in district heat demand in urban central due to heat losses -cluster_heat_buses,--,"{true, false}",Cluster residential and service heat buses in `prepare_sector_network.py `_ to one to save memory. -- forward_temperature,°C,float,Forward temperature in district heating -- return_temperature,°C,float,Return temperature in district heating. Must be lower than forward temperature -- heat_source_cooling,K,float,Cooling of heat source for heat pumps @@ -17,10 +14,9 @@ cluster_heat_buses,--,"{true, false}",Cluster residential and service heat buses -- -- heat_exchanger_pinch_point_temperature_difference,K,float,Heat pump pinch point temperature difference in heat exchangers assumed for approximation. -- -- isentropic_compressor_efficiency,--,float,Isentropic efficiency of heat pump compressor assumed for approximation. Must be between 0 and 1. -- -- heat_loss,--,float,Heat pump heat loss assumed for approximation. Must be between 0 and 1. --- heat_pump_sources,,, --- -- central,--,"Any subset of {ground, air}", Heat pump sources for central heating heat pumps --- -- decentral,--,"Any subset of {ground, air}", Heat pump sources for decentral heating heat pumps - +-- progress,--,Dictionary with planning horizons as keys., Increase of today's district heating demand to potential maximum district heating share. Progress = 0 means today's district heating share. Progress = 1 means maximum fraction of urban demand is supplied by district heating +-- district_heating_loss,--,float,Share increase in district heat demand in urban central due to heat losses +cluster_heat_buses,--,"{true, false}",Cluster residential and service heat buses in `prepare_sector_network.py `_ to one to save memory. ,,, bev_dsm_restriction _value,--,float,Adds a lower state of charge (SOC) limit for battery electric vehicles (BEV) to manage its own energy demand (DSM). Located in `build_transport_demand.py `_. Set to 0 for no restriction on BEV DSM bev_dsm_restriction _time,--,float,Time at which SOC of BEV has to be dsm_restriction_value From 4cfca27e4f623b4c8bf69793c9ecb4c0a81a02ec Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 31 Jul 2024 14:55:09 +0000 Subject: [PATCH 35/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- config/config.default.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index 9f5954010..794b2baea 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -418,10 +418,10 @@ sector: heat_loss: 0.0 heat_pump_sources: central: - - air + - air decentral: - - air - - ground + - air + - ground cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 From caa260fddb51ef6619c990e379d0ea3de2bd9406 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 31 Jul 2024 17:01:27 +0200 Subject: [PATCH 36/58] update class docs --- .../build_cop_profiles/BaseCopApproximator.py | 50 ++++++++++++- .../CentralHeatingCopApproximator.py | 73 ++++++++++++++++++- .../DecentralHeatingCopApproximator.py | 44 ++++++++--- 3 files changed, 153 insertions(+), 14 deletions(-) diff --git a/scripts/build_cop_profiles/BaseCopApproximator.py b/scripts/build_cop_profiles/BaseCopApproximator.py index 891182847..10019b3d3 100644 --- a/scripts/build_cop_profiles/BaseCopApproximator.py +++ b/scripts/build_cop_profiles/BaseCopApproximator.py @@ -14,6 +14,24 @@ class BaseCopApproximator(ABC): """ Abstract class for approximating the coefficient of performance (COP) of a heat pump. + + Attributes: + ---------- + forward_temperature_celsius : Union[xr.DataArray, np.array] + The forward temperature in Celsius. + source_inlet_temperature_celsius : Union[xr.DataArray, np.array] + The source inlet temperature in Celsius. + + Methods: + ------- + __init__(self, forward_temperature_celsius, source_inlet_temperature_celsius) + Initialize CopApproximator. + approximate_cop(self) + Approximate heat pump coefficient of performance (COP). + celsius_to_kelvin(t_celsius) + Convert temperature from Celsius to Kelvin. + logarithmic_mean(t_hot, t_cold) + Calculate the logarithmic mean temperature difference. """ def __init__( @@ -28,8 +46,8 @@ def __init__( ---------- forward_temperature_celsius : Union[xr.DataArray, np.array] The forward temperature in Celsius. - return_temperature_celsius : Union[xr.DataArray, np.array] - The return temperature in Celsius. + source_inlet_temperature_celsius : Union[xr.DataArray, np.array] + The source inlet temperature in Celsius. """ pass @@ -49,6 +67,19 @@ def approximate_cop(self) -> Union[xr.DataArray, np.array]: def celsius_to_kelvin( t_celsius: Union[float, xr.DataArray, np.array] ) -> Union[float, xr.DataArray, np.array]: + """ + Convert temperature from Celsius to Kelvin. + + Parameters: + ---------- + t_celsius : Union[float, xr.DataArray, np.array] + Temperature in Celsius. + + Returns: + ------- + Union[float, xr.DataArray, np.array] + Temperature in Kelvin. + """ if (np.asarray(t_celsius) > 200).any(): raise ValueError( "t_celsius > 200. Are you sure you are using the right units?" @@ -60,6 +91,21 @@ def logarithmic_mean( t_hot: Union[float, xr.DataArray, np.ndarray], t_cold: Union[float, xr.DataArray, np.ndarray], ) -> Union[float, xr.DataArray, np.ndarray]: + """ + Calculate the logarithmic mean temperature difference. + + Parameters: + ---------- + t_hot : Union[float, xr.DataArray, np.ndarray] + Hot temperature. + t_cold : Union[float, xr.DataArray, np.ndarray] + Cold temperature. + + Returns: + ------- + Union[float, xr.DataArray, np.ndarray] + Logarithmic mean temperature difference. + """ if (np.asarray(t_hot <= t_cold)).any(): raise ValueError("t_hot must be greater than t_cold") return (t_hot - t_cold) / np.log(t_hot / t_cold) diff --git a/scripts/build_cop_profiles/CentralHeatingCopApproximator.py b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py index a29dab592..7bf15b300 100644 --- a/scripts/build_cop_profiles/CentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py @@ -20,8 +20,77 @@ class CentralHeatingCopApproximator(BaseCopApproximator): default parameters from Pieper et al. (2020). The method is based on a thermodynamic heat pump model with some hard-to-know parameters being approximated. - """ + Attributes: + ---------- + forward_temperature_celsius : Union[xr.DataArray, np.array] + The forward temperature in Celsius. + return_temperature_celsius : Union[xr.DataArray, np.array] + The return temperature in Celsius. + source_inlet_temperature_celsius : Union[xr.DataArray, np.array] + The source inlet temperature in Celsius. + source_outlet_temperature_celsius : Union[xr.DataArray, np.array] + The source outlet temperature in Celsius. + delta_t_pinch_point : float, optional + The pinch point temperature difference, by default 5. + isentropic_compressor_efficiency : float, optional + The isentropic compressor efficiency, by default 0.8. + heat_loss : float, optional + The heat loss, by default 0.0. + + Methods: + ------- + __init__( + forward_temperature_celsius: Union[xr.DataArray, np.array], + source_inlet_temperature_celsius: Union[xr.DataArray, np.array], + return_temperature_celsius: Union[xr.DataArray, np.array], + source_outlet_temperature_celsius: Union[xr.DataArray, np.array], + delta_t_pinch_point: float = 5, + isentropic_compressor_efficiency: float = 0.8, + heat_loss: float = 0.0, + ) -> None: + Initializes the CentralHeatingCopApproximator object. + + approximate_cop(self) -> Union[xr.DataArray, np.array]: + Calculate the coefficient of performance (COP) for the system. + + _approximate_delta_t_refrigerant_source( + self, delta_t_source: Union[xr.DataArray, np.array] + ) -> Union[xr.DataArray, np.array]: + Approximates the temperature difference between the refrigerant and the source. + + _approximate_delta_t_refrigerant_sink( + self, + refrigerant: str = "ammonia", + a: float = {"ammonia": 0.2, "isobutane": -0.0011}, + b: float = {"ammonia": 0.2, "isobutane": 0.3}, + c: float = {"ammonia": 0.016, "isobutane": 2.4}, + ) -> Union[xr.DataArray, np.array]: + Approximates the temperature difference between the refrigerant and heat sink. + + _ratio_evaporation_compression_work_approximation( + self, + refrigerant: str = "ammonia", + a: float = {"ammonia": 0.0014, "isobutane": 0.0035}, + ) -> Union[xr.DataArray, np.array]: + Calculate the ratio of evaporation to compression work based on approximation. + + _approximate_delta_t_refrigerant_sink( + self, + refrigerant: str = "ammonia", + a: float = {"ammonia": 0.2, "isobutane": -0.0011}, + b: float = {"ammonia": 0.2, "isobutane": 0.3}, + c: float = {"ammonia": 0.016, "isobutane": 2.4}, + ) -> Union[xr.DataArray, np.array]: + Approximates the temperature difference between the refrigerant and heat sink. + + _ratio_evaporation_compression_work_approximation( + self, + refrigerant: str = "ammonia", + a: float = {"ammonia": 0.0014, "isobutane": 0.0035}, + ) -> Union[xr.DataArray, np.array]: + Calculate the ratio of evaporation to compression work based on approximation. + """ def __init__( self, forward_temperature_celsius: Union[xr.DataArray, np.array], @@ -33,6 +102,7 @@ def __init__( heat_loss: float = 0.0, ) -> None: """ + Initializes the CentralHeatingCopApproximator object. Parameters: ---------- @@ -74,6 +144,7 @@ def approximate_cop(self) -> Union[xr.DataArray, np.array]: Calculate the coefficient of performance (COP) for the system. Returns: + -------- Union[xr.DataArray, np.array]: The calculated COP values. """ return ( diff --git a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py index 11be7407f..d84b67956 100644 --- a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py @@ -16,7 +16,27 @@ class DecentralHeatingCopApproximator(BaseCopApproximator): Approximate the coefficient of performance (COP) for a heat pump in a decentral heating system (individual/household heating). - Uses a quadratic regression on the temperature difference between the source and sink based on empirical data proposed by Staffell et al. 2012 . + Uses a quadratic regression on the temperature difference between the source and sink based on empirical data proposed by Staffell et al. 2012. + + Attributes + ---------- + forward_temperature_celsius : Union[xr.DataArray, np.array] + The forward temperature in Celsius. + source_inlet_temperature_celsius : Union[xr.DataArray, np.array] + The source inlet temperature in Celsius. + source_type : str + The source of the heat pump. Must be either 'air' or 'ground'. + + Methods + ------- + __init__(forward_temperature_celsius, source_inlet_temperature_celsius, source_type) + Initialize the DecentralHeatingCopApproximator object. + approximate_cop() + Compute the COP values using quadratic regression for air-/ground-source heat pumps. + _approximate_cop_air_source() + Evaluate quadratic regression for an air-sourced heat pump. + _approximate_cop_ground_source() + Evaluate quadratic regression for a ground-sourced heat pump. References ---------- @@ -30,30 +50,32 @@ def __init__( source_type: str, ): """ - Initialize the COPProfileBuilder object. + Initialize the DecentralHeatingCopApproximator object. - Parameters: + Parameters ---------- forward_temperature_celsius : Union[xr.DataArray, np.array] The forward temperature in Celsius. - return_temperature_celsius : Union[xr.DataArray, np.array] - The return temperature in Celsius. - source: str - The source of the heat pump. Must be either 'air' or 'ground' + source_inlet_temperature_celsius : Union[xr.DataArray, np.array] + The source inlet temperature in Celsius. + source_type : str + The source of the heat pump. Must be either 'air' or 'ground'. """ self.delta_t = forward_temperature_celsius - source_inlet_temperature_celsius if source_type not in ["air", "ground"]: - raise ValueError("'source' must be one of ['air', 'ground']") + raise ValueError("'source_type' must be one of ['air', 'ground']") else: self.source_type = source_type def approximate_cop(self) -> Union[xr.DataArray, np.array]: """ - Compute output of quadratic regression for air-/ground-source heat - pumps. + Compute the COP values using quadratic regression for air-/ground-source heat pumps. - Calls the appropriate method depending on `source`. + Returns + ------- + Union[xr.DataArray, np.array] + The calculated COP values. """ if self.source_type == "air": return self._approximate_cop_air_source() From d273de86001d29bd8996d218eb5cc01f569f1a26 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 31 Jul 2024 15:01:48 +0000 Subject: [PATCH 37/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- scripts/build_cop_profiles/CentralHeatingCopApproximator.py | 1 + scripts/build_cop_profiles/DecentralHeatingCopApproximator.py | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/build_cop_profiles/CentralHeatingCopApproximator.py b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py index 7bf15b300..08dd6a1a8 100644 --- a/scripts/build_cop_profiles/CentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/CentralHeatingCopApproximator.py @@ -91,6 +91,7 @@ class CentralHeatingCopApproximator(BaseCopApproximator): ) -> Union[xr.DataArray, np.array]: Calculate the ratio of evaporation to compression work based on approximation. """ + def __init__( self, forward_temperature_celsius: Union[xr.DataArray, np.array], diff --git a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py index d84b67956..e5f58af41 100644 --- a/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py +++ b/scripts/build_cop_profiles/DecentralHeatingCopApproximator.py @@ -70,7 +70,8 @@ def __init__( def approximate_cop(self) -> Union[xr.DataArray, np.array]: """ - Compute the COP values using quadratic regression for air-/ground-source heat pumps. + Compute the COP values using quadratic regression for air-/ground- + source heat pumps. Returns ------- From 214efeb0569a9a8c72bff32d8226a79891f1f466 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Wed, 31 Jul 2024 17:30:24 +0200 Subject: [PATCH 38/58] make test.sh executable --- test.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 test.sh diff --git a/test.sh b/test.sh old mode 100644 new mode 100755 From b0150bd65d4fb7afd107a1edd9bebf5757f0feba Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Thu, 1 Aug 2024 11:59:26 +0200 Subject: [PATCH 39/58] refactor prepare_sector_network.add_heat using Enums --- config/config.default.yaml | 9 +++ rules/build_sector.smk | 1 + scripts/prepare_sector_network.py | 104 ++++++++++++------------------ 3 files changed, 53 insertions(+), 61 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index 794b2baea..bfa99d90f 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -422,6 +422,15 @@ sector: decentral: - air - ground + heat_systems: + rural: + - residential rural + - services rural + urban decentral: + - residential urban decentral + - services urban decentral + urban central: + - urban central cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 diff --git a/rules/build_sector.smk b/rules/build_sector.smk index b7d916ea4..34477f5b4 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -965,6 +965,7 @@ rule prepare_sector_network: emissions_scope=config_provider("energy", "emissions"), RDIR=RDIR, heat_pump_sources=config_provider("sector", "heat_pump_sources"), + heat_systems=config_provider("sector", "heat_systems") input: unpack(input_profile_offwind), **rules.cluster_gas_network.output, diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index f71dd5f58..52989c2d7 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -22,6 +22,7 @@ set_scenario_config, update_config_from_wildcards, ) +from _entities import HeatSystem, HeatSector from add_electricity import calculate_annuity, sanitize_carriers, sanitize_locations from build_energy_totals import ( build_co2_totals, @@ -1817,14 +1818,6 @@ def add_heat(n, costs): for sector in sectors: heat_demand[sector + " space"] = (1 - dE) * heat_demand[sector + " space"] - heat_systems = [ - "residential rural", - "services rural", - "residential urban decentral", - "services urban decentral", - "urban central", - ] - if options["solar_thermal"]: solar_thermal = ( xr.open_dataarray(snakemake.input.solar_thermal_total) @@ -1835,31 +1828,31 @@ def add_heat(n, costs): solar_thermal = options["solar_cf_correction"] * solar_thermal / 1e3 cop = xr.open_dataarray(snakemake.input.cop_profiles) - for heat_system in heat_systems: - system_type = "central" if heat_system == "urban central" else "decentral" + for heat_system in HeatSystem: #this loops through all heat systems defined in _entities.HeatSystem + # system_type = "central" if heat_system == "urban central" else "decentral" - if heat_system == "urban central": + if heat_system == HeatSystem.URBAN_CENTRAL: nodes = dist_fraction.index[dist_fraction > 0] else: nodes = pop_layout.index - n.add("Carrier", heat_system + " heat") + n.add("Carrier", f"{heat_system} heat") n.madd( "Bus", nodes + f" {heat_system} heat", location=nodes, - carrier=heat_system + " heat", + carrier=f"{heat_system} heat", unit="MWh_th", ) - if heat_system == "urban central" and options.get("central_heat_vent"): + if heat_system == HeatSystem.URBAN_CENTRAL and options.get("central_heat_vent"): n.madd( "Generator", nodes + f" {heat_system} heat vent", bus=nodes + f" {heat_system} heat", location=nodes, - carrier=heat_system + " heat vent", + carrier=f"{heat_system} heat vent", p_nom_extendable=True, p_max_pu=0, p_min_pu=-1, @@ -1867,30 +1860,18 @@ def add_heat(n, costs): ) ## Add heat load + factor = heat_system.heat_demand_weighting(urban_fraction=urban_fraction[nodes], dist_fraction=dist_fraction[nodes]) + if not heat_system == HeatSystem.URBAN_CENTRAL: + heat_load = ( + heat_demand[[heat_system.sector.value + " water", heat_system.sector.value + " space"]] + .T.groupby(level=1) + .sum() + .T[nodes] + .multiply(factor) + ) - for sector in sectors: - # heat demand weighting - if "rural" in heat_system: - factor = 1 - urban_fraction[nodes] - elif "urban central" in heat_system: - factor = dist_fraction[nodes] - elif "urban decentral" in heat_system: - factor = urban_fraction[nodes] - dist_fraction[nodes] - else: - raise NotImplementedError( - f" {heat_system} not in " f"heat systems: {heat_systems}" - ) - - if sector in heat_system: - heat_load = ( - heat_demand[[sector + " water", sector + " space"]] - .T.groupby(level=1) - .sum() - .T[nodes] - .multiply(factor) - ) - if heat_system == "urban central": + if heat_system == HeatSystem.URBAN_CENTRAL: heat_load = ( heat_demand.T.groupby(level=1) .sum() @@ -1905,15 +1886,15 @@ def add_heat(n, costs): nodes, suffix=f" {heat_system} heat", bus=nodes + f" {heat_system} heat", - carrier=heat_system + " heat", + carrier=heat_system.value + " heat", p_set=heat_load, ) ## Add heat pumps - for heat_source in snakemake.params.heat_pump_sources[system_type]: - costs_name = f"{system_type} {heat_source}-sourced heat pump" + for heat_source in snakemake.params.heat_pump_sources[heat_system.system_type]: + costs_name = heat_system.heat_pump_costs_name(heat_source) efficiency = ( - cop.sel(heat_system=system_type, heat_source=heat_source, name=nodes) + cop.sel(heat_system=heat_system.system_type, heat_source=heat_source, name=nodes) .to_pandas() .reindex(index=n.snapshots) if options["time_dep_hp_cop"] @@ -1936,13 +1917,13 @@ def add_heat(n, costs): ) if options["tes"]: - n.add("Carrier", heat_system + " water tanks") + n.add("Carrier", heat_system.value + " water tanks") n.madd( "Bus", nodes + f" {heat_system} water tanks", location=nodes, - carrier=heat_system + " water tanks", + carrier=heat_system.value + " water tanks", unit="MWh_th", ) @@ -1952,7 +1933,7 @@ def add_heat(n, costs): bus0=nodes + f" {heat_system} heat", bus1=nodes + f" {heat_system} water tanks", efficiency=costs.at["water tank charger", "efficiency"], - carrier=heat_system + " water tanks charger", + carrier=heat_system.value + " water tanks charger", p_nom_extendable=True, ) @@ -1961,12 +1942,12 @@ def add_heat(n, costs): nodes + f" {heat_system} water tanks discharger", bus0=nodes + f" {heat_system} water tanks", bus1=nodes + f" {heat_system} heat", - carrier=heat_system + " water tanks discharger", + carrier=heat_system.value + " water tanks discharger", efficiency=costs.at["water tank discharger", "efficiency"], p_nom_extendable=True, ) - tes_time_constant_days = options["tes_tau"][system_type] + tes_time_constant_days = options["tes_tau"][heat_system.system_type] n.madd( "Store", @@ -1974,21 +1955,21 @@ def add_heat(n, costs): bus=nodes + f" {heat_system} water tanks", e_cyclic=True, e_nom_extendable=True, - carrier=heat_system + " water tanks", + carrier=heat_system.value + " water tanks", standing_loss=1 - np.exp(-1 / 24 / tes_time_constant_days), - capital_cost=costs.at[system_type + " water tank storage", "fixed"], - lifetime=costs.at[system_type + " water tank storage", "lifetime"], + capital_cost=costs.at[heat_system.system_type + " water tank storage", "fixed"], + lifetime=costs.at[heat_system.system_type + " water tank storage", "lifetime"], ) if options["resistive_heaters"]: - key = f"{system_type} resistive heater" + key = f"{heat_system.system_type} resistive heater" n.madd( "Link", nodes + f" {heat_system} resistive heater", bus0=nodes, bus1=nodes + f" {heat_system} heat", - carrier=heat_system + " resistive heater", + carrier=heat_system.value + " resistive heater", efficiency=costs.at[key, "efficiency"], capital_cost=costs.at[key, "efficiency"] * costs.at[key, "fixed"] @@ -1998,7 +1979,7 @@ def add_heat(n, costs): ) if options["boilers"]: - key = f"{system_type} gas boiler" + key = f"{heat_system.system_type} gas boiler" n.madd( "Link", @@ -2007,7 +1988,7 @@ def add_heat(n, costs): bus0=spatial.gas.df.loc[nodes, "nodes"].values, bus1=nodes + f" {heat_system} heat", bus2="co2 atmosphere", - carrier=heat_system + " gas boiler", + carrier=heat_system.value + " gas boiler", efficiency=costs.at[key, "efficiency"], efficiency2=costs.at["gas", "CO2 intensity"], capital_cost=costs.at[key, "efficiency"] @@ -2017,19 +1998,19 @@ def add_heat(n, costs): ) if options["solar_thermal"]: - n.add("Carrier", heat_system + " solar thermal") + n.add("Carrier", heat_system.value + " solar thermal") n.madd( "Generator", nodes, suffix=f" {heat_system} solar thermal collector", bus=nodes + f" {heat_system} heat", - carrier=heat_system + " solar thermal", + carrier=heat_system.value + " solar thermal", p_nom_extendable=True, - capital_cost=costs.at[system_type + " solar thermal", "fixed"] + capital_cost=costs.at[heat_system.system_type + " solar thermal", "fixed"] * overdim_factor, p_max_pu=solar_thermal[nodes], - lifetime=costs.at[system_type + " solar thermal", "lifetime"], + lifetime=costs.at[heat_system.system_type + " solar thermal", "lifetime"], ) if options["chp"] and heat_system == "urban central": @@ -2125,16 +2106,16 @@ def add_heat(n, costs): # share of space heat demand 'w_space' of total heat demand w_space = {} - for sector in sectors: - w_space[sector] = heat_demand[sector + " space"] / ( - heat_demand[sector + " space"] + heat_demand[sector + " water"] + for sector in HeatSector: + w_space[sector.value] = heat_demand[sector.value + " space"] / ( + heat_demand[sector.value + " space"] + heat_demand[sector.value + " water"] ) w_space["tot"] = ( heat_demand["services space"] + heat_demand["residential space"] ) / heat_demand.T.groupby(level=[1]).sum().T for heat_system in n.loads[ - n.loads.carrier.isin([x + " heat" for x in heat_systems]) + n.loads.carrier.isin([x.value + " heat" for x in HeatSystem]) ].index: node = n.buses.loc[heat_system, "location"] ct = pop_layout.loc[node, "ct"] @@ -2148,6 +2129,7 @@ def add_heat(n, costs): f = 1 - urban_fraction[node] if f == 0: continue + # get sector name ("residential"/"services"/or both "tot" for urban central) if "urban central" in heat_system: sec = "tot" From 4a6dd2fe33125086926f6653b55c308b8efb8f0c Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 2 Aug 2024 15:56:37 +0200 Subject: [PATCH 40/58] fix naming bugs --- config/config.default.yaml | 15 +++-------- scripts/build_cop_profiles/run.py | 12 ++++----- scripts/prepare_sector_network.py | 43 +++++++++++++++---------------- 3 files changed, 31 insertions(+), 39 deletions(-) diff --git a/config/config.default.yaml b/config/config.default.yaml index bfa99d90f..ebb8eb4f1 100644 --- a/config/config.default.yaml +++ b/config/config.default.yaml @@ -417,20 +417,13 @@ sector: isentropic_compressor_efficiency: 0.8 heat_loss: 0.0 heat_pump_sources: - central: + urban central: - air - decentral: + urban decentral: - air - - ground - heat_systems: rural: - - residential rural - - services rural - urban decentral: - - residential urban decentral - - services urban decentral - urban central: - - urban central + - air + - ground cluster_heat_buses: true heat_demand_cutout: default bev_dsm_restriction_value: 0.75 diff --git a/scripts/build_cop_profiles/run.py b/scripts/build_cop_profiles/run.py index 5178483a8..583d097aa 100644 --- a/scripts/build_cop_profiles/run.py +++ b/scripts/build_cop_profiles/run.py @@ -12,18 +12,18 @@ def get_cop( - heat_system_type: str, + heat_system_category: str, heat_source: str, source_inlet_temperature_celsius: xr.DataArray, ) -> xr.DataArray: - if heat_system_type == "decentral": + if heat_system_category in ["urban decentral", "rural"]: return DecentralHeatingCopApproximator( forward_temperature_celsius=snakemake.params.heat_pump_sink_T_decentral_heating, source_inlet_temperature_celsius=source_inlet_temperature_celsius, source_type=heat_source, ).approximate_cop() - elif heat_system_type == "central": + elif heat_system_category == "urban central": return CentralHeatingCopApproximator( forward_temperature_celsius=snakemake.params.forward_temperature_central_heating, return_temperature_celsius=snakemake.params.return_temperature_central_heating, @@ -33,7 +33,7 @@ def get_cop( ).approximate_cop() else: raise ValueError( - f"Invalid heat system type '{heat_system_type}'. Must be one of ['decentral', 'central']" + f"Invalid heat system type '{heat_system_category}'. Must be one of ['urban decentral', 'urban central', 'rural]" ) @@ -50,14 +50,14 @@ def get_cop( set_scenario_config(snakemake) cop_all_system_types = [] - for heat_system_type, heat_sources in snakemake.params.heat_pump_sources.items(): + for heat_system_category, heat_sources in snakemake.params.heat_pump_sources.items(): cop_this_system_type = [] for heat_source in heat_sources: source_inlet_temperature_celsius = xr.open_dataarray( snakemake.input[f"temp_{heat_source.replace('ground', 'soil')}_total"] ) cop_da = get_cop( - heat_system_type=heat_system_type, + heat_system_category=heat_system_category, heat_source=heat_source, source_inlet_temperature_celsius=source_inlet_temperature_celsius, ) diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index 52989c2d7..989f4dc26 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1840,9 +1840,9 @@ def add_heat(n, costs): n.madd( "Bus", - nodes + f" {heat_system} heat", + nodes + f" {heat_system.value} heat", location=nodes, - carrier=f"{heat_system} heat", + carrier=f"{heat_system.value} heat", unit="MWh_th", ) @@ -1891,10 +1891,10 @@ def add_heat(n, costs): ) ## Add heat pumps - for heat_source in snakemake.params.heat_pump_sources[heat_system.system_type]: + for heat_source in snakemake.params.heat_pump_sources[heat_system.system_category]: costs_name = heat_system.heat_pump_costs_name(heat_source) efficiency = ( - cop.sel(heat_system=heat_system.system_type, heat_source=heat_source, name=nodes) + cop.sel(heat_system=heat_system.system_category, heat_source=heat_source, name=nodes) .to_pandas() .reindex(index=n.snapshots) if options["time_dep_hp_cop"] @@ -2013,7 +2013,7 @@ def add_heat(n, costs): lifetime=costs.at[heat_system.system_type + " solar thermal", "lifetime"], ) - if options["chp"] and heat_system == "urban central": + if options["chp"] and heat_system == HeatSystem.URBAN_CENTRAL: # add gas CHP; biomass CHP is added in biomass section n.madd( "Link", @@ -2070,7 +2070,7 @@ def add_heat(n, costs): lifetime=costs.at["central gas CHP", "lifetime"], ) - if options["chp"] and options["micro_chp"] and heat_system != "urban central": + if options["chp"] and options["micro_chp"] and heat_system.value != "urban central": n.madd( "Link", nodes + f" {heat_system} micro gas CHP", @@ -2079,7 +2079,7 @@ def add_heat(n, costs): bus1=nodes, bus2=nodes + f" {heat_system} heat", bus3="co2 atmosphere", - carrier=heat_system + " micro gas CHP", + carrier=heat_system.value + " micro gas CHP", efficiency=costs.at["micro CHP", "efficiency"], efficiency2=costs.at["micro CHP", "efficiency-heat"], efficiency3=costs.at["gas", "CO2 intensity"], @@ -2106,36 +2106,35 @@ def add_heat(n, costs): # share of space heat demand 'w_space' of total heat demand w_space = {} - for sector in HeatSector: - w_space[sector.value] = heat_demand[sector.value + " space"] / ( - heat_demand[sector.value + " space"] + heat_demand[sector.value + " water"] + for sector in sectors: + w_space[sector] = heat_demand[sector + " space"] / ( + heat_demand[sector + " space"] + heat_demand[sector + " water"] ) w_space["tot"] = ( heat_demand["services space"] + heat_demand["residential space"] ) / heat_demand.T.groupby(level=[1]).sum().T - for heat_system in n.loads[ - n.loads.carrier.isin([x.value + " heat" for x in HeatSystem]) + for name in n.loads[ + n.loads.carrier.isin([x + " heat" for x in heat_systems]) ].index: - node = n.buses.loc[heat_system, "location"] + node = n.buses.loc[name, "location"] ct = pop_layout.loc[node, "ct"] # weighting 'f' depending on the size of the population at the node - if "urban central" in heat_system: + if "urban central" in name: f = dist_fraction[node] - elif "urban decentral" in heat_system: + elif "urban decentral" in name: f = urban_fraction[node] - dist_fraction[node] else: f = 1 - urban_fraction[node] if f == 0: continue - # get sector name ("residential"/"services"/or both "tot" for urban central) - if "urban central" in heat_system: + if "urban central" in name: sec = "tot" - if "residential" in heat_system: + if "residential" in name: sec = "residential" - if "services" in heat_system: + if "services" in name: sec = "services" # get floor aread at node and region (urban/rural) in m^2 @@ -2143,7 +2142,7 @@ def add_heat(n, costs): pop_layout.loc[node].fraction * floor_area.loc[ct, "value"] * 10**6 ).loc[sec] * f # total heat demand at node [MWh] - demand = n.loads_t.p_set[heat_system] + demand = n.loads_t.p_set[name] # space heat demand at node [MWh] space_heat_demand = demand * w_space[sec][node] @@ -2184,12 +2183,12 @@ def add_heat(n, costs): # add for each retrofitting strength a generator with heat generation profile following the profile of the heat demand for strength in strengths: - node_name = " ".join(heat_system.split(" ")[2::]) + node_name = " ".join(name.split(" ")[2::]) n.madd( "Generator", [node], suffix=" retrofitting " + strength + " " + node_name, - bus=heat_system, + bus=name, carrier="retrofitting", p_nom_extendable=True, p_nom_max=dE_diff[strength] From 318e05c9fb663c467f59f7610679aca0db40cbf6 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 2 Aug 2024 16:29:54 +0200 Subject: [PATCH 41/58] refactor naming --- scripts/build_cop_profiles/run.py | 42 +++++++++++++++++++++---------- scripts/prepare_sector_network.py | 41 +++++++++++++++--------------- 2 files changed, 49 insertions(+), 34 deletions(-) diff --git a/scripts/build_cop_profiles/run.py b/scripts/build_cop_profiles/run.py index 583d097aa..7aa5b1bf9 100644 --- a/scripts/build_cop_profiles/run.py +++ b/scripts/build_cop_profiles/run.py @@ -7,23 +7,35 @@ import pandas as pd import xarray as xr from _helpers import set_scenario_config +import sys; sys.path.append("..") +from scripts._entities import HeatSystemType from CentralHeatingCopApproximator import CentralHeatingCopApproximator from DecentralHeatingCopApproximator import DecentralHeatingCopApproximator def get_cop( - heat_system_category: str, + heat_system_type: str, heat_source: str, source_inlet_temperature_celsius: xr.DataArray, ) -> xr.DataArray: - if heat_system_category in ["urban decentral", "rural"]: - return DecentralHeatingCopApproximator( - forward_temperature_celsius=snakemake.params.heat_pump_sink_T_decentral_heating, - source_inlet_temperature_celsius=source_inlet_temperature_celsius, - source_type=heat_source, - ).approximate_cop() + """ + Calculate the coefficient of performance (COP) for a heating system. + + Parameters + ---------- + heat_system_type : str + The type of heating system. + heat_source : str + The heat source used in the heating system. + source_inlet_temperature_celsius : xr.DataArray + The inlet temperature of the heat source in Celsius. - elif heat_system_category == "urban central": + Returns + ------- + xr.DataArray + The calculated coefficient of performance (COP) for the heating system. + """ + if HeatSystemType(heat_system_type).is_central: return CentralHeatingCopApproximator( forward_temperature_celsius=snakemake.params.forward_temperature_central_heating, return_temperature_celsius=snakemake.params.return_temperature_central_heating, @@ -31,10 +43,14 @@ def get_cop( source_outlet_temperature_celsius=source_inlet_temperature_celsius - snakemake.params.heat_source_cooling_central_heating, ).approximate_cop() + else: - raise ValueError( - f"Invalid heat system type '{heat_system_category}'. Must be one of ['urban decentral', 'urban central', 'rural]" - ) + return DecentralHeatingCopApproximator( + forward_temperature_celsius=snakemake.params.heat_pump_sink_T_decentral_heating, + source_inlet_temperature_celsius=source_inlet_temperature_celsius, + source_type=heat_source, + ).approximate_cop() + if __name__ == "__main__": @@ -50,14 +66,14 @@ def get_cop( set_scenario_config(snakemake) cop_all_system_types = [] - for heat_system_category, heat_sources in snakemake.params.heat_pump_sources.items(): + for heat_system_type, heat_sources in snakemake.params.heat_pump_sources.items(): cop_this_system_type = [] for heat_source in heat_sources: source_inlet_temperature_celsius = xr.open_dataarray( snakemake.input[f"temp_{heat_source.replace('ground', 'soil')}_total"] ) cop_da = get_cop( - heat_system_category=heat_system_category, + heat_system_type=heat_system_type, heat_source=heat_source, source_inlet_temperature_celsius=source_inlet_temperature_celsius, ) diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index 989f4dc26..c15d81675 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1829,7 +1829,6 @@ def add_heat(n, costs): cop = xr.open_dataarray(snakemake.input.cop_profiles) for heat_system in HeatSystem: #this loops through all heat systems defined in _entities.HeatSystem - # system_type = "central" if heat_system == "urban central" else "decentral" if heat_system == HeatSystem.URBAN_CENTRAL: nodes = dist_fraction.index[dist_fraction > 0] @@ -1886,15 +1885,15 @@ def add_heat(n, costs): nodes, suffix=f" {heat_system} heat", bus=nodes + f" {heat_system} heat", - carrier=heat_system.value + " heat", + carrier=f"{heat_system} heat", p_set=heat_load, ) ## Add heat pumps - for heat_source in snakemake.params.heat_pump_sources[heat_system.system_category]: + for heat_source in snakemake.params.heat_pump_sources[heat_system.system_type.value]: costs_name = heat_system.heat_pump_costs_name(heat_source) efficiency = ( - cop.sel(heat_system=heat_system.system_category, heat_source=heat_source, name=nodes) + cop.sel(heat_system=heat_system.system_type.value, heat_source=heat_source, name=nodes) .to_pandas() .reindex(index=n.snapshots) if options["time_dep_hp_cop"] @@ -1917,13 +1916,13 @@ def add_heat(n, costs): ) if options["tes"]: - n.add("Carrier", heat_system.value + " water tanks") + n.add("Carrier", f"{heat_system} water tanks") n.madd( "Bus", nodes + f" {heat_system} water tanks", location=nodes, - carrier=heat_system.value + " water tanks", + carrier=f"{heat_system} water tanks", unit="MWh_th", ) @@ -1933,7 +1932,7 @@ def add_heat(n, costs): bus0=nodes + f" {heat_system} heat", bus1=nodes + f" {heat_system} water tanks", efficiency=costs.at["water tank charger", "efficiency"], - carrier=heat_system.value + " water tanks charger", + carrier=f"{heat_system} water tanks charger", p_nom_extendable=True, ) @@ -1942,12 +1941,12 @@ def add_heat(n, costs): nodes + f" {heat_system} water tanks discharger", bus0=nodes + f" {heat_system} water tanks", bus1=nodes + f" {heat_system} heat", - carrier=heat_system.value + " water tanks discharger", + carrier=f"{heat_system} water tanks discharger", efficiency=costs.at["water tank discharger", "efficiency"], p_nom_extendable=True, ) - tes_time_constant_days = options["tes_tau"][heat_system.system_type] + tes_time_constant_days = options["tes_tau"][heat_system.central_or_decentral] n.madd( "Store", @@ -1955,21 +1954,21 @@ def add_heat(n, costs): bus=nodes + f" {heat_system} water tanks", e_cyclic=True, e_nom_extendable=True, - carrier=heat_system.value + " water tanks", + carrier=f"{heat_system} water tanks", standing_loss=1 - np.exp(-1 / 24 / tes_time_constant_days), - capital_cost=costs.at[heat_system.system_type + " water tank storage", "fixed"], - lifetime=costs.at[heat_system.system_type + " water tank storage", "lifetime"], + capital_cost=costs.at[heat_system.central_or_decentral + " water tank storage", "fixed"], + lifetime=costs.at[heat_system.central_or_decentral + " water tank storage", "lifetime"], ) if options["resistive_heaters"]: - key = f"{heat_system.system_type} resistive heater" + key = f"{heat_system.central_or_decentral} resistive heater" n.madd( "Link", nodes + f" {heat_system} resistive heater", bus0=nodes, bus1=nodes + f" {heat_system} heat", - carrier=heat_system.value + " resistive heater", + carrier=f"{heat_system} resistive heater", efficiency=costs.at[key, "efficiency"], capital_cost=costs.at[key, "efficiency"] * costs.at[key, "fixed"] @@ -1979,7 +1978,7 @@ def add_heat(n, costs): ) if options["boilers"]: - key = f"{heat_system.system_type} gas boiler" + key = f"{heat_system.central_or_decentral} gas boiler" n.madd( "Link", @@ -1988,7 +1987,7 @@ def add_heat(n, costs): bus0=spatial.gas.df.loc[nodes, "nodes"].values, bus1=nodes + f" {heat_system} heat", bus2="co2 atmosphere", - carrier=heat_system.value + " gas boiler", + carrier=f"{heat_system} gas boiler", efficiency=costs.at[key, "efficiency"], efficiency2=costs.at["gas", "CO2 intensity"], capital_cost=costs.at[key, "efficiency"] @@ -1998,19 +1997,19 @@ def add_heat(n, costs): ) if options["solar_thermal"]: - n.add("Carrier", heat_system.value + " solar thermal") + n.add("Carrier", f"{heat_system} solar thermal") n.madd( "Generator", nodes, suffix=f" {heat_system} solar thermal collector", bus=nodes + f" {heat_system} heat", - carrier=heat_system.value + " solar thermal", + carrier=f"{heat_system} solar thermal", p_nom_extendable=True, - capital_cost=costs.at[heat_system.system_type + " solar thermal", "fixed"] + capital_cost=costs.at[heat_system.central_or_decentral + " solar thermal", "fixed"] * overdim_factor, p_max_pu=solar_thermal[nodes], - lifetime=costs.at[heat_system.system_type + " solar thermal", "lifetime"], + lifetime=costs.at[heat_system.central_or_decentral + " solar thermal", "lifetime"], ) if options["chp"] and heat_system == HeatSystem.URBAN_CENTRAL: @@ -2115,7 +2114,7 @@ def add_heat(n, costs): ) / heat_demand.T.groupby(level=[1]).sum().T for name in n.loads[ - n.loads.carrier.isin([x + " heat" for x in heat_systems]) + n.loads.carrier.isin([x + " heat" for x in HeatSystem]) ].index: node = n.buses.loc[name, "location"] ct = pop_layout.loc[node, "ct"] From 76b377b2d149c6637fa9637ff99335ce89af0ada Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 2 Aug 2024 17:02:16 +0200 Subject: [PATCH 42/58] udpate docs --- doc/configtables/sector.csv | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/configtables/sector.csv b/doc/configtables/sector.csv index e14da5573..a075dd3d7 100644 --- a/doc/configtables/sector.csv +++ b/doc/configtables/sector.csv @@ -6,6 +6,8 @@ industry,--,"{true, false}",Flag to include industry sector. agriculture,--,"{true, false}",Flag to include agriculture sector. district_heating,--,,`prepare_sector_network.py `_ -- potential,--,float,maximum fraction of urban demand which can be supplied by district heating. Ignored where below current fraction. +-- progress,--,Dictionary with planning horizons as keys., Increase of today's district heating demand to potential maximum district heating share. Progress = 0 means today's district heating share. Progress = 1 means maximum fraction of urban demand is supplied by district heating +-- district_heating_loss,--,float,Share increase in district heat demand in urban central due to heat losses -- forward_temperature,°C,float,Forward temperature in district heating -- return_temperature,°C,float,Return temperature in district heating. Must be lower than forward temperature -- heat_source_cooling,K,float,Cooling of heat source for heat pumps @@ -14,8 +16,10 @@ district_heating,--,,`prepare_sector_network.py `_ to one to save memory. ,,, bev_dsm_restriction _value,--,float,Adds a lower state of charge (SOC) limit for battery electric vehicles (BEV) to manage its own energy demand (DSM). Located in `build_transport_demand.py `_. Set to 0 for no restriction on BEV DSM From bbf64a2fde2825f0a954526b1b99cc53ce1f7b60 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 2 Aug 2024 17:03:34 +0200 Subject: [PATCH 43/58] Refactor module structure --- scripts/build_cop_profiles/run.py | 2 +- scripts/enums/HeatSector.py | 25 ++++ scripts/enums/HeatSystem.py | 218 ++++++++++++++++++++++++++++++ scripts/enums/HeatSystemType.py | 35 +++++ scripts/prepare_sector_network.py | 4 +- 5 files changed, 282 insertions(+), 2 deletions(-) create mode 100644 scripts/enums/HeatSector.py create mode 100644 scripts/enums/HeatSystem.py create mode 100644 scripts/enums/HeatSystemType.py diff --git a/scripts/build_cop_profiles/run.py b/scripts/build_cop_profiles/run.py index 7aa5b1bf9..776ed289a 100644 --- a/scripts/build_cop_profiles/run.py +++ b/scripts/build_cop_profiles/run.py @@ -8,7 +8,7 @@ import xarray as xr from _helpers import set_scenario_config import sys; sys.path.append("..") -from scripts._entities import HeatSystemType +from scripts.enums.HeatSystemType import HeatSystemType from CentralHeatingCopApproximator import CentralHeatingCopApproximator from DecentralHeatingCopApproximator import DecentralHeatingCopApproximator diff --git a/scripts/enums/HeatSector.py b/scripts/enums/HeatSector.py new file mode 100644 index 000000000..008a06933 --- /dev/null +++ b/scripts/enums/HeatSector.py @@ -0,0 +1,25 @@ +# SPDX-License-Identifier: MIT + +from enum import Enum + +class HeatSector(Enum): + """ + Enumeration class representing different heat sectors. + + Attributes: + RESIDENTIAL (str): Represents the residential heat sector. + SERVICES (str): Represents the services heat sector. + """ + + RESIDENTIAL = "residential" + SERVICES = "services" + + def __str__(self) -> str: + """ + Returns the string representation of the heat sector. + + Returns: + str: The string representation of the heat sector. + """ + return self.value + diff --git a/scripts/enums/HeatSystem.py b/scripts/enums/HeatSystem.py new file mode 100644 index 000000000..042793a6c --- /dev/null +++ b/scripts/enums/HeatSystem.py @@ -0,0 +1,218 @@ +# -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# +# SPDX-License-Identifier: MIT + +from enum import Enum + +from .HeatSystemType import HeatSystemType +from .HeatSector import HeatSector + +class HeatSystem(Enum): + """ + Enumeration representing different heat systems. + + Attributes + ---------- + RESIDENTIAL_RURAL : str + Heat system for residential areas in rural locations. + SERVICES_RURAL : str + Heat system for service areas in rural locations. + RESIDENTIAL_URBAN_DECENTRAL : str + Heat system for residential areas in urban decentralized locations. + SERVICES_URBAN_DECENTRAL : str + Heat system for service areas in urban decentralized locations. + URBAN_CENTRAL : str + Heat system for urban central areas. + + Methods + ------- + __str__() + Returns the string representation of the heat system. + central_or_decentral() + Returns whether the heat system is central or decentralized. + system_type() + Returns the type of the heat system. + sector() + Returns the sector of the heat system. + rural() + Returns whether the heat system is for rural areas. + urban_decentral() + Returns whether the heat system is for urban decentralized areas. + urban() + Returns whether the heat system is for urban areas. + heat_demand_weighting(urban_fraction=None, dist_fraction=None) + Calculates the heat demand weighting based on urban fraction and distribution fraction. + heat_pump_costs_name(heat_source) + Generates the name for the heat pump costs based on the heat source. + """ + + RESIDENTIAL_RURAL = "residential rural" + SERVICES_RURAL = "services rural" + RESIDENTIAL_URBAN_DECENTRAL = "residential urban decentral" + SERVICES_URBAN_DECENTRAL = "services urban decentral" + URBAN_CENTRAL = "urban central" + + def __init__(self, *args): + super().__init__(*args) + + def __str__(self) -> str: + """ + Returns the string representation of the heat system. + + Returns + ------- + str + The string representation of the heat system. + """ + return self.value + + @property + def central_or_decentral(self) -> str: + """ + Returns whether the heat system is central or decentralized. + + Returns + ------- + str + "central" if the heat system is central, "decentral" otherwise. + """ + if self == HeatSystem.URBAN_CENTRAL: + return "central" + else: + return "decentral" + + @property + def system_type(self) -> HeatSystemType: + """ + Returns the type of the heat system. + + Returns + ------- + str + The type of the heat system. + + Raises + ------ + RuntimeError + If the heat system is invalid. + """ + if self == HeatSystem.URBAN_CENTRAL: + return HeatSystemType.URBAN_CENTRAL + elif self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL or self == HeatSystem.SERVICES_URBAN_DECENTRAL: + return HeatSystemType.URBAN_DECENTRAL + elif self == HeatSystem.RESIDENTIAL_RURAL or self == HeatSystem.SERVICES_RURAL: + return HeatSystemType.RURAL + else: + raise RuntimeError(f"Invalid heat system: {self}") + + @property + def sector(self) -> HeatSector: + """ + Returns the sector of the heat system. + + Returns + ------- + HeatSector + The sector of the heat system. + """ + if ( + self == HeatSystem.RESIDENTIAL_RURAL + or self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL + ): + return HeatSector.RESIDENTIAL + elif ( + self == HeatSystem.SERVICES_RURAL + or self == HeatSystem.SERVICES_URBAN_DECENTRAL + ): + return HeatSector.SERVICES + else: + 'tot' + + @property + def is_rural(self) -> bool: + """ + Returns whether the heat system is for rural areas. + + Returns + ------- + bool + True if the heat system is for rural areas, False otherwise. + """ + if self == HeatSystem.RESIDENTIAL_RURAL or self == HeatSystem.SERVICES_RURAL: + return True + else: + return False + + @property + def is_urban_decentral(self) -> bool: + """ + Returns whether the heat system is for urban decentralized areas. + + Returns + ------- + bool + True if the heat system is for urban decentralized areas, False otherwise. + """ + if self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL or self == HeatSystem.SERVICES_URBAN_DECENTRAL: + return True + else: + return False + + @property + def is_urban(self) -> bool: + """ + Returns whether the heat system is for urban areas. + + Returns + ------- + bool True if the heat system is for urban areas, False otherwise. """ + return not self.is_rural + + def heat_demand_weighting(self, urban_fraction=None, dist_fraction=None) -> float: + """ + Calculates the heat demand weighting based on urban fraction and distribution fraction. + + Parameters + ---------- + urban_fraction : float, optional + The fraction of urban heat demand. + dist_fraction : float, optional + The fraction of distributed heat demand. + + Returns + ------- + float + The heat demand weighting. + + Raises + ------ + RuntimeError + If the heat system is invalid. + """ + if "rural" in self.value: + return 1 - urban_fraction + elif "urban central" in self.value: + return dist_fraction + elif "urban decentral" in self.value: + return urban_fraction - dist_fraction + else: + raise RuntimeError(f"Invalid heat system: {self}") + + def heat_pump_costs_name(self, heat_source: str) -> str: + """ + Generates the name for the heat pump costs based on the heat source. + + Parameters + ---------- + heat_source : str + The heat source. + + Returns + ------- + str + The name for the heat pump costs. + """ + return f"{self.central_or_decentral} {heat_source}-sourced heat pump" + + diff --git a/scripts/enums/HeatSystemType.py b/scripts/enums/HeatSystemType.py new file mode 100644 index 000000000..6847965da --- /dev/null +++ b/scripts/enums/HeatSystemType.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# +# SPDX-License-Identifier: MIT + +from enum import Enum + +class HeatSystemType(Enum): + """ + Enumeration representing different types of heat systems. + """ + + URBAN_CENTRAL = "urban central" + URBAN_DECENTRAL = "urban decentral" + RURAL = "rural" + + def __str__(self) -> str: + """ + Returns the string representation of the heat system type. + + Returns: + str: The string representation of the heat system type. + """ + return self.value + + @property + def is_central(self) -> bool: + """ + Returns whether the heat system type is central. + + Returns: + bool: True if the heat system type is central, False otherwise. + """ + return self == HeatSystemType.URBAN_CENTRAL + diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index c15d81675..99598f45f 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -22,7 +22,9 @@ set_scenario_config, update_config_from_wildcards, ) -from _entities import HeatSystem, HeatSector +from scripts.enums.HeatSystem import HeatSystem +from scripts.enums.HeatSystemType import HeatSystemType +from scripts.enums.HeatSector import HeatSector from add_electricity import calculate_annuity, sanitize_carriers, sanitize_locations from build_energy_totals import ( build_co2_totals, From 6b924ecfb0088e1100df0edadedbebcd98d917a5 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 2 Aug 2024 15:15:09 +0000 Subject: [PATCH 44/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- rules/build_sector.smk | 2 +- scripts/build_cop_profiles/run.py | 9 +++-- scripts/enums/HeatSector.py | 3 +- scripts/enums/HeatSystem.py | 35 +++++++++++------- scripts/enums/HeatSystemType.py | 4 +- scripts/prepare_sector_network.py | 61 +++++++++++++++++++++++-------- 6 files changed, 78 insertions(+), 36 deletions(-) diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 34477f5b4..5916aa02b 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -965,7 +965,7 @@ rule prepare_sector_network: emissions_scope=config_provider("energy", "emissions"), RDIR=RDIR, heat_pump_sources=config_provider("sector", "heat_pump_sources"), - heat_systems=config_provider("sector", "heat_systems") + heat_systems=config_provider("sector", "heat_systems"), input: unpack(input_profile_offwind), **rules.cluster_gas_network.output, diff --git a/scripts/build_cop_profiles/run.py b/scripts/build_cop_profiles/run.py index 776ed289a..6a4a00618 100644 --- a/scripts/build_cop_profiles/run.py +++ b/scripts/build_cop_profiles/run.py @@ -7,11 +7,15 @@ import pandas as pd import xarray as xr from _helpers import set_scenario_config -import sys; sys.path.append("..") -from scripts.enums.HeatSystemType import HeatSystemType from CentralHeatingCopApproximator import CentralHeatingCopApproximator from DecentralHeatingCopApproximator import DecentralHeatingCopApproximator +from scripts.enums.HeatSystemType import HeatSystemType + +import sys + +sys.path.append("..") + def get_cop( heat_system_type: str, @@ -52,7 +56,6 @@ def get_cop( ).approximate_cop() - if __name__ == "__main__": if "snakemake" not in globals(): from _helpers import mock_snakemake diff --git a/scripts/enums/HeatSector.py b/scripts/enums/HeatSector.py index 008a06933..4c763fec1 100644 --- a/scripts/enums/HeatSector.py +++ b/scripts/enums/HeatSector.py @@ -1,7 +1,9 @@ +# -*- coding: utf-8 -*- # SPDX-License-Identifier: MIT from enum import Enum + class HeatSector(Enum): """ Enumeration class representing different heat sectors. @@ -22,4 +24,3 @@ def __str__(self) -> str: str: The string representation of the heat sector. """ return self.value - diff --git a/scripts/enums/HeatSystem.py b/scripts/enums/HeatSystem.py index 042793a6c..608da92fa 100644 --- a/scripts/enums/HeatSystem.py +++ b/scripts/enums/HeatSystem.py @@ -5,8 +5,9 @@ from enum import Enum -from .HeatSystemType import HeatSystemType -from .HeatSector import HeatSector +from scripts.enums.HeatSector import HeatSector +from scripts.enums.HeatSystemType import HeatSystemType + class HeatSystem(Enum): """ @@ -55,7 +56,7 @@ class HeatSystem(Enum): def __init__(self, *args): super().__init__(*args) - + def __str__(self) -> str: """ Returns the string representation of the heat system. @@ -81,7 +82,7 @@ def central_or_decentral(self) -> str: return "central" else: return "decentral" - + @property def system_type(self) -> HeatSystemType: """ @@ -99,7 +100,10 @@ def system_type(self) -> HeatSystemType: """ if self == HeatSystem.URBAN_CENTRAL: return HeatSystemType.URBAN_CENTRAL - elif self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL or self == HeatSystem.SERVICES_URBAN_DECENTRAL: + elif ( + self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL + or self == HeatSystem.SERVICES_URBAN_DECENTRAL + ): return HeatSystemType.URBAN_DECENTRAL elif self == HeatSystem.RESIDENTIAL_RURAL or self == HeatSystem.SERVICES_RURAL: return HeatSystemType.RURAL @@ -127,7 +131,7 @@ def sector(self) -> HeatSector: ): return HeatSector.SERVICES else: - 'tot' + "tot" @property def is_rural(self) -> bool: @@ -143,7 +147,7 @@ def is_rural(self) -> bool: return True else: return False - + @property def is_urban_decentral(self) -> bool: """ @@ -154,7 +158,10 @@ def is_urban_decentral(self) -> bool: bool True if the heat system is for urban decentralized areas, False otherwise. """ - if self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL or self == HeatSystem.SERVICES_URBAN_DECENTRAL: + if ( + self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL + or self == HeatSystem.SERVICES_URBAN_DECENTRAL + ): return True else: return False @@ -166,12 +173,14 @@ def is_urban(self) -> bool: Returns ------- - bool True if the heat system is for urban areas, False otherwise. """ + bool True if the heat system is for urban areas, False otherwise. + """ return not self.is_rural - + def heat_demand_weighting(self, urban_fraction=None, dist_fraction=None) -> float: """ - Calculates the heat demand weighting based on urban fraction and distribution fraction. + Calculates the heat demand weighting based on urban fraction and + distribution fraction. Parameters ---------- @@ -198,7 +207,7 @@ def heat_demand_weighting(self, urban_fraction=None, dist_fraction=None) -> floa return urban_fraction - dist_fraction else: raise RuntimeError(f"Invalid heat system: {self}") - + def heat_pump_costs_name(self, heat_source: str) -> str: """ Generates the name for the heat pump costs based on the heat source. @@ -214,5 +223,3 @@ def heat_pump_costs_name(self, heat_source: str) -> str: The name for the heat pump costs. """ return f"{self.central_or_decentral} {heat_source}-sourced heat pump" - - diff --git a/scripts/enums/HeatSystemType.py b/scripts/enums/HeatSystemType.py index 6847965da..5bd1bee32 100644 --- a/scripts/enums/HeatSystemType.py +++ b/scripts/enums/HeatSystemType.py @@ -5,6 +5,7 @@ from enum import Enum + class HeatSystemType(Enum): """ Enumeration representing different types of heat systems. @@ -22,7 +23,7 @@ def __str__(self) -> str: str: The string representation of the heat system type. """ return self.value - + @property def is_central(self) -> bool: """ @@ -32,4 +33,3 @@ def is_central(self) -> bool: bool: True if the heat system type is central, False otherwise. """ return self == HeatSystemType.URBAN_CENTRAL - diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index cd3c2beb9..88748dcc6 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -22,9 +22,6 @@ set_scenario_config, update_config_from_wildcards, ) -from scripts.enums.HeatSystem import HeatSystem -from scripts.enums.HeatSystemType import HeatSystemType -from scripts.enums.HeatSector import HeatSector from add_electricity import calculate_annuity, sanitize_carriers, sanitize_locations from build_energy_totals import ( build_co2_totals, @@ -40,6 +37,10 @@ from pypsa.io import import_components_from_dataframe from scipy.stats import beta +from scripts.enums.HeatSector import HeatSector +from scripts.enums.HeatSystem import HeatSystem +from scripts.enums.HeatSystemType import HeatSystemType + spatial = SimpleNamespace() logger = logging.getLogger(__name__) @@ -1833,7 +1834,11 @@ def add_heat(n, costs): solar_thermal = options["solar_cf_correction"] * solar_thermal / 1e3 cop = xr.open_dataarray(snakemake.input.cop_profiles) - for heat_system in HeatSystem: #this loops through all heat systems defined in _entities.HeatSystem + for ( + heat_system + ) in ( + HeatSystem + ): # this loops through all heat systems defined in _entities.HeatSystem if heat_system == HeatSystem.URBAN_CENTRAL: nodes = dist_fraction.index[dist_fraction > 0] @@ -1864,17 +1869,23 @@ def add_heat(n, costs): ) ## Add heat load - factor = heat_system.heat_demand_weighting(urban_fraction=urban_fraction[nodes], dist_fraction=dist_fraction[nodes]) + factor = heat_system.heat_demand_weighting( + urban_fraction=urban_fraction[nodes], dist_fraction=dist_fraction[nodes] + ) if not heat_system == HeatSystem.URBAN_CENTRAL: heat_load = ( - heat_demand[[heat_system.sector.value + " water", heat_system.sector.value + " space"]] + heat_demand[ + [ + heat_system.sector.value + " water", + heat_system.sector.value + " space", + ] + ] .T.groupby(level=1) .sum() .T[nodes] .multiply(factor) ) - if heat_system == HeatSystem.URBAN_CENTRAL: heat_load = ( heat_demand.T.groupby(level=1) @@ -1895,10 +1906,16 @@ def add_heat(n, costs): ) ## Add heat pumps - for heat_source in snakemake.params.heat_pump_sources[heat_system.system_type.value]: + for heat_source in snakemake.params.heat_pump_sources[ + heat_system.system_type.value + ]: costs_name = heat_system.heat_pump_costs_name(heat_source) efficiency = ( - cop.sel(heat_system=heat_system.system_type.value, heat_source=heat_source, name=nodes) + cop.sel( + heat_system=heat_system.system_type.value, + heat_source=heat_source, + name=nodes, + ) .to_pandas() .reindex(index=n.snapshots) if options["time_dep_hp_cop"] @@ -1951,7 +1968,9 @@ def add_heat(n, costs): p_nom_extendable=True, ) - tes_time_constant_days = options["tes_tau"][heat_system.central_or_decentral] + tes_time_constant_days = options["tes_tau"][ + heat_system.central_or_decentral + ] n.madd( "Store", @@ -1961,8 +1980,12 @@ def add_heat(n, costs): e_nom_extendable=True, carrier=f"{heat_system} water tanks", standing_loss=1 - np.exp(-1 / 24 / tes_time_constant_days), - capital_cost=costs.at[heat_system.central_or_decentral + " water tank storage", "fixed"], - lifetime=costs.at[heat_system.central_or_decentral + " water tank storage", "lifetime"], + capital_cost=costs.at[ + heat_system.central_or_decentral + " water tank storage", "fixed" + ], + lifetime=costs.at[ + heat_system.central_or_decentral + " water tank storage", "lifetime" + ], ) if options["resistive_heaters"]: @@ -2011,10 +2034,14 @@ def add_heat(n, costs): bus=nodes + f" {heat_system} heat", carrier=f"{heat_system} solar thermal", p_nom_extendable=True, - capital_cost=costs.at[heat_system.central_or_decentral + " solar thermal", "fixed"] + capital_cost=costs.at[ + heat_system.central_or_decentral + " solar thermal", "fixed" + ] * overdim_factor, p_max_pu=solar_thermal[nodes], - lifetime=costs.at[heat_system.central_or_decentral + " solar thermal", "lifetime"], + lifetime=costs.at[ + heat_system.central_or_decentral + " solar thermal", "lifetime" + ], ) if options["chp"] and heat_system == HeatSystem.URBAN_CENTRAL: @@ -2074,7 +2101,11 @@ def add_heat(n, costs): lifetime=costs.at["central gas CHP", "lifetime"], ) - if options["chp"] and options["micro_chp"] and heat_system.value != "urban central": + if ( + options["chp"] + and options["micro_chp"] + and heat_system.value != "urban central" + ): n.madd( "Link", nodes + f" {heat_system} micro gas CHP", From a990a898ef3535000204fbc1508f88b69b3c2896 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Fri, 2 Aug 2024 17:27:16 +0200 Subject: [PATCH 45/58] update naming in add_existing_baseyear --- scripts/add_existing_baseyear.py | 43 +++++++++++++++++--------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index 610523e99..6edc7b7bc 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -23,6 +23,9 @@ ) from add_electricity import sanitize_carriers from prepare_sector_network import cluster_heat_buses, define_spatial, prepare_costs +from scripts.enums.HeatSystem import HeatSystem +from scripts.enums.HeatSystemType import HeatSystemType +from scripts.enums.HeatSector import HeatSector logger = logging.getLogger(__name__) cc = coco.CountryConverter() @@ -443,23 +446,23 @@ def add_heating_capacities_installed_before_baseyear( logger.debug(f"Adding heating capacities installed before {baseyear}") for heat_system in existing_heating.columns.get_level_values(0).unique(): - system_type = "central" if heat_system == "urban central" else "decentral" + heat_system = HeatSystem(heat_system) nodes = pd.Index( n.buses.location[n.buses.index.str.contains(f"{heat_system} heat")] ) - if (system_type != "central") and options["electricity_distribution_grid"]: + if (not heat_system.is_central) and options["electricity_distribution_grid"]: nodes_elec = nodes + " low voltage" else: nodes_elec = nodes # Add heat pumps - heat_source = snakemake.params.heat_pump_sources[system_type] - costs_name = f"{system_type} {heat_source}-sourced heat pump" + heat_source = snakemake.params.heat_pump_sources[heat_system.system_type.value] + costs_name = f"{heat_system.system_type} {heat_source}-sourced heat pump" efficiency = ( - cop.sel(heat_system=system_type, heat_source=heat_source, name=nodes) + cop.sel(heat_system=heat_system.system_type.value, heat_source=heat_source, name=nodes) .to_pandas() .reindex(index=n.snapshots) if options["time_dep_hp_cop"] @@ -496,13 +499,13 @@ def add_heating_capacities_installed_before_baseyear( nodes, suffix=f" {heat_system} {heat_source} heat pump-{grouping_year}", bus0=nodes_elec, - bus1=nodes + " " + heat_system + " heat", + bus1=nodes + " " + heat_system.value + " heat", carrier=f"{heat_system} {heat_source} heat pump", efficiency=efficiency, capital_cost=costs.at[costs_name, "efficiency"] * costs.at[costs_name, "fixed"], p_nom=existing_heating.loc[ - nodes, (heat_system, f"{heat_source} heat pump") + nodes, (heat_system.value, f"{heat_source} heat pump") ] * ratio / costs.at[costs_name, "efficiency"], @@ -516,20 +519,20 @@ def add_heating_capacities_installed_before_baseyear( nodes, suffix=f" {heat_system} resistive heater-{grouping_year}", bus0=nodes_elec, - bus1=nodes + " " + heat_system + " heat", + bus1=nodes + " " + heat_system.value + " heat", carrier=heat_system + " resistive heater", - efficiency=costs.at[f"{system_type} resistive heater", "efficiency"], + efficiency=costs.at[f"{heat_system.system_type} resistive heater", "efficiency"], capital_cost=( - costs.at[f"{system_type} resistive heater", "efficiency"] - * costs.at[f"{system_type} resistive heater", "fixed"] + costs.at[f"{heat_system.system_type} resistive heater", "efficiency"] + * costs.at[f"{heat_system.system_type} resistive heater", "fixed"] ), p_nom=( - existing_heating.loc[nodes, (heat_system, "resistive heater")] + existing_heating.loc[nodes, (heat_system.value, "resistive heater")] * ratio - / costs.at[f"{system_type} resistive heater", "efficiency"] + / costs.at[f"{heat_system.system_type} resistive heater", "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{system_type} resistive heater", "lifetime"], + lifetime=costs.at[f"{heat_system.system_type} resistive heater", "lifetime"], ) n.madd( @@ -540,19 +543,19 @@ def add_heating_capacities_installed_before_baseyear( bus1=nodes + " " + heat_system + " heat", bus2="co2 atmosphere", carrier=heat_system + " gas boiler", - efficiency=costs.at[f"{system_type} gas boiler", "efficiency"], + efficiency=costs.at[f"{heat_system.system_type} gas boiler", "efficiency"], efficiency2=costs.at["gas", "CO2 intensity"], capital_cost=( - costs.at[f"{system_type} gas boiler", "efficiency"] - * costs.at[f"{system_type} gas boiler", "fixed"] + costs.at[f"{heat_system.system_type} gas boiler", "efficiency"] + * costs.at[f"{heat_system.system_type} gas boiler", "fixed"] ), p_nom=( existing_heating.loc[nodes, (heat_system, "gas boiler")] * ratio - / costs.at[f"{system_type} gas boiler", "efficiency"] + / costs.at[f"{heat_system.system_type} gas boiler", "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{system_type} gas boiler", "lifetime"], + lifetime=costs.at[f"{heat_system.system_type} gas boiler", "lifetime"], ) n.madd( @@ -573,7 +576,7 @@ def add_heating_capacities_installed_before_baseyear( / costs.at["decentral oil boiler", "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{system_type} gas boiler", "lifetime"], + lifetime=costs.at[f"{heat_system.system_type} gas boiler", "lifetime"], ) # delete links with p_nom=nan corresponding to extra nodes in country From 0259e066e4a5688d002e47ec9b34bc9e45ae437d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 2 Aug 2024 15:28:09 +0000 Subject: [PATCH 46/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- scripts/add_existing_baseyear.py | 29 ++++++++++++++++++++++------- scripts/build_cop_profiles/run.py | 4 ++-- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index 6edc7b7bc..bf5a8dc35 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -23,9 +23,10 @@ ) from add_electricity import sanitize_carriers from prepare_sector_network import cluster_heat_buses, define_spatial, prepare_costs + +from scripts.enums.HeatSector import HeatSector from scripts.enums.HeatSystem import HeatSystem from scripts.enums.HeatSystemType import HeatSystemType -from scripts.enums.HeatSector import HeatSector logger = logging.getLogger(__name__) cc = coco.CountryConverter() @@ -462,7 +463,11 @@ def add_heating_capacities_installed_before_baseyear( costs_name = f"{heat_system.system_type} {heat_source}-sourced heat pump" efficiency = ( - cop.sel(heat_system=heat_system.system_type.value, heat_source=heat_source, name=nodes) + cop.sel( + heat_system=heat_system.system_type.value, + heat_source=heat_source, + name=nodes, + ) .to_pandas() .reindex(index=n.snapshots) if options["time_dep_hp_cop"] @@ -521,18 +526,26 @@ def add_heating_capacities_installed_before_baseyear( bus0=nodes_elec, bus1=nodes + " " + heat_system.value + " heat", carrier=heat_system + " resistive heater", - efficiency=costs.at[f"{heat_system.system_type} resistive heater", "efficiency"], + efficiency=costs.at[ + f"{heat_system.system_type} resistive heater", "efficiency" + ], capital_cost=( - costs.at[f"{heat_system.system_type} resistive heater", "efficiency"] + costs.at[ + f"{heat_system.system_type} resistive heater", "efficiency" + ] * costs.at[f"{heat_system.system_type} resistive heater", "fixed"] ), p_nom=( existing_heating.loc[nodes, (heat_system.value, "resistive heater")] * ratio - / costs.at[f"{heat_system.system_type} resistive heater", "efficiency"] + / costs.at[ + f"{heat_system.system_type} resistive heater", "efficiency" + ] ), build_year=int(grouping_year), - lifetime=costs.at[f"{heat_system.system_type} resistive heater", "lifetime"], + lifetime=costs.at[ + f"{heat_system.system_type} resistive heater", "lifetime" + ], ) n.madd( @@ -543,7 +556,9 @@ def add_heating_capacities_installed_before_baseyear( bus1=nodes + " " + heat_system + " heat", bus2="co2 atmosphere", carrier=heat_system + " gas boiler", - efficiency=costs.at[f"{heat_system.system_type} gas boiler", "efficiency"], + efficiency=costs.at[ + f"{heat_system.system_type} gas boiler", "efficiency" + ], efficiency2=costs.at["gas", "CO2 intensity"], capital_cost=( costs.at[f"{heat_system.system_type} gas boiler", "efficiency"] diff --git a/scripts/build_cop_profiles/run.py b/scripts/build_cop_profiles/run.py index 6a4a00618..7e405a424 100644 --- a/scripts/build_cop_profiles/run.py +++ b/scripts/build_cop_profiles/run.py @@ -3,6 +3,8 @@ # # SPDX-License-Identifier: MIT +import sys + import numpy as np import pandas as pd import xarray as xr @@ -12,8 +14,6 @@ from scripts.enums.HeatSystemType import HeatSystemType -import sys - sys.path.append("..") From 5362c376966bdb7b996040ae6850f9154c634e27 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 5 Aug 2024 11:27:52 +0200 Subject: [PATCH 47/58] update myopic mode to heat system declarations --- rules/solve_myopic.smk | 14 +-- scripts/add_existing_baseyear.py | 172 +++++++++++++----------------- scripts/enums/HeatSystem.py | 40 ++++++- scripts/prepare_sector_network.py | 5 +- 4 files changed, 118 insertions(+), 113 deletions(-) diff --git a/rules/solve_myopic.smk b/rules/solve_myopic.smk index 09f25b241..8d7fa2841 100644 --- a/rules/solve_myopic.smk +++ b/rules/solve_myopic.smk @@ -69,6 +69,7 @@ rule add_brownfield: snapshots=config_provider("snapshots"), drop_leap_day=config_provider("enable", "drop_leap_day"), carriers=config_provider("electricity", "renewable_carriers"), + heat_pump_sources=config_provider("sector", "heat_pump_sources"), input: unpack(input_profile_tech_brownfield), simplify_busmap=resources("busmap_elec_s{simpl}.csv"), @@ -77,18 +78,7 @@ rule add_brownfield: + "prenetworks/elec_s{simpl}_{clusters}_l{ll}_{opts}_{sector_opts}_{planning_horizons}.nc", network_p=solved_previous_horizon, #solved network at previous time step costs=resources("costs_{planning_horizons}.csv"), - cop_soil_decentral_heating=resources( - "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_air_decentral_heating=resources( - "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_air_central_heating=resources( - "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_soil_central_heating=resources( - "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" - ), + cop_profiles=resources("cop_profiles_elec_s{simpl}_{clusters}.nc"), output: RESULTS + "prenetworks-brownfield/elec_s{simpl}_{clusters}_l{ll}_{opts}_{sector_opts}_{planning_horizons}.nc", diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index 6edc7b7bc..1c6209893 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -438,8 +438,8 @@ def add_heating_capacities_installed_before_baseyear( currently assumed heating capacities split between residential and services proportional to heating load in both 50% capacities in rural buses 50% in urban buses - cop: dict - Dictionary with time-dependent coefficients of performance (COPs) for air and ground heat pumps as values and keys "air decentral", "ground decentral", "air central", "ground central" + cop: xr.DataArray + DataArray with time-dependent coefficients of performance (COPs) heat pumps. Coordinates are heat sources (see config), heat system types (see :file:`scripts/enums/HeatSystemType.py`), nodes and snapshots. time_dep_hp_cop: bool If True, time-dependent (dynamic) COPs are used for heat pumps """ @@ -452,66 +452,65 @@ def add_heating_capacities_installed_before_baseyear( n.buses.location[n.buses.index.str.contains(f"{heat_system} heat")] ) - if (not heat_system.is_central) and options["electricity_distribution_grid"]: + if (not heat_system == HeatSystem.URBAN_CENTRAL) and options["electricity_distribution_grid"]: nodes_elec = nodes + " low voltage" else: nodes_elec = nodes - # Add heat pumps - heat_source = snakemake.params.heat_pump_sources[heat_system.system_type.value] - costs_name = f"{heat_system.system_type} {heat_source}-sourced heat pump" - - efficiency = ( - cop.sel(heat_system=heat_system.system_type.value, heat_source=heat_source, name=nodes) - .to_pandas() - .reindex(index=n.snapshots) - if options["time_dep_hp_cop"] - else costs.at[costs_name, "efficiency"] - ) - - too_large_grouping_years = [gy for gy in grouping_years if gy >= int(baseyear)] - if too_large_grouping_years: - logger.warning( - f"Grouping years >= baseyear are ignored. Dropping {too_large_grouping_years}." + too_large_grouping_years = [gy for gy in grouping_years if gy >= int(baseyear)] + if too_large_grouping_years: + logger.warning( + f"Grouping years >= baseyear are ignored. Dropping {too_large_grouping_years}." + ) + valid_grouping_years = pd.Series( + [ + int(grouping_year) + for grouping_year in grouping_years + if int(grouping_year) + default_lifetime > int(baseyear) + and int(grouping_year) < int(baseyear) + ] ) - valid_grouping_years = pd.Series( - [ - int(grouping_year) - for grouping_year in grouping_years - if int(grouping_year) + default_lifetime > int(baseyear) - and int(grouping_year) < int(baseyear) - ] - ) - assert valid_grouping_years.is_monotonic_increasing + assert valid_grouping_years.is_monotonic_increasing - # get number of years of each interval - _years = valid_grouping_years.diff() - # Fill NA from .diff() with value for the first interval - _years[0] = valid_grouping_years[0] - baseyear + default_lifetime - # Installation is assumed to be linear for the past - ratios = _years / _years.sum() + # get number of years of each interval + _years = valid_grouping_years.diff() + # Fill NA from .diff() with value for the first interval + _years[0] = valid_grouping_years[0] - baseyear + default_lifetime + # Installation is assumed to be linear for the past + ratios = _years / _years.sum() for ratio, grouping_year in zip(ratios, valid_grouping_years): + # Add heat pumps + for heat_source in snakemake.params.heat_pump_sources[heat_system.system_type.value]: + costs_name = heat_system.heat_pump_costs_name(heat_source) + + efficiency = ( + cop.sel(heat_system=heat_system.system_type.value, heat_source=heat_source, name=nodes) + .to_pandas() + .reindex(index=n.snapshots) + if options["time_dep_hp_cop"] + else costs.at[costs_name, "efficiency"] + ) - n.madd( - "Link", - nodes, - suffix=f" {heat_system} {heat_source} heat pump-{grouping_year}", - bus0=nodes_elec, - bus1=nodes + " " + heat_system.value + " heat", - carrier=f"{heat_system} {heat_source} heat pump", - efficiency=efficiency, - capital_cost=costs.at[costs_name, "efficiency"] - * costs.at[costs_name, "fixed"], - p_nom=existing_heating.loc[ - nodes, (heat_system.value, f"{heat_source} heat pump") - ] - * ratio - / costs.at[costs_name, "efficiency"], - build_year=int(grouping_year), - lifetime=costs.at[costs_name, "lifetime"], - ) + n.madd( + "Link", + nodes, + suffix=f" {heat_system} {heat_source} heat pump-{grouping_year}", + bus0=nodes_elec, + bus1=nodes + " " + heat_system.value + " heat", + carrier=f"{heat_system} {heat_source} heat pump", + efficiency=efficiency, + capital_cost=costs.at[costs_name, "efficiency"] + * costs.at[costs_name, "fixed"], + p_nom=existing_heating.loc[ + nodes, (heat_system.value, f"{heat_source} heat pump") + ] + * ratio + / costs.at[costs_name, "efficiency"], + build_year=int(grouping_year), + lifetime=costs.at[costs_name, "lifetime"], + ) # add resistive heater, gas boilers and oil boilers n.madd( @@ -520,42 +519,42 @@ def add_heating_capacities_installed_before_baseyear( suffix=f" {heat_system} resistive heater-{grouping_year}", bus0=nodes_elec, bus1=nodes + " " + heat_system.value + " heat", - carrier=heat_system + " resistive heater", - efficiency=costs.at[f"{heat_system.system_type} resistive heater", "efficiency"], + carrier=heat_system.value + " resistive heater", + efficiency=costs.at[heat_system.resistive_heater_costs_name, "efficiency"], capital_cost=( - costs.at[f"{heat_system.system_type} resistive heater", "efficiency"] - * costs.at[f"{heat_system.system_type} resistive heater", "fixed"] + costs.at[heat_system.resistive_heater_costs_name, "efficiency"] + * costs.at[heat_system.resistive_heater_costs_name, "fixed"] ), p_nom=( existing_heating.loc[nodes, (heat_system.value, "resistive heater")] * ratio - / costs.at[f"{heat_system.system_type} resistive heater", "efficiency"] + / costs.at[heat_system.resistive_heater_costs_name, "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{heat_system.system_type} resistive heater", "lifetime"], + lifetime=costs.at[heat_system.resistive_heater_costs_name, "lifetime"], ) n.madd( "Link", nodes, - suffix=f" {heat_system} gas boiler-{grouping_year}", + suffix=f"{heat_system} gas boiler-{grouping_year}", bus0="EU gas" if "EU gas" in spatial.gas.nodes else nodes + " gas", - bus1=nodes + " " + heat_system + " heat", + bus1=f"{nodes} {heat_system} heat", bus2="co2 atmosphere", - carrier=heat_system + " gas boiler", - efficiency=costs.at[f"{heat_system.system_type} gas boiler", "efficiency"], + carrier=heat_system.value + " gas boiler", + efficiency=costs.at[heat_system.gas_boiler_costs_name, "efficiency"], efficiency2=costs.at["gas", "CO2 intensity"], capital_cost=( - costs.at[f"{heat_system.system_type} gas boiler", "efficiency"] - * costs.at[f"{heat_system.system_type} gas boiler", "fixed"] + costs.at[heat_system.gas_boiler_costs_name, "efficiency"] + * costs.at[heat_system.gas_boiler_costs_name, "fixed"] ), p_nom=( - existing_heating.loc[nodes, (heat_system, "gas boiler")] + existing_heating.loc[nodes, (heat_system.value, "gas boiler")] * ratio - / costs.at[f"{heat_system.system_type} gas boiler", "efficiency"] + / costs.at[heat_system.gas_boiler_costs_name, "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{heat_system.system_type} gas boiler", "lifetime"], + lifetime=costs.at[heat_system.gas_boiler_costs_name, "lifetime"], ) n.madd( @@ -563,20 +562,20 @@ def add_heating_capacities_installed_before_baseyear( nodes, suffix=f" {heat_system} oil boiler-{grouping_year}", bus0=spatial.oil.nodes, - bus1=nodes + " " + heat_system + " heat", + bus1=f"{nodes} {heat_system} heat", bus2="co2 atmosphere", - carrier=heat_system + " oil boiler", - efficiency=costs.at["decentral oil boiler", "efficiency"], + carrier=heat_system.value + " oil boiler", + efficiency=costs.at[heat_system.oil_boiler_costs_name, "efficiency"], efficiency2=costs.at["oil", "CO2 intensity"], - capital_cost=costs.at["decentral oil boiler", "efficiency"] - * costs.at["decentral oil boiler", "fixed"], + capital_cost=costs.at[heat_system.oil_boiler_costs_name, "efficiency"] + * costs.at[heat_system.oil_boiler_costs_name, "fixed"], p_nom=( - existing_heating.loc[nodes, (heat_system, "oil boiler")] + existing_heating.loc[nodes, (heat_system.value, "oil boiler")] * ratio - / costs.at["decentral oil boiler", "efficiency"] + / costs.at[heat_system.oil_boiler_costs_name, "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{heat_system.system_type} gas boiler", "lifetime"], + lifetime=costs.at[f"{heat_system.central_or_decentral} gas boiler", "lifetime"], ) # delete links with p_nom=nan corresponding to extra nodes in country @@ -651,28 +650,7 @@ def add_heating_capacities_installed_before_baseyear( n=n, baseyear=baseyear, grouping_years=grouping_years_heat, - cop={ - "air decentral": xr.open_dataarray( - snakemake.input.cop_air_decentral_heating - ) - .to_pandas() - .reindex(index=n.snapshots), - "ground decentral": xr.open_dataarray( - snakemake.input.cop_soil_decentral_heating - ) - .to_pandas() - .reindex(index=n.snapshots), - "air central": xr.open_dataarray( - snakemake.input.cop_air_central_heating - ) - .to_pandas() - .reindex(index=n.snapshots), - "ground central": xr.open_dataarray( - snakemake.input.cop_soil_central_heating - ) - .to_pandas() - .reindex(index=n.snapshots), - }, + cop=xr.open_dataarray(snakemake.input.cop_profiles), time_dep_hp_cop=options["time_dep_hp_cop"], costs=costs, default_lifetime=snakemake.params.existing_capacities[ diff --git a/scripts/enums/HeatSystem.py b/scripts/enums/HeatSystem.py index 608da92fa..4b1c11af4 100644 --- a/scripts/enums/HeatSystem.py +++ b/scripts/enums/HeatSystem.py @@ -210,7 +210,7 @@ def heat_demand_weighting(self, urban_fraction=None, dist_fraction=None) -> floa def heat_pump_costs_name(self, heat_source: str) -> str: """ - Generates the name for the heat pump costs based on the heat source. + Generates the name for the heat pump costs based on the heat source and system. Parameters ---------- @@ -223,3 +223,41 @@ def heat_pump_costs_name(self, heat_source: str) -> str: The name for the heat pump costs. """ return f"{self.central_or_decentral} {heat_source}-sourced heat pump" + + @property + def resistive_heater_costs_name(self) -> str: + """ + Generates the name for the resistive heater costs based on the heat system. + + Returns + ------- + str + The name for the heater costs. + """ + return f"{self.central_or_decentral} resistive heater" + + @property + def gas_boiler_costs_name(self) -> str: + """ + Generates the name for the gas boiler costs based on the heat system. + + Returns + ------- + str + The name for the gas boiler costs. + """ + return f"{self.central_or_decentral} gas boiler" + + @property + def oil_boiler_costs_name(self) -> str: + """ + Generates the name for the oil boiler costs based on the heat system. + + Returns + ------- + str + The name for the oil boiler costs. + """ + return "decentral oil boiler" + + diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index 88748dcc6..9ea69dfb4 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1802,7 +1802,7 @@ def build_heat_demand(n): return heat_demand -def add_heat(n, costs): +def add_heat(n, costs, cop): logger.info("Add heat sector") sectors = ["residential", "services"] @@ -1833,7 +1833,6 @@ def add_heat(n, costs): # 1e3 converts from W/m^2 to MW/(1000m^2) = kW/m^2 solar_thermal = options["solar_cf_correction"] * solar_thermal / 1e3 - cop = xr.open_dataarray(snakemake.input.cop_profiles) for ( heat_system ) in ( @@ -4098,7 +4097,7 @@ def add_enhanced_geothermal(n, egs_potentials, egs_overlap, costs): add_land_transport(n, costs) if options["heating"]: - add_heat(n, costs) + add_heat(n=n, costs=costs, cop=xr.open_dataarray(snakemake.input.cop_profiles)) if options["biomass"]: add_biomass(n, costs) From 390085aaad9088942701470ef0a0bd3e46f0fdd2 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 5 Aug 2024 11:35:34 +0200 Subject: [PATCH 48/58] update add_existing_baseyear --- scripts/add_existing_baseyear.py | 53 -------------------------------- 1 file changed, 53 deletions(-) diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index abdd0a8d3..593dfa266 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -458,7 +458,6 @@ def add_heating_capacities_installed_before_baseyear( else: nodes_elec = nodes -<<<<<<< HEAD too_large_grouping_years = [gy for gy in grouping_years if gy >= int(baseyear)] if too_large_grouping_years: logger.warning( @@ -471,28 +470,6 @@ def add_heating_capacities_installed_before_baseyear( if int(grouping_year) + default_lifetime > int(baseyear) and int(grouping_year) < int(baseyear) ] -======= - # Add heat pumps - heat_source = snakemake.params.heat_pump_sources[heat_system.system_type.value] - costs_name = f"{heat_system.system_type} {heat_source}-sourced heat pump" - - efficiency = ( - cop.sel( - heat_system=heat_system.system_type.value, - heat_source=heat_source, - name=nodes, - ) - .to_pandas() - .reindex(index=n.snapshots) - if options["time_dep_hp_cop"] - else costs.at[costs_name, "efficiency"] - ) - - too_large_grouping_years = [gy for gy in grouping_years if gy >= int(baseyear)] - if too_large_grouping_years: - logger.warning( - f"Grouping years >= baseyear are ignored. Dropping {too_large_grouping_years}." ->>>>>>> 0259e066e4a5688d002e47ec9b34bc9e45ae437d ) assert valid_grouping_years.is_monotonic_increasing @@ -543,42 +520,19 @@ def add_heating_capacities_installed_before_baseyear( suffix=f" {heat_system} resistive heater-{grouping_year}", bus0=nodes_elec, bus1=nodes + " " + heat_system.value + " heat", -<<<<<<< HEAD carrier=heat_system.value + " resistive heater", efficiency=costs.at[heat_system.resistive_heater_costs_name, "efficiency"], capital_cost=( costs.at[heat_system.resistive_heater_costs_name, "efficiency"] * costs.at[heat_system.resistive_heater_costs_name, "fixed"] -======= - carrier=heat_system + " resistive heater", - efficiency=costs.at[ - f"{heat_system.system_type} resistive heater", "efficiency" - ], - capital_cost=( - costs.at[ - f"{heat_system.system_type} resistive heater", "efficiency" - ] - * costs.at[f"{heat_system.system_type} resistive heater", "fixed"] ->>>>>>> 0259e066e4a5688d002e47ec9b34bc9e45ae437d ), p_nom=( existing_heating.loc[nodes, (heat_system.value, "resistive heater")] * ratio -<<<<<<< HEAD / costs.at[heat_system.resistive_heater_costs_name, "efficiency"] ), build_year=int(grouping_year), lifetime=costs.at[heat_system.resistive_heater_costs_name, "lifetime"], -======= - / costs.at[ - f"{heat_system.system_type} resistive heater", "efficiency" - ] - ), - build_year=int(grouping_year), - lifetime=costs.at[ - f"{heat_system.system_type} resistive heater", "lifetime" - ], ->>>>>>> 0259e066e4a5688d002e47ec9b34bc9e45ae437d ) n.madd( @@ -588,15 +542,8 @@ def add_heating_capacities_installed_before_baseyear( bus0="EU gas" if "EU gas" in spatial.gas.nodes else nodes + " gas", bus1=f"{nodes} {heat_system} heat", bus2="co2 atmosphere", -<<<<<<< HEAD carrier=heat_system.value + " gas boiler", efficiency=costs.at[heat_system.gas_boiler_costs_name, "efficiency"], -======= - carrier=heat_system + " gas boiler", - efficiency=costs.at[ - f"{heat_system.system_type} gas boiler", "efficiency" - ], ->>>>>>> 0259e066e4a5688d002e47ec9b34bc9e45ae437d efficiency2=costs.at["gas", "CO2 intensity"], capital_cost=( costs.at[heat_system.gas_boiler_costs_name, "efficiency"] From 61bb225a34fadc2eda0eb35c81b33efd86bda296 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 5 Aug 2024 09:42:42 +0000 Subject: [PATCH 49/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- scripts/add_existing_baseyear.py | 26 ++++++++++++++++++++------ scripts/enums/HeatSystem.py | 8 ++++---- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index 593dfa266..15c57f32b 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -453,12 +453,16 @@ def add_heating_capacities_installed_before_baseyear( n.buses.location[n.buses.index.str.contains(f"{heat_system} heat")] ) - if (not heat_system == HeatSystem.URBAN_CENTRAL) and options["electricity_distribution_grid"]: + if (not heat_system == HeatSystem.URBAN_CENTRAL) and options[ + "electricity_distribution_grid" + ]: nodes_elec = nodes + " low voltage" else: nodes_elec = nodes - too_large_grouping_years = [gy for gy in grouping_years if gy >= int(baseyear)] + too_large_grouping_years = [ + gy for gy in grouping_years if gy >= int(baseyear) + ] if too_large_grouping_years: logger.warning( f"Grouping years >= baseyear are ignored. Dropping {too_large_grouping_years}." @@ -483,11 +487,17 @@ def add_heating_capacities_installed_before_baseyear( for ratio, grouping_year in zip(ratios, valid_grouping_years): # Add heat pumps - for heat_source in snakemake.params.heat_pump_sources[heat_system.system_type.value]: + for heat_source in snakemake.params.heat_pump_sources[ + heat_system.system_type.value + ]: costs_name = heat_system.heat_pump_costs_name(heat_source) efficiency = ( - cop.sel(heat_system=heat_system.system_type.value, heat_source=heat_source, name=nodes) + cop.sel( + heat_system=heat_system.system_type.value, + heat_source=heat_source, + name=nodes, + ) .to_pandas() .reindex(index=n.snapshots) if options["time_dep_hp_cop"] @@ -521,7 +531,9 @@ def add_heating_capacities_installed_before_baseyear( bus0=nodes_elec, bus1=nodes + " " + heat_system.value + " heat", carrier=heat_system.value + " resistive heater", - efficiency=costs.at[heat_system.resistive_heater_costs_name, "efficiency"], + efficiency=costs.at[ + heat_system.resistive_heater_costs_name, "efficiency" + ], capital_cost=( costs.at[heat_system.resistive_heater_costs_name, "efficiency"] * costs.at[heat_system.resistive_heater_costs_name, "fixed"] @@ -576,7 +588,9 @@ def add_heating_capacities_installed_before_baseyear( / costs.at[heat_system.oil_boiler_costs_name, "efficiency"] ), build_year=int(grouping_year), - lifetime=costs.at[f"{heat_system.central_or_decentral} gas boiler", "lifetime"], + lifetime=costs.at[ + f"{heat_system.central_or_decentral} gas boiler", "lifetime" + ], ) # delete links with p_nom=nan corresponding to extra nodes in country diff --git a/scripts/enums/HeatSystem.py b/scripts/enums/HeatSystem.py index 4b1c11af4..75cd3344e 100644 --- a/scripts/enums/HeatSystem.py +++ b/scripts/enums/HeatSystem.py @@ -210,7 +210,8 @@ def heat_demand_weighting(self, urban_fraction=None, dist_fraction=None) -> floa def heat_pump_costs_name(self, heat_source: str) -> str: """ - Generates the name for the heat pump costs based on the heat source and system. + Generates the name for the heat pump costs based on the heat source and + system. Parameters ---------- @@ -227,7 +228,8 @@ def heat_pump_costs_name(self, heat_source: str) -> str: @property def resistive_heater_costs_name(self) -> str: """ - Generates the name for the resistive heater costs based on the heat system. + Generates the name for the resistive heater costs based on the heat + system. Returns ------- @@ -259,5 +261,3 @@ def oil_boiler_costs_name(self) -> str: The name for the oil boiler costs. """ return "decentral oil boiler" - - From f593983ea04bb7e44c6fdb2699c67d8505ca52bf Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 5 Aug 2024 11:45:12 +0200 Subject: [PATCH 50/58] update copyright notic in heatSector --- scripts/enums/HeatSector.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/enums/HeatSector.py b/scripts/enums/HeatSector.py index 4c763fec1..03bcaffdb 100644 --- a/scripts/enums/HeatSector.py +++ b/scripts/enums/HeatSector.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# # SPDX-License-Identifier: MIT from enum import Enum From 268ff9378375e8618130833274a772e27041e2b4 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 5 Aug 2024 12:07:24 +0200 Subject: [PATCH 51/58] fix boiler buses for existing heating --- scripts/add_existing_baseyear.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index 15c57f32b..d0f85a1a2 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -552,7 +552,7 @@ def add_heating_capacities_installed_before_baseyear( nodes, suffix=f"{heat_system} gas boiler-{grouping_year}", bus0="EU gas" if "EU gas" in spatial.gas.nodes else nodes + " gas", - bus1=f"{nodes} {heat_system} heat", + bus1=nodes + " " + heat_system.value + " heat", bus2="co2 atmosphere", carrier=heat_system.value + " gas boiler", efficiency=costs.at[heat_system.gas_boiler_costs_name, "efficiency"], @@ -575,7 +575,7 @@ def add_heating_capacities_installed_before_baseyear( nodes, suffix=f" {heat_system} oil boiler-{grouping_year}", bus0=spatial.oil.nodes, - bus1=f"{nodes} {heat_system} heat", + bus1=nodes + " " + heat_system.value + " heat", bus2="co2 atmosphere", carrier=heat_system.value + " oil boiler", efficiency=costs.at[heat_system.oil_boiler_costs_name, "efficiency"], From ea7fc92546ce05e9fbc4e36f2562b47e3a107859 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 5 Aug 2024 12:19:43 +0200 Subject: [PATCH 52/58] update solve_perfect.add_existing_baseyear input/params --- rules/solve_perfect.smk | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rules/solve_perfect.smk b/rules/solve_perfect.smk index d2ea1a16a..057f7ee2a 100644 --- a/rules/solve_perfect.smk +++ b/rules/solve_perfect.smk @@ -7,6 +7,7 @@ rule add_existing_baseyear: sector=config_provider("sector"), existing_capacities=config_provider("existing_capacities"), costs=config_provider("costs"), + heat_pump_sources=config_provider("sector", "heat_pump_sources"), input: network=RESULTS + "prenetworks/elec_s{simpl}_{clusters}_l{ll}_{opts}_{sector_opts}_{planning_horizons}.nc", @@ -19,6 +20,7 @@ rule add_existing_baseyear: config_provider("scenario", "planning_horizons", 0)(w) ) ), + cop_profiles=resources("cop_profiles_elec_s{simpl}_{clusters}.nc"), cop_soil_decentral_heating=resources( "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" ), From 93d60a2927bf7c5cf9872d8fd123319503f8d8c2 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 5 Aug 2024 12:26:26 +0200 Subject: [PATCH 53/58] remove obsolote cop inputs from solve_perfect.add_existing_baseyear --- rules/solve_perfect.smk | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/rules/solve_perfect.smk b/rules/solve_perfect.smk index 057f7ee2a..a06c6dfa1 100644 --- a/rules/solve_perfect.smk +++ b/rules/solve_perfect.smk @@ -21,18 +21,6 @@ rule add_existing_baseyear: ) ), cop_profiles=resources("cop_profiles_elec_s{simpl}_{clusters}.nc"), - cop_soil_decentral_heating=resources( - "cop_soil_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_air_decentral_heating=resources( - "cop_air_decentral_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_air_central_heating=resources( - "cop_air_central_heating_elec_s{simpl}_{clusters}.nc" - ), - cop_soil_central_heating=resources( - "cop_soil_central_heating_elec_s{simpl}_{clusters}.nc" - ), existing_heating_distribution=resources( "existing_heating_distribution_elec_s{simpl}_{clusters}_{planning_horizons}.csv" ), From 4fe8eeeffab8191ff2fb69f9f5a4320c4bd3ab2d Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 5 Aug 2024 15:07:46 +0200 Subject: [PATCH 54/58] rename "enums" to "definitions" and write modules in snake case --- scripts/definitions/heat_sector.py | 28 +++ scripts/definitions/heat_system.py | 263 ++++++++++++++++++++++++ scripts/definitions/heat_system_type.py | 35 ++++ 3 files changed, 326 insertions(+) create mode 100644 scripts/definitions/heat_sector.py create mode 100644 scripts/definitions/heat_system.py create mode 100644 scripts/definitions/heat_system_type.py diff --git a/scripts/definitions/heat_sector.py b/scripts/definitions/heat_sector.py new file mode 100644 index 000000000..03bcaffdb --- /dev/null +++ b/scripts/definitions/heat_sector.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# +# SPDX-License-Identifier: MIT + +from enum import Enum + + +class HeatSector(Enum): + """ + Enumeration class representing different heat sectors. + + Attributes: + RESIDENTIAL (str): Represents the residential heat sector. + SERVICES (str): Represents the services heat sector. + """ + + RESIDENTIAL = "residential" + SERVICES = "services" + + def __str__(self) -> str: + """ + Returns the string representation of the heat sector. + + Returns: + str: The string representation of the heat sector. + """ + return self.value diff --git a/scripts/definitions/heat_system.py b/scripts/definitions/heat_system.py new file mode 100644 index 000000000..2f305644c --- /dev/null +++ b/scripts/definitions/heat_system.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# +# SPDX-License-Identifier: MIT + +from enum import Enum + +from scripts.definitions.heat_sector import HeatSector +from scripts.definitions.heat_system_type import HeatSystemType + + +class HeatSystem(Enum): + """ + Enumeration representing different heat systems. + + Attributes + ---------- + RESIDENTIAL_RURAL : str + Heat system for residential areas in rural locations. + SERVICES_RURAL : str + Heat system for service areas in rural locations. + RESIDENTIAL_URBAN_DECENTRAL : str + Heat system for residential areas in urban decentralized locations. + SERVICES_URBAN_DECENTRAL : str + Heat system for service areas in urban decentralized locations. + URBAN_CENTRAL : str + Heat system for urban central areas. + + Methods + ------- + __str__() + Returns the string representation of the heat system. + central_or_decentral() + Returns whether the heat system is central or decentralized. + system_type() + Returns the type of the heat system. + sector() + Returns the sector of the heat system. + rural() + Returns whether the heat system is for rural areas. + urban_decentral() + Returns whether the heat system is for urban decentralized areas. + urban() + Returns whether the heat system is for urban areas. + heat_demand_weighting(urban_fraction=None, dist_fraction=None) + Calculates the heat demand weighting based on urban fraction and distribution fraction. + heat_pump_costs_name(heat_source) + Generates the name for the heat pump costs based on the heat source. + """ + + RESIDENTIAL_RURAL = "residential rural" + SERVICES_RURAL = "services rural" + RESIDENTIAL_URBAN_DECENTRAL = "residential urban decentral" + SERVICES_URBAN_DECENTRAL = "services urban decentral" + URBAN_CENTRAL = "urban central" + + def __init__(self, *args): + super().__init__(*args) + + def __str__(self) -> str: + """ + Returns the string representation of the heat system. + + Returns + ------- + str + The string representation of the heat system. + """ + return self.value + + @property + def central_or_decentral(self) -> str: + """ + Returns whether the heat system is central or decentralized. + + Returns + ------- + str + "central" if the heat system is central, "decentral" otherwise. + """ + if self == HeatSystem.URBAN_CENTRAL: + return "central" + else: + return "decentral" + + @property + def system_type(self) -> HeatSystemType: + """ + Returns the type of the heat system. + + Returns + ------- + str + The type of the heat system. + + Raises + ------ + RuntimeError + If the heat system is invalid. + """ + if self == HeatSystem.URBAN_CENTRAL: + return HeatSystemType.URBAN_CENTRAL + elif ( + self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL + or self == HeatSystem.SERVICES_URBAN_DECENTRAL + ): + return HeatSystemType.URBAN_DECENTRAL + elif self == HeatSystem.RESIDENTIAL_RURAL or self == HeatSystem.SERVICES_RURAL: + return HeatSystemType.RURAL + else: + raise RuntimeError(f"Invalid heat system: {self}") + + @property + def sector(self) -> HeatSector: + """ + Returns the sector of the heat system. + + Returns + ------- + HeatSector + The sector of the heat system. + """ + if ( + self == HeatSystem.RESIDENTIAL_RURAL + or self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL + ): + return HeatSector.RESIDENTIAL + elif ( + self == HeatSystem.SERVICES_RURAL + or self == HeatSystem.SERVICES_URBAN_DECENTRAL + ): + return HeatSector.SERVICES + else: + "tot" + + @property + def is_rural(self) -> bool: + """ + Returns whether the heat system is for rural areas. + + Returns + ------- + bool + True if the heat system is for rural areas, False otherwise. + """ + if self == HeatSystem.RESIDENTIAL_RURAL or self == HeatSystem.SERVICES_RURAL: + return True + else: + return False + + @property + def is_urban_decentral(self) -> bool: + """ + Returns whether the heat system is for urban decentralized areas. + + Returns + ------- + bool + True if the heat system is for urban decentralized areas, False otherwise. + """ + if ( + self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL + or self == HeatSystem.SERVICES_URBAN_DECENTRAL + ): + return True + else: + return False + + @property + def is_urban(self) -> bool: + """ + Returns whether the heat system is for urban areas. + + Returns + ------- + bool True if the heat system is for urban areas, False otherwise. + """ + return not self.is_rural + + def heat_demand_weighting(self, urban_fraction=None, dist_fraction=None) -> float: + """ + Calculates the heat demand weighting based on urban fraction and + distribution fraction. + + Parameters + ---------- + urban_fraction : float, optional + The fraction of urban heat demand. + dist_fraction : float, optional + The fraction of distributed heat demand. + + Returns + ------- + float + The heat demand weighting. + + Raises + ------ + RuntimeError + If the heat system is invalid. + """ + if "rural" in self.value: + return 1 - urban_fraction + elif "urban central" in self.value: + return dist_fraction + elif "urban decentral" in self.value: + return urban_fraction - dist_fraction + else: + raise RuntimeError(f"Invalid heat system: {self}") + + def heat_pump_costs_name(self, heat_source: str) -> str: + """ + Generates the name for the heat pump costs based on the heat source and + system. + + Parameters + ---------- + heat_source : str + The heat source. + + Returns + ------- + str + The name for the heat pump costs. + """ + return f"{self.central_or_decentral} {heat_source}-sourced heat pump" + + @property + def resistive_heater_costs_name(self) -> str: + """ + Generates the name for the resistive heater costs based on the heat + system. + + Returns + ------- + str + The name for the heater costs. + """ + return f"{self.central_or_decentral} resistive heater" + + @property + def gas_boiler_costs_name(self) -> str: + """ + Generates the name for the gas boiler costs based on the heat system. + + Returns + ------- + str + The name for the gas boiler costs. + """ + return f"{self.central_or_decentral} gas boiler" + + @property + def oil_boiler_costs_name(self) -> str: + """ + Generates the name for the oil boiler costs based on the heat system. + + Returns + ------- + str + The name for the oil boiler costs. + """ + return "decentral oil boiler" diff --git a/scripts/definitions/heat_system_type.py b/scripts/definitions/heat_system_type.py new file mode 100644 index 000000000..5bd1bee32 --- /dev/null +++ b/scripts/definitions/heat_system_type.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors +# +# SPDX-License-Identifier: MIT + +from enum import Enum + + +class HeatSystemType(Enum): + """ + Enumeration representing different types of heat systems. + """ + + URBAN_CENTRAL = "urban central" + URBAN_DECENTRAL = "urban decentral" + RURAL = "rural" + + def __str__(self) -> str: + """ + Returns the string representation of the heat system type. + + Returns: + str: The string representation of the heat system type. + """ + return self.value + + @property + def is_central(self) -> bool: + """ + Returns whether the heat system type is central. + + Returns: + bool: True if the heat system type is central, False otherwise. + """ + return self == HeatSystemType.URBAN_CENTRAL From 2e35bef480614a09ff25e7154cbb8f1028b6e1c5 Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 5 Aug 2024 15:08:05 +0200 Subject: [PATCH 55/58] rename "enums" to "definitions" and write modules in snake case --- scripts/add_existing_baseyear.py | 6 +- scripts/build_cop_profiles/run.py | 2 +- scripts/enums/HeatSector.py | 28 ---- scripts/enums/HeatSystem.py | 263 ------------------------------ scripts/enums/HeatSystemType.py | 35 ---- scripts/prepare_sector_network.py | 6 +- 6 files changed, 7 insertions(+), 333 deletions(-) delete mode 100644 scripts/enums/HeatSector.py delete mode 100644 scripts/enums/HeatSystem.py delete mode 100644 scripts/enums/HeatSystemType.py diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index d0f85a1a2..ff1a3e46a 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -24,9 +24,9 @@ from add_electricity import sanitize_carriers from prepare_sector_network import cluster_heat_buses, define_spatial, prepare_costs -from scripts.enums.HeatSector import HeatSector -from scripts.enums.HeatSystem import HeatSystem -from scripts.enums.HeatSystemType import HeatSystemType +from scripts.definitions.heat_sector import HeatSector +from scripts.definitions.heat_system import HeatSystem +from scripts.definitions.heat_system_type import HeatSystemType logger = logging.getLogger(__name__) cc = coco.CountryConverter() diff --git a/scripts/build_cop_profiles/run.py b/scripts/build_cop_profiles/run.py index 7e405a424..4d57db310 100644 --- a/scripts/build_cop_profiles/run.py +++ b/scripts/build_cop_profiles/run.py @@ -12,7 +12,7 @@ from CentralHeatingCopApproximator import CentralHeatingCopApproximator from DecentralHeatingCopApproximator import DecentralHeatingCopApproximator -from scripts.enums.HeatSystemType import HeatSystemType +from scripts.definitions.heat_system_type import HeatSystemType sys.path.append("..") diff --git a/scripts/enums/HeatSector.py b/scripts/enums/HeatSector.py deleted file mode 100644 index 03bcaffdb..000000000 --- a/scripts/enums/HeatSector.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- -# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors -# -# SPDX-License-Identifier: MIT - -from enum import Enum - - -class HeatSector(Enum): - """ - Enumeration class representing different heat sectors. - - Attributes: - RESIDENTIAL (str): Represents the residential heat sector. - SERVICES (str): Represents the services heat sector. - """ - - RESIDENTIAL = "residential" - SERVICES = "services" - - def __str__(self) -> str: - """ - Returns the string representation of the heat sector. - - Returns: - str: The string representation of the heat sector. - """ - return self.value diff --git a/scripts/enums/HeatSystem.py b/scripts/enums/HeatSystem.py deleted file mode 100644 index 75cd3344e..000000000 --- a/scripts/enums/HeatSystem.py +++ /dev/null @@ -1,263 +0,0 @@ -# -*- coding: utf-8 -*- -# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors -# -# SPDX-License-Identifier: MIT - -from enum import Enum - -from scripts.enums.HeatSector import HeatSector -from scripts.enums.HeatSystemType import HeatSystemType - - -class HeatSystem(Enum): - """ - Enumeration representing different heat systems. - - Attributes - ---------- - RESIDENTIAL_RURAL : str - Heat system for residential areas in rural locations. - SERVICES_RURAL : str - Heat system for service areas in rural locations. - RESIDENTIAL_URBAN_DECENTRAL : str - Heat system for residential areas in urban decentralized locations. - SERVICES_URBAN_DECENTRAL : str - Heat system for service areas in urban decentralized locations. - URBAN_CENTRAL : str - Heat system for urban central areas. - - Methods - ------- - __str__() - Returns the string representation of the heat system. - central_or_decentral() - Returns whether the heat system is central or decentralized. - system_type() - Returns the type of the heat system. - sector() - Returns the sector of the heat system. - rural() - Returns whether the heat system is for rural areas. - urban_decentral() - Returns whether the heat system is for urban decentralized areas. - urban() - Returns whether the heat system is for urban areas. - heat_demand_weighting(urban_fraction=None, dist_fraction=None) - Calculates the heat demand weighting based on urban fraction and distribution fraction. - heat_pump_costs_name(heat_source) - Generates the name for the heat pump costs based on the heat source. - """ - - RESIDENTIAL_RURAL = "residential rural" - SERVICES_RURAL = "services rural" - RESIDENTIAL_URBAN_DECENTRAL = "residential urban decentral" - SERVICES_URBAN_DECENTRAL = "services urban decentral" - URBAN_CENTRAL = "urban central" - - def __init__(self, *args): - super().__init__(*args) - - def __str__(self) -> str: - """ - Returns the string representation of the heat system. - - Returns - ------- - str - The string representation of the heat system. - """ - return self.value - - @property - def central_or_decentral(self) -> str: - """ - Returns whether the heat system is central or decentralized. - - Returns - ------- - str - "central" if the heat system is central, "decentral" otherwise. - """ - if self == HeatSystem.URBAN_CENTRAL: - return "central" - else: - return "decentral" - - @property - def system_type(self) -> HeatSystemType: - """ - Returns the type of the heat system. - - Returns - ------- - str - The type of the heat system. - - Raises - ------ - RuntimeError - If the heat system is invalid. - """ - if self == HeatSystem.URBAN_CENTRAL: - return HeatSystemType.URBAN_CENTRAL - elif ( - self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL - or self == HeatSystem.SERVICES_URBAN_DECENTRAL - ): - return HeatSystemType.URBAN_DECENTRAL - elif self == HeatSystem.RESIDENTIAL_RURAL or self == HeatSystem.SERVICES_RURAL: - return HeatSystemType.RURAL - else: - raise RuntimeError(f"Invalid heat system: {self}") - - @property - def sector(self) -> HeatSector: - """ - Returns the sector of the heat system. - - Returns - ------- - HeatSector - The sector of the heat system. - """ - if ( - self == HeatSystem.RESIDENTIAL_RURAL - or self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL - ): - return HeatSector.RESIDENTIAL - elif ( - self == HeatSystem.SERVICES_RURAL - or self == HeatSystem.SERVICES_URBAN_DECENTRAL - ): - return HeatSector.SERVICES - else: - "tot" - - @property - def is_rural(self) -> bool: - """ - Returns whether the heat system is for rural areas. - - Returns - ------- - bool - True if the heat system is for rural areas, False otherwise. - """ - if self == HeatSystem.RESIDENTIAL_RURAL or self == HeatSystem.SERVICES_RURAL: - return True - else: - return False - - @property - def is_urban_decentral(self) -> bool: - """ - Returns whether the heat system is for urban decentralized areas. - - Returns - ------- - bool - True if the heat system is for urban decentralized areas, False otherwise. - """ - if ( - self == HeatSystem.RESIDENTIAL_URBAN_DECENTRAL - or self == HeatSystem.SERVICES_URBAN_DECENTRAL - ): - return True - else: - return False - - @property - def is_urban(self) -> bool: - """ - Returns whether the heat system is for urban areas. - - Returns - ------- - bool True if the heat system is for urban areas, False otherwise. - """ - return not self.is_rural - - def heat_demand_weighting(self, urban_fraction=None, dist_fraction=None) -> float: - """ - Calculates the heat demand weighting based on urban fraction and - distribution fraction. - - Parameters - ---------- - urban_fraction : float, optional - The fraction of urban heat demand. - dist_fraction : float, optional - The fraction of distributed heat demand. - - Returns - ------- - float - The heat demand weighting. - - Raises - ------ - RuntimeError - If the heat system is invalid. - """ - if "rural" in self.value: - return 1 - urban_fraction - elif "urban central" in self.value: - return dist_fraction - elif "urban decentral" in self.value: - return urban_fraction - dist_fraction - else: - raise RuntimeError(f"Invalid heat system: {self}") - - def heat_pump_costs_name(self, heat_source: str) -> str: - """ - Generates the name for the heat pump costs based on the heat source and - system. - - Parameters - ---------- - heat_source : str - The heat source. - - Returns - ------- - str - The name for the heat pump costs. - """ - return f"{self.central_or_decentral} {heat_source}-sourced heat pump" - - @property - def resistive_heater_costs_name(self) -> str: - """ - Generates the name for the resistive heater costs based on the heat - system. - - Returns - ------- - str - The name for the heater costs. - """ - return f"{self.central_or_decentral} resistive heater" - - @property - def gas_boiler_costs_name(self) -> str: - """ - Generates the name for the gas boiler costs based on the heat system. - - Returns - ------- - str - The name for the gas boiler costs. - """ - return f"{self.central_or_decentral} gas boiler" - - @property - def oil_boiler_costs_name(self) -> str: - """ - Generates the name for the oil boiler costs based on the heat system. - - Returns - ------- - str - The name for the oil boiler costs. - """ - return "decentral oil boiler" diff --git a/scripts/enums/HeatSystemType.py b/scripts/enums/HeatSystemType.py deleted file mode 100644 index 5bd1bee32..000000000 --- a/scripts/enums/HeatSystemType.py +++ /dev/null @@ -1,35 +0,0 @@ -# -*- coding: utf-8 -*- -# SPDX-FileCopyrightText: : 2020-2024 The PyPSA-Eur Authors -# -# SPDX-License-Identifier: MIT - -from enum import Enum - - -class HeatSystemType(Enum): - """ - Enumeration representing different types of heat systems. - """ - - URBAN_CENTRAL = "urban central" - URBAN_DECENTRAL = "urban decentral" - RURAL = "rural" - - def __str__(self) -> str: - """ - Returns the string representation of the heat system type. - - Returns: - str: The string representation of the heat system type. - """ - return self.value - - @property - def is_central(self) -> bool: - """ - Returns whether the heat system type is central. - - Returns: - bool: True if the heat system type is central, False otherwise. - """ - return self == HeatSystemType.URBAN_CENTRAL diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index 83b76bb97..d9d0f6e32 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -37,9 +37,9 @@ from pypsa.io import import_components_from_dataframe from scipy.stats import beta -from scripts.enums.HeatSector import HeatSector -from scripts.enums.HeatSystem import HeatSystem -from scripts.enums.HeatSystemType import HeatSystemType +from scripts.definitions.heat_sector import HeatSector +from scripts.definitions.heat_system import HeatSystem +from scripts.definitions.heat_system_type import HeatSystemType spatial = SimpleNamespace() logger = logging.getLogger(__name__) From 0e8fb80bc42adb6bb098c08645da3472efb1081f Mon Sep 17 00:00:00 2001 From: AmosSchledorn Date: Mon, 5 Aug 2024 16:11:18 +0200 Subject: [PATCH 56/58] clean up, improve docs --- scripts/add_existing_baseyear.py | 12 +++---- scripts/definitions/heat_system.py | 4 +++ scripts/prepare_sector_network.py | 55 +++++++++++++++++------------- 3 files changed, 41 insertions(+), 30 deletions(-) diff --git a/scripts/add_existing_baseyear.py b/scripts/add_existing_baseyear.py index ff1a3e46a..f67c38d9f 100644 --- a/scripts/add_existing_baseyear.py +++ b/scripts/add_existing_baseyear.py @@ -420,13 +420,13 @@ def add_power_capacities_installed_before_baseyear(n, grouping_years, costs, bas def add_heating_capacities_installed_before_baseyear( - n, - baseyear, - grouping_years, + n: pypsa.Network, + baseyear: int, + grouping_years: list, cop: dict, time_dep_hp_cop: bool, - costs, - default_lifetime, + costs: pd.DataFrame, + default_lifetime: int, existing_heating: pd.DataFrame, ): """ @@ -500,7 +500,7 @@ def add_heating_capacities_installed_before_baseyear( ) .to_pandas() .reindex(index=n.snapshots) - if options["time_dep_hp_cop"] + if time_dep_hp_cop else costs.at[costs_name, "efficiency"] ) diff --git a/scripts/definitions/heat_system.py b/scripts/definitions/heat_system.py index 2f305644c..b907b0fef 100644 --- a/scripts/definitions/heat_system.py +++ b/scripts/definitions/heat_system.py @@ -212,6 +212,7 @@ def heat_pump_costs_name(self, heat_source: str) -> str: """ Generates the name for the heat pump costs based on the heat source and system. + Used to retrieve data from `technology-data `. Parameters ---------- @@ -230,6 +231,7 @@ def resistive_heater_costs_name(self) -> str: """ Generates the name for the resistive heater costs based on the heat system. + Used to retrieve data from `technology-data `. Returns ------- @@ -242,6 +244,7 @@ def resistive_heater_costs_name(self) -> str: def gas_boiler_costs_name(self) -> str: """ Generates the name for the gas boiler costs based on the heat system. + Used to retrieve data from `technology-data `. Returns ------- @@ -254,6 +257,7 @@ def gas_boiler_costs_name(self) -> str: def oil_boiler_costs_name(self) -> str: """ Generates the name for the oil boiler costs based on the heat system. + Used to retrieve data from `technology-data `. Returns ------- diff --git a/scripts/prepare_sector_network.py b/scripts/prepare_sector_network.py index d9d0f6e32..585b3f258 100644 --- a/scripts/prepare_sector_network.py +++ b/scripts/prepare_sector_network.py @@ -1780,7 +1780,7 @@ def build_heat_demand(n): .unstack(level=1) ) - sectors = ["residential", "services"] + sectors = [sector.value for sector in HeatSector] uses = ["water", "space"] heat_demand = {} @@ -1808,10 +1808,21 @@ def build_heat_demand(n): return heat_demand -def add_heat(n, costs, cop): +def add_heat(n: pypsa.Network, costs: pd.DataFrame, cop: xr.DataArray): + """ + Add heat sector to the network. + + Parameters: + n (pypsa.Network): The PyPSA network object. + costs (pd.DataFrame): DataFrame containing cost information. + cop (xr.DataArray): DataArray containing coefficient of performance (COP) values. + + Returns: + None + """ logger.info("Add heat sector") - sectors = ["residential", "services"] + sectors = [sector.value for sector in HeatSector] heat_demand = build_heat_demand(n) @@ -3113,27 +3124,23 @@ def add_industry(n, costs): if options["oil_boilers"]: nodes = pop_layout.index - for name in [ - "residential rural", - "services rural", - "residential urban decentral", - "services urban decentral", - ]: - n.madd( - "Link", - nodes + f" {name} oil boiler", - p_nom_extendable=True, - bus0=spatial.oil.nodes, - bus1=nodes + f" {name} heat", - bus2="co2 atmosphere", - carrier=f"{name} oil boiler", - efficiency=costs.at["decentral oil boiler", "efficiency"], - efficiency2=costs.at["oil", "CO2 intensity"], - capital_cost=costs.at["decentral oil boiler", "efficiency"] - * costs.at["decentral oil boiler", "fixed"] - * options["overdimension_individual_heating"], - lifetime=costs.at["decentral oil boiler", "lifetime"], - ) + for heat_system in HeatSystem: + if not heat_system == HeatSystem.URBAN_CENTRAL: + n.madd( + "Link", + nodes + f" {heat_system} oil boiler", + p_nom_extendable=True, + bus0=spatial.oil.nodes, + bus1=nodes + f" {heat_system} heat", + bus2="co2 atmosphere", + carrier=f"{heat_system} oil boiler", + efficiency=costs.at["decentral oil boiler", "efficiency"], + efficiency2=costs.at["oil", "CO2 intensity"], + capital_cost=costs.at["decentral oil boiler", "efficiency"] + * costs.at["decentral oil boiler", "fixed"] + * options["overdimension_individual_heating"], + lifetime=costs.at["decentral oil boiler", "lifetime"], + ) n.madd( "Link", From 9c32932eee710bb2cb2d549bd4ce6f9a690d5664 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 7 Aug 2024 08:18:38 +0000 Subject: [PATCH 57/58] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- doc/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/conf.py b/doc/conf.py index a166dd70e..efce867ed 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -342,5 +342,5 @@ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - 'https://docs.python.org/': ('https://docs.python.org/3', None), + "https://docs.python.org/": ("https://docs.python.org/3", None), } From bab392f37896e249a8b45a8cecb9cd2de335b19a Mon Sep 17 00:00:00 2001 From: lisazeyen <35347358+lisazeyen@users.noreply.github.com> Date: Wed, 7 Aug 2024 14:14:19 +0200 Subject: [PATCH 58/58] remove not needed function --- rules/build_sector.smk | 9 --------- 1 file changed, 9 deletions(-) diff --git a/rules/build_sector.smk b/rules/build_sector.smk index 5916aa02b..d1a29e832 100644 --- a/rules/build_sector.smk +++ b/rules/build_sector.smk @@ -215,15 +215,6 @@ rule build_temperature_profiles: "../scripts/build_temperature_profiles.py" -# def output_cop(wildcards): -# return { -# f"cop_{source}_{sink}": resources( -# "cop_" + source + "_" + sink + "_" + "elec_s{simpl}_{clusters}.nc" -# ) -# for sink, source in config["sector"]["heat_pump_sources"].items() -# } - - rule build_cop_profiles: params: heat_pump_sink_T_decentral_heating=config_provider(