def plot_radar_plot(dh_profile, fig_name, plot_steps=30, plotshow=False):
    """Plot daily load profile on a radar plot

    Arguments
    ---------
    dh_profile : list
        Dh values to plot
    fig_name : str
        Path to save figure

    SOURCE: https://python-graph-gallery.com/390-basic-radar-chart/
    """

    # Get maximum demand
    max_entry = np.array(dh_profile).max()
    max_demand = round(max_entry, -1) + 10  # Round to nearest 10 plus add 10
    max_demand = 120

    nr_of_plot_steps = int(max_demand / plot_steps) + 1

    axis_plots_inner = []
    axis_plots_innter_position = []

    # Inner ciruclar axis
    for i in range(nr_of_plot_steps):
        axis_plots_inner.append(plot_steps * i)
        axis_plots_innter_position.append(str(plot_steps * i))

    data = {'dh_profile': ['testname']}

    for hour in range(24):

        # Key: Label outer circle
        data[hour] = dh_profile[hour]

    # Set data
    df = pd.DataFrame(data)

    # number of variable
    categories = list(df)[1:]

    N = len(categories)

    # We are going to plot the first line of the data frame.
    # But we need to repeat the first value to close the circular graph:
    values = df.loc[0].drop('dh_profile').values.flatten().tolist()

    # Because 0 entry in list is 01:00 time, a value needs to be
    # added for the midnight hour. We therefore add the last entry
    # also to the first position (24:00 value).
    values.insert(0, values[23])

    # What will be the angle of each axis in the plot? (we divide the plot / number of variable)
    angles = [n / float(N) * 2 * math.pi for n in range(N)]
    angles += angles[:1]

    # Initialise the spider plot
    ax = plt.subplot(111, polar=True)

    # Change circula axis
    ax.yaxis.grid(color='lightgrey', linestyle='--', linewidth=0.8,
                  alpha=0.8)  # Circular axis
    ax.xaxis.grid(color='lightgrey', linestyle='--', linewidth=0.8,
                  alpha=0.8)  # Regular axis

    # Change to clockwise cirection
    ax.set_theta_direction(-1)
    #ax.set_theta_offset(pi/2.0)

    # Set first hour on top
    ax.set_theta_zero_location("N")

    # Draw one axe per variable + add labels labels yet
    plt.xticks(angles[:-1], categories, color='grey', size=8)

    # Draw ylabels
    ax.set_rlabel_position(0)
    plt.yticks(axis_plots_inner,
               axis_plots_innter_position,
               color="grey",
               size=7)

    # Set limit to size
    plt.ylim(0, max_demand)

    # Smooth lines
    angles_smoothed, values_smoothed = basic_plot_functions.smooth_data(
        angles, values, spider=True)

    # Plot data
    ax.plot(angles_smoothed, values_smoothed, linestyle='--', linewidth=0.5)

    # plot data points
    '''ax.scatter(angles, values, color="blue", s=10)'''
    '''line_zeros = np.zeros(len(angles_smoothed))
    ax.fill_between(
        angles_smoothed, #zero coordinates
        line_zeros, # line 1
        values_smoothed, # line 2
        color='blue',
        alpha=0.1)'''

    # Fill below
    ax.fill(
        angles_smoothed,  #angles,
        values_smoothed,  #values,
        'blue',  #b
        alpha=0.1)

    # Save fig
    plt.savefig(fig_name)

    if plotshow:
        plt.show()
        plt.close()
    else:
        plt.close()
def plot_radar_plot_multiple_lines(dh_profiles,
                                   fig_name,
                                   plot_steps,
                                   scenario_names,
                                   plotshow=False,
                                   lf_y_by=None,
                                   lf_y_cy=None,
                                   list_diff_max_h=None):
    """Plot daily load profile on a radar plot

    Arguments
    ---------
    dh_profile : list
        Dh values to plot
    fig_name : str
        Path to save figure

    SOURCE: https://python-graph-gallery.com/390-basic-radar-chart/
    """
    fig = plt.figure(figsize=basic_plot_functions.cm2inch(9, 14))

    # Get maximum demand of all lines
    max_entry = 0
    for line_entries in dh_profiles:
        max_in_line = max(line_entries)
        if max_in_line > max_entry:
            max_entry = max_in_line

    max_demand = round(max_entry, -1) + 10  # Round to nearest 10 plus add 10

    nr_of_plot_steps = int(max_demand / plot_steps) + 1

    axis_plots_inner = []
    axis_plots_innter_position = []

    # --------------------
    # Ciruclar axis
    # --------------------
    for i in range(nr_of_plot_steps):
        axis_plots_inner.append(plot_steps * i)
        axis_plots_innter_position.append(str(plot_steps * i))

    # Minor ticks
    minor_tick_interval = plot_steps / 2
    minor_ticks = []
    for i in range(nr_of_plot_steps * 2):
        minor_ticks.append(minor_tick_interval * i)

    # ----
    # Select color scheme
    # ----

    # Colors with scenarios
    #color_scenarios = plotting_styles.color_list_scenarios() #Color scheme Fig 13

    # Colors for plotting Fig. 13
    #color_scenarios = plotting_styles.color_list_selection_dm() # Color scheme Fig 13

    # Color sheme multiple scenarios
    color_scenarios = ['orange', 'darkred', '#3b2c85',
                       '#85cfcb']  #Lines for Fig 12

    color_lines = ['black'] + color_scenarios
    #color_lines = color_scenarios
    years = ['2015', '2050']
    linewidth_list = [1.0, 0.7]
    linestyle_list = ['-', '--']
    scenario_names.insert(0, "any")

    # Iterate lines
    cnt = -1
    for dh_profile in dh_profiles:

        if cnt >= 0:
            cnt_year = 1
        else:
            cnt_year = 0
        cnt += 1

        # Line properties
        color_line = color_lines[cnt]
        year_line = years[cnt_year]

        data = {'dh_profile': ['testname']}

        # Key: Label outer circle
        for hour in range(24):
            data[hour] = dh_profile[hour]

        # Set data
        df = pd.DataFrame(data)

        # number of variable
        categories = list(df)[1:]
        N = len(categories)

        # We are going to plot the first line of the data frame.
        # But we need to repeat the first value to close the circular graph:
        values = df.loc[0].drop('dh_profile').values.flatten().tolist()
        values += values[:1]

        # What will be the angle of each axis in the plot? (we divide the plot / number of variable)
        angles = [n / float(N) * 2 * math.pi for n in range(N)]
        angles += angles[:1]

        # Initialise the spider plot
        ax = plt.subplot(111, polar=True)

        # Change axis properties
        ax.yaxis.grid(color='grey', linestyle=':', linewidth=0.4)
        ax.xaxis.grid(color='lightgrey', linestyle=':', linewidth=0.4)

        # Change to clockwise cirection
        ax.set_theta_direction(-1)

        # Set first hour on top
        ax.set_theta_zero_location("N")

        # Draw one axe per variable + add labels labels yet (numbers)
        plt.xticks(angles[:-1], categories, color='black', size=8)

        # Draw ylabels (numbers)
        ax.set_rlabel_position(0)

        # Working alternative
        plt.yticks(axis_plots_inner,
                   axis_plots_innter_position,
                   color="black",
                   size=8)

        #ax.set_yticks(axis_plots_inner, minor=False)
        #ax.tick_params(axis='y', pad=35)
        #ax.set_yticks(minor_ticks, minor=True) #Somehow not working

        # Set limit to size
        plt.ylim(0, max_demand)
        plt.ylim(0, nr_of_plot_steps * plot_steps)

        # Smooth lines
        angles_smoothed, values_smoothed = basic_plot_functions.smooth_data(
            angles, values, spider=True)

        # Plot data
        ax.plot(angles_smoothed,
                values_smoothed,
                color=color_line,
                linestyle=linestyle_list[cnt_year],
                linewidth=linewidth_list[cnt_year],
                label="{} {}".format(year_line, scenario_names[cnt]))

        # Radar area
        ax.fill(angles_smoothed, values_smoothed, color_line, alpha=0.05)

    # ------------
    # Write outs
    # ------------
    font_additional_info = plotting_styles.font_info(size=4)

    for cnt, entry in enumerate(list_diff_max_h):
        plt.text(0.15,
                 0 + cnt / 50,
                 entry,
                 fontsize=2,
                 fontdict=font_additional_info,
                 transform=plt.gcf().transFigure)

    # ------------
    # Legend
    # ------------
    plt.legend(ncol=1,
               bbox_to_anchor=(0.3, -0.05),
               prop={'size': 4},
               frameon=False)

    plt.savefig(fig_name)

    if plotshow:
        plt.show()

    plt.close()
