Ejemplo n.º 1
0
    def update_ui(self):
        pred_label = self.pred_labels[self.vis_image_index]
        img_obj = self.dataset.images[self.vis_image_index]
        scores = self.pred_scores[self.vis_image_index]

        self.w_image_header.value = "Image index: {}".format(
            self.vis_image_index)
        self.w_img.value = wImread(img_obj, self.context)
        self.w_gt_label.value = self.dataset.get_labels_for_image(
            img_obj)[0].name
        self.w_pred_label.value = str(pred_label)
        self.w_pred_score.value = str(
            self.pred_scores[self.vis_image_index,
                             self.label_to_id[pred_label]])
        self.w_index.value = str(self.vis_image_index)
        self.w_filename.value = img_obj.name
        self.w_path.value = img_obj.storage_path
        bqPyplot.clear()
        bqPyplot.bar(
            self.labels,
            scores,
            align='center',
            alpha=1.0,
            color=np.abs(scores),
            scales={'color': bqplot.ColorScale(scheme='Blues', min=0)})
Ejemplo n.º 2
0
    def update(self):
        scores = self.pred_scores[self.vis_image_index]
        im = self.dataset[self.vis_image_index][0]  # fastai Image object

        _, sort_order = self._list_sort(scores, reverse=True)
        pred_labels_str = ""
        for i in sort_order:
            pred_labels_str += f"{self.labels[i]} ({scores[i]:3.2f})\n"
        self.w_pred_labels.value = str(pred_labels_str)

        self.w_image_header.value = f"Image index: {self.vis_image_index}"

        self.w_img.value = im._repr_png_()
        # Fix the width of the image widget and adjust the height
        self.w_img.layout.height = (
            f"{int(self.IM_WIDTH * (im.size[1]/im.size[0]))}px")

        self.w_gt_label.value = str(
            self.labels[self.dataset[self.vis_image_index][1]])

        self.w_filename.value = str(
            self.dataset.items[self.vis_image_index].name)
        self.w_path.value = str(
            self.dataset.items[self.vis_image_index].parent)
        bqpyplot.clear()
        bqpyplot.bar(
            self.labels,
            scores,
            align="center",
            alpha=1.0,
            color=np.abs(scores),
            scales={"color": bqplot.ColorScale(scheme="Blues", min=0)},
        )
Ejemplo n.º 3
0
def show_cohort(y_true, protected, backend="bqplot"):
    """Show the base rates in the cohort by protected attribute."""

    # jerry-rig confusion matrix to count prevalence in the population
    mn, fn, mp, fp = confusion_matrix(y_true, protected).ravel()
    # Now we can do two histograms:
    values = [[mp, fp], [mn, fn]]
    colors = ["green", "red"]

    if backend == "bqplot":
        fig = plt.figure(min_aspect_ratio=1, max_aspect_ratio=1)
        # First index is colour, second index is X

        # Note - putting negative does cool weird stuff
        bars = plt.bar(
            x_ticks,
            values,
            colors=colors,
            # display_legend=False,
            # labels=["Good Customers", "Bad Customers"],
        )
        siz = "4in"
        fig.layout.width = siz
        fig.layout.height = siz

    else:
        fig, ax = mplt.subplots(figsize=(5, 5), dpi=DPI)
        ax.bar(x_ticks, values[0], color=colors[0])
        ax.bar(x_ticks, values[1], bottom=values[0], color=colors[1])
    return fig
Ejemplo n.º 4
0
 def bqbars(values, colors, title, stake):
     fig = plt.figure()
     eo_bars = plt.bar(x_ticks, values, colors=colors)
     plt.ylabel("Fraction (%)")
     plt.xlabel(stake)
     fig.title = title
     return fig
Ejemplo n.º 5
0
def new_cases(countries, country, dfs, kw, n_mov_ave=5):
    xax = get_xaxis()

    df = dfs[country]
    h_bar = plt.bar(x=xax, y=df[kw])
    h_ave = plt.plot(xax, moving_average(df[kw], n_mov_ave), 'green')
    return h_bar, h_ave
 def updateUI(self):
     predLabel = self.predLabels[self.visImageIndex]
     imgObj = self.dataset.images[self.visImageIndex]
     scores = self.predScores[self.visImageIndex]
     self.wImageHeader.value = "Image index: {}".format(self.visImageIndex)
     self.wImg.value = wImread(imgObj, self.imgOrigDir)
     self.wGtLabel.value = imgObj.label
     self.wPredLabel.value = str(self.lutId2Label[predLabel])
     self.wPredScore.value = str(self.predScores[self.visImageIndex,
                                                 predLabel])
     self.wIndex.value = str(self.visImageIndex)
     self.wFilename.value = imgObj.filename
     bqPyplot.clear()
     bqPyplot.bar(
         self.labels,
         scores,
         align='center',
         alpha=1.0,
         color=np.abs(scores),
         scales={'color': bqplot.ColorScale(scheme='Blues', min=0)})
