def __init__(self, simulation, emitter): self.simulation = simulation self.hmap = simulation.hmap self.emitter = emitter self.coords = np.array( [self.hmap.hmap[i].coords for i in range(self.hmap.n**2)]) self.colors = [ 'green' if self.hmap.hmap[i].state == 'terrain' else 'steelblue' for i in range(self.hmap.n**2) ] ax_x = Axis(label="x", scale=bqplot.LinearScale(min=0, max=2)) ax_y = Axis(label="y", scale=bqplot.LinearScale(min=0, max=2), orientation="vertical", side="left") self.grid_scat = plt.scatter(x=self.coords[:, 0], y=self.coords[:, 1], colors=self.colors, default_size=3, default_opacities=[.3], marker='rectangle') self.particles_scat = plt.scatter( x=[p.x for p in simulation.particles], y=[p.y for p in simulation.particles]) self.fig = plt.Figure(marks=[self.grid_scat, self.particles_scat], axes=[ax_x, ax_y], animation_duration=100, padding_x=.05, padding_y=.05) self.out = widgets.Output() def on_value_change(change): t = change['new'] if t == 1: self.simulation.reset() self.emitter.reset() self.hmap.reset() self.out.clear_output() self.particles_scat.x = [p.x for p in self.simulation.particles] self.particles_scat.y = [p.y for p in self.simulation.particles] self.simulation.update_particles() p = self.emitter.emit() if p: self.simulation.add_particle(p) self.slider = widgets.IntSlider(min=0, max=1000, step=1, continuous_update=True) self.play = widgets.Play(min=1, max=1000, interval=150) self.slider.observe(on_value_change, 'value') widgets.jslink((self.play, 'value'), (self.slider, 'value'))
def create_widget(self, output, plot, dataset, limits): self.plot = plot self.output = output self.dataset = dataset self.limits = np.array(limits).tolist() self.scale_x = bqplot.LinearScale(min=limits[0][0], max=limits[0][1]) self.scale_y = bqplot.LinearScale(min=limits[1][0], max=limits[1][1]) self.scale_rotation = bqplot.LinearScale(min=0, max=1) self.scale_size = bqplot.LinearScale(min=0, max=1) self.scale_opacity = bqplot.LinearScale(min=0, max=1) self.scales = {'x': self.scale_x, 'y': self.scale_y, 'rotation': self.scale_rotation, 'size': self.scale_size, 'opacity': self.scale_opacity} margin = {'bottom': 30, 'left': 60, 'right': 0, 'top': 0} self.figure = plt.figure(self.figure_key, fig=self.figure, scales=self.scales, fig_margin=margin) self.figure.layout.min_width = '900px' plt.figure(fig=self.figure) self.figure.padding_y = 0 x = np.arange(0, 10) y = x ** 2 self._fix_scatter = s = plt.scatter(x, y, visible=False, rotation=x, scales=self.scales) self._fix_scatter.visible = False # self.scale_rotation = self.scales['rotation'] src = "" # vaex.image.rgba_to_url(self._create_rgb_grid()) # self.scale_x.min, self.scale_x.max = self.limits[0] # self.scale_y.min, self.scale_y.max = self.limits[1] self.image = bqplot_image.Image(scales=self.scales, src=src, x=self.scale_x.min, y=self.scale_y.max, width=self.scale_x.max - self.scale_x.min, height=-(self.scale_y.max - self.scale_y.min)) self.figure.marks = self.figure.marks + [self.image] # self.figure.animation_duration = 500 self.figure.layout.width = '100%' self.figure.layout.max_width = '500px' self.scatter = s = plt.scatter(x, y, visible=False, rotation=x, scales=self.scales, size=x, marker="arrow") self.panzoom = bqplot.PanZoom(scales={'x': [self.scale_x], 'y': [self.scale_y]}) self.figure.interaction = self.panzoom # self.figure.axes[0].label = self.x # self.figure.axes[1].label = self.y self.scale_x.observe(self._update_limits, "min") self.scale_x.observe(self._update_limits, "max") self.scale_y.observe(self._update_limits, "min") self.scale_y.observe(self._update_limits, "max") self.observe(self._update_scales, "limits") self.image.observe(self._on_view_count_change, 'view_count') self.control_widget = widgets.VBox() self.widget = widgets.VBox(children=[self.control_widget, self.figure]) self.create_tools()
def create_widget(self, output, plot, dataset, limits): self.plot = plot self.output = output self.dataset = dataset self.limits = np.array(limits).tolist() self.scale_x = bqplot.LinearScale(min=limits[0][0].item(), max=limits[0][1].item()) self.scale_y = bqplot.LinearScale(min=limits[1][0].item(), max=limits[1][1].item()) self.scale_rotation = bqplot.LinearScale(min=0, max=1) self.scale_size = bqplot.LinearScale(min=0, max=1) self.scale_opacity = bqplot.LinearScale(min=0, max=1) self.scales = {'x': self.scale_x, 'y': self.scale_y, 'rotation': self.scale_rotation, 'size': self.scale_size, 'opacity': self.scale_opacity} margin = {'bottom': 30, 'left': 60, 'right': 0, 'top': 0} self.figure = plt.figure(self.figure_key, fig=self.figure, scales=self.scales, fig_margin=margin) self.figure.layout.min_width = '900px' plt.figure(fig=self.figure) self.figure.padding_y = 0 x = np.arange(0, 10) y = x ** 2 self._fix_scatter = s = plt.scatter(x, y, visible=False, rotation=x, scales=self.scales) self._fix_scatter.visible = False # self.scale_rotation = self.scales['rotation'] src = "" # vaex.image.rgba_to_url(self._create_rgb_grid()) # self.scale_x.min, self.scale_x.max = self.limits[0] # self.scale_y.min, self.scale_y.max = self.limits[1] self.image = bqplot_image.Image(scales=self.scales, src=src, x=self.scale_x.min, y=self.scale_y.max, width=self.scale_x.max - self.scale_x.min, height=-(self.scale_y.max - self.scale_y.min)) self.figure.marks = self.figure.marks + [self.image] # self.figure.animation_duration = 500 self.figure.layout.width = '100%' self.figure.layout.max_width = '500px' self.scatter = s = plt.scatter(x, y, visible=False, rotation=x, scales=self.scales, size=x, marker="arrow") self.panzoom = bqplot.PanZoom(scales={'x': [self.scale_x], 'y': [self.scale_y]}) self.figure.interaction = self.panzoom # self.figure.axes[0].label = self.x # self.figure.axes[1].label = self.y self.scale_x.observe(self._update_limits, "min") self.scale_x.observe(self._update_limits, "max") self.scale_y.observe(self._update_limits, "min") self.scale_y.observe(self._update_limits, "max") self.observe(self._update_scales, "limits") self.image.observe(self._on_view_count_change, 'view_count') self.control_widget = widgets.VBox() self.widget = widgets.VBox(children=[self.control_widget, self.figure]) self.create_tools()
def LoadScatterPlotEvaluation(Y, Y_hat, prediction_size): """Prepara debajo de la celda una gráfica para observar visualmente el resultado de una predicción. Args : Y (:obj: `numpy.array`): datos reales. Y_hat (:obj: `numpy.array`): datos predichos. prediction_size (int): número de años predichos. """ n = int(Y.shape[0] / prediction_size) colors = [] if prediction_size >= 1: colors.append(1) if prediction_size >= 2: colors.append(2) if prediction_size >= 3: colors.append(3) if prediction_size >= 4: colors.append(4) if prediction_size >= 5: colors.append(5) colors = np.array(colors * n) axes_options = { 'x': dict(label='Valor real (alumnos)'), 'y': dict(label='Valor predicho (alumnos)'), 'color': dict(label='Año', side='right') } scatter2 = plt.scatter(Y, Y_hat, color=colors, stroke='black', axes_options=axes_options)
def build_widgets(self, *args, **kwargs): # residuals plot self.residuals_fig = plt.figure(title='Residuals vs Predicted Values', layout=Layout(width='960px', height='600px', overflow_x='hidden', overflow_y='hidden')) axes_options = { 'y': { 'label': 'Residual', 'tick_format': '0.1f' }, 'x': { 'label': 'Predicted Value' } } self.residuals_plot = plt.scatter([], [], colors=['yellow'], default_size=16, stroke='black', axes_options=axes_options) # zero line plt.hline(level=0, colors=['limegreen'], stroke_width=3) self.widgets_layout = HBox([self.residuals_fig])
def LoadEvaluationPlot(result, prediction_size, conjunto, modelo): """Prepara debajo de la celda una gráfica que detalla visualmente el resultado de la evaluación de un conjunto de datos utilizando un modelo específico. Args: result (:obj: `TestResult`): instancia de TestResult con los resultados de la evaluación. prediction_size (int): número de años predichos conjunto (str): conjunto de datos evaluado. modelo (str): método de predicción utilizado. """ n = int(result.Y.shape[0] / prediction_size) m = max(np.amax(result.Y_hat), np.amax(result.Y)) colors = [] if prediction_size >= 1: colors.append(1) if prediction_size >= 2: colors.append(2) if prediction_size >= 3: colors.append(3) if prediction_size >= 4: colors.append(4) if prediction_size >= 5: colors.append(5) colors = np.array(colors * n) fig = plt.figure( title='Proyección de matrícula escolar en %s utilizando %s' % (conjunto, modelo), legend_location='top-left', fig_margin=dict(top=50, bottom=70, left=100, right=100)) plt.scales( scales={ 'color': OrdinalColorScale( colors=['Green', 'DodgerBlue', 'Yellow', 'Orange', 'Red']) }) axes_options = { 'x': dict(label='Valor real (alumnos)'), 'y': dict(label='Valor predicho (alumnos)'), 'color': dict(label='Año', side='right') } scatter2 = plt.scatter(result.Y, result.Y_hat, color=colors, stroke='black', axes_options=axes_options) plt.plot(x=np.array([0, m]), y=np.array([0, m]), labels=['Línea base de predicción'], display_legend=True)
def generate_scatter(df, title="", scientific_notation=False, small_xlabel=True): 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])) scatter = plt.scatter(x=x_titles, y=df) if small_xlabel: fig.axes[0].tick_style = {"font-size": "6"} if not scientific_notation: fig.axes[1].tick_format = ".1f" return fig
def addTimeseries(inMap,path,bands,new_plot): px_series = xr.open_dataset(path) date_start = px_series.t.min().values date_end = px_series.t.max().values color = ['blue','red','green','yellow'] for i,b in enumerate(bands): x_data = px_series.t.values y_data = px_series.to_array().loc[dict(variable=b)][:,0,0].values x_data = x_data[~np.isnan(y_data)] y_data = y_data[~np.isnan(y_data)] x_data = x_data[y_data!=0] y_data = y_data[y_data!=0] axes_options = {'x': {'label':'Time', 'side':'bottom', 'num_ticks':8, 'tick_format':'%b %y'}, 'y': {'orientation':'vertical', 'side':'left', 'num_ticks':10}} if i==0: title = '' for x in bands: title += (x + ' ') title += ' timeseries' if new_plot: inMap.figure = bqplt.figure(title=title,layout={'max_height': '250px', 'width': '600px'}) else: if inMap.figure is not None: pass else: inMap.figure = bqplt.figure(title=title,layout={'max_height': '250px', 'width': '600px'}) scatt = bqplt.scatter(x_data, y_data, labels=[b], display_legend=True, colors=[color[i]], default_size=30, axes_options=axes_options) widget_control = WidgetControl(widget=inMap.figure, position='bottomright') if inMap.figure_widget is not None: inMap.map.remove_control(inMap.figure_widget) inMap.figure_widget = widget_control inMap.map.add_control(inMap.figure_widget) return
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_Pareto_front(N,I_for,E_for,d_for,S0,Smax,Smin,env_min,c,solutions_optim_relea,results1_optim_relea,results2_optim_relea): members_num = np.shape(I_for)[0] population_size = np.shape(solutions_optim_relea)[0] sdpen = np.zeros([members_num,population_size]) sdpen_mean = np.zeros(population_size) sdpen_std = np.zeros(population_size) sd = np.zeros([members_num,population_size]) sd_mean = np.zeros(population_size) sd_std = np.zeros(population_size) for i in range(population_size): S_opt,env_opt,w_opt,r_opt = syst_sim(N,I_for+solutions_optim_relea[i],E_for,d_for,S0,Smax,env_min) sdpen[:,i] = np.sum(np.maximum(d_for-r_opt,np.zeros(np.shape(d_for)))**2,axis = 1) sdpen_mean[i] = np.mean(sdpen[:,i]) sdpen_std[i] = np.std(sdpen[:,i]) sd[:,i] = np.sum(np.maximum(d_for-r_opt,np.zeros(np.shape(d_for))),axis = 1) sd_mean[i] = np.mean(sd[:,i]) sd_std[i] = np.std(sd[:,i]) # Interactive Pareto front def update_operation(i): S,env,w,r = syst_sim(N,I_for+solutions_optim_relea[i],E_for,d_for,S0,Smax,env_min) fig_wd.title = 'Total supply deficit = '+str((sd_mean[i]).astype('int'))+' ± '+str((sd_std[i]).astype('int'))+' ML' fig_in.title = 'Natural + pumped inflows - Total pumped vol = {:.0f} ML'.format(results2_optim_relea[i]/c) return S,solutions_optim_relea[i],r,results1_optim_relea[i],results2_optim_relea[i],i def solution_selected(change): if pareto_front.selected == None: pareto_front.selected = [0] storage.y = update_operation(pareto_front.selected[0])[0] deficit.y = np.maximum(d_for-update_operation(pareto_front.selected[0])[2],np.zeros(np.shape(d_for))) pump_inflows.y = update_operation(pareto_front.selected[0])[1] tot_inflows.y = update_operation(pareto_front.selected[0])[1] + I_for pareto_front_ensemble.x = np.reshape([results2_optim_relea for i in range(0, members_num)],(members_num,population_size))[:,pareto_front.selected[0]] pareto_front_ensemble.y = sdpen[:,pareto_front.selected[0]] pareto_front_ensemble.unselected_style={'opacity': 0.1} pareto_front_ensemble.selected_style={'opacity': 0.1} pareto_front_ensemble.opacity = [0.1]*members_num x_sc_pf = LinearScale() y_sc_pf = LinearScale(min = 0,max = 4000) x_ax_pf = Axis(label='Total Pumping Cost [£]', scale=x_sc_pf) y_ax_pf = Axis(label='Total Squared Deficit [ML^2]', scale=y_sc_pf, orientation='vertical') pareto_front = plt.scatter(results2_optim_relea[:],results1_optim_relea[:],scales={'x': x_sc_pf, 'y': y_sc_pf},colors=['deepskyblue'], interactions={'hover':'tooltip','click': 'select'}) pareto_front.unselected_style={'opacity': 0.8} pareto_front.selected_style={'fill': 'red', 'stroke': 'yellow', 'width': '1125px', 'height': '125px'} if pareto_front.selected == []: pareto_front.selected = [0] pareto_front_ensemble = plt.Scatter(x=np.reshape([results2_optim_relea for i in range(0, members_num)],(members_num,population_size))[:,pareto_front.selected[0]], y=sdpen[:,pareto_front.selected[0]],scales={'x': x_sc_pf, 'y': y_sc_pf}, colors=['red'], interactions={'hover':'tooltip','click': 'select'}) pareto_front_ensemble.unselected_style={'opacity': 0.1} pareto_front_ensemble.selected_style={'opacity': 0.1} pareto_front_ensemble.opacity = [0.1]*members_num fig_pf = plt.Figure(marks=[pareto_front,pareto_front_ensemble],title = 'Pareto front', axes=[x_ax_pf, y_ax_pf],layout={'width': '500px', 'height': '500px'}, animation_duration=500) pareto_front.observe(solution_selected,'selected') S,env,w,r = syst_sim(N,I_for+solutions_optim_relea[pareto_front.selected[0]],E_for,d_for,S0,Smax,env_min) x_sc_in = OrdinalScale(min=1,max=N) y_sc_in = LinearScale(min=0,max=100) x_ax_in = Axis(label='week', scale=x_sc_in) y_ax_in = Axis(label='ML/week', scale=y_sc_in, orientation='vertical') x_sc_st = LinearScale(min=0,max=N) y_sc_st = LinearScale(min=0,max=160) x_ax_st = Axis(label='week', scale=x_sc_st)#,tick_values=[0.5,1.5,2.5,3.5]) y_ax_st = Axis(label='ML', scale=y_sc_st, orientation='vertical') x_sc_wd = LinearScale(min=0.5,max=N+0.5) y_sc_wd = LinearScale(min=0,max=100); x_ax_wd = Axis(label='week', scale=x_sc_wd,tick_values=[1,2,3,4,5,6,7,8]) y_ax_wd = Axis(label='ML/week', scale=y_sc_wd, orientation='vertical') pump_inflows = plt.Lines(x=np.arange(1,N+1), y=solutions_optim_relea[pareto_front.selected[0]], scales={'x': x_sc_in, 'y': y_sc_in}, colors=['orange'], opacities = [1], stroke_width = 1, marker = 'circle', marker_size = 10, labels = ['pump (Qreg_inf)'], fill = 'bottom', fill_opacities = [1], fill_colors = ['orange']*members_num*N) tot_inflows = plt.Lines(x = np.arange(1,N+1), y = solutions_optim_relea[pareto_front.selected[0]]+I_for, scales={'x': x_sc_wd, 'y': y_sc_wd}, colors=['blue'], opacities = [1]*members_num, stroke_width = 0.5, marker = 'circle', marker_size = 10, labels = ['nat (I) + pump (Qreg_inf)'], fill = 'bottom', fill_opacities = [1/members_num]*members_num*N, fill_colors = ['blue']*members_num*N) fig_in = plt.Figure(marks = [tot_inflows,pump_inflows],axes=[x_ax_in, y_ax_in],layout={'max_width': '480px', 'max_height': '250px'}, scales={'x': x_sc_in, 'y': y_sc_in}, animation_duration=1000,legend_location = 'bottom-right') storage = plt.plot(x=np.arange(0,N+1),y=S,scales={'x': x_sc_st, 'y': y_sc_st}, colors=['blue'], stroke_width = 0.1, fill = 'bottom', fill_opacities = [0.1]*members_num) max_storage = plt.plot(x=np.arange(0,N+1), y=[Smax]*(N+1), colors=['red'], scales={'x': x_sc_st, 'y': y_sc_st}) max_storage_label = plt.label(text = ['Max storage'], x=[0], y=[Smax+10], colors=['red']) fig_st = plt.Figure(marks = [storage,max_storage,max_storage_label], title = 'Reservoir storage volume', axes=[x_ax_st, y_ax_st], layout={'width': '1000px', 'height': '350px'}, animation_duration=1000, scales={'x': x_sc_st, 'y': y_sc_st}) deficit = plt.Lines(x = np.arange(1,N+1), y = np.maximum(d_for-r,np.zeros(np.shape(r))), scales={'x': x_sc_wd, 'y': y_sc_wd}, colors=['red'], stroke_width = 1, opacities = [1]*members_num, marker = 'circle', marker_size = 10, labels = ['max(0,d-Qreg_rel)'], fill = 'bottom', fill_opacities = [1/members_num]*members_num, fill_colors = ['red']*members_num) fig_wd = plt.Figure(marks = [deficit],axes=[x_ax_wd, y_ax_wd], layout={'max_width': '480px', 'max_height': '250px'}, animation_duration=1000, legend_location = 'bottom-right') storage.y = update_operation(pareto_front.selected[0])[0] deficit.y = np.maximum(d_for-update_operation(pareto_front.selected[0])[2],np.zeros(np.shape(d_for))) pump_inflows.y = update_operation(pareto_front.selected[0])[1] tot_inflows.y = update_operation(pareto_front.selected[0])[1] + I_for storage.observe(solution_selected, ['x', 'y']) deficit.observe(solution_selected, ['x', 'y']) pump_inflows.observe(solution_selected, ['x', 'y']) tot_inflows.observe(solution_selected, ['x', 'y']) return fig_pf,fig_wd,fig_st,fig_in,pareto_front
def Interactive_Pareto_front_act(N,I_act,E_act,d_act,S0,Smax,Smin,env_min,c,solutions_optim_relea_2,results1_optim_relea_2,results2_optim_relea_2,sel_policy): population_size = np.shape(solutions_optim_relea_2)[0] sdpen_act_4 = np.zeros(population_size); pcost_act_4 = np.zeros(population_size) for i in range(population_size): pinfl_policy_4 = np.array(solutions_optim_relea_2[i]) S_act_4,env_act_4,w_act_4,r_act_4 = syst_sim(N,I_act+pinfl_policy_4,E_act,d_act,S0,Smax,env_min) sdpen_act_4[i] = (np.sum((np.maximum(d_act-r_act_4,[0]*N))**2)).astype('int') pcost_act_4[i] = (np.sum(np.array(pinfl_policy_4)*c)).astype('int') def update_operation_act_4(i): u = solutions_optim_relea_2[i] S,env,w,r = syst_sim(N,I_act+u,E_act,d_act,S0,Smax,env_min) fig_4b.title = 'Total supply deficit = '+str((np.sum((np.maximum(d_act-r,[0]*N)))).astype('int'))+' ML' fig_4d.title = 'Natural + pumped inflows - Total pumped vol = '+str((np.sum(np.array(u))).astype('int'))+' ML' return S,u,r,i def solution_selected_act_4(change): if pareto_front_act_4.selected == None: pareto_front_act_4.selected = [0] deficit_4.y = np.maximum(d_act-update_operation_act_4(pareto_front_act_4.selected[0])[2], [0]*N) storage_4.y = update_operation_act_4(pareto_front_act_4.selected[0])[0] pump_inflows_4.y = [update_operation_act_4(pareto_front_act_4.selected[0])[1]] tot_inflows_4.y = [update_operation_act_4(pareto_front_act_4.selected[0])[1]+I_act[0]] def on_hover_4pf(self, target): hover_elem_id = list(target.values())[1]['index'] def on_element_click_4pf(self, target): click_elem_id = list(target.values())[1]['index'] colors = ['deepskyblue']*population_size colors[click_elem_id] = 'red' pareto_front_4.colors = colors x_sc_2pf = LinearScale() y_sc_2pf = LinearScale() x_ax_2pf = Axis(label='Total Pumping Cost [£]', scale=x_sc_2pf) y_ax_2pf = Axis(label='Total Squared Deficit [ML^2]', scale=y_sc_2pf, orientation='vertical') pareto_front_4 = plt.scatter(results2_optim_relea_2[:], results1_optim_relea_2[:], scales={'x': x_sc_2pf, 'y': y_sc_2pf}, colors=['deepskyblue'], opacity = [0.11]*population_size, interactions={'hover':'tooltip'}) pareto_front_4.tooltip = None pareto_front_act_4 = plt.scatter(pcost_act_4[:],sdpen_act_4[:],scales={'x': x_sc_2pf, 'y': y_sc_2pf}, colors=['green'], interactions={'hover':'tooltip'}) pareto_front_act_4.unselected_style = {'opacity': 0} pareto_front_act_4.selected_style = {'fill': 'black', 'stroke': 'black', 'width': '1125px', 'height': '125px'} pareto_front_4.selected_style = {'fill': 'red', 'stroke': 'red', 'width': '1125px', 'height': '125px'} pareto_front_act_4.tooltip = None fig_4pf = plt.Figure(marks = [pareto_front_4,pareto_front_act_4 ],title = 'Pareto front', axes=[x_ax_2pf, y_ax_2pf], layout={'width': '500px', 'height': '500px'}, animation_duration=1000) if pareto_front_act_4.selected == []: pareto_front_4.selected = [sel_policy] pareto_front_act_4.selected = [sel_policy] pareto_front_act_4.observe(solution_selected_act_4,'selected') pareto_front_act_4.on_hover(on_hover_4pf) pareto_front_4.on_hover(on_hover_4pf) x_sc_2b = OrdinalScale(min=1, max=N) y_sc_2b = LinearScale(min=0, max=100) x_ax_2b = Axis(label='week', scale=x_sc_2b) y_ax_2b = Axis(label='ML/week', scale=y_sc_2b, orientation='vertical') deficit_4 = plt.Lines(x=np.arange(1,N+1), y=np.maximum(d_act-r_act_4,[0]*N), colors=['red'], opacities = [1], stroke_width = 0.5, marker = 'circle', marker_size = 15, labels = ['max(0,d-Qreg_rel)'], fill = 'bottom', fill_opacities = [0.5], fill_colors = ['red'], display_legend = False, scales={'x': x_sc_2b, 'y': y_sc_2b}) fig_4b = plt.Figure(marks = [deficit_4], axes=[x_ax_2b, y_ax_2b], layout={'width': '480px', 'height': '250px'}, scales={'x': x_sc_2b, 'y': y_sc_2b}, animation_duration=1000, legend_location = 'bottom-right', legend_style = {'fill': 'white', 'opacity': 0.5}) x_sc_2c = LinearScale(min=0, max=N) y_sc_2c = LinearScale(min=0, max=160) x_ax_2c = Axis(label='week', scale=x_sc_2c) y_ax_2c = Axis(label='ML', scale=y_sc_2c, orientation='vertical') max_storage_2 = plt.plot(x=np.arange(0,N+1), y=[Smax]*(N+1), colors=['red'], scales={'x': x_sc_2c, 'y': y_sc_2c}) max_storage_label_2 = plt.label(text = ['Max storage'], x=[0], y=[Smax+10], colors=['red']) storage_4 = plt.Lines(x=np.arange(0,N+1), y=S_act_4, colors=['blue'], scales={'x': x_sc_2c, 'y': y_sc_2c}, fill = 'bottom',fill_opacities = [0.8], fill_colors = ['blue']) fig_4c = plt.Figure(marks = [storage_4,max_storage_2,max_storage_label_2], title = 'Reservoir storage (s)', axes=[x_ax_2c, y_ax_2c], layout={'width': '1000px', 'height': '350px'}, animation_duration=1000, scales={'x': x_sc_2c, 'y': y_sc_2c}) x_sc_2d = OrdinalScale(min=1, max=N) y_sc_2d = LinearScale(min=0, max=100) x_ax_2d = Axis(label='week', scale=x_sc_2d) y_ax_2d = Axis(label='ML/week', scale=y_sc_2d, orientation='vertical') pump_inflows_4 = plt.Lines(x=np.arange(1,N+1), y=[pinfl_policy_4], colors=['orange'], opacities = [1], stroke_width = 0.5, marker = 'circle', marker_size = 15, fill = 'bottom', fill_opacities = [1], fill_colors = ['orange'], labels = ['pump (Qreg_inf)'], display_legend = True, scales={'x': x_sc_2d, 'y': y_sc_2d}) tot_inflows_4 = plt.Lines(x=np.arange(1,N+1), y=[pinfl_policy_4+I_act[0]], colors=['blue'], opacities = [1], stroke_width = 1, marker = 'circle', marker_size = 15, fill = 'bottom', fill_opacities = [0.5], fill_colors = ['blue'], labels = ['nat (I) + pump (Qreg_inf)'], display_legend = True, scales={'x': x_sc_2d, 'y': y_sc_2d}) fig_4d = plt.Figure(marks = [tot_inflows_4,pump_inflows_4], title = 'Natural + pumped inflows', axes=[x_ax_2d, y_ax_2d], layout={'width': '480px', 'height': '250px'}, scales={'x': x_sc_2d, 'y': y_sc_2d}, animation_duration=1000, legend_location = 'top', legend_style = {'fill': 'white', 'opacity': 0.5}) deficit_4.y = np.maximum(d_act-update_operation_act_4(sel_policy)[2],[0]*N) storage_4.y = update_operation_act_4(sel_policy)[0] pump_inflows_4.y = [update_operation_act_4(sel_policy)[1]] tot_inflows_4.y = [update_operation_act_4(sel_policy)[1]+I_act[0]] deficit_4.observe(solution_selected_act_4, ['x', 'y']) storage_4.observe(solution_selected_act_4, ['x', 'y']) pump_inflows_4.observe(solution_selected_act_4, ['x', 'y']) tot_inflows_4.observe(solution_selected_act_4, ['x', 'y']) return fig_4b,fig_4c,fig_4d,fig_4pf
def Interactive_Pareto_front_det(N,I_sel,E,d_sel,S0,Smax,Smin,env_min,c,solutions_optim_relea_2,results1_optim_relea_2,results2_optim_relea_2): def update_operation_2(i): u = solutions_optim_relea_2[i] S,env,w,r = syst_sim(N,I_sel+u,E,d_sel,S0,Smax,env_min) fig_2b.title = 'Total supply deficit = '+str((np.sum((np.maximum(d_sel-r,[0]*N)))).astype('int'))+' ML' fig_2d.title = 'Natural + pumped inflows - Total pumped vol = '+str((np.sum(np.array(u))).astype('int'))+' ML' return S,u,r,i def solution_selected_2(change): if pareto_front_2.selected == None: pareto_front_2.selected = [0] deficit_2.y = np.maximum(d_sel-update_operation_2(pareto_front_2.selected[0])[2],[0]*N) storage_2.y = update_operation_2(pareto_front_2.selected[0])[0] pump_inflows_2.y = [update_operation_2(pareto_front_2.selected[0])[1]] tot_inflows_2.y = [update_operation_2(pareto_front_2.selected[0])[1]+I_sel[0]] x_sc_2pf = LinearScale();y_sc_2pf = LinearScale() x_ax_2pf = Axis(label='Total Pumping Cost [£]', scale=x_sc_2pf) y_ax_2pf = Axis(label='Total Squared Deficit [ML^2]', scale=y_sc_2pf, orientation='vertical') pareto_front_2 = plt.scatter(results2_optim_relea_2[:],results1_optim_relea_2[:],scales={'x': x_sc_2pf, 'y': y_sc_2pf}, colors=['deepskyblue'], interactions={'hover':'tooltip','click': 'select'}) pareto_front_2.unselected_style = {'opacity': 0.4} pareto_front_2.selected_style = {'fill': 'red', 'stroke': 'yellow', 'width': '1125px', 'height': '125px'} def_tt = Tooltip(fields=['x', 'y','index'],labels=['Pumping cost','Squared deficit', 'sol index'], formats=['.1f', '.1f', '.0f']) pareto_front_2.tooltip = def_tt fig_2pf = plt.Figure(marks = [pareto_front_2],title = 'Pareto front', axes=[x_ax_2pf, y_ax_2pf], layout={'width': '500px', 'height': '500px'}, animation_duration=1000) if pareto_front_2.selected == []: pareto_front_2.selected = [0] pareto_front_2.observe(solution_selected_2,'selected') S,env,w,r = syst_sim(N,I_sel+solutions_optim_relea_2[pareto_front_2.selected[0]],E,d_sel,S0,Smax,env_min) x_sc_2b = OrdinalScale(min=1,max=N);y_sc_2b = LinearScale(min=0,max=100) x_ax_2b = Axis(label='week', scale=x_sc_2b) y_ax_2b = Axis(label='ML/week', scale=y_sc_2b, orientation='vertical') deficit_2 = plt.Lines(x=np.arange(1,N+1), y=np.maximum(d_sel-r,[0]*N), colors=['red'], opacities = [1], stroke_width = 0.5, marker = 'circle', marker_size = 15, labels = ['max(0,d-Qreg_rel)'], fill = 'bottom', fill_opacities = [0.5], fill_colors = ['red'], display_legend = False, scales={'x': x_sc_2b, 'y': y_sc_2b}) fig_2b = plt.Figure(marks = [deficit_2], axes=[x_ax_2b, y_ax_2b], layout={'width': '480px', 'height': '250px'}, scales={'x': x_sc_2b, 'y': y_sc_2b}, animation_duration=1000, legend_location = 'bottom-right', legend_style = {'fill': 'white', 'opacity': 0.5}) x_sc_2c = LinearScale(min=0,max=N) y_sc_2c = LinearScale(min=0,max=160) x_ax_2c = Axis(label='week', scale=x_sc_2c) y_ax_2c = Axis(label='ML', scale=y_sc_2c, orientation='vertical') storage_2 = plt.Lines(x=np.arange(0,N+1), y=S,colors=['blue'], scales={'x': x_sc_2c, 'y': y_sc_2c}, fill = 'bottom', fill_opacities = [0.8], fill_colors = ['blue']) max_storage_2 = plt.plot(x=np.arange(0,N+1), y=[Smax]*(N+1), colors=['red'], scales={'x': x_sc_2c, 'y': y_sc_2c}) max_storage_label_2 = plt.label(text = ['Max storage'], x=[0], y=[Smax+10], colors=['red']) fig_2c = plt.Figure(marks = [storage_2,max_storage_2,max_storage_label_2], title = 'Reservoir storage (s)', axes=[x_ax_2c, y_ax_2c], layout={'width': '1000px', 'height': '350px'}, animation_duration=1000, scales={'x': x_sc_2c, 'y': y_sc_2c}) x_sc_2d = OrdinalScale(min=1, max=N) y_sc_2d = LinearScale(min=0, max=100) x_ax_2d = Axis(label='week', scale=x_sc_2d) y_ax_2d = Axis(label='ML/week', scale=y_sc_2d, orientation='vertical') # Stacked bars pump_inflows_2 = plt.Lines(x=np.arange(1,N+1), y=(solutions_optim_relea_2[pareto_front_2.selected[0]]), colors=['orange'], opacities = [1], stroke_width = 0.5, marker = 'circle', marker_size = 15, fill = 'bottom', fill_opacities = [1], fill_colors = ['orange'], labels = ['pump (Qreg_inf)'], display_legend = True, scales={'x': x_sc_2d, 'y': y_sc_2d}) tot_inflows_2 = plt.Lines(x=np.arange(1,N+1), y=(solutions_optim_relea_2[pareto_front_2.selected[0]]+I_sel[0]), colors=['blue'], opacities = [1], stroke_width = 1, marker = 'circle', marker_size = 15, fill = 'bottom', fill_opacities = [0.5], fill_colors = ['blue'], labels = ['nat (I) + pump (Qreg_inf)'], display_legend = True, scales={'x': x_sc_2d, 'y': y_sc_2d}) fig_2d = plt.Figure(marks = [tot_inflows_2,pump_inflows_2], title = 'Natural + pumped inflows', axes=[x_ax_2d, y_ax_2d], layout={'width': '480px', 'height': '250px'}, scales={'x': x_sc_2d, 'y': y_sc_2d}, animation_duration=1000, legend_location = 'top', legend_style = {'fill': 'white', 'opacity': 0.5}) deficit_2.y = np.maximum(d_sel-update_operation_2(pareto_front_2.selected[0])[2],[0]*N) storage_2.y = update_operation_2(pareto_front_2.selected[0])[0] pump_inflows_2.y = [update_operation_2(pareto_front_2.selected[0])[1]] tot_inflows_2.y = [update_operation_2(pareto_front_2.selected[0])[1]+I_sel[0]] deficit_2.observe(solution_selected_2, ['x', 'y']) storage_2.observe(solution_selected_2, ['x', 'y']) pump_inflows_2.observe(solution_selected_2, ['x', 'y']) tot_inflows_2.observe(solution_selected_2, ['x', 'y']) return fig_2pf,fig_2b,fig_2c,fig_2d,pareto_front_2
def create_widget(self, output, plot, dataset, limits): self.plot = plot self.output = output self.dataset = dataset self.limits = np.array(limits).tolist() def fix(v): # bqplot is picky about float and numpy scalars if hasattr(v, 'item'): return v.item() else: return v self.scale_x = bqplot.LinearScale(min=fix(limits[0][0]), max=fix(limits[0][1]), allow_padding=False) self.scale_y = bqplot.LinearScale(min=fix(limits[1][0]), max=fix(limits[1][1]), allow_padding=False) self.scale_rotation = bqplot.LinearScale(min=0, max=1) self.scale_size = bqplot.LinearScale(min=0, max=1) self.scale_opacity = bqplot.LinearScale(min=0, max=1) self.scales = { 'x': self.scale_x, 'y': self.scale_y, 'rotation': self.scale_rotation, 'size': self.scale_size, 'opacity': self.scale_opacity } margin = {'bottom': 35, 'left': 60, 'right': 5, 'top': 5} self.figure = plt.figure(self.figure_key, fig=self.figure, scales=self.scales, fig_margin=margin) self.figure.layout.min_width = '600px' plt.figure(fig=self.figure) self.figure.padding_y = 0 x = np.arange(0, 10) y = x**2 self._fix_scatter = s = plt.scatter(x, y, visible=False, rotation=x, scales=self.scales) self._fix_scatter.visible = False # self.scale_rotation = self.scales['rotation'] src = "" # vaex.image.rgba_to_url(self._create_rgb_grid()) # self.scale_x.min, self.scale_x.max = self.limits[0] # self.scale_y.min, self.scale_y.max = self.limits[1] self.core_image = widgets.Image(format='png') self.core_image_fix = widgets.Image(format='png') self.image = bqplot.Image(scales=self.scales, image=self.core_image) self.figure.marks = self.figure.marks + [self.image] # self.figure.animation_duration = 500 self.figure.layout.width = '100%' self.figure.layout.max_width = '500px' self.scatter = s = plt.scatter(x, y, visible=False, rotation=x, scales=self.scales, size=x, marker="arrow") self.panzoom = bqplot.PanZoom(scales={ 'x': [self.scale_x], 'y': [self.scale_y] }) self.figure.interaction = self.panzoom for axes in self.figure.axes: axes.grid_lines = 'none' axes.color = axes.grid_color = axes.label_color = blackish self.figure.axes[0].label = str(plot.x) self.figure.axes[1].label = str(plot.y) self.scale_x.observe(self._update_limits, "min") self.scale_x.observe(self._update_limits, "max") self.scale_y.observe(self._update_limits, "min") self.scale_y.observe(self._update_limits, "max") self.observe(self._update_scales, "limits") self.image.observe(self._on_view_count_change, 'view_count') self.control_widget = widgets.VBox() self.widget = widgets.VBox(children=[self.figure]) self.create_tools()
def create_widget(self, output, plot, dataset, limits): self.plot = plot self.output = output self.dataset = dataset self.limits = np.array(limits).tolist() def fix(v): # bqplot is picky about float and numpy scalars if hasattr(v, 'item'): return v.item() else: return v self.scale_x = bqplot.LinearScale(min=fix(limits[0][0]), max=fix(limits[0][1]), allow_padding=False) self.scale_y = bqplot.LinearScale(min=fix(limits[1][0]), max=fix(limits[1][1]), allow_padding=False) self.scales = {'x': self.scale_x, 'y': self.scale_y} self.figure = plt.figure(self.figure_key, fig=self.figure, scales=self.scales) self.figure.layout.width = 'calc(100% - 400px)' self.figure.layout.min_height = '800px' plt.figure(fig=self.figure) #self.figure.padding_y = 0 x = np.arange(0, 10) y = x**2 self.core_image = widgets.Image(format='png') self.core_image_fix = widgets.Image(format='png') self.image = bqplot.Image(scales=self.scales, image=self.core_image) # triggered by regular mouse click not a brush selector self.image.on_element_click(self.click_to_zoom) self.figure.marks = self.figure.marks + [self.image] self.scatter = s = plt.scatter(x, y, visible=False, rotation=x, scales=self.scales, size=x, marker="arrow") self.panzoom = bqplot.PanZoom(scales={ 'x': [self.scale_x], 'y': [self.scale_y] }) self.figure.interaction = self.panzoom for axes in self.figure.axes: axes.grid_lines = 'none' axes.color = axes.grid_color = axes.label_color = blackish self.figure.axes[0].label = plot.x_label self.figure.axes[1].label = plot.y_label self.figure.axes[1].scale = bqplot.LinearScale(min=0, max=self.scale_y.max - self.scale_y.min, allow_padding=False) self.stuck_ctr = 0 self.base_address = widgets.Label( value=f"Base address: 0x{int(self.limits[1][0]):X}") self.zoom_args = widgets.Text(description="Zoom Args", value=self.zoom_args_string(), disabled=True, style={'description_width': 'initial'}, layout=widgets.Layout(width='50%')) self.curr_action = Action.other self.undo_actions = list() self.redo_actions = list() self.counter = 2 self.scale_x.observe(self._update_limits) self.scale_y.observe(self._update_limits) self.widget = widgets.VBox( [self.figure, self.base_address, self.zoom_args]) self.create_tools()
import numpy as np import bqplot.pyplot as plt size = 100 plt.figure(title='Scatter plot with colors') plt.scatter(np.random.randn(size), np.random.randn(size), color=np.random.randn(size)) plt.show()
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.")
def add_scat(self, *args, **kwargs): return plt.scatter(*args, figure=self.fig, **kwargs)
def Interactive_policy_auto(N, I_hist, e_hist, s_0, s_min, s_max, u_0, u_1, u_mean, u_max, env_min, d_hist, rc, results1_optim,results2_optim,sol_optim): # Function to update the release policy when clicking on the points of the Pareto front def update_operating_policy_2(i): u_ref,s_ref_1,s_ref_2 = sol_optim[i] x0 = [0, u_0] x1 = [s_ref_1, u_ref] x2 = [s_ref_2, u_ref] x3 = [1, u_1] param = [x0, x1, x2, x3, u_mean] u_frac = four_points_policy(param)/u_mean Qreg = {'releases' : {'file_name' : 'Reservoir_operating_policy.Operating_policy_functions', 'function' : 'four_points_policy', 'param': param}, 'inflows' : [], 'rel_inf' : []} Qenv, Qspill, u, I_reg, s, E = Res_sys_sim(I_hist, e_hist, s_0, s_min, s_max, env_min, d_hist, Qreg) MSV = (np.sum((np.maximum(rc-s,[0]*(N+1))))).astype('int') fig_2c.title = 'Reservoir storage volume - MSV = '+str(MSV)+' ML' TSD = (np.sum((np.maximum(d_hist-u,[0]*N))**2)).astype('int') fig_2b.title = 'Supply vs Demand - Total squared deficit = '+str(TSD)+' ML^2' return u_frac, Qenv, Qspill, u, I_reg, s # Function to update the figures when clicking on the points of the Pareto front def update_figure_2(change): policy_function.y = update_operating_policy_2(pareto_front.selected[0])[0] releases.y = update_operating_policy_2(pareto_front.selected[0])[3] storage.y = update_operating_policy_2(pareto_front.selected[0])[5] # Fig_pf: Pareto front 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[:],results2_optim[:], 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=['index','x', 'y'], labels=['index','Water deficit', 'Min storage'], formats=['.d','.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': '400px', 'height': '400px'}, animation_duration=1000) if pareto_front.selected == []: pareto_front.selected = [0] pareto_front.observe(update_figure_2,'selected') # Initial simulation applting the point of the Pareto Fron selected by default u_ref,s_ref_1,s_ref_2 = sol_optim[pareto_front.selected[0]] x0 = [0, u_0] x1 = [s_ref_1, u_ref] x2 = [s_ref_2, u_ref] x3 = [1, u_1] param = [x0, x1, x2, x3, u_mean] u_frac = four_points_policy(param)/u_mean Qreg = {'releases' : {'file_name' : 'Reservoir_operating_policy.Operating_policy_functions', 'function' : 'four_points_policy', 'param': param}, 'inflows' : [], 'rel_inf' : []} Qenv, Qspill, u, I_reg, s, E = Res_sys_sim(I_hist, e_hist, s_0, s_min, s_max, env_min, d_hist, Qreg) # Fig 2a: Policy function s_frac = np.arange(0,1.01,0.01) x_sc_2a = LinearScale(min=0,max=1); y_sc_2a = LinearScale(min=0,max=u_max/u_mean); x_ax_2a = Axis(label='Storage fraction', scale=x_sc_2a); y_ax_2a = Axis(label='Release fraction', scale=y_sc_2a, orientation='vertical') policy_function = Lines(x = s_frac, y = u_frac , colors = ['blue'], scales = {'x': x_sc_2a, 'y': y_sc_2a}) fig_2a = plt.Figure(marks = [policy_function], title = 'Policy function', axes=[x_ax_2a, y_ax_2a], layout={'width': '400px', 'height': '375px'}, animation_duration=1000, scales={'x': x_sc_2a, 'y': y_sc_2a}) policy_function.observe(update_figure_2, ['x', 'y']) # Fig 2b: Releases vs Demand x_sc_2b = LinearScale(min=0,max=N); y_sc_2b = LinearScale(min=0,max=u_max); x_ax_2b = Axis(label='week', scale=x_sc_2b); y_ax_2b = Axis(label='ML/week', scale=y_sc_2b, orientation='vertical') demand = Bars(x = np.arange(1,N+1), y = d_hist, colors = ['gray'], scales = {'x': x_sc_2b, 'y': y_sc_2b}) releases = Bars(x = np.arange(1,N+1), y = u, colors = ['green'], scales = {'x': x_sc_2b, 'y': y_sc_2b}) TSD = (np.sum((np.maximum(d_hist-u,[0]*N))**2)).astype('int') fig_2b = plt.Figure(marks = [demand, releases], title = 'Supply vs Demand - TSD = '+str(TSD)+' ML^2', axes=[x_ax_2b, y_ax_2b], layout={'width': '950px', 'height': '250px'}, animation_duration=1000, scales={'x': x_sc_2b, 'y': y_sc_2b}) releases.observe(update_figure_2, ['x', 'y']) # Fig 2c: Storage x_sc_2c = LinearScale(); y_sc_2c = LinearScale(min=0,max=200); x_ax_2c = Axis(label='week', scale=x_sc_2c); y_ax_2c = Axis(label='ML', scale=y_sc_2c, orientation='vertical') storage = Lines(x = np.arange(0,N+1), y = s , colors = ['blue'], scales = {'x': x_sc_2c, 'y': y_sc_2c}, fill = 'bottom',fill_opacities = [0.8],fill_colors = ['blue']) max_storage = plt.plot(x=np.arange(0,N+1), y=[s_max]*(N+1), colors=['red'], scales={'x': x_sc_2c, 'y': y_sc_2c}) max_storage_label = plt.label(text = ['Max storage'], x=[0], y=[s_max+15], colors=['red']) min_storage = plt.plot(np.arange(0,N+1),rc, scales={'x': x_sc_2c, 'y': y_sc_2c}, colors=['red'],opacities = [1], line_style = 'dashed', fill = 'bottom',fill_opacities = [0.4],fill_colors = ['red'], stroke_width = 1) min_storage_label = plt.label(text = ['Min storage'], x=[0], y=[rc[0]-10], colors=['red']) MSV = (np.sum((np.maximum(rc-s,[0]*(N+1))))).astype('int') fig_2c = plt.Figure(marks = [storage,max_storage,max_storage_label, min_storage,min_storage_label], title = 'Reservoir storage volume - MSV = '+str(MSV)+' ML', axes=[x_ax_2c, y_ax_2c], layout={'width': '950px', 'height': '250px'}, animation_duration=1000, scales={'x': x_sc_2c, 'y': y_sc_2c}) storage.observe(update_figure_2, ['x', 'y']) return fig_pf, fig_2a,fig_2b,fig_2c
import numpy as np import bqplot.pyplot as plt size = 100 plt.figure(title="Scatter plot with colors") plt.scatter(np.random.randn(size), np.random.randn(size), color=np.random.randn(size)) plt.show()