Ejemplo n.º 3
0
def compare_results(name_fig,
                    path_result,
                    y_factored_indo,
                    y_calculated_array,
                    title_left,
                    days_to_plot,
                    plot_crit=False):
    """Compare national electrictiy demand data with model results

    Note
    ----
    RMSE fit criteria : Lower values of RMSE indicate better fit
    https://stackoverflow.com/questions/17197492/root-mean-square-error-in-python

    https://matplotlib.org/examples/lines_bars_and_markers/marker_fillstyle_reference.html
    """
    logging.debug("...compare elec results")
    nr_of_h_to_plot = len(days_to_plot) * 24

    x_data = range(nr_of_h_to_plot)

    y_real_indo_factored = []
    y_calculated_list = []
    y_diff_p = []
    y_diff_abs = []

    for day in days_to_plot:
        for hour in range(24):
            y_calculated_list.append(y_calculated_array[day][hour])
            y_real_indo_factored.append(y_factored_indo[day][hour])

            # Calculate absolute differences
            abs_diff = abs(y_factored_indo[day][hour] -
                           y_calculated_array[day][hour])
            y_diff_abs.append(abs_diff)

            # Calculate difference in percent
            if abs_diff == 0:
                p_diff = 0
            else:
                p_diff = (100 / y_factored_indo[day][hour]
                          ) * y_calculated_array[day][hour] - 100

            y_diff_p.append(p_diff)

    # -------------
    # RMSE
    # -------------
    rmse_val_corrected = basic_functions.rmse(np.array(y_real_indo_factored),
                                              np.array(y_calculated_list))

    # ----------
    # Standard deviation
    # ----------
    standard_dev_real_modelled = np.std(y_diff_p)  # Differences in %
    standard_dev_real_modelled_abs = np.std(y_diff_abs)  # Absolute differences

    logging.info("Standard deviation given as percentage: " +
                 str(standard_dev_real_modelled))
    logging.info("Standard deviation given as GW:         " +
                 str(standard_dev_real_modelled_abs))

    # ---------
    # R squared
    # ---------
    slope, intercept, r_value, p_value, std_err = stats.linregress(
        y_real_indo_factored, y_calculated_list)

    # ----------
    # Plot residuals
    # ----------
    #try:
    #    plot_residual_histogram(
    #        y_diff_p, path_result, "residuals_{}".format(name_fig))
    #except:
    #    pass

    # ----------
    # Plot figure
    # ----------
    fig = plt.figure(figsize=basic_plot_functions.cm2inch(22, 8))

    # smooth line
    x_data_smoothed, y_real_indo_factored_smoothed = basic_plot_functions.smooth_data(
        x_data, y_real_indo_factored, num=40000)

    # plot points
    plt.plot(x_data_smoothed,
             y_real_indo_factored_smoothed,
             label='indo_factored',
             linestyle='-',
             linewidth=0.5,
             fillstyle='full',
             color='black')

    # smooth line
    x_data_smoothed, y_calculated_list_smoothed = basic_plot_functions.smooth_data(
        x_data, y_calculated_list, num=40000)

    plt.plot(x_data_smoothed,
             y_calculated_list_smoothed,
             label='model',
             linestyle='--',
             linewidth=0.5,
             fillstyle='full',
             color='blue')

    plt.xlim([0, 8760])
    plt.margins(x=0)
    plt.axis('tight')

    # --------------------------------------
    # Label x axis in dates
    # --------------------------------------
    major_ticks_days, major_ticks_labels = get_date_strings(days_to_plot,
                                                            daystep=1)

    plt.xticks(major_ticks_days, major_ticks_labels)

    # ----------
    # Labelling
    # ----------
    font_additional_info = plotting_styles.font_info(size=4)

    plt.title('RMSE: {} Std_dev_% {} (+-{} GW) R_2: {}'.format(
        round(rmse_val_corrected, 3), round(standard_dev_real_modelled, 3),
        round(standard_dev_real_modelled_abs, 3), round(r_value, 3)),
              fontdict=font_additional_info,
              loc='right')

    plt.title(title_left, loc='left')

    plt.xlabel("hour", fontsize=10)
    plt.ylabel("uk elec use [GW] for {}".format(title_left), fontsize=10)

    plt.legend(frameon=False)

    plt.savefig(os.path.join(path_result, name_fig))

    if plot_crit:
        plt.show()
    plt.close()
Ejemplo n.º 4
0
def compare_peak(name_fig, path_result, real_elec_2015_peak, modelled_peak_dh,
                 peak_day):
    """Compare peak electricity day with calculated peak energy demand

    Arguments
    ---------
    name_fig : str
        Name of figure
    local_paths : dict
        Paths
    real_elec_2015_peak : array
        Real data of peak day
    modelled_peak_dh : array
        Modelled peak day
    """
    logging.debug("...compare elec peak results")

    real_elec_peak = np.copy(real_elec_2015_peak)
    # -------------------------------
    # Compare values
    # -------------------------------
    fig = plt.figure(figsize=basic_plot_functions.cm2inch(8, 8))

    # smooth line
    x_smoothed, y_modelled_peak_dh_smoothed = basic_plot_functions.smooth_data(
        range(24), modelled_peak_dh, num=500)

    plt.plot(x_smoothed,
             y_modelled_peak_dh_smoothed,
             color='blue',
             linestyle='--',
             linewidth=0.5,
             label='model')

    x_smoothed, real_elec_peak_smoothed = basic_plot_functions.smooth_data(
        range(24), real_elec_peak, num=500)

    plt.plot(x_smoothed,
             real_elec_peak_smoothed,
             color='black',
             linestyle='-',
             linewidth=0.5,
             label='validation')

    #raise Exception
    # Calculate hourly differences in %
    diff_p_h = np.round((100 / real_elec_peak) * modelled_peak_dh, 1)

    # Calculate maximum difference
    max_h_real = np.max(real_elec_peak)
    max_h_modelled = np.max(modelled_peak_dh)

    max_h_diff = round((100 / max_h_real) * max_h_modelled, 2)
    max_h_diff_gwh = round((abs(100 - max_h_diff) / 100) * max_h_real, 2)

    # Y-axis ticks
    plt.xlim(0, 23)
    plt.yticks(range(0, 60, 10))

    # because position 0 in list is 01:00, the labelling starts with 1
    plt.xticks([0, 5, 11, 17, 23], [1, 6, 12, 18, 24])  #ticks, labels

    plt.legend(frameon=False)

    # Labelling
    date_yearday = date_prop.yearday_to_date(2015, peak_day)
    plt.title("peak comparison {}".format(date_yearday))

    plt.xlabel("h (max {} ({} GWH)".format(max_h_diff, max_h_diff_gwh))
    plt.ylabel("uk electrictiy use [GW]")

    plt.text(
        5,  #position
        5,  #position
        diff_p_h,
        fontdict={
            'family': 'arial',
            'color': 'black',
            'weight': 'normal',
            'size': 4
        })

    # Tight layout
    plt.tight_layout()
    plt.margins(x=0)

    # Save fig
    plt.savefig(os.path.join(path_result, name_fig))
    plt.close()