Ejemplo n.º 7
0
def generate_group_bar(df, title="", scientific_notation=False):
    fig = plt.figure(title=title)
    bar_chart = plt.bar(
        x=df.columns.values.tolist(),
        y=df,
        labels=df.index.values.tolist(),
        display_legend=False,
        type="grouped",
        colors=chart_colors[:df.index.values.size],
    )
    if df.columns.name:
        plt.xlabel(df.columns.name.rsplit(" ", 1)[0])
    plt.ylim(0, np.amax(df.values))
    if not scientific_notation:
        fig.axes[1].tick_format = ".1f"
    return fig
Ejemplo n.º 8
0
def generate_bar(df, title="", scientific_notation=False, small_xlabel=False):
    fig = plt.figure(title=title)
    x_vals = df.index.values.tolist()
    if len(x_vals) > 5:
        small_xlabel = True
    x_titles = []
    for val in x_vals:
        if len(val.split(" ")) < 3:
            x_titles.append(val)
        else:
            x_titles.append(" ".join(val.split(" ")[:2]))
    bar_chart = plt.bar(x=x_titles,
                        y=df,
                        colors=chart_colors[:df.index.values.size])
    if small_xlabel:
        fig.axes[0].tick_style = {"font-size": "6"}
    if not scientific_notation:
        fig.axes[1].tick_format = ".1f"
    return fig
Ejemplo n.º 9
0
    def create_charts(self):
        self.epoch_slider = IntSlider(description='Epoch:',
                                      min=1,
                                      max=self.num_epochs,
                                      value=1)
        self.mode_dd = Dropdown(
            description='View',
            options=['Weights', 'Gradients', 'Activations'],
            value='Weights')
        self.update_btn = Button(description='Update')

        self.bar_figure = plt.figure()
        self.bar_plot = plt.bar([], [], scales={'x': OrdinalScale()})

        self.hist_figure = plt.figure(title='Histogram of Activations')
        self.hist_plot = plt.hist([], bins=20)

        self.controls = HBox(
            [self.epoch_slider, self.mode_dd, self.update_btn])
        self.graph.tooltip = self.bar_figure
Ejemplo n.º 10
0
def feature_byFeature(features, xProperty, yProperties, **kwargs):
    """Generates a Chart from a set of features. Plots the value of one or more properties for each feature.
    Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyfeature

    Args:
        features (ee.FeatureCollection): The feature collection to generate a chart from.
        xProperty (str): Features labeled by xProperty.
        yProperties (list): Values of yProperties.

    Raises:
        Exception: Errors when creating the chart.
    """

    try:

        df = ee_to_df(features)
        if "ylim" in kwargs:
            min_value = kwargs["ylim"][0]
            max_value = kwargs["ylim"][1]
        else:
            min_value = df[yProperties].to_numpy().min()
            max_value = df[yProperties].to_numpy().max()
            max_value = max_value + 0.2 * (max_value - min_value)

        if "title" not in kwargs:
            title = ""
        else:
            title = kwargs["title"]
        if "legend_location" not in kwargs:
            legend_location = "top-left"
        else:
            legend_location = kwargs["legend_location"]

        x_data = list(df[xProperty])
        y_data = df[yProperties].values.T.tolist()

        plt.bar(x_data, y_data)
        fig = plt.figure(
            title=title,
            legend_location=legend_location,
        )

        if "width" in kwargs:
            fig.layout.width = kwargs["width"]
        if "height" in kwargs:
            fig.layout.height = kwargs["height"]

        if "labels" in kwargs:
            labels = kwargs["labels"]
        else:
            labels = yProperties

        if "display_legend" not in kwargs:
            display_legend = True
        else:
            display_legend = kwargs["display_legend"]

        bar_chart = plt.bar(x_data,
                            y_data,
                            labels=labels,
                            display_legend=display_legend)

        bar_chart.type = "grouped"

        if "colors" in kwargs:
            bar_chart.colors = kwargs["colors"]

        if "xlabel" in kwargs:
            plt.xlabel(kwargs["xlabel"])
        if "ylabel" in kwargs:
            plt.ylabel(kwargs["ylabel"])
        plt.ylim(min_value, max_value)

        if "xlabel" in kwargs and ("ylabel" in kwargs):
            bar_chart.tooltip = Tooltip(
                fields=["x", "y"], labels=[kwargs["xlabel"], kwargs["ylabel"]])
        else:
            bar_chart.tooltip = Tooltip(fields=["x", "y"])

        plt.show()

    except Exception as e:
        raise Exception(e)
