def write_only_peak(sim_yr, name_new_folder, path_result, model_results, file_name_peak_day): """Write only peak demand and total regional demand for a region """ path_result_sub_folder = os.path.join(path_result, name_new_folder) basic_functions.create_folder(path_result_sub_folder) path_file_peak_day = os.path.join( path_result_sub_folder, "{}__{}__{}".format(file_name_peak_day, sim_yr, ".npy")) # ------------------------------------ # Write out peak electricity day demands # ------------------------------------ # Get peak day electricity lookups = lookup_tables.basic_lookups() fueltype_int = lookups['fueltypes']['electricity'] national_hourly_demand = np.sum(model_results[fueltype_int], axis=0) peak_day_electricity, _ = enduse_func.get_peak_day_single_fueltype( national_hourly_demand) selected_hours = date_prop.convert_yearday_to_8760h_selection( peak_day_electricity) selected_demand = model_results[:, :, selected_hours] np.save(path_file_peak_day, selected_demand)
def plot_fig_spatio_temporal_validation(path_regional_calculations, path_rolling_elec_demand, path_temporal_elec_validation, path_temporal_gas_validation, path_non_regional_elec_2015, path_out_plots, plot_show=False): """ Create plot with regional and non-regional plots for second paper Compare hdd calculations and disaggregation of regional and local """ # --------------------------------------------------------- # Iterate folders and read out all weather years and stations # --------------------------------------------------------- all_result_folders = os.listdir(path_regional_calculations) paths_folders_result = [] data_container = defaultdict(dict) ed_fueltype_regs_yh = defaultdict(dict) weather_yr_station_tot_fueltype_yh = defaultdict(dict) residential_results = defaultdict(dict) for scenario_folder in all_result_folders: result_folders = os.listdir( os.path.join(path_regional_calculations, scenario_folder)) for result_folder in result_folders: try: split_path_name = result_folder.split("__") weather_yr = int(split_path_name[0]) try: weather_station = int(split_path_name[1]) except: weather_station = "all_stations" paths_folders_result.append( os.path.join(path_regional_calculations, result_folder)) data = {} data['lookups'] = lookup_tables.basic_lookups() data['enduses'], data['assumptions'], data[ 'regions'] = data_loader.load_ini_param( os.path.join( path_regional_calculations, all_result_folders[0])) # last result folder data['assumptions']['seasons'] = date_prop.get_season( year_to_model=2015) data['assumptions']['model_yeardays_daytype'], data[ 'assumptions']['yeardays_month'], data['assumptions'][ 'yeardays_month_days'] = date_prop.get_yeardays_daytype( year_to_model=2015) results_container = read_data.read_in_results( os.path.join(path_regional_calculations, scenario_folder, "{}__{}".format(weather_yr, weather_station), 'model_run_results_txt'), data['assumptions']['seasons'], data['assumptions']['model_yeardays_daytype']) weather_yr_station_tot_fueltype_yh[weather_yr][ weather_station] = results_container['tot_fueltype_yh'] ed_fueltype_regs_yh[weather_yr][ weather_station] = results_container['ed_fueltype_regs_yh'] residential_results[weather_yr][ weather_station] = results_container['residential_results'] except ValueError: pass data_container['ed_fueltype_regs_yh'] = ed_fueltype_regs_yh data_container['tot_fueltype_yh'] = weather_yr_station_tot_fueltype_yh data_container['residential_results'] = residential_results data_container = dict(data_container) # ------------------------------------------------- # Collect non regional 2015 elec data # Calculated with all regional weather stations # ------------------------------------------------- year_non_regional = 2015 path_with_txt = os.path.join( path_non_regional_elec_2015, "{}__{}".format(str(year_non_regional), "all_stations"), 'model_run_results_txt') demand_year_non_regional = read_data.read_in_results( path_with_txt, data['assumptions']['seasons'], data['assumptions']['model_yeardays_daytype']) tot_fueltype_yh = demand_year_non_regional['tot_fueltype_yh'] fueltype_int = tech_related.get_fueltype_int('electricity') non_regional_elec_2015 = tot_fueltype_yh[year_non_regional][fueltype_int] # ---Collect real electricity data of year 2015 elec_2015_indo, _ = elec_national_data.read_raw_elec_2015( path_rolling_elec_demand) # Factor data as total sum is not identical f_diff_elec = np.sum(non_regional_elec_2015) / np.sum(elec_2015_indo) elec_factored_yh = f_diff_elec * elec_2015_indo # ***************************************************************** # Temporal validation # Compare regional and non regional and actual demand over time # ***************************************************************** simulation_yr_to_plot = 2015 winter_week, spring_week, summer_week, autumn_week = date_prop.get_seasonal_weeks( ) # Peak day peak_day, _ = enduse_func.get_peak_day_single_fueltype(elec_factored_yh) # Convert days to hours period_to_plot = list(range(0, 400)) period_to_plot = date_prop.get_8760_hrs_from_yeardays(winter_week) period_to_plot = date_prop.get_8760_hrs_from_yeardays([peak_day]) period_to_plot_winter = date_prop.get_8760_hrs_from_yeardays(winter_week) period_to_plot_spring = date_prop.get_8760_hrs_from_yeardays(spring_week) fig_p2_temporal_validation.run_fig_p2_temporal_validation( data_input=data_container['tot_fueltype_yh'], weather_yr=2015, fueltype_str='electricity', simulation_yr_to_plot=simulation_yr_to_plot, # Simulation year to plot period_h=period_to_plot, validation_elec_2015=elec_factored_yh, non_regional_elec_2015=non_regional_elec_2015, fig_name=os.path.join(path_out_plots, "temporal_validation_elec.pdf"), titel="yearday: {}".format(peak_day), y_lim_val=55, plot_validation=False, plot_show=plot_show) fueltype_gas = tech_related.get_fueltype_int('gas') fig_p2_temporal_validation.run_fig_p2_temporal_validation( data_input=data_container['tot_fueltype_yh'], weather_yr=2015, fueltype_str='gas', simulation_yr_to_plot=simulation_yr_to_plot, # Simulation year to plot period_h=period_to_plot, validation_elec_2015=None, non_regional_elec_2015=tot_fueltype_yh[year_non_regional] [fueltype_gas], fig_name=os.path.join(path_out_plots, "temporal_validation_gas.pdf"), titel="yearday: {}".format(peak_day), y_lim_val=250, plot_validation=False, plot_show=plot_show) # ------------------- # Spatial validation (not with maps) # ------------------- # non_regional: All weather station, spatially disaggregated TODO Give BETTER NAMES # regional: Only one weather station for whole countr but still data for every region weather_yr = 2015 fig_p2_spatial_val.run( simulation_yr_to_plot=simulation_yr_to_plot, demand_year_non_regional=demand_year_non_regional[ 'residential_results'][weather_yr], demand_year_regional=data_container['residential_results'][weather_yr], fueltypes=data['lookups']['fueltypes'], fig_path=path_out_plots, path_temporal_elec_validation=path_temporal_elec_validation, path_temporal_gas_validation=path_temporal_gas_validation, regions=data['regions'], plot_crit=plot_show)
def plot_radar_plots_average_peak_day(scenario_data, fueltype_to_model, fueltypes, year_to_plot, fig_name, base_yr=2015): """Compare averaged dh profile overall regions for peak day for future year and base year MAYBE: SO FAR ONLY FOR ONE SCENARIO """ fueltype_int = fueltypes[fueltype_to_model] # ---------------- # Create base year peak load profile # Aggregate load profiles of all regions # ----------------- peak_winter_individ_radars_to_plot_dh = [] trough_summer_individ_radars_to_plot_dh = [] load_factor_fueltype_y_cy = [] results_txt = [] for scenario_cnt, scenario in enumerate(scenario_data): print("-------Scenario: '{}' '{}'".format(scenario, fueltype_to_model)) # ------------------------ # Future year load profile # ------------------------ all_regs_fueltypes_yh_by = np.sum( scenario_data[scenario]['ed_fueltype_regs_yh'][base_yr], axis=1) all_regs_fueltypes_yh_cy = np.sum( scenario_data[scenario]['ed_fueltype_regs_yh'][year_to_plot], axis=1) # --------------------------- # Calculate load factors # --------------------------- peak_day_nr_by, by_max_h = enduse_func.get_peak_day_single_fueltype( all_regs_fueltypes_yh_by[fueltype_int]) test_peak_day_by = enduse_func.get_peak_day_all_fueltypes( all_regs_fueltypes_yh_by) peak_day_nr_cy, cy_max_h = enduse_func.get_peak_day_single_fueltype( all_regs_fueltypes_yh_cy[fueltype_int]) test_peak_day_cy = enduse_func.get_peak_day_all_fueltypes( all_regs_fueltypes_yh_cy) #peak_day_nr_cy = 32 _ = all_regs_fueltypes_yh_cy[fueltype_int].reshape(365, 24) print(_[peak_day_nr_cy]) print(np.max(_[peak_day_nr_cy])) print(cy_max_h) print("-----{} {}".format(scenario, peak_day_nr_cy)) print(_[peak_day_nr_cy]) print("EGON") # Minimum trough day trough_day_nr_by, by_max_h_trough = enduse_func.get_trough_day_single_fueltype( all_regs_fueltypes_yh_by[fueltype_int]) trough_day_nr_cy, cy_max_h_trough = enduse_func.get_trough_day_single_fueltype( all_regs_fueltypes_yh_cy[fueltype_int]) scen_load_factor_fueltype_y_by = load_factors.calc_lf_y( all_regs_fueltypes_yh_by) load_factor_fueltype_y_by = round( scen_load_factor_fueltype_y_by[fueltype_int], fueltype_int) scen_load_factor_fueltype_y_cy = load_factors.calc_lf_y( all_regs_fueltypes_yh_cy) load_factor_fueltype_y_cy.append( round(scen_load_factor_fueltype_y_cy[fueltype_int], fueltype_int)) # Add info on peak days #by2: {} results_txt.append( "p_day: {} by1: {} cy1: {}: cy2: {} trough_by: {} trough_cy: {}". format( peak_day_nr_cy, date_prop.yearday_to_date(2015, peak_day_nr_by), date_prop.yearday_to_date(2015, peak_day_nr_cy), #date_prop.yearday_to_date(2015, test_peak_day_by), date_prop.yearday_to_date(2015, test_peak_day_cy), date_prop.yearday_to_date(2015, trough_day_nr_by), date_prop.yearday_to_date(2015, trough_day_nr_cy))) # ------------------------ # Restult calculations # ------------------------ # Calculate share or space and water heating of total electrictiy demand in 2050 enduses_to_agg = [ 'rs_space_heating', 'rs_water_heating', 'ss_space_heating', 'ss_water_heating', 'is_space_heating' ] aggregated_enduse_fueltype_cy = np.zeros((8760)) aggregated_enduse_fueltype_by = np.zeros((8760)) for enduse in scenario_data[scenario]['results_enduse_every_year'][ year_to_plot].keys(): if enduse in enduses_to_agg: aggregated_enduse_fueltype_by += scenario_data[scenario][ 'results_enduse_every_year'][2015][enduse][fueltype_int] aggregated_enduse_fueltype_cy += scenario_data[scenario][ 'results_enduse_every_year'][year_to_plot][enduse][ fueltype_int] aggregated_enduse_fueltype_by_8760 = aggregated_enduse_fueltype_by.reshape( 365, 24) aggregated_enduse_fueltype_cy_8760 = aggregated_enduse_fueltype_cy.reshape( 365, 24) # Total demand of selected enduses selected_enduses_peak_by = round( np.max(aggregated_enduse_fueltype_by_8760[peak_day_nr_by]), 1) selected_enduses_peak_cy = round( np.max(aggregated_enduse_fueltype_cy_8760[peak_day_nr_cy]), 1) selected_enduses_min_by = round( np.max(aggregated_enduse_fueltype_by_8760[trough_day_nr_by]), 1) selected_enduses_min_cy = round( np.max(aggregated_enduse_fueltype_cy_8760[trough_day_nr_cy]), 1) # Calculate change in peak all_regs_fueltypes_yh_by = all_regs_fueltypes_yh_by.reshape( all_regs_fueltypes_yh_by.shape[0], 365, 24) all_regs_fueltypes_yh_cy = all_regs_fueltypes_yh_cy.reshape( all_regs_fueltypes_yh_cy.shape[0], 365, 24) diff_max_h = round(((100 / by_max_h) * cy_max_h) - 100, 1) txt = "peak_h_by: {} peak_h_cy: {} winter_heating_by: {} winter_heating_cy: {} trough_by: {} trough_cy: {} summer_heating_by: {} summer_heating_cy: {} {}".format( round(by_max_h, 1), round(cy_max_h, 1), selected_enduses_peak_by, selected_enduses_peak_cy, round(by_max_h_trough, 1), round(cy_max_h_trough, 1), selected_enduses_min_by, selected_enduses_min_cy, scenario) results_txt.append(txt) results_txt.append("----------") #results_txt.append("trough:day: " + str(all_regs_fueltypes_yh_by[fueltype_int][trough_day_nr_by])) print("Calculation of diff in peak: {} {} {} {}".format( scenario, round(diff_max_h, 1), round(by_max_h, 1), round(cy_max_h, 1))) # ---------------------------------- # Plot dh for peak day for base year # ---------------------------------- if scenario_cnt == 0: peak_winter_individ_radars_to_plot_dh.append( list(all_regs_fueltypes_yh_by[fueltype_int][peak_day_nr_by])) trough_summer_individ_radars_to_plot_dh.append( list(all_regs_fueltypes_yh_by[fueltype_int][trough_day_nr_cy])) else: pass # Add current year maximum winter peak day peak_winter_individ_radars_to_plot_dh.append( list(all_regs_fueltypes_yh_cy[fueltype_int][peak_day_nr_cy])) # Add current year minimum summer trough day trough_summer_individ_radars_to_plot_dh.append( list(all_regs_fueltypes_yh_cy[fueltype_int][trough_day_nr_cy])) # -------------------------- # Save model results to txt # -------------------------- name_spider_plot_peak = os.path.join( fig_name, "spider_scenarios_{}.pdf".format(fueltype_to_model)) write_data.write_list_to_txt( os.path.join(fig_name, name_spider_plot_peak[:-3] + "txt"), results_txt) name_spider_plot_trough = os.path.join( fig_name, "spider_scenarios_min_summer{}.pdf".format(fueltype_to_model)) write_data.write_list_to_txt( os.path.join(fig_name, name_spider_plot_trough[:-3] + "txt"), results_txt) # -------------------------- # Plot figure # -------------------------- # PEAK WINTER DAY PLOTS plot_radar_plot_multiple_lines(peak_winter_individ_radars_to_plot_dh, name_spider_plot_peak, plot_steps=50, scenario_names=list(scenario_data.keys()), plotshow=False, lf_y_by=[], lf_y_cy=[], list_diff_max_h=results_txt) # TROUGH Summer DAY PLOTS plot_radar_plot_multiple_lines(trough_summer_individ_radars_to_plot_dh, name_spider_plot_trough, plot_steps=50, scenario_names=list(scenario_data.keys()), plotshow=False, lf_y_by=[], lf_y_cy=[], list_diff_max_h=results_txt)
def run(results_every_year, lookups, path_plot_fig): """Plots Plot peak hour per fueltype over time for Arguments --------- tot_fuel_dh_peak : dict year, fueltype, peak_dh """ # Set figure size fig = plt.figure(figsize=basic_plot_functions.cm2inch(14, 8)) ax = fig.add_subplot(1, 1, 1) nr_y_to_plot = len(results_every_year) legend_entries = [] # Initialise (number of enduses, number of hours to plot) y_init = np.zeros((lookups['fueltypes_nr'], nr_y_to_plot)) for fueltype_str, fueltype in lookups['fueltypes'].items(): fueltype_int = tech_related.get_fueltype_int(fueltype_str) # Legend legend_entries.append(fueltype_str) # Read out fueltype specific load data_over_years = [] for model_year_object in results_every_year.values(): # Sum fuel across all regions fuel_all_regs = np.sum(model_year_object, axis=1) # (fueltypes, 8760 hours) # Get peak day across all enduses for every region _, gw_peak_fueltyp_h = enduse_func.get_peak_day_single_fueltype(fuel_all_regs[fueltype_int]) # Add peak hour data_over_years.append(gw_peak_fueltyp_h) y_init[fueltype] = data_over_years # ---------- # Plot lines # ---------- #linestyles = plotting_styles.linestyles() years = list(results_every_year.keys()) for fueltype, _ in enumerate(y_init): plt.plot( years, y_init[fueltype], linewidth=0.7) ax.legend( legend_entries, prop={ 'family': 'arial', 'size': 8}, frameon=False) # - # Axis # - base_yr = 2015 major_interval = 10 minor_interval = 5 # Major ticks major_ticks = np.arange(base_yr, years[-1] + major_interval, major_interval) ax.set_xticks(major_ticks) # Minor ticks minor_ticks = np.arange(base_yr, years[-1] + minor_interval, minor_interval) ax.set_xticks(minor_ticks, minor=True) plt.xlim(2015, years[-1]) # -------- # Labeling # -------- plt.ylabel("GW") plt.xlabel("year") plt.title("ED peak hour, y, all enduses and regions") # Tight layout plt.tight_layout() plt.margins(x=0) # Save fig fig.savefig(path_plot_fig) plt.close()
def spatio_temporal_val(ed_fueltype_national_yh, ed_fueltype_regs_yh, result_paths, paths, regions, seasons, model_yeardays_daytype, plot_crit): """Validate spatial and temporal energy demands Info ----- Because the floor area is only availabe for LADs from 2001, the LADs are converted to 2015 LADs. """ logging.info("... temporal validation") fueltypes = lookup_tables.basic_lookups()['fueltypes'] # ------------------------------------------- # Spatial validation after calculations # ------------------------------------------- subnational_elec = data_loader.read_lad_demands( paths['val_subnational_elec']) subnational_gas = data_loader.read_lad_demands( paths['val_subnational_gas']) # Create fueltype secific dict fuel_elec_regs_yh = {} for region_array_nr, region in enumerate(regions): fuel_elec_regs_yh[region] = np.sum( ed_fueltype_regs_yh[fueltypes['electricity']][region_array_nr]) # Create fueltype secific dict fuel_gas_regs_yh = {} for region_array_nr, region in enumerate(regions): fuel_gas_regs_yh[region] = np.sum( ed_fueltype_regs_yh[fueltypes['gas']][region_array_nr]) # ---------------------------------------- # Remap demands between 2011 and 2015 LADs # ---------------------------------------- subnational_elec = map_LAD_2011_2015(subnational_elec) subnational_gas = map_LAD_2011_2015(subnational_gas) fuel_elec_regs_yh = map_LAD_2011_2015(fuel_elec_regs_yh) fuel_gas_regs_yh = map_LAD_2011_2015(fuel_gas_regs_yh) spatial_validation(fuel_elec_regs_yh, subnational_elec, regions, 'elec', fig_name=os.path.join( result_paths['data_results_validation'], 'validation_spatial_elec_post_calcualtion.pdf'), label_points=False, plotshow=plot_crit) spatial_validation(fuel_gas_regs_yh, subnational_gas, regions, 'gas', fig_name=os.path.join( result_paths['data_results_validation'], 'validation_spatial_gas_post_calcualtion.pdf'), label_points=False, plotshow=plot_crit) # ------------------------------------------- # Temporal validation (hourly for national) # ------------------------------------------- # Read validation data elec_2015_indo, elec_2015_itsdo = elec_national_data.read_raw_elec_2015( paths['val_nat_elec_data']) f_diff_elec = np.sum(ed_fueltype_national_yh[ fueltypes['electricity']]) / np.sum(elec_2015_indo) logging.info("... ed diff modellend and real [p] %s: ", (1 - f_diff_elec) * 100) elec_factored_yh = f_diff_elec * elec_2015_indo temporal_validation(result_paths, ed_fueltype_national_yh[fueltypes['electricity']], elec_factored_yh, plot_crit) # --------------------------------------------------- # Calculate average season and daytypes and plot # --------------------------------------------------- logging.info("...calculate average data and plot per season and fueltype") calc_av_lp_modelled, calc_lp_modelled = load_profile.calc_av_lp( ed_fueltype_national_yh[fueltypes['electricity']], seasons, model_yeardays_daytype) calc_av_lp_real, calc_lp_real = load_profile.calc_av_lp( elec_factored_yh, seasons, model_yeardays_daytype) # Plot average daily loads fig_load_profile_dh_multiple.run( path_fig_folder=result_paths['data_results_validation'], path_plot_fig=os.path.join(result_paths['data_results_validation'], 'validation_all_season_daytypes.pdf'), calc_av_lp_modelled=calc_av_lp_modelled, calc_av_lp_real=calc_av_lp_real, calc_lp_modelled=calc_lp_modelled, calc_lp_real=calc_lp_real, plot_peak=True, plot_radar=False, plot_all_entries=False, plot_max_min_polygon=True, plotshow=False, max_y_to_plot=60, fueltype_str=False, year=False) # --------------------------------------------------- # Validation of national electrictiy demand for peak # --------------------------------------------------- logging.debug("...validation of peak data: compare peak with data") # Because the coldest day is not the same for every region, # the coldest day needs to be defined manually or defined # by getting the hours with maximum electricity demand # Peak across all fueltypes WARNING: Fueltype specific peak_day_all_fueltypes = enduse_func.get_peak_day_all_fueltypes( ed_fueltype_national_yh) logging.info("Peak day 'peak_day_all_fueltypes': " + str(peak_day_all_fueltypes)) fueltype = fueltypes['electricity'] peak_day_electricity, _ = enduse_func.get_peak_day_single_fueltype( ed_fueltype_national_yh[fueltype]) logging.info("Peak day 'peak_day_electricity': " + str(peak_day_electricity)) elec_national_data.compare_peak( "validation_peak_elec_day_all_fueltypes.pdf", result_paths['data_results_validation'], elec_2015_indo[peak_day_all_fueltypes], ed_fueltype_national_yh[ fueltypes['electricity']][peak_day_all_fueltypes], peak_day_all_fueltypes) elec_national_data.compare_peak( "validation_peak_elec_day_only_electricity.pdf", result_paths['data_results_validation'], elec_2015_indo[peak_day_electricity], ed_fueltype_national_yh[ fueltypes['electricity']][peak_day_electricity], peak_day_electricity) # Manual peak day peak_day = 19 elec_national_data.compare_peak( "validation_elec_peak_day_{}.pdf".format(peak_day), result_paths['data_results_validation'], elec_factored_yh[peak_day], ed_fueltype_national_yh[fueltypes['electricity']][peak_day], peak_day) peak_day = 33 elec_national_data.compare_peak( "validation_elec_peak_day_{}.pdf".format(peak_day), result_paths['data_results_validation'], elec_factored_yh[peak_day], ed_fueltype_national_yh[fueltypes['electricity']][peak_day], peak_day) peak_day_real_electricity, _ = enduse_func.get_peak_day_single_fueltype( elec_2015_indo) logging.info("Peak day 'peak_day_electricity': " + str(peak_day_real_electricity)) #raise Exception elec_national_data.compare_peak( "validation_elec_peak_day_{}.pdf".format(peak_day_real_electricity), result_paths['data_results_validation'], elec_factored_yh[peak_day], ed_fueltype_national_yh[fueltypes['electricity']] [peak_day_real_electricity], peak_day_real_electricity) # --------------------------------------------------- # Validate boxplots for every hour (temporal validation) # --------------------------------------------------- elec_national_data.compare_results_hour_boxplots( "validation_hourly_boxplots_electricity_01.pdf", result_paths['data_results_validation'], elec_2015_indo, ed_fueltype_national_yh[fueltypes['electricity']]) return
def write_space_and_water_heating(sim_yr, path_result, tot_fuel_y_enduse_specific_yh, filename): """Write out enduse specific results for every hour and store to `.npy` file Arguments ----------- sim_yr : int Simulation year path_result : str Path tot_fuel_y_enduse_specific_yh : dict Modelling results filename : str File name """ statistics_to_print = [] statistics_to_print.append("{}\t \t \t \t{}".format( "Enduse", "total_annual_GWh")) # Create folder for model simulation year basic_functions.create_folder(path_result) basic_functions.create_folder(path_result, "enduse_specific_results") for _, fuel in tot_fuel_y_enduse_specific_yh.items(): shape = fuel.shape fuel_aggregated = np.zeros(shape) break for enduse, fuel in tot_fuel_y_enduse_specific_yh.items(): logging.info( " ... Enduse specific writing to file: %s Total demand: %s ", enduse, np.sum(fuel)) if enduse in [ 'rs_space_heating', 'ss_space_heating', 'is_space_heating', 'rs_water_heating', 'ss_water_heating' ]: fuel_aggregated += fuel path_file = os.path.join( os.path.join(path_result, "enduse_specific_results"), "{}__{}__{}{}".format(filename, "all_heating", sim_yr, ".npy")) # Find peak day of electricity across all heating end uses lookups = lookup_tables.basic_lookups() fueltype_int = lookups['fueltypes']['electricity'] peak_day_electricity, _ = enduse_func.get_peak_day_single_fueltype( fuel_aggregated[fueltype_int]) selected_hours = date_prop.convert_yearday_to_8760h_selection( peak_day_electricity) selected_demand = fuel_aggregated[:, selected_hours] np.save(path_file, selected_demand) statistics_to_print.append("{}\t\t\t\t{}".format("all_heating", np.sum(fuel_aggregated))) # Create statistic files with sum of all end uses path_file = os.path.join( os.path.join(path_result, "enduse_specific_results"), "{}__{}__{}".format("statistics_end_uses", sim_yr, ".txt")) write_list_to_txt(path_file, statistics_to_print)
def __init__( self, name, base_yr, curr_yr, strategy_variables, t_bases, t_diff_param, tech_lists, technologies, assumptions, fueltypes, model_yeardays_nrs, model_yeardays, yeardays_month_days, all_enduses, temp_by, tech_lp, sectors, ): """Constructor of weather region """ self.name = name # ----------------------------------- # Calculate current year temperatures # ----------------------------------- temp_cy = change_temp_climate(temp_by, yeardays_month_days, strategy_variables, base_yr, curr_yr) # Change base temperatures depending on change in t_base rs_t_base_heating_cy = hdd_cdd.sigm_temp( strategy_variables['rs_t_base_heating_future_yr'] ['scenario_value'], t_bases.rs_t_heating_by, base_yr, curr_yr, t_diff_param) '''rs_t_base_cooling_cy = hdd_cdd.sigm_temp( strategy_variables['rs_t_base_cooling_future_yr']['scenario_value'], t_bases.rs_t_cooling_by, base_yr, curr_yr, t_diff_param)''' ss_t_base_heating_cy = hdd_cdd.sigm_temp( strategy_variables['ss_t_base_heating_future_yr'] ['scenario_value'], t_bases.ss_t_heating_by, base_yr, curr_yr, t_diff_param) ss_t_base_cooling_cy = hdd_cdd.sigm_temp( strategy_variables['ss_t_base_cooling_future_yr'] ['scenario_value'], t_bases.ss_t_cooling_by, base_yr, curr_yr, t_diff_param) is_t_base_heating_cy = hdd_cdd.sigm_temp( strategy_variables['is_t_base_heating_future_yr'] ['scenario_value'], t_bases.is_t_heating_by, base_yr, curr_yr, t_diff_param) '''is_t_base_cooling_cy = hdd_cdd.sigm_temp( strategy_variables['is_t_base_cooling_future_yr']['scenario_value'], t_bases.is_t_cooling_by, base_yr, curr_yr, t_diff_param)''' # ------------------- # Technology stocks # ------------------- self.rs_tech_stock = technological_stock.TechStock( 'rs_tech_stock', technologies, tech_lists, assumptions.enduse_overall_change['other_enduse_mode_info'], base_yr, curr_yr, fueltypes, temp_by, temp_cy, t_bases.rs_t_heating_by, all_enduses['rs_enduses'], rs_t_base_heating_cy, assumptions.rs_specified_tech_enduse_by) self.ss_tech_stock = technological_stock.TechStock( 'ss_tech_stock', technologies, tech_lists, assumptions.enduse_overall_change['other_enduse_mode_info'], base_yr, curr_yr, fueltypes, temp_by, temp_cy, t_bases.ss_t_heating_by, all_enduses['ss_enduses'], ss_t_base_heating_cy, assumptions.ss_specified_tech_enduse_by) self.is_tech_stock = technological_stock.TechStock( 'is_tech_stock', technologies, tech_lists, assumptions.enduse_overall_change['other_enduse_mode_info'], base_yr, curr_yr, fueltypes, temp_by, temp_cy, t_bases.is_t_heating_by, all_enduses['is_enduses'], ss_t_base_heating_cy, assumptions.is_specified_tech_enduse_by) # ------------------- # Residential Load profiles # ------------------ self.rs_load_profiles = load_profile.LoadProfileStock( "rs_load_profiles") # --------Calculate HDD/CDD self.rs_hdd_by, _ = hdd_cdd.calc_reg_hdd(temp_by, t_bases.rs_t_heating_by, model_yeardays) self.rs_hdd_cy, rs_fuel_shape_heating_yd = hdd_cdd.calc_reg_hdd( temp_cy, rs_t_base_heating_cy, model_yeardays) #self.rs_cdd_by, _ = hdd_cdd.calc_reg_cdd( # temp_by, t_bases.rs_t_cooling_by, model_yeardays) #self.rs_cdd_cy, rs_fuel_shape_cooling_yd = hdd_cdd.calc_reg_cdd( # temp_cy, rs_t_base_cooling_cy, model_yeardays) # -------Calculate climate change correction factors try: self.f_heat_rs_y = np.nan_to_num( 1.0 / float(np.sum(self.rs_hdd_by))) * np.sum(self.rs_hdd_cy) #self.f_cooling_rs_y = np.nan_to_num( # 1.0 / float(np.sum(self.rs_cdd_by))) * np.sum(self.rs_cdd_cy) self.f_cooling_rs_y = 1 except ZeroDivisionError: self.f_heat_rs_y = 1 self.f_cooling_rs_y = 1 # yd peak factors for heating and cooling rs_peak_yd_heating_factor = get_shape_peak_yd_factor(self.rs_hdd_cy) ''' # RESIDENITAL COOLING #rs_peak_yd_cooling_factor = get_shape_peak_yd_factor(self.rs_cdd_cy) rs_cold_techs = tech_lists['rs_cold'] rs_cold_techs.append('placeholder_tech') # ----Cooling residential #rs_fuel_shape_cooling_yh = load_profile.calc_yh( # rs_fuel_shape_cooling_yd, tech_lp['rs_shapes_cooling_dh'], model_yeardays) #or also (if only yd) #shape_yh=tech_lp['rs_shapes_dh'][cooling_enduse]['shape_non_peak_y_dh'] * ss_fuel_shape_coolin_yd[:, np.newaxis], rs_fuel_shape_cooling_yh = self.get_shape_cooling_yh(data, rs_fuel_shape_cooling_yd, 'rs_shapes_cooling_dh') for cooling_enduse in assumptions.enduse_rs_space_cooling: self.rs_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=rs_cold_techs, enduses=enduse, #['rs_cooling'], shape_yd=rs_fuel_shape_cooling_yd, shape_yh=rs_fuel_shape_cooling_yh, f_peak_yd=rs_peak_yd_cooling_factor, shape_peak_dh=tech_lp['rs_shapes_cooling_dh']['peakday']) ''' # ------Heating boiler rs_profile_boilers_y_dh = load_profile.calc_yh( rs_fuel_shape_heating_yd, tech_lp['rs_profile_boilers_y_dh'], model_yeardays) self.rs_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=tech_lists['heating_const'], enduses=['rs_space_heating', 'rs_water_heating'], shape_yd=rs_fuel_shape_heating_yd, shape_yh=rs_profile_boilers_y_dh, f_peak_yd=rs_peak_yd_heating_factor, shape_peak_dh=tech_lp['rs_lp_heating_boilers_dh']['peakday']) # ------Heating CHP rs_profile_chp_y_dh = load_profile.calc_yh( rs_fuel_shape_heating_yd, tech_lp['rs_profile_chp_y_dh'], model_yeardays) self.rs_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=tech_lists['tech_CHP'], enduses=['rs_space_heating', 'rs_water_heating'], shape_yd=rs_fuel_shape_heating_yd, shape_yh=rs_profile_chp_y_dh, f_peak_yd=rs_peak_yd_heating_factor, shape_peak_dh=tech_lp['rs_lp_heating_CHP_dh']['peakday']) # ------Electric heating, storage heating (primary) rs_profile_storage_heater_y_dh = load_profile.calc_yh( rs_fuel_shape_heating_yd, tech_lp['rs_profile_storage_heater_y_dh'], model_yeardays) self.rs_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=tech_lists['storage_heating_electricity'], enduses=['rs_space_heating', 'rs_water_heating'], shape_yd=rs_fuel_shape_heating_yd, shape_yh=rs_profile_storage_heater_y_dh, f_peak_yd=rs_peak_yd_heating_factor, shape_peak_dh=tech_lp['rs_lp_storage_heating_dh']['peakday']) # ------Electric heating secondary (direct elec heating) rs_profile_elec_heater_y_dh = load_profile.calc_yh( rs_fuel_shape_heating_yd, tech_lp['rs_profile_elec_heater_y_dh'], model_yeardays) self.rs_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=tech_lists['secondary_heating_electricity'], enduses=['rs_space_heating', 'rs_water_heating'], shape_yd=rs_fuel_shape_heating_yd, shape_yh=rs_profile_elec_heater_y_dh, f_peak_yd=rs_peak_yd_heating_factor, shape_peak_dh=tech_lp['rs_lp_second_heating_dh']['peakday']) # ------Heat pump heating rs_fuel_shape_hp_yh, _ = get_fuel_shape_heating_hp_yh( tech_lp['rs_profile_hp_y_dh'], self.rs_tech_stock, self.rs_hdd_cy, model_yeardays) self.rs_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=tech_lists['heating_non_const'], enduses=['rs_space_heating', 'rs_water_heating'], shape_yd=rs_fuel_shape_heating_yd, shape_yh=rs_fuel_shape_hp_yh, f_peak_yd=rs_peak_yd_heating_factor, shape_peak_dh=tech_lp['rs_lp_heating_CHP_dh']['peakday']) # ------District_heating_electricity --> Assumption made that same curve as CHP rs_profile_chp_y_dh = load_profile.calc_yh( rs_fuel_shape_heating_yd, tech_lp['rs_profile_chp_y_dh'], model_yeardays) self.rs_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=tech_lists['tech_district_heating'], enduses=['rs_space_heating', 'rs_water_heating'], shape_yd=rs_fuel_shape_heating_yd, shape_yh=rs_profile_chp_y_dh, f_peak_yd=rs_peak_yd_heating_factor, shape_peak_dh=tech_lp['rs_lp_heating_boilers_dh']['peakday']) # ------------------- # Service Load profiles # ------------------ self.ss_load_profiles = load_profile.LoadProfileStock( "ss_load_profiles") # --------HDD/CDD ss_hdd_by, _ = hdd_cdd.calc_reg_hdd(temp_by, t_bases.ss_t_heating_by, model_yeardays) ss_hdd_cy, ss_fuel_shape_heating_yd = hdd_cdd.calc_reg_hdd( temp_cy, ss_t_base_heating_cy, model_yeardays) ss_cdd_by, _ = hdd_cdd.calc_reg_cdd(temp_by, t_bases.ss_t_cooling_by, model_yeardays) ss_cdd_cy, ss_fuel_shape_coolin_yd = hdd_cdd.calc_reg_cdd( temp_cy, ss_t_base_cooling_cy, model_yeardays) try: self.f_heat_ss_y = np.nan_to_num( 1.0 / float(np.sum(ss_hdd_by))) * np.sum(ss_hdd_cy) self.f_cooling_ss_y = np.nan_to_num( 1.0 / float(np.sum(ss_cdd_by))) * np.sum(ss_cdd_cy) except ZeroDivisionError: self.f_heat_ss_y = 1 self.f_cooling_ss_y = 1 # ---------------------------------------------- # Apply weekend correction factor fo ss heating # ---------------------------------------------- ss_peak_yd_heating_factor = get_shape_peak_yd_factor(ss_hdd_cy) ss_peak_yd_cooling_factor = get_shape_peak_yd_factor(ss_cdd_cy) # --Heating technologies for service sector # # (the heating shape follows the gas shape of aggregated sectors) # meaning that for all technologies, the load profile is the same ss_fuel_shape_any_tech, ss_fuel_shape = ss_get_sector_enduse_shape( tech_lp['ss_all_tech_shapes_dh'], ss_fuel_shape_heating_yd, 'ss_space_heating', model_yeardays_nrs) # Apply correction factor for weekend_effect # ------ ss_fuel_shape_heating_yd = ss_fuel_shape_heating_yd * assumptions.ss_weekend_f ss_fuel_shape_heating_yd_weighted = load_profile.abs_to_rel( ss_fuel_shape_heating_yd) # ------ # Flatten list of all potential technologies ss_space_heating_tech_lists = list(tech_lists.values()) all_techs_ss_space_heating = [ item for sublist in ss_space_heating_tech_lists for item in sublist ] # ---------------- # Get peak day and calculate peak load profile for peak day # ---------------- peak_day = get_peak_day_single_fueltype(ss_fuel_shape) ss_space_heating_shape_peak_dh = load_profile.abs_to_rel( ss_fuel_shape[peak_day]) self.ss_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=all_techs_ss_space_heating, enduses=['ss_space_heating'], sectors=sectors['ss_sectors'], shape_yd=ss_fuel_shape_heating_yd_weighted, shape_yh=ss_fuel_shape_any_tech, f_peak_yd=ss_peak_yd_heating_factor, shape_peak_dh=ss_space_heating_shape_peak_dh) #------ # Add cooling technologies for service sector #------ coolings_techs = tech_lists['cooling_const'] for cooling_enduse in assumptions.ss_enduse_space_cooling: for sector in sectors['ss_sectors']: # Apply correction factor for weekend_effect 'cdd_weekend_cfactors' ss_fuel_shape_coolin_yd = ss_fuel_shape_coolin_yd * assumptions.cdd_weekend_cfactors ss_fuel_shape_coolin_yd = load_profile.abs_to_rel( ss_fuel_shape_coolin_yd) # Ev auch tech_lp['ss_shapes_cooling_dh'] ss_shape_yh = load_profile.calc_yh( ss_fuel_shape_coolin_yd, tech_lp['ss_profile_cooling_y_dh'], model_yeardays) self.ss_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=coolings_techs, enduses=[cooling_enduse], sectors=[sector], shape_yd=ss_fuel_shape_coolin_yd, shape_yh=ss_shape_yh, f_peak_yd=ss_peak_yd_cooling_factor, shape_peak_dh=tech_lp['ss_shapes_cooling_dh']['peakday']) # -------------------------------- # Industry submodel # -------------------------------- self.is_load_profiles = load_profile.LoadProfileStock( "is_load_profiles") # --------HDD/CDD is_hdd_by, _ = hdd_cdd.calc_reg_hdd(temp_by, t_bases.is_t_heating_by, model_yeardays) #is_cdd_by, _ = hdd_cdd.calc_reg_cdd( # temp_by, t_bases.is_t_cooling_by, model_yeardays) # Take same base temperature as for service sector is_hdd_cy, is_fuel_shape_heating_yd = hdd_cdd.calc_reg_hdd( temp_cy, is_t_base_heating_cy, model_yeardays) #is_cdd_cy, _ = hdd_cdd.calc_reg_cdd( # temp_cy, ss_t_base_cooling_cy, model_yeardays) try: self.f_heat_is_y = np.nan_to_num( 1.0 / float(np.sum(is_hdd_by))) * np.sum(is_hdd_cy) #self.f_cooling_is_y = np.nan_to_num(1.0 / float(np.sum(is_cdd_by))) * np.sum(is_cdd_cy) self.f_cooling_is_y = 1 except ZeroDivisionError: self.f_heat_is_y = 1 self.f_cooling_is_y = 1 is_peak_yd_heating_factor = get_shape_peak_yd_factor(is_hdd_cy) #is_peak_yd_cooling_factor = self.get_shape_peak_yd_factor(is_cdd_cy) # Cooling for industrial enduse # --Heating technologies for service sector (the heating shape follows # the gas shape of aggregated sectors) # Flatten list of all potential heating technologies is_space_heating_tech_lists = list(tech_lists.values()) all_techs_is_space_heating = [ item for sublist in is_space_heating_tech_lists for item in sublist ] # Apply correction factor for weekend_effect for space heating load profile is_fuel_shape_heating_yd = is_fuel_shape_heating_yd * assumptions.is_weekend_f is_fuel_shape_heating_yd = load_profile.abs_to_rel( is_fuel_shape_heating_yd) # Y_dh Heating profile is taken from service sector is_fuel_shape_any_tech, _ = ss_get_sector_enduse_shape( tech_lp['ss_all_tech_shapes_dh'], is_fuel_shape_heating_yd, 'ss_space_heating', assumptions.model_yeardays_nrs) # Alternatively generate y_dh flat profile #from energy_demand.profiles import generic_shapes #shape_peak_dh, _, shape_peak_yd_factor, shape_non_peak_yd, shape_non_peak_yh = generic_shapes.flat_shape( # assumptions.model_yeardays_nrs) #flat_is_fuel_shape_any_tech = np.full((assumptions.model_yeardays_nrs, 24), (1.0/24.0), dtype=float) #flat_is_fuel_shape_any_tech = flat_is_fuel_shape_any_tech * is_fuel_shape_heating_yd[:, np.newaxis] self.is_load_profiles.add_lp( unique_identifier=uuid.uuid4(), technologies=all_techs_is_space_heating, enduses=['is_space_heating'], sectors=sectors['is_sectors'], shape_yd=is_fuel_shape_heating_yd, shape_yh=is_fuel_shape_any_tech, #flat_is_fuel_shape_any_tech, f_peak_yd=is_peak_yd_heating_factor)
def lad_comparison_peak(base_yr, comparison_year, regions, ed_year_fueltype_regs_yh, fueltype_int, fueltype_str, fig_name, label_points=False, plotshow=False): """Compare energy demand for regions for the base yeard and a future year Arguments ---------- comparison_year : int Year to compare base year values to Note ----- SOURCE OF LADS: - Data for northern ireland is not included in that, however in BEIS dataset! """ result_dict = defaultdict(dict) # ------------------------------------------- # Get base year modelled demand # ------------------------------------------- for year, fuels in ed_year_fueltype_regs_yh.items(): if year == base_yr: for region_array_nr, reg_geocode in enumerate(regions): _, gw_peak_fueltyp_h = enduse_func.get_peak_day_single_fueltype( fuels[fueltype_int][region_array_nr]) result_dict['demand_by'][reg_geocode] = gw_peak_fueltyp_h elif year == comparison_year: for region_array_nr, reg_geocode in enumerate(regions): _, gw_peak_fueltyp_h = enduse_func.get_peak_day_single_fueltype( fuels[fueltype_int][region_array_nr]) result_dict['demand_cy'][reg_geocode] = gw_peak_fueltyp_h else: pass # ----------------- # Sort results according to size # ----------------- sorted_dict_real = sorted(result_dict['demand_by'].items(), key=operator.itemgetter(1)) # ------------------------------------- # Plot # ------------------------------------- fig = plt.figure(figsize=basic_plot_functions.cm2inch(9, 8)) #width, height ax = fig.add_subplot(1, 1, 1) x_values = np.arange(0, len(sorted_dict_real), 1) y_real_elec_demand = [] y_modelled_elec_demand = [] labels = [] for sorted_region in sorted_dict_real: geocode_lad = sorted_region[0] y_real_elec_demand.append(result_dict['demand_by'][geocode_lad]) y_modelled_elec_demand.append(result_dict['demand_cy'][geocode_lad]) logging.debug( "validation for LAD region: %s %s diff: %s", result_dict['demand_by'][geocode_lad], result_dict['demand_cy'][geocode_lad], result_dict['demand_cy'][geocode_lad] - result_dict['demand_by'][geocode_lad]) labels.append(geocode_lad) # -------- # Axis # -------- plt.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off') # labels along the bottom edge are off # ---------------------------------------------- # Plot # ---------------------------------------------- plt.plot( x_values, y_real_elec_demand, linestyle='None', marker='o', markersize=1.6, #1.6 fillstyle='full', markerfacecolor='grey', markeredgewidth=0.2, color='black', label='base year: {}'.format(base_yr)) plt.plot(x_values, y_modelled_elec_demand, marker='o', linestyle='None', markersize=1.6, markerfacecolor='white', fillstyle='none', markeredgewidth=0.5, markeredgecolor='blue', color='black', label='current year: {}'.format(comparison_year)) # Limit plt.ylim(ymin=0, ymax=1.2) # ----------- # Labelling # ----------- if label_points: for pos, txt in enumerate(labels): ax.text(x_values[pos], y_modelled_elec_demand[pos], txt, horizontalalignment="right", verticalalignment="top", fontsize=3) plt.xlabel("UK regions (excluding northern ireland)") plt.ylabel("peak h {} [GWh]".format(fueltype_str)) # -------- # Legend # -------- plt.legend(prop={'family': 'arial', 'size': 8}, frameon=False) # Tight layout plt.margins(x=0) plt.tight_layout() plt.savefig(fig_name) if plotshow: plt.show() plt.close() else: plt.close()
for initialization in all_realizations: path_sim_yr = os.path.join( path_results, scenario, initialization, "simulation_results", "model_run_results_txt", "only_fueltype_reg_8760", "fueltype_reg_8760__{}.npy".format(simulation_yr)) print(" ... loading scenario: {}".format(initialization), flush=True) full_result = np.load(path_sim_yr) container_all_initialisations.append(full_result) # Check peak fueltype_int = tech_related.get_fueltype_int('electricity') national_hourly_demand = np.sum(full_result[fueltype_int], axis=0) peak_day_electricity, _ = enduse_func.get_peak_day_single_fueltype( national_hourly_demand) selected_hours = date_prop.convert_yearday_to_8760h_selection( peak_day_electricity) print("PEAK electricity: " + str(np.max(national_hourly_demand[selected_hours]))) for fueltype_str in fueltypes: print(" ...fueltype {}".format(fueltype_str), flush=True) fueltype_int = tech_related.get_fueltype_int(fueltype_str) # -------- # Calculate # -------- path_ini_file = os.path.join(path_results, scenario, all_realizations[0]) _, _, regions = data_loader.load_ini_param(path_ini_file)
def plt_regions_peak_h(results_every_year, lookups, regions, path_plot_fig, fueltype_str_to_plot): """Plot Arguments --------- """ fig = plt.figure(figsize=basic_plot_functions.cm2inch(14, 8)) ax = fig.add_subplot(1, 1, 1) nr_y_to_plot = len(results_every_year) legend_entries = [] for fueltype_str, fueltype in lookups['fueltypes'].items(): if fueltype_str != fueltype_str_to_plot: pass else: # Legend # Read out fueltype specific load data_over_years = {} for reg_nr, reg_geocode in enumerate(regions): data_over_years[reg_nr] = [] for model_year_object in results_every_year.values(): for reg_nr, reg_geocode in enumerate(regions): # Get peak hour value _, peak_fueltyp_h = enduse_func.get_peak_day_single_fueltype( model_year_object[fueltype][reg_nr]) # Add peak hour data_over_years[reg_nr].append(peak_fueltyp_h) y_init = data_over_years # ---------- # Plot lines # ---------- #linestyles = plotting_styles.linestyles() years = list(results_every_year.keys()) for reg in y_init: plt.plot( years, y_init[reg], #linestyle=linestyles[fueltype], color='lightblue', linewidth=0.2, ) ax.legend(legend_entries, prop={ 'family': 'arial', 'size': 8 }, frameon=False) # - # Axis # - base_yr = 2015 major_interval = 10 minor_interval = 5 # Major ticks major_ticks = np.arange(base_yr, years[-1] + major_interval, major_interval) ax.set_xticks(major_ticks) # Minor ticks minor_ticks = np.arange(base_yr, years[-1] + minor_interval, minor_interval) ax.set_xticks(minor_ticks, minor=True) plt.xlim(2015, years[-1]) # -------- # Labeling # -------- plt.ylabel("GW") plt.xlabel("year") plt.title("ED peak hour, y, all enduses, single regs") # Tight layout plt.tight_layout() plt.margins(x=0) # Save fig fig.savefig(path_plot_fig) plt.close()