Ejemplo n.º 5
0
def scenario_over_time(scenario_result_container,
                       sim_yrs,
                       fig_name,
                       result_path,
                       plot_points,
                       crit_smooth_line=True,
                       seperate_legend=False):
    """Plot peak over time
    """
    statistics_to_print = []

    fig = plt.figure(figsize=basic_plot_functions.cm2inch(10,
                                                          10))  #width, height

    ax = fig.add_subplot(1, 1, 1)

    for cnt_scenario, i in enumerate(scenario_result_container):
        scenario_name = i['scenario_name']
        national_peak = i['national_peak']

        # dataframe with national peak (columns= simulation year, row: Realisation)
        # Calculate quantiles
        quantile_95 = 0.95
        quantile_05 = 0.05

        try:
            color = colors[scenario_name]
            marker = marker_styles[scenario_name]
        except KeyError:
            color = list(colors.values())[cnt_scenario]

        try:
            marker = marker_styles[scenario_name]
        except KeyError:
            marker = list(marker_styles.values())[cnt_scenario]

        print("SCENARIO NAME {}  {}".format(scenario_name, color))

        # Calculate average across all weather scenarios
        mean_national_peak = national_peak.mean(axis=0)
        mean_national_peak_sim_yrs = copy.copy(mean_national_peak)

        statistics_to_print.append("scenario: {} values over years: {}".format(
            scenario_name, mean_national_peak_sim_yrs))

        # Standard deviation over all realisations
        df_q_05 = national_peak.quantile(quantile_05)
        df_q_95 = national_peak.quantile(quantile_95)

        statistics_to_print.append("scenario: {} df_q_05: {}".format(
            scenario_name, df_q_05))
        statistics_to_print.append("scenario: {} df_q_95: {}".format(
            scenario_name, df_q_95))

        # --------------------
        # Try to smooth lines
        # --------------------
        sim_yrs_smoothed = sim_yrs
        if crit_smooth_line:
            try:
                sim_yrs_smoothed, mean_national_peak_smoothed = basic_plot_functions.smooth_data(
                    sim_yrs, mean_national_peak, num=40000)
                _, df_q_05_smoothed = basic_plot_functions.smooth_data(
                    sim_yrs, df_q_05, num=40000)
                _, df_q_95_smoothed = basic_plot_functions.smooth_data(
                    sim_yrs, df_q_95, num=40000)

                mean_national_peak = pd.Series(mean_national_peak_smoothed,
                                               sim_yrs_smoothed)
                df_q_05 = pd.Series(df_q_05_smoothed, sim_yrs_smoothed)
                df_q_95 = pd.Series(df_q_95_smoothed, sim_yrs_smoothed)
            except:
                sim_yrs_smoothed = sim_yrs

        # -----------------------
        # Plot lines
        # ------------------------
        plt.plot(mean_national_peak,
                 label="{} (mean)".format(scenario_name),
                 color=color)

        # ------------------------
        # Plot markers
        # ------------------------
        if plot_points:
            plt.scatter(sim_yrs,
                        mean_national_peak_sim_yrs,
                        c=color,
                        marker=marker,
                        edgecolor='black',
                        linewidth=0.5,
                        s=15,
                        clip_on=False)  #do not clip points on axis

        # Plottin qunatilse and average scenario
        df_q_05.plot.line(color=color,
                          linestyle='--',
                          linewidth=0.1,
                          label='_nolegend_')  #, label="0.05")
        df_q_95.plot.line(color=color,
                          linestyle='--',
                          linewidth=0.1,
                          label='_nolegend_')  #, label="0.05")

        plt.fill_between(
            sim_yrs_smoothed,
            list(df_q_95),  #y1
            list(df_q_05),  #y2
            alpha=0.25,
            facecolor=color,
        )

    plt.xlim(2015, 2050)
    plt.ylim(0)

    # --------
    # Different style
    # --------
    ax = plt.gca()
    ax.grid(which='major', color='black', axis='y', linestyle='--')

    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['top'].set_visible(False)

    plt.tick_params(
        axis='y',  # changes apply to the x-axis
        which='both',  # both major and minor ticks are affected
        bottom=False,  # ticks along the bottom edge are off
        top=False,  # ticks along the top edge are off
        left=False,
        right=False,
        labelbottom=False,
        labeltop=False,
        labelleft=True,
        labelright=False)  # labels along the bottom edge are off

    # --------
    # Legend
    # --------
    legend = plt.legend(
        #title="tt",
        ncol=2,
        prop={'size': 10},
        loc='upper center',
        bbox_to_anchor=(0.5, -0.1),
        frameon=False)
    legend.get_title().set_fontsize(8)

    if seperate_legend:
        basic_plot_functions.export_legend(
            legend,
            os.path.join(result_path, "{}__{}__legend.pdf".format(fig_name)))
        legend.remove()

    # --------
    # Labeling
    # --------
    plt.ylabel("national peak demand (GW)")
    #plt.xlabel("year")
    #plt.title("Title")

    plt.tight_layout()

    plt.savefig(os.path.join(result_path, fig_name))
    plt.close()

    # Write info to txt
    write_data.write_list_to_txt(
        os.path.join(result_path, fig_name).replace(".pdf", ".txt"),
        statistics_to_print)
