Beispiel #1
0
def get_simpleplot(savepath, forecasts, obs_week, week):
    """Get Simple plot:
    ------------------------------------
    This function plots a simple line plot of student's weekly averaged
    forecast for a week
    ------------------------------------
    Parameters:
    forecasts = array
                provides weekly forecasted flow of each student
    obs_week  = float
                week's observed flow
    week = string
                Week number for the forecast (1 or 2)
    ------------------------------------
    Outputs: figure of simple line plot

    """
    # Get the array of firstnames for the plot
    firstnames = ef.getFirstNames()

    fig3, ax = plt.subplots()
    fig3.set_size_inches(10, 4)
    clean_forecasts = [x for x in forecasts if not np.isnan(x)]
    class_avg = np.mean(clean_forecasts)
    simple_plot = ax.plot(forecasts, '-g', label='Forecast', alpha=.8)
    plt.axhline(y=class_avg,
                linestyle='dashed',
                label='Class Avg',
                alpha=.8,
                color='red')
    plt.axhline(y=obs_week,
                linestyle='dotted',
                label='Observed',
                alpha=.8,
                color='blue')
    plt.xticks(ticks=np.arange(0, 19, 1), labels=firstnames, rotation=60)
    title_string = 'Week ' + str(week) + ' Forecasts'
    ax.set(title=title_string,
           xlabel="Students",
           ylabel="Weekly Avg Flow [cfs]")
    ax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)
    fig3.patch.set_facecolor('xkcd:white')
    plt.tight_layout()
    plt.show()

    fig3.savefig(savepath)

    return simple_plot
Beispiel #2
0
def last_2_weeks_diff(savepath, obs_week, oneweek_forecasts, twoweek_forecasts,
                      bar_width):

    # Get the array of firstnames for the plot
    firstnames = ef.getFirstNames()
    class_forecasts = pd.DataFrame(
        {
            'oneweek_forecasts': oneweek_forecasts,
            'twoweek_forecasts': twoweek_forecasts
        },
        index=firstnames,
        columns=['oneweek_forecasts', 'twoweek_forecasts'])

    class_forecasts.insert(
        2, 'Diff_1', np.array(class_forecasts['oneweek_forecasts'] - obs_week),
        True)
    class_forecasts.insert(
        3, 'Diff_2', np.array(class_forecasts['twoweek_forecasts'] - obs_week),
        True)

    # Plotting Diff
    stu = np.arange(0, 19, 1)
    fig14 = plt.figure()
    fig14.set_size_inches(25, 8)
    ax = fig14.add_subplot()
    w = bar_width
    plt.xticks(stu + w / 2, firstnames, rotation=60, fontsize=15)
    ax.bar(stu, class_forecasts.Diff_1, width=w, align='center', label='week1')
    ax.bar(stu + w,
           class_forecasts.Diff_2,
           width=w,
           align='center',
           label='week2')
    ax.axhline(y=0, linewidth=2, linestyle='--', color='k')
    plt.xlabel('Student', fontsize=15)
    plt.ylabel('Average Flow', fontsize=15)
    ax.legend(loc='lower center',
              fontsize=20,
              bbox_to_anchor=(.5, -0.4),
              ncol=5)
    # plt.text(0, 0, 'Observed Flow', fontsize=21)
    fig14.patch.set_facecolor('xkcd:white')
    plt.tight_layout()
    plt.show()

    fig14.savefig(savepath)
# %%
import pandas as pd
import sys
sys.path.append('../')
import eval_functions as ef
import random

# ENTER INFO HERE
weekly_winners = ["Diana", "Alexa", "Ben", "Jake"]
evaluators = ["Adam", "Jill"]

# %%
# get list of students in the class using functions
# names = ef.getLastNames()
firstnames = ef.getFirstNames()
nstudent = len(firstnames)

# %%
# remove ineligible persons
not_eligible = weekly_winners + evaluators
for i in range(len(not_eligible)):
    firstnames.remove(not_eligible[i])

firstnames

