def get_share_of_federal_states_by_region(year, regions, name): """ Parameters ---------- year : int regions : tuple or list name : tuple or list Returns ------- Examples -------- >>> regions=geometries.load( ... cfg.get('paths', 'geometry'), ... cfg.get('geometry', 'de21_polygons'), index_col='region') >>> inh=get_share_of_federal_states_by_region(2014, regions, 'de21') >>> round(inh.loc['DE01']['BB'], 2) 0.74 >>> round(inh.loc['DE01']['BE'], 2) 1.0 """ # Get inhabitants for federal states and the given regions fs_geo = geometries.get_federal_states_polygon() ew = get_inhabitants_by_multi_regions(year, [regions, fs_geo], name=[name, "federal_states"]) ew = ew[ew != 0] # Calculate the share of the federal states within the regions. fs_sum = ew.groupby(level=1).sum().copy() for reg in ew.index.get_level_values(0).unique(): for fs in ew.loc[reg].index: ew.loc[reg, fs] = ew.loc[reg, fs] / fs_sum[fs] return ew
def federal_state_average_weather(year, parameter): """ Example for spatial_average_weather() with federal states polygons. Parameters ---------- year parameter Returns ------- """ federal_states = geometries.get_federal_states_polygon() filename = os.path.join( cfg.get("paths", "coastdat"), "average_{0}_BB_TH_{1}.csv".format(parameter, year), ) if not os.path.isfile(filename): spatial_average_weather(year, federal_states, parameter, "federal_states", outfile=filename) return pd.read_csv( filename, index_col=[0], parse_dates=True, date_parser=lambda col: pd.to_datetime(col, utc=True), )
def fig_electricity_demand_by_state(): """ Comparison of two methods to get the electricity demand for the federal states of Germany. The reegis energy balance module and the reegis openego module. The openego module can be used for any region polygon. """ plt.rcParams.update({"font.size": 14}) ax = plt.figure(figsize=(9, 4)).add_subplot(1, 1, 1) eb = energy_balance.get_states_energy_balance(2014).swaplevel() total = eb.loc["Endenergieverbrauch", "electricity"].sum() elec_fs = eb.loc["Endenergieverbrauch", "electricity"] elec_fs.name = "energy balance" share = pd.DataFrame(elec_fs.div(total).mul(100)) federal_states = geometries.get_federal_states_polygon() ego_demand = openego.get_ego_demand_by_region(federal_states, "federal_states", grouped=True) share["openego"] = ego_demand.div(ego_demand.sum()).mul(100) print(share) share.plot(kind="bar", ax=ax) share["diff"] = (share["energy balance"] - share["openego"]) / share["energy balance"] print(share) ax.set_ylabel("share [%]") t = ("Share of overall electricity demand from the reegis\n energy" " balance module and from the reegis openego module.") plt.title(t) plt.subplots_adjust(right=0.96, left=0.09, bottom=0.13, top=0.85) return "electricity_demand_by_state"
def pp_reegis2deflex(regions, name, filename_in=None, filename_out=None): """ Add federal states and deflex regions to powerplant table from reegis. As the process takes a while the result is stored for further usage. Returns ------- str : The full path where the result file is stored. """ if filename_out is None: filename_out = os.path.join( cfg.get("paths", "powerplants"), cfg.get("powerplants", "deflex_pp"), ).format(map=cfg.get("init", "map")) # Add deflex regions to powerplants pp = powerplants.add_regions_to_powerplants(regions, name, dump=False, filename=filename_in) # Add federal states to powerplants federal_states = reegis_geometries.get_federal_states_polygon() pp = powerplants.add_regions_to_powerplants(federal_states, "federal_states", pp=pp, dump=False) # store the results for further usage of deflex pp.to_hdf(filename_out, "pp") return filename_out
def fig_scaled_electricity_profile(): """ Comparison of different methods to fetch the annual electricity demand to scale the entso-e profile. """ ax = plt.figure(figsize=(8, 4)).add_subplot(1, 1, 1) fs = geometries.get_federal_states_polygon() p = pd.Series() p1 = demand_elec.get_entsoe_profile_by_region(fs, 2014, "test", "entsoe") p["entsoe"] = p1.sum().sum() p2 = demand_elec.get_entsoe_profile_by_region(fs, 2013, "test", "bmwi") p["bmwi"] = p2.sum().sum() p3 = demand_elec.get_entsoe_profile_by_region(fs, 2013, "test", "openego") p["openego"] = p3.sum().sum() p4 = demand_elec.get_entsoe_profile_by_region(fs, 2011, "test", 555555) p["user value"] = p4.sum().sum() p.plot(kind="bar", ax=ax) plt.xticks(rotation=0) ax.set_ylabel("energy demand [GWh]") plt.title("Energy demand of Germany to scale the overall demand.") plt.subplots_adjust(right=0.95, left=0.13, bottom=0.13, top=0.91) return "scaled_electricity_profile"
def table_demand_federal_states(outpath): ego_year = 2014 path = cfg.get('paths', 'data_my_reegis') filename = 'lak_electricity_demand_federal_states.csv' lak = pd.read_csv(os.path.join(path, filename), index_col=[0, 1], sep=';') lak = lak.swaplevel() federal_states = geometries.get_federal_states_polygon() ego = oego.get_ego_demand_by_region( federal_states, 'federal_states', grouped=True) ego_sum = ego.sum() lak = lak.rename(index=cfg.get_dict('STATES')) lak['Strom'] = pd.to_numeric(lak['Strom'], errors='coerce') new_table = pd.DataFrame( columns=pd.MultiIndex(levels=[[], []], codes=[[], []]), index=ego.index) new_table[('openEgo', ego_year)] = ego for y in [2010, 2011, 2012, 2013, 2014]: key = ('lak', y) new_table[key] = lak.loc[y]['Strom'] / 3.6 f = new_table[key].sum() / ego_sum new_table[('frac', y)] = (((new_table[('openEgo', ego_year)] * f) - new_table[key]) / new_table[key]) fk = new_table[('lak', ego_year)].sum() / ego_sum new_table[('openEgo', ego_year)] = new_table[('openEgo', ego_year)] * fk new_table.sort_index(axis=1, inplace=True) new_table.to_excel( os.path.join(outpath, 'federal_states_demand_ego_lak.xls')) print(new_table)
def setUpClass(cls): cfg.tmp_set("open_ego", "ego_load_areas", "ego_load_areas_db_test.csv") openego.get_ego_data(osf=False, query="?where=un_id<10") cfg.tmp_set("open_ego", "ego_load_areas", "ego_load_areas_test.csv") cfg.tmp_set("open_ego", "osf_url", "https://osf.io/w9pv6/download") cfg.tmp_set("open_ego", "ego_file", "oep_ego_demand_combined_test1.h5") cls.load = openego.get_ego_data() cls.geo = geometries.get_federal_states_polygon() filename = "oep_ego_demand_combined_test.h5" path = cfg.get("paths", "demand") cls.fn = os.path.join(path, filename) cls.load.to_hdf(cls.fn, "demand")
def setup_class(cls): path = os.path.join(os.path.dirname(__file__), "data") cfg.tmp_set("paths_pattern", "opsd", path) cfg.tmp_set("paths", "powerplants", path) fn_opsd = opsd.opsd_power_plants() os.remove(fn_opsd) fn_opsd = os.path.join(cfg.get("paths_pattern", "opsd"), cfg.get("opsd", "opsd_prepared")) fn_test = fn_opsd.replace(".h5", "_test.h5") copyfile(fn_test, fn_opsd) fn_reegis = powerplants.pp_opsd2reegis() os.remove(fn_opsd) filename = str(fn_reegis.split(os.sep)[-1]) cls.gdf1 = geo.get_federal_states_polygon() powerplants.add_regions_to_powerplants(cls.gdf1, "fed_states", filename=filename, path=path, dump=True) geo_path = cfg.get("paths", "geometry") geo_file = cfg.get("coastdat", "coastdatgrid_polygon") gdf2 = geo.load(path=geo_path, filename=geo_file) cls.pp = powerplants.add_regions_to_powerplants(gdf2, "coastdat2", filename=filename, path=path, dump=False) year = 2014 cls.pp2 = powerplants.get_powerplants_by_region( cls.gdf1, year, "my_states") cls.pp2["efficiency_{0}".format(year)] = cls.pp2["capacity_{0}".format( year)].div(cls.pp2["capacity_in_{0}".format(year)]) cls.pp2.drop( ["capacity", "capacity_in", "thermal_capacity"], axis=1, inplace=True, ) fn_reegis2 = fn_reegis.replace(".h5", "_my_states.h5") os.remove(fn_reegis2) os.remove(fn_reegis) rmtree(os.path.join(path, "messages"))
def fig_federal_states_polygons(): """ Plot federal states and the exclusive economic zone of Germany as map. """ ax = plt.figure(figsize=(9, 7)).add_subplot(1, 1, 1) # change for a better/worse resolution ( simple = 0.02 cmap = LinearSegmentedColormap.from_list( "mycmap", [(0, "#badd69"), (1, "#a5bfdd")], 2 ) fs = geometries.get_federal_states_polygon() # drop buffer region fs.drop("P0", axis=0, inplace=True) # dissolve offshore regions to one region fs["region"] = fs.index # prevent index fs.loc[["O0", "N0", "N1"], "SN_L"] = "00" fs = fs.dissolve(by="SN_L") fs.loc["00", "region"] = "AW" fs.loc["00", "name"] = "Ausschließliche Wirtschaftszone" fs.set_index("region", inplace=True) # write back index # simplify the geometry to make the resulting file smaller fs["geometry"] = fs["geometry"].simplify(simple) # set color column fs["color"] = 0 fs.loc["AW", "color"] = 1 # plot map fs.plot(ax=ax, cmap=cmap, column="color", edgecolor="#888888") # adjust plot plt.subplots_adjust(right=1, left=0, bottom=0, top=1) ax.set_axis_off() return "federal_states_region_plot"
def fig_electricity_profile_from_entsoe(): """ Electricity profile from entso-e scaled on the annual demand of three different federal states. """ ax = plt.figure(figsize=(10, 4)).add_subplot(1, 1, 1) fs = geometries.get_federal_states_polygon() df = demand_elec.get_entsoe_profile_by_region(fs, 2014, "federal_states", "bmwi") df[["NW", "NI", "MV"]].mul(1000).plot(ax=ax) plt.title("Demand profile for three federal states in 2014") ax.set_ylabel("electricity demand [GW]") ax.set_xlabel("hour of the year") box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(loc="upper left", bbox_to_anchor=(1, 0.5)) plt.subplots_adjust(right=0.91, left=0.08, bottom=0.13, top=0.91) return "electricity_profile_from_entsoe"
def test_too_old_year(): fs = geo.get_federal_states_polygon() with assert_raises_regexp( Exception, "Years < 2011 are not allowed in this function."): inhabitants.get_inhabitants_by_region(2010, fs, "federal_states")
def federal_states_feedin_example(): """Get fullload hours for renewable sources for a federal states.""" federal_states = geometries.get_federal_states_polygon() get_feedin_per_region(2014, federal_states, "federal_states") return scenario_feedin(2014, "federal_states")
p_per_qm_wind = 8 / 1e6 # 8 W/m² Fläche p_per_qm_pv = 200 / 1e6 # 200 W/m² Fläche -> eta=20% # Calculate maximum installable capacity for onshore wind and rooftop-PV P_max_wind = suitable_area['wind_area'] * p_per_qm_wind P_max_pv = suitable_area['pv_area'] * p_per_qm_pv # Load NUTS3-mixed-COPS nuts3_cops = pd.read_csv('/home/dbeier/Daten/COP_NUTS3.csv') nuts3_cops.drop('Unnamed: 0', axis='columns', inplace=True) nuts3_cops.set_index(pd.date_range('1/1/2014', periods=8760, freq='H'), inplace=True) # Get indices for zones of interest de22_list = geo_deflex.deflex_regions(rmap='de22', rtype='polygons').index de17_list = geo_reegis.get_federal_states_polygon().index # Aggregate values for de17 and de22 regions to prepare for # Create empty Dataframes dflx_input = pd.DataFrame( index=de22_list, columns=['power', 'lt-heat', 'ht-heat', 'P_wind', 'P_pv']) dflx_input_fedstates = pd.DataFrame( index=de17_list, columns=['power', 'lt-heat', 'ht-heat', 'P_wind', 'P_pv']) dflx_cop_de17_heat = pd.DataFrame(index=pd.date_range('1/1/2014', periods=8760, freq='H'), columns=de17_list) dflx_cop_de22_heat = pd.DataFrame(index=pd.date_range('1/1/2014', periods=8760, freq='H'),
def fig_powerplants(): """ Figure compares the results of the reegis 'get_powerplants_by_region' with statistical data of the Federal Network Agency (BNetzA). """ plt.rcParams.update({"font.size": 14}) geo = geometries.get_federal_states_polygon() my_name = "my_federal_states" # doctest: +SKIP my_year = 2015 # doctest: +SKIP pp_reegis = powerplants.get_powerplants_by_region(geo, my_year, my_name) data_path = os.path.join( os.path.dirname(__file__), os.pardir, "data", "static" ) fn_bnetza = os.path.join(data_path, "powerplants_bnetza_2015.csv") pp_bnetza = pd.read_csv(fn_bnetza, index_col=[0], skiprows=2, header=[0]) ax = plt.figure(figsize=(9, 5)).add_subplot(1, 1, 1) see = "other renew." my_dict = { "Bioenergy": see, "Geothermal": see, "Hard coal": "coal", "Hydro": see, "Lignite": "coal", "Natural gas": "natural gas", "Nuclear": "nuclear", "Oil": "other fossil", "Other fossil fuels": "other fossil", "Other fuels": "other fossil", "Solar": "solar power", "Waste": "other fossil", "Wind": "wind power", "unknown from conventional": "other fossil", } my_dict2 = { "Biomasse": see, "Braunkohle": "coal", "Erdgas": "natural gas", "Kernenergie": "nuclear", "Laufwasser": see, "Solar": "solar power", "Sonstige (ne)": "other fossil", "Steinkohle": "coal", "Wind": "wind power", "Sonstige (ee)": see, "Öl": "other fossil", } my_colors = [ "#6c3012", "#555555", "#db0b0b", "#501209", "#163e16", "#ffde32", "#335a8a", ] pp_reegis = ( pp_reegis.capacity_2015.unstack().groupby(my_dict, axis=1).sum() ) pp_reegis.loc["EEZ"] = ( pp_reegis.loc["N0"] + pp_reegis.loc["N1"] + pp_reegis.loc["O0"] ) pp_reegis.drop(["N0", "N1", "O0", "unknown", "P0"], inplace=True) pp_bnetza = pp_bnetza.groupby(my_dict2, axis=1).sum() ax = ( pp_reegis.sort_index() .sort_index(1) .div(1000) .plot( kind="bar", stacked=True, position=1.1, width=0.3, legend=False, color=my_colors, ax=ax, ) ) pp_bnetza.sort_index().sort_index(1).div(1000).plot( kind="bar", stacked=True, position=-0.1, width=0.3, ax=ax, color=my_colors, alpha=0.9, ) plt.xlabel("federal state / exclusive economic zone (EEZ)") plt.ylabel("installed capacity [GW]") plt.xlim(left=-0.5) plt.subplots_adjust(bottom=0.17, top=0.98, left=0.08, right=0.96) b_sum = pp_bnetza.sum() / 1000 b_total = int(round(b_sum.sum())) b_ee_sum = int(round(b_sum.loc[["wind power", "solar power", see]].sum())) b_fs_sum = int( round( b_sum.loc[["natural gas", "coal", "nuclear", "other fossil"]].sum() ) ) r_sum = pp_reegis.sum() / 1000 r_total = int(round(r_sum.sum())) r_ee_sum = int(round(r_sum.loc[["wind power", "solar power", see]].sum())) r_fs_sum = int( round( r_sum.loc[["natural gas", "coal", "nuclear", "other fossil"]].sum() ) ) text = { "reegis": (2.3, 42, "reegis"), "BNetzA": (3.9, 42, "BNetzA"), "b_sum1": (0, 39, "total"), "b_sum2": (2.5, 39, "{0} {1}".format(r_total, b_total)), "b_fs": (0, 36, "fossil"), "b_fs2": (2.5, 36, " {0} {1}".format(r_fs_sum, b_fs_sum)), "b_ee": (0, 33, "renewable"), "b_ee2": (2.5, 33, " {0} {1}".format(r_ee_sum, b_ee_sum)), } for t, c in text.items(): plt.text(c[0], c[1], c[2], size=14, ha="left", va="center") b = patches.Rectangle((-0.2, 31.8), 5.7, 12, color="#cccccc") ax.add_patch(b) ax.add_patch(patches.Shadow(b, -0.05, -0.2)) plt.title("Capacity of power plants in 2014") plt.subplots_adjust(right=0.96, left=0.08, bottom=0.17, top=0.93) return "compare_power_plants_reegis_bnetza"
import os from disaggregator import config, data from reegis import geometries as geo, config as rconfig, demand_elec, demand_heat nuts_geo_fn = os.path.join(rconfig.get('paths', 'geometry'), 'NUTS_RG_03M_2016_4326_LEVL_3_DE.geojson') nuts_geo = geo.load(fullname=nuts_geo_fn) nuts_geo.set_index('id', drop=True, inplace=True) fed_states = geo.get_federal_states_polygon() nuts_geo = geo.spatial_join_with_buffer(nuts_geo.centroid, fed_states, 'fs') fed_states['nuts'] = '0' for state in fed_states.index: fed_states.loc[state, 'nuts'] = list(nuts_geo.loc[nuts_geo['fs'] == state].index) cfg = config.get_config() dict_nuts3_name = config.region_id_to_nuts3(nuts3_to_name=True) df_spatial = data.database_description('spatial') df_temporal = data.database_description('temporal') elc_consumption_hh_spat = data.elc_consumption_HH_spatial() elc_consumption_hh_spattemp = data.elc_consumption_HH_spatiotemporal() print(elc_consumption_hh_spattemp[fed_states.loc['BB', 'nuts']]) print(elc_consumption_hh_spattemp[fed_states.loc['HH', 'nuts']]) # Testing Disaggregator reegis functions fed_states_nuts = fed_states.loc['BY', 'nuts'] demand_elec.get_household_powerload_by_NUTS3_profile(2014, fed_states_nuts,
filename, index_col=[0], header=[0, 1], parse_dates=True, date_parser=lambda col: pd.to_datetime(col, utc=True), ).tz_convert("Europe/Berlin") if annual_demand is None: return df else: return df.mul(annual_demand / df.sum().sum()) if __name__ == "__main__": # from reegis import geometries from oemof.tools import logger logger.define_logging() fs = geometries.get_federal_states_polygon() print( get_open_ego_slp_profile_by_region(fs, 2014, "federal_states").sum().sum()) print( get_open_ego_slp_profile_by_region(fs, 2014, "federal_states", annual_demand=500000).sum().sum()) if __name__ == "__main__": pass