Ejemplo n.º 11
0
def plot_profitability_distributions(scenarios, backend):
    for id in scenarios:
        # Make scenario data
        scenario = scenarios[id]
        desc = scenario.description

        train_data = scenario.gendata("train")
        test_data = scenario.gendata("test")
        np.random.seed(42)
        X_train, y_train = scenario.get_modelling_data(train_data)
        X_test, y_test = scenario.get_modelling_data(test_data)
        data = {
            'training': (X_train, y_train, train_data.disadv_flag),
            'deployment': (X_test, y_test, test_data.disadv_flag),
        }

        figure_name = f"Profitability_{id}_{desc}"
        print(f"for Scenario {id}: {desc}")

        if backend == "matplotlib":
            l = len(data.items())
            fig, ax = mplt.subplots(1, l, figsize=(5 * l, 5), dpi=DPI)
            i = 0
        else:
            plts = []

        for cohort, (X, y_true, prot) in data.items():
            dis = prot.astype(int)
            mn, fn, mp, fp = confusion_matrix(y_true, dis).ravel()
            values = [[mp, fp], [mn, fn]]
            # half way between selected and not
            colors = ["#ff4045", "#48B748"]
            title = f"Representation in {cohort} cohort."
            ylabel = "Number of Applicants"

            if backend == "matplotlib":
                bars = mplt_bars(ax[i], scenario.ticks, values, colors, ylabel,
                                 title)
                mplt.legend(
                    bars,
                    ["profitable customers", "non-profitable customers"],
                    bbox_to_anchor=(1.05, 0.5)  # sit outside plot...
                )
                i += 1

            else:
                fig = plt.figure(min_aspect_ratio=1, max_aspect_ratio=1)
                # First index is colour, second index is X

                # Note - putting negative does cool weird stuff
                bars = plt.bar(
                    scenario.ticks,
                    values,
                    colors=colors,
                    # display_legend=False,
                    # labels=["Good Customers", "Bad Customers"],
                )
                siz = "4in"
                fig.layout.width = siz
                fig.layout.height = siz

                fig.title = title
                fig.axes[0].color = fig.axes[1].color = "Black"
                plt.ylabel(ylabel)
                plts.append(fig)

        if backend == "matplotlib":
            fig.savefig("images/" + figure_name + ".png",
                        bbox_inches="tight",
                        dpi=300)

        elif backend == "bqplot":
            box = widgets.HBox(plts)
            box.layout.width = "90%"
            display(box)

        figure_name = f"Profitability_{id}_{desc}"
Ejemplo n.º 12
0
def plot_feature_importances(scenarios, backend):
    # Plot all the feature importances
    for id in scenarios:
        # Make scenario data
        scenario = scenarios[id]
        desc = scenario.description
        figure_name = f"Importance_{id}_{desc}"
        train_data = scenario.gendata("train")
        test_data = scenario.gendata("test")
        np.random.seed(42)
        X_train, y_train = scenario.get_modelling_data(train_data)
        X_test, y_test = scenario.get_modelling_data(test_data)

        dis = scenario.ticks[1]
        if dis != "SE Asian proxy":  # proper noun
            dis = dis.lower()

        if "pinterest" in train_data.columns:
            ren = {
                "pinterest": scenario.proxy_name,
                'disadv_flag': dis,
            }
            # warning: train data seems to be writable in-place
            X_train = X_train.rename(columns=ren)
            X_test = X_test.rename(columns=ren)
        clf = LogisticRegression()
        clf.fit(X_train, y_train)
        columns = list(X_train.columns)
        importance = clf.coef_[0]

        if True:
            # standardize?
            importance = importance / X_train.std(axis=0)

        heights = np.abs(importance)
        cols = ['orange', 'blue']
        colors = (np.array(cols)[(importance >= 0).astype(int)]).tolist()
        title = "Model Feature Importance"

        print("Importance: {}".format(importance))

        if backend == "matplotlib":
            fig, ax = mplt.subplots(figsize=(5, 5), dpi=DPI)
            ax.bar(columns, importance, color=colors)
            ax.axhline(0, color="Black", lw=1.)

            # Add some dummies for a legend
            c = columns[0]
            mplt.bar([c], [0], color=cols[1], label="Increases Score")
            mplt.bar([c], [0], color=cols[0], label="Decreases Score")
            mplt.plot([-0.5, len(columns) - 0.5], [0, 0], 'k')

            scale = 10
            if int(id) == 5:
                # this scenario uses huge weights for some reason...
                scale = 40

            mplt.ylim(-scale, scale)
            mplt.legend(bbox_to_anchor=(1.5, 0.5))

            ax.set_title(title)
            fig.savefig("images/" + figure_name + ".png",
                        bbox_inches="tight",
                        dpi=300)

        elif backend == "bqplot":
            fig = plt.figure(title=title,
                             min_aspect_ratio=1,
                             max_aspect_ratio=1)
            for c, h, colr in zip(columns, importance, colors):
                plt.bar([c], [h], colors=[colr])  # each bar is its own bar
            plt.ylim(-10, 10)  # was -10, 10 except for scenario 5?
            fig.axes[0].color = fig.axes[1].color = "Black"
            fig.layout.width = fig.layout.height = "5in"
            display(fig)