# %%
# create list of emojis and shuffle randomly
# SHAPE (# of list items) MUST MATCH FIRSTNAMES LIST
emoji_list = [
    "🥇", "🥈", "🥉", "😭", "😭",
Beispiel #4
0
def plot_seasonal_rmse(savepath, seasonal_rmse):
    """Seasonal Root Mean Square Error:
    -----------------------------------
    This function plots the root mean square error of seasonal flow
    data for week 1 to the most recent entry.
    You have the option of entering in minumum and maximum y values.
    -----------------------------------
    Parameters:
    Seasonal_rmse = pandas dataframe
                    every student's seasonal root meet square error
    -----------------------------------
    Output:
    Figure of long term weekly prediction root mean square errors
    """
    # Request the parameters for the plots
    y_low = (
        input('Please introduce the lower limit for y-Axis (Hit enter for \
             default value 0):'))
    y_max = (
        input('Please introduce the upper limit for y-Axis (Hit enter for \
            default values):'))
    column_weeks = [i for i in seasonal_rmse.columns]

    # Markers for the plot
    markers = [
        'o', 'v', '^', 'D', '>', 's', 'P', 'X', '<', '>', 'X', 'o', 'v', 's',
        '^', 'P', '<', 'D', 's'
    ]

    # Get the array of firstnames for the plot
    firstnames = ef.getFirstNames()

    # plotting
    fig10, ax = plt.subplots()
    ax.plot(seasonal_rmse)
    for i, line in enumerate(ax.get_lines()):
        line.set_marker(markers[i])
    ax.set_xlabel('Weeks', fontsize=13, fontweight='bold')
    ax.set_ylabel("Root Mean Square Error", fontsize=13, fontweight='bold')
    ax.set_title("Seasonal Root Mean Square Error",
                 fontsize=13,
                 fontweight='bold')

    # Assigns the limits for y-axis based on user's input
    if y_low == '' and y_max != '':
        ax.set_ylim(seasonal_rmse[column_weeks].min().min(), float(y_max))
    elif y_max == '' and y_low != '':
        ax.set_ylim(float(y_low), seasonal_rmse[column_weeks].max().max())
    elif y_max == '' and y_low == '':
        ax.set_ylim(seasonal_rmse[column_weeks].min().min(),
                    seasonal_rmse[column_weeks].max().max())
    else:
        ax.set_ylim(float(y_low), float(y_max))
    # showing the legend
    ax.legend(firstnames,
              loc='lower center',
              bbox_to_anchor=(.5, -0.4),
              ncol=6)
    fig10.patch.set_facecolor('xkcd:white')
    plt.show()

    fig10.savefig(savepath)
Beispiel #5
0
def plot_class_forecasts(df, week_flows, leadtime, type_plot):
    """ plot_class_forecasts()
    ---------------------------------------------------------------------
    This function plots the forecasts submitted by each student for both
    Week 1 & 2 Forecasts. In addition, is capable of plotting the absolute
    error in regards the observed value.
    ---------------------------------------------------------------------
    Parameters:
    df = Dataframe
        Includes the weekly forecast values for Week 1 and 2 for each student.
    week_flows = Dataframe
                 Observed flows per week obtained from USGS.
    leadtime: int
          leadtime for the forecast. It can only be 1 or 2
    type_plot: string
               Enter 'forecasts' to plot all submitted values, or 'abs_error'
               to plot the deviation from the observed value.
    ---------------------------------------------------------------------
    Outputs: Plot of the forecasted values or the absolute error depending the
             user input
    """

    # Request the parameters for the plots
    y_low = (
        input('Please introduce the lower limit for y-Axis (Hit enter for \
             default value 0):'))
    y_max = (
        input('Please introduce the upper limit for y-Axis (Hit enter for \
            default values):'))

    plot_weeks_inp = input('Please introduce the list of weeks to consider as \
        ["Week #", "Week #", ...]. Otherwise, if you want to include all weeks\
        hit enter:')

    if plot_weeks_inp == '':
        column_weeks = [i for i in df.columns]
    else:
        column_weeks = [i for i in df.columns if i in plot_weeks_inp]

    # Markers for the plot
    markers = [
        'o', 'v', '^', 'D', '>', 's', 'P', 'X', '<', '>', 'X', 'o', 'v', 's',
        '^', 'P', '<', 'D', 's'
    ]

    # Get the array of firstnames for the plot
    firstnames = ef.getFirstNames()

    # Trim and set index the same weekly flow (start 8/23)
    weekly_flows = week_flows.iloc[1:len(column_weeks) + 1, 3:4]
    weekly_flows.set_index(df.columns, append=False, inplace=True)

    # Assign values depending the plot type selected
    if type_plot == 'abs_error':
        df = df.T.subtract(weekly_flows['observed'], axis=0).T
        plot_ylabel = "Deviation from Weekly Avg Flow [cfs]"
        plot_title = 'Absolute Error in ' + str(
            leadtime) + ' Week Forecast for \n\
        HAS-Tools Class'

    elif type_plot == 'forecast':
        plot_ylabel = "Weekly Avg Flow [cfs]"
        plot_title = str(leadtime) + ' Week Forecast for HAS-Tools Class \n '

    # Plotting process
    fig, ax = plt.subplots()
    ax.plot(df.T)
    for i, line in enumerate(ax.get_lines()):
        line.set_marker(markers[i])

    # Plot observed flow if the selected plot is the forecast
    if type_plot == 'forecast':
        ax.plot(column_weeks,
                weekly_flows['observed'],
                color='black',
                marker='o',
                linestyle='--',
                linewidth=3)
        plot_labels = firstnames + ['Observed Flow']
    elif type_plot == 'abs_error':
        plot_labels = firstnames

    # Format for labels and plot title
    ax.set_xlabel('Weeks \n', fontsize=13, fontweight='bold')
    ax.set_ylabel(plot_ylabel, fontsize=13, fontweight='bold')
    ax.set_title(plot_title, fontsize=15, fontweight='bold')

    # Assigns the limits for y-axis based on user's input
    if y_low == '' and y_max != '':
        ax.set_ylim(df[column_weeks].min().min(), float(y_max))
    elif y_max == '' and y_low != '':
        ax.set_ylim(float(y_low), df[column_weeks].max().max())
    elif y_max == '' and y_low == '':
        ax.set_ylim(df[column_weeks].min().min(), df[column_weeks].max().max())
    else:
        ax.set_ylim(float(y_low), float(y_max))

    ax.legend(plot_labels,
              loc='lower center',
              bbox_to_anchor=(.5, -0.4),
              ncol=6)
    fig.set_size_inches(9, 5)
    fig.patch.set_facecolor('xkcd:white')
    plt.show()