def run(data_input, simulation_yr_to_plot, period_h, fueltype_str, fig_name):
    """

    https://stackoverflow.com/questions/18313322/plotting-quantiles-median-and-spread-using-scipy-and-matplotlib

    https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.quantile.html

    """
    # Select period and fueltype
    fueltype_int = tech_related.get_fueltype_int(fueltype_str)

    # -----------------------------------------------------------
    # Iterate overall weather_yrs and store data in dataframe
    # (columns = timestep, rows: value of year)
    # -----------------------------------------------------------
    columns = period_h  # hours in 8760 hours

    # List of selected data for every weather year (which is then converted to array)
    weather_yrs_data = []

    print("Weather yrs: " + str(list(data_input.keys())), flush=True)

    for weather_yr, data_weather_yr in data_input.items():

        # Weather year specific data
        data_input_fueltype = data_weather_yr[simulation_yr_to_plot][
            fueltype_int]  # Select fueltype
        data_input_reshape = data_input_fueltype.reshape(8760)  # reshape
        data_input_selection_hrs = data_input_reshape[
            period_h]  # select period
        weather_yrs_data.append(data_input_selection_hrs)

    weather_yrs_data = np.array(weather_yrs_data)

    # Create dataframe
    df = pd.DataFrame(weather_yrs_data, columns=columns)

    # Calculate quantiles
    quantile_95 = 0.95
    quantile_05 = 0.05

    df_q_95 = df.quantile(quantile_95)
    df_q_05 = df.quantile(quantile_05)

    #Transpose for plotting purposes
    df = df.T
    df_q_95 = df_q_95.T
    df_q_05 = df_q_05.T

    fig = plt.figure()  #(figsize = cm2inch(10,10))

    ax = fig.add_subplot(111)

    # 2015 weather year
    data_2015 = data_weather_yr[2015][fueltype_int].reshape(8760)[period_h]

    # ---------------
    # Smoothing lines
    # ---------------
    try:
        period_h_smoothed, df_q_95_smoothed = basic_plot_functions.smooth_data(
            period_h, df_q_95, num=40000)
        period_h_smoothed, df_q_05_smoothed = basic_plot_functions.smooth_data(
            period_h, df_q_05, num=40000)
        period_h_smoothed, data_2015_smoothed = basic_plot_functions.smooth_data(
            period_h, data_2015, num=40000)
    except:
        period_h_smoothed = period_h
        df_q_95_smoothed = df_q_95
        df_q_05_smoothed = df_q_05
        data_2015_smoothed = data_2015

    plt.plot(period_h_smoothed,
             data_2015_smoothed,
             color='tomato',
             linestyle='-',
             linewidth=2,
             label="2015 weather_yr")
    plt.plot(period_h_smoothed,
             df_q_05_smoothed,
             color='black',
             linestyle='--',
             linewidth=0.5,
             label="0.05")
    plt.plot(period_h_smoothed,
             df_q_95_smoothed,
             color='black',
             linestyle='--',
             linewidth=0.5,
             label="0.95")

    # -----------------
    # Uncertainty range
    # -----------------
    plt.fill_between(
        period_h_smoothed,  #x
        df_q_95_smoothed,  #y1
        df_q_05_smoothed,  #y2
        alpha=.25,
        facecolor="grey",
        label="uncertainty band")

    plt.legend(prop={
        'family': 'arial',
        'size': 10
    },
               loc='best',
               frameon=False,
               shadow=True)

    plt.show()
Ejemplo n.º 7
0
def fueltypes_over_time(scenario_result_container,
                        sim_yrs,
                        fig_name,
                        fueltypes,
                        result_path,
                        plot_points=False,
                        unit='TWh',
                        crit_smooth_line=True,
                        seperate_legend=False):
    """Plot fueltypes over time
    """
    statistics_to_print = []

    fig = plt.figure(figsize=basic_plot_functions.cm2inch(10,
                                                          10))  #width, height
    ax = fig.add_subplot(1, 1, 1)

    colors = {
        # Low elec
        'electricity': '#3e3838',
        'gas': '#ae7c7c',
        'hydrogen': '#6cbbb3',
    }

    line_styles_default = plotting_styles.linestyles()

    linestyles = {
        'h_max': line_styles_default[0],
        'h_min': line_styles_default[6],
        'l_min': line_styles_default[8],
        'l_max': line_styles_default[9],
    }

    for cnt_scenario, i in enumerate(scenario_result_container):
        scenario_name = i['scenario_name']

        for cnt_linestyle, fueltype_str in enumerate(fueltypes):
            national_sum = i['national_{}'.format(fueltype_str)]

            if unit == 'TWh':
                unit_factor = conversions.gwh_to_twh(1)
            elif unit == 'GWh':
                unit_factor = 1
            else:
                raise Exception("Wrong unit")

            national_sum = national_sum * unit_factor

            # Calculate quantiles
            quantile_95 = 0.95
            quantile_05 = 0.05

            try:
                color = colors[fueltype_str]
            except KeyError:
                #color = list(colors.values())[cnt_linestyle]
                raise Exception("Wrong color")

            try:
                linestyle = linestyles[scenario_name]
            except KeyError:
                linestyle = list(linestyles.values())[cnt_scenario]
            try:
                marker = marker_styles[scenario_name]
            except KeyError:
                marker = list(marker_styles.values())[cnt_scenario]

            # Calculate average across all weather scenarios
            mean_national_sum = national_sum.mean(axis=0)
            mean_national_sum_sim_yrs = copy.copy(mean_national_sum)

            statistics_to_print.append(
                "{} fueltype_str: {} mean_national_sum_sim_yrs: {}".format(
                    scenario_name, fueltype_str, mean_national_sum_sim_yrs))

            # Standard deviation over all realisations
            df_q_05 = national_sum.quantile(quantile_05)
            df_q_95 = national_sum.quantile(quantile_95)

            statistics_to_print.append(
                "{} fueltype_str: {} df_q_05: {}".format(
                    scenario_name, fueltype_str, df_q_05))
            statistics_to_print.append(
                "{} fueltype_str: {} df_q_95: {}".format(
                    scenario_name, fueltype_str, df_q_95))
            # --------------------
            # Try to smooth lines
            # --------------------
            sim_yrs_smoothed = sim_yrs
            if crit_smooth_line:
                try:
                    sim_yrs_smoothed, mean_national_sum_smoothed = basic_plot_functions.smooth_data(
                        sim_yrs, mean_national_sum, num=500)
                    _, df_q_05_smoothed = basic_plot_functions.smooth_data(
                        sim_yrs, df_q_05, num=500)
                    _, df_q_95_smoothed = basic_plot_functions.smooth_data(
                        sim_yrs, df_q_95, num=500)

                    mean_national_sum = pd.Series(mean_national_sum_smoothed,
                                                  sim_yrs_smoothed)
                    df_q_05 = pd.Series(df_q_05_smoothed, sim_yrs_smoothed)
                    df_q_95 = pd.Series(df_q_95_smoothed, sim_yrs_smoothed)
                except:
                    print("did not owrk {} {}".format(fueltype_str,
                                                      scenario_name))
                    pass

            # ------------------------
            # Plot lines
            # ------------------------
            plt.plot(mean_national_sum,
                     label="{} {}".format(fueltype_str, scenario_name),
                     linestyle=linestyle,
                     color=color,
                     zorder=1,
                     clip_on=True)

            # ------------------------
            # Plot markers
            # ------------------------
            if plot_points:
                plt.scatter(sim_yrs,
                            mean_national_sum_sim_yrs,
                            marker=marker,
                            edgecolor='black',
                            linewidth=0.5,
                            c=color,
                            zorder=2,
                            s=15,
                            clip_on=False)  #do not clip points on axis

            # Plottin qunatilse and average scenario
            df_q_05.plot.line(color=color,
                              linestyle='--',
                              linewidth=0.1,
                              label='_nolegend_')  #, label="0.05")
            df_q_95.plot.line(color=color,
                              linestyle='--',
                              linewidth=0.1,
                              label='_nolegend_')  #, label="0.05")

            plt.fill_between(
                sim_yrs_smoothed,
                list(df_q_95),  #y1
                list(df_q_05),  #y2
                alpha=0.25,
                facecolor=color,
            )

    plt.xlim(2015, 2050)
    plt.ylim(0)

    ax = plt.gca()

    # Major ticks every 20, minor ticks every 5
    major_ticks = [200, 400, 600]  #np.arange(0, 600, 200)
    minor_ticks = [100, 200, 300, 400, 500, 600]  #np.arange(0, 600, 100)

    ax.set_yticks(major_ticks)
    ax.set_yticks(minor_ticks, minor=True)

    # And a corresponding grid
    ax.grid(which='both',
            color='black',
            linewidth=0.5,
            axis='y',
            linestyle=line_styles_default[3])  #[6])

    # Or if you want different settings for the grids:
    ax.grid(which='minor', axis='y', alpha=0.4)
    ax.grid(which='major', axis='y', alpha=0.8)

    # Achsen
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['top'].set_visible(False)

    # Ticks
    plt.tick_params(
        axis='y',  # changes apply to the x-axis
        which='both',  # both major and minor ticks are affected
        bottom=False,  # ticks along the bottom edge are off
        top=False,  # ticks along the top edge are off
        left=False,
        right=False,
        labelbottom=False,
        labeltop=False,
        labelleft=True,
        labelright=False)  # labels along the bottom edge are off

    # --------
    # Legend
    # --------
    legend = plt.legend(
        #title="tt",
        ncol=2,
        prop={'size': 6},
        loc='upper center',
        bbox_to_anchor=(0.5, -0.1),
        frameon=False)
    legend.get_title().set_fontsize(8)

    if seperate_legend:
        basic_plot_functions.export_legend(
            legend, os.path.join(result_path,
                                 "{}__legend.pdf".format(fig_name)))
        legend.remove()

    # --------
    # Labeling
    # --------
    plt.ylabel("national fuel over time [in {}]".format(unit))
    #plt.xlabel("year")
    #plt.title("Title")

    plt.tight_layout()
    #plt.show()
    plt.savefig(os.path.join(result_path, fig_name))
    plt.close()

    write_data.write_list_to_txt(
        os.path.join(result_path, fig_name).replace(".pdf", ".txt"),
        statistics_to_print)