def Interactive_Pareto_front(simtime,I,E,d,S0,Smax,ms,env_min, demand_plot,solutions_optim_relea,results1_optim_relea,results2_optim_relea):
    def syst_sim(simtime,I,E,d,S0,Smax,env_min,Qreg):
    
        # Declare output variables
    
        S = [0]*(simtime+1) # reservoir storage in ML
    
        spill = [0]*(simtime) # spillage in ML
    
        env = [env_min]*(simtime) # environmental compensation flow
        
        S[0] = S0 # initial storage
    
        for t in range(simtime): # Loop for each time-step (week)
    
            # If at week t the inflow (I) is lower than the minimum environmental compensation (env_min), 
            # then the environmental compensation (env) = inflow (I)  
            if env_min >= I[t] :
                env[t] = I[t]
            # If the minimum environmental compensation is higher than the water resource available (S + I - E)
            # then the environmental compensation is equal to the higher value between 0 and the resource available
            if env_min >= S[t] + I[t] - E[t]:
                env[t] = max(0,S[t] + I[t] - E[t]) # S[t] = Smin then env[t] = I[t] and S[t+1] < Smin
            # If the demand is higher than the water resource available (S + I - E - env)
            # then the release for water supply is equal to the higher value between 0 and the resource available            
            if d[t] >= S[t] + I[t] - E[t] - env[t]:
                Qreg[t] = min(Qreg[t],max(0,S[t] + I[t] - E[t] - env[t]))
            # The spillage is equal to the higher value between 0 and the resource available exceeding the reservoir capacity
            spill[t] = max(0,S[t] + I[t] - Qreg[t] - env[t] - E[t] - Smax)
            # The final storage (initial storage in the next step) is equal to the storage + inflow - outflows
            S[t+1] = S[t] + I[t] - Qreg[t] - env[t]- E[t] - spill[t]
            
        return S,env,spill,Qreg
    
    def update_operation_4(i):
        Qreg = solutions_optim_relea[i]
        S,env,spill,Qreg1 = syst_sim(simtime,I,E,d,S0,Smax,env_min,Qreg)
        lspen = np.sum((np.maximum(ms-S,[0]*(simtime+1)))).astype('int')
        fig_4a.title = 'Reservoir storage - Minimum storage violation = '+str(lspen)+' ML'
        sdpen = (np.sum((np.maximum(d-Qreg1,[0]*simtime))**2)).astype('int')
        fig_4b.title = 'Supply vs Demand - Total squared deficit = '+str(sdpen)+' ML^2'
        return S,env,spill,Qreg1
    
    def solution_selected(change):
        if pareto_front.selected == None:
            pareto_front.selected = [0]
        y_vals_4a = update_operation_4(pareto_front.selected[0])[0]
        storage_4.y = y_vals_4a
        y_vals_4b = update_operation_4(pareto_front.selected[0])[3]
        releases_4.y = y_vals_4b
    
    x_sc_pf = LinearScale();y_sc_pf = LinearScale()
    x_ax_pf = Axis(label='Total squared deficit [ML^2]', scale=x_sc_pf)
    y_ax_pf = Axis(label='Minimum storage violation [ML]', scale=y_sc_pf, orientation='vertical')
    pareto_front = plt.scatter(results1_optim_relea[:],results2_optim_relea[:],scales={'x': x_sc_pf, 'y': y_sc_pf},
                               colors=['deepskyblue'], interactions={'hover':'tooltip','click': 'select'})
    pareto_front.unselected_style={'opacity': 0.4}
    pareto_front.selected_style={'fill': 'red', 'stroke': 'yellow', 'width': '1125px', 'height': '125px'}
    def_tt = Tooltip(fields=['x', 'y'],labels=['Water deficit', 'Min storage'], formats=['.1f', '.1f'])
    pareto_front.tooltip=def_tt
    fig_pf = plt.Figure(marks = [pareto_front],title = 'Interactive Pareto front', axes=[x_ax_pf, y_ax_pf],
                        layout={'width': '500px', 'height': '500px'}, animation_duration=1000)
    
    if pareto_front.selected == []:
        pareto_front.selected = [0]
    
    pareto_front.observe(solution_selected,'selected')
    
    S,env,w,u1 = syst_sim(simtime,I,E,d,S0,Smax,env_min,solutions_optim_relea[pareto_front.selected[0]])

    x_sc_1 = LinearScale();y_sc_1 = LinearScale(min=0,max=35);x_ax_1 = Axis(label='week', scale=x_sc_1);y_ax_1 = Axis(label='ML/week', scale=y_sc_1, orientation='vertical')
    
    x_sc_2a             = LinearScale(min=0,max=simtime);y_sc_2a = LinearScale(min=0,max=200);x_ax_2a = Axis(label='week', scale=x_sc_2a,tick_values=np.arange(8)+0.5);y_ax_2a = Axis(label='ML', scale=y_sc_2a, orientation='vertical')
    max_storage_2       = plt.plot(x=np.arange(0,simtime+1),y=[Smax]*(simtime+1),colors=['red'],scales={'x': x_sc_2a, 'y': y_sc_2a})
    max_storage_label_2 = plt.label(text = ['Max storage'], x=[0],y=[Smax+15],colors=['red'])

    min_storage_3 = plt.plot(np.arange(0,simtime+1),ms,scales={'x': x_sc_2a, 'y': y_sc_2a},colors=['red'],opacities = [1],line_style = 'dashed',
                           fill = 'bottom',fill_opacities = [0.4],fill_colors = ['red'], stroke_width = 1)
    min_storage_label_3 = plt.label(text = ['Min storage'], x=[0],y=[ms[0]-10],colors=['red'])
    
    storage_4 = Lines(x=range(simtime+1),y=S,scales={'x': x_sc_2a, 'y': y_sc_2a}, fill = 'bottom',fill_opacities = [0.7]*simtime,
                      fill_colors = ['blue'])
    fig_4a = plt.Figure(marks = [min_storage_3,storage_4,max_storage_2,max_storage_label_2,min_storage_label_3], 
                        axes=[x_ax_2a, y_ax_2a],layout={'width': '480px', 'height': '250px'},animation_duration=1000)
    
    releases_4 = plt.bar(np.arange(1,simtime+1),u1,colors=['green'],opacities = [0.7]*simtime,scales={'x': x_sc_1, 'y': y_sc_1},
                                labels = ['release'], display_legend = True, stroke_width = 1)
    fig_4b = plt.Figure(marks = [demand_plot, releases_4], axes=[x_ax_1, y_ax_1],layout={'width': '480px', 'height': '250px'},
                        animation_duration=1000,legend_location = 'top-left',legend_style = {'fill': 'white', 'opacity': 0.5})
                                                                                                                  
    storage_4.y  = update_operation_4(pareto_front.selected[0])[0]
    releases_4.y = update_operation_4(pareto_front.selected[0])[3]
                         
    storage_4.observe(solution_selected, ['x', 'y'])
    releases_4.observe(solution_selected, ['x', 'y'])
    
    return fig_4a,fig_4b,fig_pf
