def _make_plot(self): plt.close(1) margin = {'top': 25, 'bottom': 35, 'left': 35, 'right': 25} fig_layout = {'height': '100%', 'width': '100%'} self.I_fig = plt.figure(1, title='Stokes I', fig_margin=margin, layout=fig_layout) self.I_plot = plt.plot(self.u, self.I) plt.xlabel("Δλ / ΔλD") plt.close(2) self.Q_fig = plt.figure(2, title='Stokes Q', fig_margin=margin, layout=fig_layout) self.Q_plot = plt.plot(self.u, self.Q) plt.xlabel("Δλ / ΔλD") plt.close(3) self.U_fig = plt.figure(3, title='Stokes U', fig_margin=margin, layout=fig_layout) self.U_plot = plt.plot(self.u, self.U) plt.xlabel("Δλ / ΔλD") plt.close(4) self.V_fig = plt.figure(4, title='Stokes V', fig_margin=margin, layout=fig_layout) self.V_plot = plt.plot(self.u, self.V) plt.xlabel("Δλ / ΔλD")
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 test_figure(self): size = 100 scale = 100.0 np.random.seed(0) x_data = np.arange(size) y_data = np.cumsum(np.random.randn(size) * scale) fig = plt.figure(title='First Example') plt.plot(y_data) fig.save_png()
def plot_ellipse(a,b,xdis,ydis,iang,fang): #xdisplacement, ydisplacement, initial_angle, final_angle q=100 step = (fang-iang)/q x=np.ones(q+1) y=np.ones(q+1) for t in range(q+1): theta = iang + step*t x[t] *= (xdis+a*np.cos(theta)) y[t] *= (ydis+b*np.sin(theta)) plt.plot(x,y,'k')
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 create_figure(self): cc = self.coords tree = self.tree fig = plt.figure(figsize=(8,0.5)) lines = OrderedDict() for n in tree.nodes: c0 = cc[n] for nn in tree.children(n): c1 = cc[nn] l = plt.plot([c0[0],c1[0]],[c0[1],c1[1]],'b') lines[(n,nn)] = l xv = [c[0] for c in (cc).values()] yv = [c[1] for c in (cc).values()] points = plt.plot(xv,yv,'o') self.fig = fig self.lines = lines self.points = points
def __init__(self, animation_duration=100, aspect_ratio=1, tail_len=1000, lim=2): axes_options = {'x': {'label': 'x'}, 'y': {'label': 'y'}} self.fig = plt.figure(animation_duration=animation_duration, min_aspect_ratio=aspect_ratio, max_aspect_ratio=aspect_ratio) self.line = plt.plot([], [], marker_str='b-', axes_options=axes_options) self.hline = plt.hline(0, opacities=[0], colors=['red'], stroke_width=3) self.scat = plt.plot([], [], 'ro') self.tail_len = tail_len plt.xlim(-lim, lim) plt.ylim(-lim, lim)
def show_measurement_1d(measurements_or_func, figure=None, throttling=False, **kwargs): if figure is None: figure = plt.figure(fig_margin={ 'top': 0, 'bottom': 50, 'left': 50, 'right': 0 }) figure.layout.height = '250px' figure.layout.width = '300px' try: measurements = measurements_or_func() return_callback = True except TypeError: measurements = measurements_or_func return_callback = False lines = [] for measurement, color in zip(measurements, TABLEAU_COLORS.values()): calibration = measurement.calibrations[0] array = measurement.array x = np.linspace(calibration.offset, calibration.offset + len(array) * calibration.sampling, len(array)) line = plt.plot(x, array, colors=[color], **kwargs) figure.axes[0].label = format_label(measurement.calibrations[0]) lines.append(line) # figure.axes[1].label = format_label(measurement) if return_callback: @throttle(throttling) def callback(*args, **kwargs): for line, measurement in zip(lines, measurements_or_func()): x = np.linspace( calibration.offset, calibration.offset + len(array) * calibration.sampling, len(array)) line.x = x line.y = measurement.array return figure, callback else: return figure
def build_widgets(self, *args, **kwargs): # residuals plot self.residuals_fig = plt.figure(title='Residuals vs Predicted Values', layout=Layout(width='960px', height='600px')) axes_options = {'y': {'label': 'Residual', 'tick_format': '0.1f'}, 'x': {'label': 'Predicted Value'}} self.residuals_plot = plt.plot([], [], 'yo', 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 __init__(self, simu, net, emb_index=0): """ The initializer of the Latent Embedding Workbench. Args: simu: The simulation object to simulate net: The NN trained to extract embedding """ # We check input assert issubclass(type(simu), simulation.BaseSimulation) assert issubclass(type(net), network.BaseNetwork) # We instantiate arguments self._simulation = simu self._emb_index = emb_index self._network = net self._sliders = [ ipw.FloatSlider( min=0., max=1., step=0.01, description=self._simulation.get_factor_labels()[i]) for i in range(self._simulation.nb_params()) ] self._factors = list(np.ones(self._simulation.nb_params())) self._latent_serie = np.zeros( [self._network.get_latent_size()[-1], NB_SAMPLES]) # We generate view elements self._latent_fig = plt.figure() self._latent_plot = plt.plot(range(NB_SAMPLES), self._latent_serie) # We create a slider with callback for each parameter for index, slider in enumerate(self._sliders): slider.observe(self._callback_closure(index), 'value') self._title = ipw.HTML('<h2>Latent Space WorkBench</h2>') self._caption = ipw.HTML('Manipulate the generative factors:') # We layout the different parts left_elmts = [self._title, self._caption] + self._sliders left_layout = ipw.Layout(padding='50px 0px 0px 0px') left_pane = ipw.VBox(left_elmts, layout=left_layout) self._latent_fig.layout = ipw.Layout(width='50%') self._layout = ipw.HBox([left_pane, self._latent_fig]) IPython.display.display(self._layout)
def plot_line(ipt, fpt, col): q = 10 xstep=(fpt[0]-ipt[0])/q ystep=(fpt[1]-ipt[1])/q if(ipt[0]==fpt[0]): x = np.ones(q+1) x *= ipt[0] y=np.arange(ipt[1],fpt[1],ystep) y=np.append(y,[fpt[1]]) if(ipt[1]==fpt[1]): x=np.arange(ipt[0],fpt[0],xstep) x=np.append(x,[fpt[0]]) y = np.ones(q+1) y *= ipt[1] if(ipt[0]==fpt[0] and ipt[1]==fpt[1]): x = np.ones(q+1) x *= ipt[0] y = np.ones(q+1) y *= ipt[1] elif((ipt[0] != fpt[0]) and (ipt[1] != fpt[1])): x=np.arange(ipt[0],fpt[0],xstep) x=np.append(x,[fpt[0]]) y=np.arange(ipt[1],fpt[1],ystep) y=np.append(y,[fpt[1]]) if(col==0): plt.plot(x,y,'k') if(col==1): plt.plot(x,y,'b', linewidth = 0.5) if(col==2): plt.plot(x,y,'r', linewidth = 0.5) if(col==3): plt.plot(x,y,'m',linewidth=0.1)
def _make_plot(self): plt.close(1) fig_margin = {'top': 25, 'bottom': 35, 'left': 35, 'right':25} fig_layout = {'height': '100%', 'width': '100%' } layout_args = {'fig_margin': fig_margin, 'layout': fig_layout, 'max_aspect_ratio': 1.618} self.voigt_fig = plt.figure(1, title='Voigt profile', **layout_args) self.voigt_plot = plt.plot(self.freq, self.h, scales={'y': LogScale()}) plt.xlabel("Δν / ΔνD") plt.close(2) self.abs_fig = plt.figure(2, title='(αᶜ + αˡ) / α₅₀₀', **layout_args) self.abs_plot = plt.plot(self.freq, self.xq, scales={'y': LogScale()}) plt.xlabel("Δν / ΔνD") plt.close(3) self.int_fig = plt.figure(3, title='Intensity', **layout_args) self.int_plot = plt.plot(self.freq, self.prof, scales={'y': LogScale()}) plt.xlabel("Δν / ΔνD") plt.close(4) self.source_fig = plt.figure(4, title='Source Function', **layout_args) self.source_plot = plt.plot(np.log10(self.tau500), self.source_function, scales={'y': LogScale()}) plt.xlabel("lg(τ₅₀₀)") self.tau_labels = plt.label(['τᶜ = 1', 'τˡ = 1'], colors=['black'], x=np.array([np.log10(self.tau500_cont), np.log10(self.tau500_line)]), y=np.array([self.source_function_cont, self.source_function_line]), y_offset=-25, align='middle') self.tau_line_plot = plt.plot(np.array([np.log10(self.tau500_line), np.log10(self.tau500_line)]), np.array([self.source_function_line / 1.5, self.source_function_line * 1.5]), colors=['black']) self.tau_cont_plot = plt.plot(np.array([np.log10(self.tau500_cont), np.log10(self.tau500_cont)]), np.array([self.source_function_cont / 1.5, self.source_function_cont * 1.5]), colors=['black'])
# generate some fake data np.random.seed(0) n = 2000 x = np.linspace(0.0, 10.0, n) y = np.cumsum(np.random.randn(n)*10).astype(int) # create a bqplot figure fig_hist = plt.figure(title='Histogram') hist = plt.hist(y, bins=25) # slider slider = v.Slider(thumb_label='always', class_="px-4", v_model=30) widgets.link((slider, 'v_model'), (hist, 'bins')) fig_lines = plt.figure( title='Line Chart') lines = plt.plot(x, y) # even handling selector = plt.brush_int_selector() def update_range(*ignore): if selector.selected is not None and len(selector.selected) == 2: xmin, xmax = selector.selected mask = (x > xmin) & (x < xmax) hist.sample = y[mask] selector.observe(update_range, 'selected') # control for linestyle line_styles = ['dashed', 'solid', 'dotted'] widget_line_styles = v.Select(items=line_styles, label='line style', v_model=line_styles[0])
hist.scales['sample'].max = float(y.max()) display(fig) fig.layout.width = 'auto' fig.layout.height = 'auto' fig.layout.min_height = '300px' # so it shows nicely in the notebook fig.layout.flex = '1' # %% grid_columns=12 grid_rows=6 import numpy as np from bqplot import pyplot as plt import bqplot fig = plt.figure( title='Line Chart') np.random.seed(0) n = 200 p = plt.plot(x, y) fig # %% fig.layout.width = 'auto' fig.layout.height = 'auto' fig.layout.min_height = '300px' # so it shows nicely in the notebook fig.layout.flex = '1' # %% brushintsel = bqplot.interacts.BrushIntervalSelector(scale=p.scales['x']) # %% def update_range(*args): label_selected.value = "Selected range {}".format(brushintsel.selected)
from __future__ import print_function from bqplot import pyplot as plt from bqplot import topo_load from bqplot.interacts import panzoom from numpy import * import pandas as pd random.seed(0) size = 100 y_data = cumsum(random.randn(size) * 100.0) y_data_2 = cumsum(random.randn(size)) y_data_3 = cumsum(random.randn(size) * 100.) plt.figure(1) n = 100 x = linspace(0.0, 10.0, n) plt.plot(x, y_data, axes_options={'y': {'grid_lines': 'dashed'}}) plt.show()
def submit_clicked(b): with output_widget: output_widget.clear_output() print('Computing...') Map.default_style = {'cursor': 'wait'} try: admin1_id = admin1_widget.value admin2_id = admin2_widget.value band1 = first_band.value band2 = second_band.value selected_year = year_widget.value threshold = nd_threshold.value bands = band_combo.value.split('/') apply_fmask = fmask_widget.value palette = nd_color.value use_aoi = aoi_widget.value download = download_widget.value if use_aoi: if Map.user_roi is not None: roi = Map.user_roi layer_name = 'User drawn AOI' geom = roi else: output_widget.clear_output() print('No user AOI could be found.') return else: statefp = ee.Feature(states.filter(ee.Filter.eq('NAME', admin1_id)).first()).get('STATEFP') roi = fc.filter(ee.Filter.And(ee.Filter.eq('NAME', admin2_id), ee.Filter.eq('STATEFP', statefp))) layer_name = admin1_id + '-' + admin2_id geom = roi.geometry() Map.layers = Map.layers[:4] Map.addLayer(ee.Image().paint(geom, 0, 2), {'palette': 'red'}, layer_name) images = geemap.landsat_timeseries(roi=roi, start_year=1984, end_year=2020, start_date='01-01', end_date='12-31', apply_fmask=apply_fmask) nd_images = images.map(lambda img: img.normalizedDifference([band1, band2])) result_images = nd_images.map(lambda img: img.gt(threshold)) selected_image = ee.Image(images.toList(images.size()).get(selected_year - 1984)) selected_result_image = ee.Image(result_images.toList(result_images.size()).get(selected_year - 1984)).selfMask() vis_params = { 'bands': bands, 'min': 0, 'max': 3000 } Map.addLayer(selected_image, vis_params, 'Landsat ' + str(selected_year)) Map.addLayer(selected_result_image, {'palette': palette}, 'Result ' + str(selected_year)) def cal_area(img): pixel_area = img.multiply(ee.Image.pixelArea()).divide(1e4) img_area = pixel_area.reduceRegion(**{ 'geometry': geom, 'reducer': ee.Reducer.sum(), 'scale': 1000, 'maxPixels': 1e12, 'bestEffort': True }) return img.set({'area': img_area}) areas = result_images.map(cal_area) stats = areas.aggregate_array('area').getInfo() x = list(range(1984, 2021)) y = [item.get('nd') for item in stats] fig = plt.figure(1) fig.layout.height = '270px' plt.clear() plt.plot(x, y) plt.title('Temporal trend (1984-2020)') plt.xlabel('Year') plt.ylabel('Area (ha)') output_widget.clear_output() plt.show() if download: out_dir = os.path.join(os.path.expanduser('~'), 'Downloads') out_name = 'chart_' + geemap.random_string() + '.csv' out_csv = os.path.join(out_dir, out_name) if not os.path.exists(out_dir): os.makedirs(out_dir) with open(out_csv, 'w') as f: f.write('year, area (ha)\n') for index, item in enumerate(x): line = '{},{:.2f}\n'.format(item, y[index]) f.write(line) link = geemap.create_download_link( out_csv, title="Click here to download the chart data: ") display(link) except Exception as e: print(e) print('An error occurred during computation.') Map.default_style = {'cursor': 'default'}
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 slab(): """ Displays a widget illustrating line formation in a homogenous slab. Runs only in Jupyter notebook or JupyterLab. Requires bqplot. """ # Don't display some ipywidget warnings warnings.simplefilter(action='ignore', category=FutureWarning) def _compute_slab(i0, source, tau_cont, tau_line): """ Calculates slab line profile. """ NPT = 101 MAX_DX = 5. x = np.arange(NPT) - (NPT - 1.) / 2 x *= MAX_DX / x.max() tau = tau_cont + tau_line * np.exp(-x * x) extinc = np.exp(-tau) intensity = float(i0) * extinc + float(source) * (1. - extinc) return (x, intensity) I0 = 15 S = 65 x, y = _compute_slab(I0, S, 0.5, 0.9) base = np.zeros_like(x) fig = plt.figure(title='Slab line formation') int_plot = plt.plot(x, y, 'b-') source_line = plt.plot(x, base + S, 'k--') i0_line = plt.plot(x, base + I0, 'k:') labels = plt.label(['I₀', 'I', 'S'], x=np.array([int_plot.x[0] + 0.2, int_plot.x[-1] - 0.2, int_plot.x[0] + 0.2]), y=np.array([i0_line.y[0], int_plot.y[0], source_line.y[0]]) + 2, colors=['black']) plt.ylim(0, 100) i0_slider = IntSlider(min=0, max=100, value=I0, description=r'$I_0$') s_slider = IntSlider(min=0, max=100, value=S, description=r'$S$') tau_c_slider = FloatSlider(min=0, max=1., step=0.01, value=0.5, description=r'$\tau_{\mathrm{cont}}$') tau_l_slider = FloatSlider(min=0, max=10., step=0.01, value=0.9, description=r'$\tau_{\mathrm{line}}$') def plot_update(i0=I0, source=S, tau_cont=0.5, tau_line=0.9): _, y = _compute_slab(i0, source, tau_cont, tau_line) int_plot.y = y source_line.y = base + source i0_line.y = base + i0 labels.y = np.array([i0, y[0], source]) + 2 widg = interactive(plot_update, i0=i0_slider, source=s_slider, tau_cont=tau_c_slider, tau_line=tau_l_slider) help_w = HTMLMath("<p><b>Purpose: </b>" "This widget-based procedure is used for " "studying spectral line formation in a " "homogeneous slab.</p>" "<p><b>Inputs:</b></p>" "<ul>" r" <li>$I_0$: The incident intensity.</li>" r" <li>$S$: The source function.</li>" r" <li>$\tau_{\mathrm{cont}}$ : The continuum optical depth.</li>" r" <li>$\tau_{\mathrm{line}}$ : The integrated optical depth in the spectral line.</li>" "</ul>") return HBox([VBox([widg, help_w], layout=Layout(width='33%', top='50px', left='5px')), Box([fig], layout=Layout(width='66%'))], layout=Layout(border='50px'))
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 __init__(self, img): self.colors = ['#ED2445', 'green', '#6EFDFF'] self.ax_options = { 'x': { 'label': 'Intensity', 'orientation': 'horizontal', 'color': 'white', 'grid_lines': 'none', #'grid_color': 'black', }, 'y': { 'label': 'Frequency', 'orientation': 'vertical', 'color': 'white', 'grid_lines': 'none', #'grid_color': 'black', } } self.fig = plt.figure( 0, title='Histogram', title_style={'font-size': '16px'}, legend_location='top-right', background_style={'fill': '#FF000000'}, axes_options=self.ax_options, animation_duration=1000, padding_y=0, layout={ 'height': '400px', 'width': '550px' }, fig_margin={ 'top': 30, 'bottom': 40, 'left': 60, 'right': 30 }, ) if len(img.shape) == 3: for i, color in enumerate(self.colors): histr = cv2.calcHist([img], [i], None, [256], [0, 256]) plt.plot( x=np.arange(0, 257, 1), y=histr.flatten(), colors=[color], stroke_width=1.2, axes_options=self.ax_options, fill='bottom', fill_opacities=[0.2], ) elif len(img.shape) == 2: hist = cv2.calcHist([img], None, [256], [0, 256]) plt.plot(x=np.arange(0, 257, 1), y=hist, color='white', stroke_width=1.2, axes_options=self.ax_options, fill='bottom', fill_opacities=[0.2]) self.wid = v.Card( children=[self.fig], #justify='end', style_='\ display: block; \ position: absolute; \ background-color: #000000BF; \ ')
def add_line(self, *args, **kwargs): return plt.plot(*args, figure=self.fig, **kwargs)
def plot_error(): """Plot error of our filter along time.""" axes_options = {'x': {'label': 't'}, 'y': {'label': 'error'}} fig = plt.figure() plt.plot(np.arange(1000) * 0.1, error, axes_options=axes_options) display(fig)
df = response[0].df() # Drop N/A values and reset the dataframe index df = df.dropna().reset_index() # Pivot the DataFrame on the columns to plot df = df.pivot("DATE", "ID", "#LAST_PRICE") # Check the DataFrame columns df.head() #************bqviz Line Plot Example************ # Pass the example DataFrame to the bqviz LinePlot object and apply Bloomberg styles bqv_plot = bqv.LinePlot(df).set_style() # Display the plot bqv_plot.show() #*************bqplot Line Plot Example************ # Define series objects for the price lines aapl_price = df['AAPL US Equity'] ibm_price = df['IBM US Equity'] # Define a series object for the date index plot_dates = df.index # Create the figure canvas plt.figure() # Define the plot using the price date and price series objects aapl_line = plt.plot(plot_dates, [aapl_price, ibm_price]) # Display the plot plt.show()
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
def Interactive_policy_manual(N, I_hist, e_hist, s_0, s_min, s_max, u_0, u_1, u_mean, u_max, env_min, d_hist, rc): #Function to update the release policy when changing the parameters with the sliders def update_operating_policy_1(s_ref_1,s_ref_2,u_ref): if s_ref_1 > s_ref_2: s_ref_1 = s_ref_2 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) TSD = (np.sum((np.maximum(d_hist-u,[0]*N))**2)).astype('int') fig_1b.title = 'Supply vs Demand - TSD = '+str(TSD)+' ML^2' MSV = (np.sum((np.maximum(rc-s,[0]*(N+1))))).astype('int') fig_1c.title = 'Reservoir storage volume - MSV = '+str(MSV)+' ML' return u_frac, Qenv, Qspill, u, I_reg, s # Function to update the figures when changing the parameters with the sliders def update_figure_1(change): policy_function.y = update_operating_policy_1(s_ref_1.value,s_ref_2.value,u_ref.value)[0] releases.y = update_operating_policy_1(s_ref_1.value,s_ref_2.value,u_ref.value)[3] storage.y = update_operating_policy_1(s_ref_1.value,s_ref_2.value,u_ref.value)[5] # Definition of the sliders u_ref = widgets.FloatSlider(min=0.5, max=u_1, value=1, step=0.05, description = 'u_ref: ', continuous_update = False) u_ref.observe(update_figure_1,names = 'value') s_ref_1 = widgets.FloatSlider(min=0, max=1, value=0.25, step=0.05, description = 's_ref_1: ', continuous_update=False) s_ref_1.observe(update_figure_1,names = 'value') s_ref_2 = widgets.FloatSlider(min=0, max=1, value=0.75, step=0.05, description = 's_ref_2: ', continuous_update=False) s_ref_2.observe(update_figure_1,names = 'value') # Initial simulation applying the default slider values of the parameters x0 = [0, u_0] x1 = [s_ref_1.value, u_ref.value] x2 = [s_ref_2.value, u_ref.value] 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) ### Figures ### # Fig 1a: Policy function s_frac = np.arange(0,1.01,0.01) x_sc_1a = LinearScale(min=0,max=1); y_sc_1a = LinearScale(min=0,max=u_1); x_ax_1a = Axis(label='Storage fraction', scale=x_sc_1a); y_ax_1a = Axis(label='Release fraction', scale=y_sc_1a, orientation='vertical') policy_function = Lines(x = s_frac, y = u_frac, colors = ['blue'], scales = {'x': x_sc_1a, 'y': y_sc_1a}) fig_1a = plt.Figure(marks = [policy_function], title = 'Policy function', axes=[x_ax_1a, y_ax_1a], layout={'width': '400px', 'height': '375px'}, animation_duration=1000, scales={'x': x_sc_1a, 'y': y_sc_1a}) policy_function.observe(update_figure_1, ['x', 'y']) # Fig 1b: Releases vs Demand x_sc_1b = LinearScale(min=0,max=N); y_sc_1b = LinearScale(min=0,max=u_max); x_ax_1b = Axis(label='week', scale=x_sc_1b); y_ax_1b = Axis(label='ML/week', scale=y_sc_1b, orientation='vertical') demand = Bars(x = np.arange(1,N+1), y = d_hist, colors = ['gray'], scales = {'x': x_sc_1b, 'y': y_sc_1b}) releases = Bars(x = np.arange(1,N+1), y = u, colors = ['green'], scales = {'x': x_sc_1b, 'y': y_sc_1b}) TSD = (np.sum((np.maximum(d_hist-u,[0]*N))**2)).astype('int') fig_1b = plt.Figure(marks = [demand, releases], title = 'Supply vs Demand - TSD = '+str(TSD)+' ML^2', axes=[x_ax_1b, y_ax_1b], layout={'width': '950px', 'height': '250px'}, animation_duration=1000, scales={'x': x_sc_1b, 'y': y_sc_1b}) releases.observe(update_figure_1, ['x', 'y']) # Fig 1c: Storage x_sc_1c = LinearScale(); y_sc_1c = LinearScale(min=0,max=200); x_ax_1c = Axis(label='week', scale=x_sc_1c); y_ax_1c = Axis(label='ML', scale=y_sc_1c, orientation='vertical') storage = Lines(x = np.arange(0,N+1), y = s , colors = ['blue'], scales = {'x': x_sc_1c, 'y': y_sc_1c}, 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_1c, 'y': y_sc_1c}) 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_1c, 'y': y_sc_1c}, 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_1c = 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_1c, y_ax_1c], layout={'width': '950px', 'height': '250px'}, animation_duration=1000, scales={'x': x_sc_1c, 'y': y_sc_1c}) storage.observe(update_figure_1, ['x', 'y']) return fig_1a,fig_1b,fig_1c, u_ref,s_ref_1,s_ref_2
def vue_do_aper_phot(self, *args, **kwargs): if self._selected_data is None or self._selected_subset is None: self.result_available = False self.results = [] self.plot_available = False self.radial_plot = '' self.hub.broadcast(SnackbarMessage( "No data for aperture photometry", color='error', sender=self)) return data = self._selected_data reg = self._selected_subset try: comp = data.get_component(data.main_components[0]) try: bg = float(self.background_value) except ValueError: # Clearer error message raise ValueError('Missing or invalid background value') comp_no_bg = comp.data - bg # TODO: Use photutils when it supports astropy regions. if not isinstance(reg, RectanglePixelRegion): aper_mask = reg.to_mask(mode='exact') else: # TODO: https://github.com/astropy/regions/issues/404 (moot if we use photutils?) aper_mask = reg.to_mask(mode='subpixels', subpixels=32) npix = np.sum(aper_mask) * u.pix img = aper_mask.get_values(comp_no_bg, mask=None) aper_mask_stat = reg.to_mask(mode='center') comp_no_bg_cutout = aper_mask_stat.cutout(comp_no_bg) img_stat = aper_mask_stat.get_values(comp_no_bg, mask=None) include_pixarea_fac = False include_counts_fac = False include_flux_scale = False if comp.units: img_unit = u.Unit(comp.units) img = img * img_unit img_stat = img_stat * img_unit bg = bg * img_unit comp_no_bg_cutout = comp_no_bg_cutout * img_unit if u.sr in img_unit.bases: # TODO: Better way to detect surface brightness unit? try: pixarea = float(self.pixel_area) except ValueError: # Clearer error message raise ValueError('Missing or invalid pixel area') if not np.allclose(pixarea, 0): include_pixarea_fac = True if img_unit != u.count: try: ctfac = float(self.counts_factor) except ValueError: # Clearer error message raise ValueError('Missing or invalid counts conversion factor') if not np.allclose(ctfac, 0): include_counts_fac = True try: flux_scale = float(self.flux_scaling) except ValueError: # Clearer error message raise ValueError('Missing or invalid flux scaling') if not np.allclose(flux_scale, 0): include_flux_scale = True rawsum = np.nansum(img) d = {'id': 1, 'xcenter': reg.center.x * u.pix, 'ycenter': reg.center.y * u.pix} if data.coords is not None: d['sky_center'] = data.coords.pixel_to_world(reg.center.x, reg.center.y) else: d['sky_center'] = None d.update({'background': bg, 'npix': npix}) if include_pixarea_fac: pixarea = pixarea * (u.arcsec * u.arcsec / u.pix) pixarea_fac = npix * pixarea.to(u.sr / u.pix) d.update({'aperture_sum': rawsum * pixarea_fac, 'pixarea_tot': pixarea_fac}) else: d.update({'aperture_sum': rawsum, 'pixarea_tot': None}) if include_counts_fac: ctfac = ctfac * (rawsum.unit / u.count) sum_ct = rawsum / ctfac d.update({'aperture_sum_counts': sum_ct, 'aperture_sum_counts_err': np.sqrt(sum_ct.value) * sum_ct.unit, 'counts_fac': ctfac}) else: d.update({'aperture_sum_counts': None, 'aperture_sum_counts_err': None, 'counts_fac': None}) if include_flux_scale: flux_scale = flux_scale * rawsum.unit d.update({'aperture_sum_mag': -2.5 * np.log10(rawsum / flux_scale) * u.mag, 'flux_scaling': flux_scale}) else: d.update({'aperture_sum_mag': None, 'flux_scaling': None}) # Extra stats beyond photutils. d.update({'mean': np.nanmean(img_stat), 'stddev': np.nanstd(img_stat), 'median': np.nanmedian(img_stat), 'min': np.nanmin(img_stat), 'max': np.nanmax(img_stat), 'data_label': data.label, 'subset_label': reg.meta.get('label', ''), 'timestamp': Time(datetime.utcnow())}) # Attach to app for Python extraction. if (not hasattr(self.app, '_aper_phot_results') or not isinstance(self.app._aper_phot_results, QTable)): self.app._aper_phot_results = _qtable_from_dict(d) else: try: d['id'] = self.app._aper_phot_results['id'].max() + 1 self.app._aper_phot_results.add_row(d.values()) except Exception: # Discard incompatible QTable d['id'] = 1 self.app._aper_phot_results = _qtable_from_dict(d) # Radial profile reg_bb = reg.bounding_box reg_ogrid = np.ogrid[reg_bb.iymin:reg_bb.iymax, reg_bb.ixmin:reg_bb.ixmax] radial_dx = reg_ogrid[1] - reg.center.x radial_dy = reg_ogrid[0] - reg.center.y radial_r = np.hypot(radial_dx, radial_dy).ravel() # pix radial_img = comp_no_bg_cutout.ravel() if comp.units: y_data = radial_img.value y_label = radial_img.unit.to_string() else: y_data = radial_img y_label = 'Value' bqplt.clear() # NOTE: default margin in bqplot is 60 in all directions fig = bqplt.figure(1, title='Radial profile from Subset center', fig_margin={'top': 60, 'bottom': 60, 'left': 40, 'right': 10}, title_style={'font-size': '12px'}) # TODO: Jenn wants title at bottom. # noqa bqplt.plot(radial_r, y_data, 'go', figure=fig, default_size=1) bqplt.xlabel(label='pix', mark=fig.marks[-1], figure=fig) bqplt.ylabel(label=y_label, mark=fig.marks[-1], figure=fig) except Exception as e: # pragma: no cover self.result_available = False self.results = [] self.plot_available = False self.radial_plot = '' self.hub.broadcast(SnackbarMessage( f"Aperture photometry failed: {repr(e)}", color='error', sender=self)) else: # Parse results for GUI. tmp = [] for key, x in d.items(): if key in ('id', 'data_label', 'subset_label', 'background', 'pixarea_tot', 'counts_fac', 'aperture_sum_counts_err', 'flux_scaling', 'timestamp'): continue if (isinstance(x, (int, float, u.Quantity)) and key not in ('xcenter', 'ycenter', 'sky_center', 'npix', 'aperture_sum_counts')): x = f'{x:.4e}' tmp.append({'function': key, 'result': x}) elif key == 'sky_center' and x is not None: tmp.append({'function': 'RA center', 'result': f'{x.ra.deg:.4f} deg'}) tmp.append({'function': 'Dec center', 'result': f'{x.dec.deg:.4f} deg'}) elif key in ('xcenter', 'ycenter', 'npix'): x = f'{x:.1f}' tmp.append({'function': key, 'result': x}) elif key == 'aperture_sum_counts' and x is not None: x = f'{x:.4e} ({d["aperture_sum_counts_err"]:.4e})' tmp.append({'function': key, 'result': x}) elif not isinstance(x, str): x = str(x) tmp.append({'function': key, 'result': x}) self.results = tmp self.result_available = True self.radial_plot = fig self.bqplot_figs_resize = [fig] self.plot_available = True
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 build_widgets(self): # loss curve self.loss_fig = plt.figure(title='Loss Curve') axes_options = { 'y': { 'label': 'Loss', 'tick_format': '.1f', 'label_offset': '-1em', 'label_location': 'end' }, 'x': { 'label': 'Epochs' } } self.loss_plot = plt.plot([], [], colors=['orangered', 'limegreen'], axes_options=axes_options, display_legend=True, labels=['Train', 'Test']) # accuracy curve self.accuracy_fig = plt.figure(title='Accuracy Curve') plt.scales(scales={'y': LinearScale(min=0, max=1)}) axes_options = { 'y': { 'label': 'R Square', 'tick_format': '.1%', 'label_offset': '-1em', 'label_location': 'end' }, 'x': { 'label': 'Epochs' } } self.accuracy_plot = plt.plot([], [], colors=['orangered', 'limegreen'], axes_options=axes_options, display_legend=True, labels=['Train', 'Test']) self.progress_bar = IntProgress(description='Training Progress', min=0, max=(self.epochs - 1), style={'description_width': 'initial'}) # first tab components: loss/accuracy curves self.plots_layout = VBox( [self.progress_bar, HBox([self.loss_fig, self.accuracy_fig])], layout=self.tab_layout) axes_options = { 'x': { 'grid_lines': 'none', 'tick_format': '.1f', 'num_ticks': 5 }, 'y': { 'grid_lines': 'none', 'num_ticks': 6 } } # weights hist self.weights_fig = plt.figure(title='Weights') self.weights_hist = plt.bin(sample=np.array([]), colors=['salmon'], axes_options=axes_options) # biases hist self.biases_fig = plt.figure(title='Biases') self.biases_hist = plt.bin(sample=np.array([]), colors=['salmon'], axes_options=axes_options) # activations hist self.activations_fig = plt.figure(title='Activations') self.activations_hist = plt.bin(sample=np.array([]), colors=['salmon'], axes_options=axes_options) for fig in [self.weights_fig, self.biases_fig, self.activations_fig]: fig.layout.width = '400px' fig.layout.height = '350px' self.layers_dd = Dropdown(description='Layers') self.epoch_slider = IntSlider(description='Epoch', min=1, step=1) # second tab components: distributions of weights/biases/activations self.distributions_layout = VBox([ self.layers_dd, self.epoch_slider, HBox([self.weights_fig, self.biases_fig, self.activations_fig]) ], layout=self.tab_layout) self.tab = Tab([self.plots_layout, self.distributions_layout], _titles={ 0: 'Loss/Accuracy Plots', 1: 'Distributions' }) self.widgets_layout = self.tab
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_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