def run(years_simulated,
        results_enduse_every_year,
        enduses,
        color_list,
        fig_name,
        plot_legend=True):
    """Plots stacked energy demand

    Arguments
    ----------
    years_simulated : list
        Simulated years
    results_enduse_every_year : dict
        Results [year][enduse][fueltype_array_position]

    enduses :
    fig_name : str
        Figure name

    Note
    ----
        -   Sum across all fueltypes
        -   Not possible to plot single year

    https://matplotlib.org/examples/pylab_examples/stackplot_demo.html
    """
    print("...plot stacked enduses")
    nr_of_modelled_years = len(years_simulated)

    x_data = np.array(years_simulated)

    y_value_arrays = []
    legend_entries = []

    for enduse in enduses:
        legend_entries.append(enduse)

        y_values_enduse_yrs = np.zeros((nr_of_modelled_years))

        for year_array_nr, model_year in enumerate(
                results_enduse_every_year.keys()):

            # Sum across all fueltypes
            tot_across_fueltypes = np.sum(
                results_enduse_every_year[model_year][enduse])

            # Conversion: Convert GWh per years to GW
            yearly_sum_twh = conversions.gwh_to_twh(tot_across_fueltypes)

            logging.debug("... model_year {} enduse {}  twh {}".format(
                model_year, enduse, np.sum(yearly_sum_twh)))

            if yearly_sum_twh < 0:
                raise Exception("no minus values allowed {}  {}  {}".format(
                    enduse, yearly_sum_twh, model_year))

            y_values_enduse_yrs[year_array_nr] = yearly_sum_twh

        # Add array with values for every year to list
        y_value_arrays.append(y_values_enduse_yrs)

    # Try smoothing line
    try:
        x_data_smoothed, y_value_arrays_smoothed = basic_plot_functions.smooth_data(
            x_data, y_value_arrays, num=40000)
    except:
        x_data_smoothed = x_data
        y_value_arrays_smoothed = y_value_arrays

    # Convert to stacked
    y_stacked = np.row_stack((y_value_arrays_smoothed))

    # Set figure size
    fig = plt.figure(figsize=basic_plot_functions.cm2inch(8, 8))

    ax = fig.add_subplot(1, 1, 1)

    # ----------
    # Stack plot
    # ----------
    color_stackplots = color_list[:len(enduses)]

    ax.stackplot(x_data_smoothed,
                 y_stacked,
                 alpha=0.8,
                 colors=color_stackplots)

    if plot_legend:
        plt.legend(legend_entries,
                   prop={
                       'family': 'arial',
                       'size': 5
                   },
                   ncol=2,
                   loc='upper center',
                   bbox_to_anchor=(0.5, -0.1),
                   frameon=False,
                   shadow=True)

    # -------
    # Axis
    # -------
    year_interval = 10
    major_ticks = np.arange(years_simulated[0],
                            years_simulated[-1] + year_interval, year_interval)

    plt.xticks(major_ticks, major_ticks)

    plt.ylim(ymax=500)
    #yticks = [100, 200, 300, 400, 500]
    #plt.yticks(yticks, yticks)
    # -------
    # Labels
    # -------
    plt.ylabel("TWh", fontsize=10)
    plt.xlabel("Year", fontsize=10)
    #plt.title("ED whole UK", fontsize=10)

    # Tight layout
    fig.tight_layout()

    plt.margins(x=0)
    plt.savefig(fig_name)
    plt.close()