def Interactive_release_single(simtime,I,E,d,S0,Smax,env_min, demand_plot):
    def syst_sim(simtime,I,E,d,S0,Smax,env_min,Qreg):
    
        # Declare output variables
    
        S = [0]*(simtime+1) # reservoir storage in ML
    
        spill = [0]*(simtime) # spillage in ML
    
        env = [env_min]*(simtime) # environmental compensation flow
        
        S[0] = S0 # initial storage
    
        for t in range(simtime): # Loop for each time-step (week)
    
            # If at week t the inflow (I) is lower than the minimum environmental compensation (env_min), 
            # then the environmental compensation (env) = inflow (I)  
            if env_min >= I[t] :
                env[t] = I[t]
            # If the minimum environmental compensation is higher than the water resource available (S + I - E)
            # then the environmental compensation is equal to the higher value between 0 and the resource available
            if env_min >= S[t] + I[t] - E[t]:
                env[t] = max(0,S[t] + I[t] - E[t]) # S[t] = Smin then env[t] = I[t] and S[t+1] < Smin
            # If the demand is higher than the water resource available (S + I - E - env)
            # then the release for water supply is equal to the higher value between 0 and the resource available            
            if d[t] >= S[t] + I[t] - E[t] - env[t]:
                Qreg[t] = min(Qreg[t],max(0,S[t] + I[t] - E[t] - env[t]))
            # The spillage is equal to the higher value between 0 and the resource available exceeding the reservoir capacity
            spill[t] = max(0,S[t] + I[t] - Qreg[t] - env[t] - E[t] - Smax)
            # The final storage (initial storage in the next step) is equal to the storage + inflow - outflows
            S[t+1] = S[t] + I[t] - Qreg[t] - env[t]- E[t] - spill[t]
            
        return S,env,spill,Qreg
    
    # Interactive operating rule definition
    def update_operation_2(Qreg):
        S,env,spill,Qreg1 = syst_sim(simtime,I,E,d,S0,Smax,env_min,Qreg)
        sdpen = (np.sum((np.maximum(d-Qreg1,[0]*simtime))**2)).astype('int')
        fig_2b.title = 'Supply vs Demand - Total squared deficit = '+str(sdpen)+' ML^2'
        return S,Qreg1
    
    def policy_changed_2a(change):
        y_vals_2a = update_operation_2([release1.value,release2.value,release3.value,release4.value,
                                        release5.value,release6.value,release7.value,release8.value])[0]
        storage_2.y = y_vals_2a
        
    def policy_changed_2b(change):
        y_vals_2b = update_operation_2([release1.value,release2.value,release3.value,release4.value,
                                        release5.value,release6.value,release7.value,release8.value])[1]
        releases_2.y = y_vals_2b
        
    release1 = widgets.FloatSlider(min = 0, max = 40, step=1, value = 0, description = 'Week 1',orientation='vertical',layout={'width': '100px'})
    release1.observe(policy_changed_2a,'value')
    release1.observe(policy_changed_2b,'value')
    release2 = widgets.FloatSlider(min = 0, max = 40, step=1, value = 0, description = 'Week 2',orientation='vertical',layout={'width': '100px'})
    release2.observe(policy_changed_2a,'value')
    release2.observe(policy_changed_2b,'value')
    release3 = widgets.FloatSlider(min = 0, max = 40, step=1, value = 0, description = 'Week 3',orientation='vertical',layout={'width': '100px'})
    release3.observe(policy_changed_2a,'value')
    release3.observe(policy_changed_2b,'value')
    release4 = widgets.FloatSlider(min = 0, max = 40, step=1, value = 0, description = 'Week 4',orientation='vertical',layout={'width': '100px'})
    release4.observe(policy_changed_2a,'value')
    release4.observe(policy_changed_2b,'value')
    release5 = widgets.FloatSlider(min = 0, max = 40, step=1, value = 0, description = 'Week 5',orientation='vertical',layout={'width': '100px'})
    release5.observe(policy_changed_2a,'value')
    release5.observe(policy_changed_2b,'value')
    release6 = widgets.FloatSlider(min = 0, max = 40, step=1, value = 0, description = 'Week 6',orientation='vertical',layout={'width': '100px'})
    release6.observe(policy_changed_2a,'value')
    release6.observe(policy_changed_2b,'value')
    release7 = widgets.FloatSlider(min = 0, max = 40, step=1, value = 0, description = 'Week 7',orientation='vertical',layout={'width': '100px'})
    release7.observe(policy_changed_2a,'value')
    release7.observe(policy_changed_2b,'value')
    release8 = widgets.FloatSlider(min = 0, max = 40, step=1, value = 0, description = 'Week 8',orientation='vertical',layout={'width': '100px'})
    release8.observe(policy_changed_2a,'value')
    release8.observe(policy_changed_2b,'value')
    
    u=[release1.value,release2.value,release3.value,release4.value,release5.value,release6.value,release7.value,release8.value]
    
    S,env,w,u1 = syst_sim(simtime,I,E,d,S0,Smax,env_min,np.array([0]*simtime))
    sdpen = np.sum((np.maximum(d-u1,[0]*simtime))**2).astype('int')

    x_sc_1 = LinearScale();y_sc_1 = LinearScale(min=0,max=35);x_ax_1 = Axis(label='week', scale=x_sc_1);y_ax_1 = Axis(label='ML/week', scale=y_sc_1, orientation='vertical')
    
    x_sc_2a             = LinearScale(min=0,max=simtime);y_sc_2a = LinearScale(min=0,max=200);x_ax_2a = Axis(label='week', scale=x_sc_2a,tick_values=np.arange(8)+0.5);y_ax_2a = Axis(label='ML', scale=y_sc_2a, orientation='vertical')
    storage_2           = Lines(x=np.arange(0,simtime+1),y=S,colors=['blue'],scales={'x': x_sc_2a, 'y': y_sc_2a},fill = 'bottom',fill_opacities = [0.8],fill_colors = ['blue'])
    max_storage_2       = plt.plot(x=np.arange(0,simtime+1),y=[Smax]*(simtime+1),colors=['red'],scales={'x': x_sc_2a, 'y': y_sc_2a})
    max_storage_label_2 = plt.label(text = ['Max storage'], x=[0],y=[Smax+15],colors=['red'])
    fig_2a              = plt.Figure(marks = [storage_2,max_storage_2,max_storage_label_2],title = 'Reservoir storage volume',
                                     axes=[x_ax_2a, y_ax_2a],layout={'width': '950px', 'height': '300px'}, 
                                       animation_duration=1000,scales={'x': x_sc_2a, 'y': y_sc_2a})
    
    releases_2 = plt.bar(np.arange(1,simtime+1),u1,colors=['green'],opacities = [0.7]*simtime,
                        labels = ['release'], display_legend = True, stroke_width = 1,scales={'x': x_sc_1, 'y': y_sc_1})
    fig_2b   = plt.Figure(marks = [demand_plot,releases_2],axes=[x_ax_1, y_ax_1],
                        layout={'min_width': '950px', 'max_height': '300px'}, 
                        animation_duration=0,legend_location = 'top-left',legend_style = {'fill': 'white', 'opacity': 0.5})
    
    storage_2.y  = update_operation_2(u)[0]
    releases_2.y = update_operation_2(u)[1]
    
    storage_2.observe(policy_changed_2a, ['x', 'y'])
    releases_2.observe(policy_changed_2b, ['x', 'y'])
    
    return fig_2a,fig_2b,release1,release2,release3,release4,release5,release6,release7,release8
Ejemplo n.º 15
0
def total_numbers(countries, country, dfs, kw, **kwargs):
    xax = get_xaxis()
    df = dfs[country]
    return plt.bar(x=xax, y=df[kw], **kwargs)
Ejemplo n.º 16
0
def feature_groups(features, xProperty, yProperty, seriesProperty, **kwargs):
    """Generates a Chart from a set of features.
    Plots the value of one property for each feature.
    Reference:
    https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturegroups
    Args:
        features (ee.FeatureCollection): The feature collection to make a chart from.
        xProperty (str): Features labeled by xProperty.
        yProperty (str): Features labeled by yProperty.
        seriesProperty (str): The property used to label each feature in the legend.
    Raises:
        Exception: Errors when creating the chart.
    """

    try:
        df = ee_to_df(features)
        df[yProperty] = pd.to_numeric(df[yProperty])
        unique_series_values = df[seriesProperty].unique().tolist()
        new_column_names = []

        for value in unique_series_values:
            sample_filter = (df[seriesProperty] == value).map({
                True: 1,
                False: 0
            })
            column_name = str(yProperty) + "_" + str(value)
            df[column_name] = df[yProperty] * sample_filter
            new_column_names.append(column_name)

        if "labels" in kwargs:
            labels = kwargs["labels"]
        else:
            labels = [str(x) for x in unique_series_values]

        if "ylim" in kwargs:
            min_value = kwargs["ylim"][0]
            max_value = kwargs["ylim"][1]
        else:
            min_value = df[yProperty].to_numpy().min()
            max_value = df[yProperty].to_numpy().max()
            max_value = max_value + 0.2 * (max_value - min_value)

        if "title" not in kwargs:
            title = ""
        else:
            title = kwargs["title"]
        if "legend_location" not in kwargs:
            legend_location = "top-left"
        else:
            legend_location = kwargs["legend_location"]

        x_data = list(df[xProperty])
        y_data = [df[x] for x in new_column_names]

        plt.bar(x_data, y_data)
        fig = plt.figure(
            title=title,
            legend_location=legend_location,
        )

        if "width" in kwargs:
            fig.layout.width = kwargs["width"]
        if "height" in kwargs:
            fig.layout.height = kwargs["height"]

        if "display_legend" not in kwargs:
            display_legend = True
        else:
            display_legend = kwargs["display_legend"]

        bar_chart = plt.bar(x_data,
                            y_data,
                            labels=labels,
                            display_legend=display_legend)

        if "colors" in kwargs:
            bar_chart.colors = kwargs["colors"]

        if "xlabel" in kwargs:
            plt.xlabel(kwargs["xlabel"])
        if "ylabel" in kwargs:
            plt.ylabel(kwargs["ylabel"])
        plt.ylim(min_value, max_value)

        if "xlabel" in kwargs and ("ylabel" in kwargs):
            bar_chart.tooltip = Tooltip(
                fields=["x", "y"], labels=[kwargs["xlabel"], kwargs["ylabel"]])
        else:
            bar_chart.tooltip = Tooltip(fields=["x", "y"])

        plt.show()

    except Exception as e:
        raise Exception(e)