Ejemplo n.º 9
0
def scenario_over_time(
        scenario_result_container,
        field_name,
        sim_yrs,
        fig_name,
        result_path,
        plot_points,
        crit_smooth_line=True,
        seperate_legend=False
    ):
    """Plot peak over time
    """
    statistics_to_print = []

    fig = plt.figure(figsize=basic_plot_functions.cm2inch(10, 10)) #width, height

    ax = fig.add_subplot(1, 1, 1)

    for cnt_scenario, i in enumerate(scenario_result_container):
        scenario_name = i['scenario_name']
        national_peak = i[field_name]

        # dataframe with national peak (columns= simulation year, row: Realisation) 
        # Calculate quantiles
        #quantile_95 = 0.68 #0.95 #0.68
        #quantile_05 = 0.32 #0.05 #0.32

        try:
            color = colors[scenario_name]
            marker = marker_styles[scenario_name]
        except KeyError:
            color = list(colors.values())[cnt_scenario]

        try:
            marker = marker_styles[scenario_name]
        except KeyError:
            marker = list(marker_styles.values())[cnt_scenario]

        #print("SCENARIO NAME {}  {}".format(scenario_name, color))

        # Calculate average across all weather scenarios
        mean_national_peak = national_peak.mean(axis=0)

        mean_national_peak_sim_yrs = copy.copy(mean_national_peak)

        statistics_to_print.append("scenario: {} values over years: {}".format(scenario_name, mean_national_peak_sim_yrs))

        # Standard deviation over all realisations
        #df_q_05 = national_peak.quantile(quantile_05)
        #df_q_95 = national_peak.quantile(quantile_95)

        # Number of sigma
        nr_of_sigma = 1
        std_dev = national_peak.std(axis=0)
        two_std_line_pos = mean_national_peak + (nr_of_sigma * std_dev)
        two_std_line_neg = mean_national_peak - (nr_of_sigma * std_dev)

        # Maximum and minium values
        max_values = national_peak.max()
        min_values = national_peak.min()
        median_values = national_peak.median()

        statistics_to_print.append("scenario: {} two_sigma_pos: {}".format(scenario_name, two_std_line_pos))
        statistics_to_print.append("scenario: {} two_sigma_neg: {}".format(scenario_name, two_std_line_neg))
        statistics_to_print.append("--------min-------------- {}".format(scenario_name))
        statistics_to_print.append("{}".format(min_values)) #Get minimum value for every simulation year of all realizations
        statistics_to_print.append("--------max-------------- {}".format(scenario_name))
        statistics_to_print.append("{}".format(max_values))
        statistics_to_print.append("--------median_-------------- {}".format(scenario_name))
        statistics_to_print.append("{}".format(median_values))
        # --------------------
        # Try to smooth lines
        # --------------------
        sim_yrs_smoothed = sim_yrs
        if crit_smooth_line:
            try:
                sim_yrs_smoothed, mean_national_peak_smoothed = basic_plot_functions.smooth_data(sim_yrs, mean_national_peak, num=40000)
                #_, df_q_05_smoothed = basic_plot_functions.smooth_data(sim_yrs, df_q_05, num=40000)
                #_, df_q_95_smoothed = basic_plot_functions.smooth_data(sim_yrs, df_q_95, num=40000)
                _, two_std_line_pos_smoothed = basic_plot_functions.smooth_data(sim_yrs, two_std_line_pos, num=40000)
                _, two_std_line_neg_smoothed = basic_plot_functions.smooth_data(sim_yrs, two_std_line_neg, num=40000)
                _, max_values_smoothed = basic_plot_functions.smooth_data(sim_yrs, max_values, num=40000)
                _, min_values_smoothed = basic_plot_functions.smooth_data(sim_yrs, min_values, num=40000)
                mean_national_peak = pd.Series(mean_national_peak_smoothed, sim_yrs_smoothed)
                #df_q_05 = pd.Series(df_q_05_smoothed, sim_yrs_smoothed)
                #df_q_95 = pd.Series(df_q_95_smoothed, sim_yrs_smoothed)
                two_std_line_pos = pd.Series(two_std_line_pos_smoothed, sim_yrs_smoothed)
                two_std_line_neg = pd.Series(two_std_line_neg_smoothed, sim_yrs_smoothed)

                max_values = pd.Series(max_values_smoothed, sim_yrs_smoothed).values
                min_values = pd.Series(min_values_smoothed, sim_yrs_smoothed).values
            except:
                sim_yrs_smoothed = sim_yrs

        # -----------------------
        # Plot lines
        # ------------------------
        plt.plot(
            mean_national_peak,
            label="{} (mean)".format(scenario_name),
            zorder=1,
            color=color)

        # ------------------------
        # Plot markers
        # ------------------------
        if plot_points:
            plt.scatter(
                sim_yrs,
                mean_national_peak_sim_yrs,
                c=color,
                marker=marker,
                edgecolor='black',
                linewidth=0.5,
                zorder=2,
                s=15,
                clip_on=False) #do not clip points on axis

        # ------------------
        # Start with uncertainty one model step later (=> 2020)
        # ------------------
        start_yr_uncertainty = 2020

        if crit_smooth_line:
            #Get position in array of start year uncertainty
            pos_unc_yr = len(np.where(sim_yrs_smoothed < start_yr_uncertainty)[0])
        else:
            pos_unc_yr = 0
            for cnt, year in enumerate(sim_yrs_smoothed):
                if year == start_yr_uncertainty:
                    pos_unc_yr = cnt

        # select based on index which is year
        #df_q_05 = df_q_05.loc[start_yr_uncertainty:]
        #df_q_95 = df_q_95.loc[start_yr_uncertainty:]
        two_std_line_pos = two_std_line_pos.loc[start_yr_uncertainty:]
        two_std_line_neg = two_std_line_neg.loc[start_yr_uncertainty:]
        sim_yrs_smoothed = sim_yrs_smoothed[pos_unc_yr:]

        min_values = min_values[pos_unc_yr:] #min_values.loc[start_yr_uncertainty:]
        max_values = max_values[pos_unc_yr:] #max_values.loc[start_yr_uncertainty:]

        # --------------------------------------
        # Plottin qunatilse and average scenario
        # --------------------------------------
        #df_q_05.plot.line(color=color, linestyle='--', linewidth=0.1, label='_nolegend_')
        #df_q_95.plot.line(color=color, linestyle='--', linewidth=0.1, label='_nolegend_')

        # Plot standard deviation
        #two_std_line_pos.plot.line(color=color, linestyle='--', linewidth=0.1, label='_nolegend_')
        #two_std_line_neg.plot.line(color=color, linestyle='--', linewidth=0.1, label='_nolegend_')

        # plot min and maximum values
        plt.plot(sim_yrs_smoothed, min_values, color=color, linestyle='--', linewidth=0.3, label='_nolegend_')
        plt.plot(sim_yrs_smoothed, max_values, color=color, linestyle='--', linewidth=0.3, label='_nolegend_')

        plt.fill_between(
            sim_yrs_smoothed,
            list(two_std_line_pos),
            list(two_std_line_neg),
            alpha=0.25,
            facecolor=color)

    plt.xlim(2015, 2050)
    plt.ylim(0)

    # --------
    # Different style
    # --------
    ax = plt.gca()
    ax.grid(which='major', color='black', axis='y', linestyle='--')

    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['top'].set_visible(False)

    plt.tick_params(
        axis='y',          # changes apply to the x-axis
        which='both',      # both major and minor ticks are affected
        bottom=False,      # ticks along the bottom edge are off
        top=False,         # ticks along the top edge are off
        left=False,
        right=False,
        labelbottom=False,
        labeltop=False,
        labelleft=True,
        labelright=False) # labels along the bottom edge are off

    # --------
    # Legend
    # --------
    legend = plt.legend(
        ncol=2,
        prop={'size': 10},
        loc='upper center',
        bbox_to_anchor=(0.5, -0.1),
        frameon=False)
    legend.get_title().set_fontsize(8)

    if seperate_legend:
        basic_plot_functions.export_legend(
            legend,
            os.path.join(result_path, "{}__legend.pdf".format(fig_name[:-4])))
        legend.remove()

    # --------
    # Labeling
    # --------
    plt.ylabel("national peak demand (GW)")
    plt.tight_layout()
    plt.savefig(os.path.join(result_path, fig_name))
    plt.close()

    # Write info to txt
    write_data.write_list_to_txt(
        os.path.join(result_path, fig_name).replace(".pdf", ".txt"),
        statistics_to_print)