Ejemplo n.º 17
0
def feature_byProperty(features, xProperties, seriesProperty, **kwargs):
    """Generates a Chart from a set of features. Plots property values of one or more features.
    Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyproperty

    Args:
        features (ee.FeatureCollection): The features to include in the chart.
        xProperties (list | dict): One of (1) a list of properties to be plotted on the x-axis; or (2) a (property, label) dictionary specifying labels for properties to be used as values on the x-axis.
        seriesProperty (str): The name of the property used to label each feature in the legend.

    Raises:
        Exception: If the provided xProperties is not a list or dict.
        Exception: If the chart fails to create.
    """
    try:
        df = ee_to_df(features)

        if isinstance(xProperties, list):
            x_data = xProperties
            y_data = df[xProperties].values
        elif isinstance(xProperties, dict):
            x_data = list(xProperties.values())
            y_data = df[list(xProperties.keys())].values
        else:
            raise Exception("xProperties must be a list or dictionary.")

        labels = list(df[seriesProperty])

        if "ylim" in kwargs:
            min_value = kwargs["ylim"][0]
            max_value = kwargs["ylim"][1]
        else:
            min_value = y_data.min()
            max_value = y_data.max()
            max_value = max_value + 0.2 * (max_value - min_value)

        if "title" not in kwargs:
            title = ""
        else:
            title = kwargs["title"]
        if "legend_location" not in kwargs:
            legend_location = "top-left"
        else:
            legend_location = kwargs["legend_location"]

        if "display_legend" not in kwargs:
            display_legend = True
        else:
            display_legend = kwargs["display_legend"]

        fig = plt.figure(
            title=title,
            legend_location=legend_location,
        )

        if "width" in kwargs:
            fig.layout.width = kwargs["width"]
        if "height" in kwargs:
            fig.layout.height = kwargs["height"]

        bar_chart = plt.bar(x=x_data,
                            y=y_data,
                            labels=labels,
                            display_legend=display_legend)

        bar_chart.type = "grouped"

        if "colors" in kwargs:
            bar_chart.colors = kwargs["colors"]

        if "xlabel" in kwargs:
            plt.xlabel(kwargs["xlabel"])
        if "ylabel" in kwargs:
            plt.ylabel(kwargs["ylabel"])
        plt.ylim(min_value, max_value)

        if "xlabel" in kwargs and ("ylabel" in kwargs):
            bar_chart.tooltip = Tooltip(
                fields=["x", "y"], labels=[kwargs["xlabel"], kwargs["ylabel"]])
        else:
            bar_chart.tooltip = Tooltip(fields=["x", "y"])

        plt.show()

    except Exception as e:
        raise Exception(e)