def run(data_input, fueltype_str, fig_name):
    """Plot peak demand and total demand over time in same plot
    """
    statistics_to_print = []

    # Select period and fueltype
    fueltype_int = tech_related.get_fueltype_int(fueltype_str)

    # -----------------------------------------------------------
    # Modelled years
    # -----------------------------------------------------------

    # List of selected data for every weather year (which is then converted to array)
    weather_yrs_total_demand = []
    weather_yrs_peak_demand = []

    nr_weather_yrs = list(data_input.keys())
    statistics_to_print.append("_____________________________")
    statistics_to_print.append("Weather years")
    statistics_to_print.append(str(data_input.keys()))

    # Iterate weather years
    for weather_yr, data_weather_yr in data_input.items():

        total_demands = []
        peak_demands = []
        sim_yrs = []
        for sim_yr in data_weather_yr.keys():
            sim_yrs.append(sim_yr)
            data_input_fueltype = data_weather_yr[sim_yr][
                fueltype_int]  # Select fueltype

            # sum total annual demand and convert gwh to twh
            sum_gwh_y = np.sum(data_input_fueltype)
            sum_thw_y = conversions.gwh_to_twh(sum_gwh_y)

            # Get peak
            peak_h = np.max(data_input_fueltype.reshape(8760))

            total_demands.append(sum_thw_y)
            peak_demands.append(peak_h)

        weather_yrs_total_demand.append(total_demands)
        weather_yrs_peak_demand.append(peak_demands)

    columns = sim_yrs

    # Convert to array
    weather_yrs_total_demand = np.array(weather_yrs_total_demand)
    weather_yrs_peak_demand = np.array(weather_yrs_peak_demand)

    # Calculate std per simulation year
    std_total_demand = list(np.std(weather_yrs_total_demand,
                                   axis=0))  # across columns calculate std
    std_peak_demand = list(np.std(weather_yrs_peak_demand,
                                  axis=0))  # across columns calculate std

    # Create dataframe
    if len(nr_weather_yrs) > 2:

        # Create dataframes
        df_total_demand = pd.DataFrame(weather_yrs_total_demand,
                                       columns=columns)
        df_peak = pd.DataFrame(weather_yrs_peak_demand, columns=columns)

        # Calculate quantiles
        quantile_95 = 0.95
        quantile_05 = 0.05

        # Calculate quantiles
        df_total_demand_q_95 = df_total_demand.quantile(quantile_95)
        df_total_demand_q_05 = df_total_demand.quantile(quantile_05)
        df_peak_q_95 = df_peak.quantile(quantile_95)
        df_peak_q_05 = df_peak.quantile(quantile_05)

        # convert to list
        df_total_demand_q_95 = df_total_demand_q_95.tolist()
        df_total_demand_q_05 = df_total_demand_q_05.tolist()
        df_peak_q_95 = df_peak_q_95.tolist()
        df_peak_q_05 = df_peak_q_05.tolist()
        #df_peak = df_peak.T #All indivdiual values
    else:
        #df_total_demand = weather_yrs_total_demand
        #df_peak = weather_yrs_peak_demand
        pass

    # -------------------
    # Base year data (2015)
    # -------------------
    # total demand
    tot_demand_twh_2015 = []
    for sim_yr, data_sim_yr in data_input[2015].items():
        gwh_2015_y = np.sum(data_sim_yr[fueltype_int])
        twh_2015_y = conversions.gwh_to_twh(gwh_2015_y)
        tot_demand_twh_2015.append(twh_2015_y)

    # peak
    df_peak_2015 = []
    for sim_yr, data_sim_yr in data_input[2015].items():
        peak_gwh_2015_y = np.max(data_sim_yr[fueltype_int])
        df_peak_2015.append(peak_gwh_2015_y)

    # ---------------
    # Smoothing lines
    # ---------------
    if len(nr_weather_yrs) > 2:
        try:
            period_h_smoothed, tot_demand_twh_2015_smoothed = basic_plot_functions.smooth_data(
                columns, tot_demand_twh_2015, num=40000)
            period_h_smoothed, df_total_demand_q_95_smoothed = basic_plot_functions.smooth_data(
                list(columns), df_total_demand_q_95, num=40000)
            period_h_smoothed, df_total_demand_q_05_smoothed = basic_plot_functions.smooth_data(
                columns, df_total_demand_q_05, num=40000)
            period_h_smoothed, df_peak_q_95_smoothed = basic_plot_functions.smooth_data(
                list(columns), df_peak_q_95, num=40000)
            period_h_smoothed, df_peak_q_05_smoothed = basic_plot_functions.smooth_data(
                columns, df_peak_q_05, num=40000)
            period_h_smoothed, df_peak_2015_smoothed = basic_plot_functions.smooth_data(
                columns, df_peak_2015, num=40000)
        except:
            period_h_smoothed = columns
            df_total_demand_q_95_smoothed = df_total_demand_q_95
            df_total_demand_q_05_smoothed = df_total_demand_q_05
            df_peak_q_95_smoothed = df_peak_q_95
            df_peak_q_05_smoothed = df_peak_q_05
            tot_demand_twh_2015_smoothed = tot_demand_twh_2015
            df_peak_2015_smoothed = df_peak_2015
    else:
        try:
            period_h_smoothed, tot_demand_twh_2015_smoothed = basic_plot_functions.smooth_data(
                columns, tot_demand_twh_2015, num=40000)
            period_h_smoothed, df_peak_2015_smoothed = basic_plot_functions.smooth_data(
                columns, df_peak_2015, num=40000)
        except:
            period_h_smoothed = columns
            tot_demand_twh_2015_smoothed = tot_demand_twh_2015
            df_peak_2015_smoothed = df_peak_2015

    # --------------
    # Two axis figure
    # --------------
    fig, ax1 = plt.subplots(figsize=basic_plot_functions.cm2inch(15, 10))

    ax2 = ax1.twinx()

    # Axis label
    ax1.set_xlabel('Years')
    ax2.set_ylabel('Peak hour {} demand (GW)'.format(fueltype_str),
                   color='black')
    ax1.set_ylabel('Total {} demand (TWh)'.format(fueltype_str), color='black')

    # Make the y-axis label, ticks and tick labels match the line color.¨
    color_axis1 = 'lightgrey'
    color_axis2 = 'blue'

    ax1.tick_params('y', colors='black')
    ax2.tick_params('y', colors='black')

    if len(nr_weather_yrs) > 2:

        # -----------------
        # Uncertainty range total demand
        # -----------------
        '''ax1.plot(
            period_h_smoothed,
            df_total_demand_q_05_smoothed,
            color='tomato', linestyle='--', linewidth=0.5, label="0.05_total_demand")'''
        '''ax1.plot(
            period_h_smoothed,
            df_total_demand_q_95_smoothed,
            color=color_axis1, linestyle='--', linewidth=0.5, label="0.95_total_demand")

        ax1.fill_between(
            period_h_smoothed, #x
            df_total_demand_q_95_smoothed,  #y1
            df_total_demand_q_05_smoothed,  #y2
            alpha=.25,
            facecolor=color_axis1,
            label="uncertainty band demand")'''

        # -----------------
        # Uncertainty range peaks
        # -----------------
        ##ax2.plot(period_h_smoothed, df_peak_q_05_smoothed, color=color_axis2, linestyle='--', linewidth=0.5, label="0.05_peak")
        ##ax2.plot(period_h_smoothed, df_peak_q_95_smoothed, color=color_axis2, linestyle='--', linewidth=0.5, label="0.95_peak")
        ax2.plot(period_h_smoothed,
                 df_peak_2015_smoothed,
                 color=color_axis2,
                 linestyle="--",
                 linewidth=0.4)

        # Error bar of bar charts
        ax2.errorbar(columns,
                     df_peak_2015,
                     linewidth=0.5,
                     color='black',
                     yerr=std_peak_demand,
                     linestyle="None")

        # Error bar bar plots
        ax1.errorbar(columns,
                     tot_demand_twh_2015,
                     linewidth=0.5,
                     color='black',
                     yerr=std_total_demand,
                     linestyle="None")
        '''ax2.fill_between(
            period_h_smoothed, #x
            df_peak_q_95_smoothed,  #y1
            df_peak_q_05_smoothed,  #y2
            alpha=.25,
            facecolor="blue",
            label="uncertainty band peak")'''

    # Total demand bar plots
    ##ax1.plot(period_h_smoothed, tot_demand_twh_2015_smoothed, color='tomato', linestyle='-', linewidth=2, label="tot_demand_weather_yr_2015")
    ax1.bar(columns,
            tot_demand_twh_2015,
            width=2,
            alpha=1,
            align='center',
            color=color_axis1,
            label="total {} demand".format(fueltype_str))

    statistics_to_print.append("_____________________________")
    statistics_to_print.append("total demand per model year")
    statistics_to_print.append(str(tot_demand_twh_2015))

    # Line of peak demand
    #ax2.plot(columns, df_peak, color=color_axis2, linestyle='--', linewidth=0.5, label="peak_0.95")
    ax2.plot(period_h_smoothed,
             df_peak_2015_smoothed,
             color=color_axis2,
             linestyle='-',
             linewidth=2,
             label="{} peak demand (base weather yr)".format(fueltype_str))

    statistics_to_print.append("_____________________________")
    statistics_to_print.append("peak demand per model year")
    statistics_to_print.append(str(df_peak_2015))

    # Scatter plots of peak demand
    ax2.scatter(columns,
                df_peak_2015,
                marker='o',
                s=20,
                color=color_axis2,
                alpha=1)

    ax1.legend(prop={
        'family': 'arial',
        'size': 10
    },
               loc='upper center',
               bbox_to_anchor=(0.9, -0.1),
               frameon=False,
               shadow=True)

    ax2.legend(prop={
        'family': 'arial',
        'size': 10
    },
               loc='upper center',
               bbox_to_anchor=(0.1, -0.1),
               frameon=False,
               shadow=True)

    # More space at bottom
    #fig.subplots_adjust(bottom=0.4)
    fig.tight_layout()

    plt.savefig(fig_name)
    plt.close()

    # Write info to txt
    write_data.write_list_to_txt(
        os.path.join(fig_name.replace(".pdf", ".txt")), statistics_to_print)
    print("--")