Ejemplo n.º 18
0
    def plot(self,
             x,
             y,
             plot_type=None,
             overlay=False,
             position='bottomright',
             min_width=None,
             max_width=None,
             min_height=None,
             max_height=None,
             **kwargs):
        """Creates a plot based on x-array and y-array data.

        Args:
            x (numpy.ndarray or list): The x-coordinates of the plotted line.
            y (numpy.ndarray or list): The y-coordinates of the plotted line.
            plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
            overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
            position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
            min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
            max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
            min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
            max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.            

        """
        if self.plot_widget is not None:
            plot_widget = self.plot_widget
        else:
            plot_widget = widgets.Output(layout={'border': '1px solid black'})
            plot_control = WidgetControl(widget=plot_widget,
                                         position=position,
                                         min_width=min_width,
                                         max_width=max_width,
                                         min_height=min_height,
                                         max_height=max_height)
            self.plot_widget = plot_widget
            self.plot_control = plot_control
            self.add_control(plot_control)

        if max_width is None:
            max_width = 500
        if max_height is None:
            max_height = 300

        if (plot_type is None) and ('markers' not in kwargs.keys()):
            kwargs['markers'] = 'circle'

        with plot_widget:
            try:
                fig = plt.figure(1, **kwargs)
                if max_width is not None:
                    fig.layout.width = str(max_width) + 'px'
                if max_height is not None:
                    fig.layout.height = str(max_height) + 'px'

                plot_widget.clear_output(wait=True)
                if not overlay:
                    plt.clear()

                if plot_type is None:
                    if 'marker' not in kwargs.keys():
                        kwargs['marker'] = 'circle'
                    plt.plot(x, y, **kwargs)
                elif plot_type == 'bar':
                    plt.bar(x, y, **kwargs)
                elif plot_type == 'scatter':
                    plt.scatter(x, y, **kwargs)
                elif plot_type == 'hist':
                    plt.hist(y, **kwargs)
                plt.show()

            except Exception as e:
                print(e)
                print("Failed to create plot.")