Ejemplo n.º 11
0
def run_fig_p2_temporal_validation(
        data_input,
        weather_yr,
        fueltype_str,
        simulation_yr_to_plot,
        period_h,
        validation_elec_2015,
        non_regional_elec_2015,
        fig_name,
        titel="titel",
        y_lim_val=100,
        plot_validation=False,
        plot_show=False
    ):
    """
    """
    fueltype_int = tech_related.get_fueltype_int(fueltype_str)

    # -----------------------------------------------------------
    # Iterate overall weather_yrs and store data in dataframe
    # (columns = timestep, rows: value of year)
    # -----------------------------------------------------------
    selection_hours = period_h

    # List of selected data for every weather year (which is then converted to array)
    weather_yrs_data = []
    weather_yrs_full_year = []

    for station_id, data_weather_yr in data_input[weather_yr].items():

        # Weather year specific data
        data_input_fueltype = data_weather_yr[simulation_yr_to_plot][fueltype_int]     # Select fueltype
        data_input_reshape = data_input_fueltype.reshape(8760)  # reshape
        data_input_selection_hrs = data_input_reshape[selection_hours] # select period

        weather_yrs_data.append(data_input_selection_hrs)
        weather_yrs_full_year.append(data_input_reshape)

    weather_yrs_data = np.array(weather_yrs_data)

    # Create dataframe
    df = pd.DataFrame(weather_yrs_data, columns=period_h)

    df_full_year = pd.DataFrame(weather_yrs_full_year, columns=range(8760))

    # Calculate quantiles
    quantile_95 = 0.95
    quantile_05 = 0.05

    df_q_95 = df.quantile(quantile_95)
    df_q_05 = df.quantile(quantile_05)

    #Transpose for plotting purposes
    df = df.T
    df_q_95 = df_q_95.T
    df_q_05 = df_q_05.T

    fig = plt.figure()

    ax = fig.add_subplot(111)

    # ---------------
    # Smoothing lines
    # ---------------
    try:
        period_h_smoothed, df_q_95_smoothed = basic_plot_functions.smooth_data(period_h, df_q_95, num=40000)
        period_h_smoothed, df_q_05_smoothed = basic_plot_functions.smooth_data(period_h, df_q_05, num=40000)
        #period_h_smoothed, data_2015_smoothed = basic_plot_functions.smooth_data(period_h, data_2015, num=40000)
    except:
        period_h_smoothed = period_h
        df_q_95_smoothed = df_q_95
        df_q_05_smoothed = df_q_05

    #plt.plot(period_h_smoothed, data_2015_smoothed, color='tomato', linestyle='-', linewidth=2, label="2015 weather_yr")
    plt.plot(period_h_smoothed, df_q_05_smoothed, color='black', linestyle='--', linewidth=0.5, label="0.05")
    plt.plot(period_h_smoothed, df_q_95_smoothed, color='black', linestyle='--', linewidth=0.5, label="0.95")

    # -----------------
    # Uncertainty range
    # -----------------
    plt.fill_between(
        period_h_smoothed, #x
        df_q_95_smoothed,  #y1
        df_q_05_smoothed,  #y2
        alpha=1,
        facecolor="lightgrey",
        label="uncertainty band")

    # -----------------
    # All weather stations are used for this data
    # -----------------
    all_weather_stations_2015 = non_regional_elec_2015.reshape(8760)[period_h] 

    # -----------------
    # Validation data
    # -----------------
    if plot_validation:
        validation_2015 = validation_elec_2015.reshape(8760)[selection_hours] 

        try:
            period_h_smoothed, validation_2015_smoothed = basic_plot_functions.smooth_data(period_h, validation_2015, num=40000)
        except:
            period_h_smoothed = period_h
            validation_2015_smoothed = validation_2015

        plt.plot(
            period_h_smoothed,
            validation_2015_smoothed,
            color='green',
            linestyle='--',
            linewidth=1.5, label="validation 2015")

        # -----------
        # statistics
        # -----------
        # Calculate mean of all all single station runs
        mean_all_single_runs = df_full_year.mean(axis=0).tolist()
        mean_all_single_runs = np.array(mean_all_single_runs)[period_h]

        slope, intercept, r_value, p_value, std_err = stats.linregress(
            validation_2015,
            all_weather_stations_2015)
        slope, intercept, r_value2, p_value, std_err = stats.linregress(
            validation_2015,
            mean_all_single_runs)

        print("R_Value_all_stations: " + str(r_value))
        print("R_Value_single_stations: " + str(r_value2))
        plt.title(
            "R_value: all stations: {} mean_single_weather_stations: {}".format(
                round(r_value, 2),
                round(r_value2, 2)))
    
    try:
        period_h_smoothed, all_weather_stations_2015_smoothed = basic_plot_functions.smooth_data(
            period_h, all_weather_stations_2015, num=40000)
    except:
        period_h_smoothed = period_h
        all_weather_stations_2015_smoothed = all_weather_stations_2015

    plt.plot(
        period_h_smoothed,
        all_weather_stations_2015_smoothed,
        color='blue',
        linestyle='--',
        linewidth=1.2,
        label="all stations")

    # Ticks for single day
    #major_ticks_days, major_ticks_labels = get_date_strings(
    #    days_to_plot,
    #    daystep=1)
    #plt.xticks(major_ticks_days, major_ticks_labels)
    zero_entry = period_h[0]
    plt.xticks([0 + zero_entry, 5 + zero_entry, 11 + zero_entry, 17 + zero_entry, 23 + zero_entry], ['1', '6', '12', '18', '24'])

    plt.ylim(0, y_lim_val)
    plt.xlim(period_h[0], period_h[-1])
    plt.title("Peak day: " + str(titel))
    plt.legend(
        prop={
            'family':'arial',
            'size': 10},
        loc='best',
        frameon=False,
        shadow=True)

    if plot_show:
        plt.show()
    else:
        pass
    plt.savefig(fig_name)
    plt.close()