def integrated_charge(limit_a, limit_b, y, iteration): # compute 1D histogram energy_hist, bin_edges, nbins = particle_energy_histogram( tseries=time_series, it=iteration, cutoff=np.inf, # no cutoff energy_max=e_max, ) histogram = hv.Histogram((bin_edges, energy_hist), kdims=energy, vdims=count) curve = hv.Curve(histogram) e_min = histogram.edges[0] limit_a = e_min if limit_a is None else np.clip(limit_a, e_min, e_max) limit_b = e_max if limit_b is None else np.clip(limit_b, e_min, e_max) area = hv.Area((curve.dimension_values('energy'), curve.dimension_values('frequency')))[limit_a:limit_b] charge = np.sum( np.diff(histogram[limit_a:limit_b].edges) * histogram[limit_a:limit_b].values) return curve * area * hv.VLine(limit_a) * hv.VLine(limit_b) * hv.Text( limit_b - 2., 5, 'Q = %.0f pC' % charge)
def get_crosshair(self): self.xy_v = hv.VLine(self.x_viewer._widget.value, kdims=['x', 'y'], label='xyV', group='orthoview') self.xy_h = hv.HLine(self.y_viewer._widget.value, kdims=['x', 'y'], label='xyH', group='orthoview') self.zy_v = hv.VLine(self.z_viewer._widget.value, kdims=['za', 'y'], label='zyV', group='orthoview') self.zy_h = hv.HLine(self.y_viewer._widget.value, kdims=['za', 'y'], label='zyH', group='orthoview') self.xz_v = hv.VLine(self.x_viewer._widget.value, kdims=['x', 'zb'], label='xzV', group='orthoview') self.xz_h = hv.HLine(self.z_viewer._widget.value, kdims=['x', 'zb'], label='xzH', group='orthoview') return [(self.xy_v, self.xy_h), (self.zy_v, self.zy_h), (self.xz_v, self.xz_h)]
def plot_distribution(self): """ Visualizes the distribution of cumulative returns simulated using calc_cumulative_return method. """ # Check to make sure that simulation has run previously. if not isinstance(self.simulated_return, pd.DataFrame): self.calc_cumulative_return() # Use the `plot` function to create a probability distribution histogram of simulated ending prices # with markings for a 95% confidence interval plot_title = f"Distribution of {self.portfolio_data.columns.get_level_values(0).unique().tolist()[0:3]} Final Cumuluative Returns Across All {self.nSim} Simulations" plt1 = self.simulated_return.iloc[-1, :].hvplot( kind='hist', bins=10, title=plot_title, width=500, xlabel='probability').opts(fontsize={ 'title': "75%", 'legend': '50%' }, axiswise=True) vline1 = hv.VLine(self.confidence_interval.iloc[0]).opts(color='red', axiswise=True) vline2 = hv.VLine(self.confidence_interval.iloc[1]).opts(color='red', axiswise=True) plt = (plt1 * vline1 * vline2).opts(axiswise=True) return plt
def integral(limit_a, limit_b, y, time): limit_a = -3 if limit_a is None else np.clip(limit_a, -3, 3) limit_b = 3 if limit_b is None else np.clip(limit_b, -3, 3) curve = hv.Curve((xs, function(xs, time))) area = hv.Area((xs, function(xs, time)))[limit_a:limit_b] summed = area.dimension_values('y').sum() * 0.015 # Numeric approximation return (area * curve * hv.VLine(limit_a) * hv.VLine(limit_b) * hv.Text(limit_b - 0.8, 2.0, '%.2f' % summed))
def _season_vlines(): season_vlines = hv.Overlay( [hv.VLine(pd.to_datetime(season_start).dayofyear) .options(line_width=1.5, alpha=0.9, color=color, line_dash='dotted') for season_start, color in SEASON_STARTS.items()] ) return season_vlines
def plot_flatband_v(x, y, ana_type, **kwargs): ''' **kwargs for customizing the plot, ana_type must ether be "fit" or "derivative" ''' x, y = list(x), list(y) if ana_type == "fit": voltage, middle_line, right_line = fit_analysis(x, y) elif ana_type == "derivative": voltage = derivative_analysis(x, y) else: log.error("ana_type must either be 'derivative' or 'fit'") exit(1) curve = hv.Curve(zip(x, y), kdims="voltage_hvsrc", vdims="capactiance") text_str = "Flatband Voltage: " + str(voltage) + "\nAnalysis Type: " + ana_type text = hv.Text(max(x) * (3 / 4), max(y) * (3 / 4), text_str, fontsize=20) line = hv.VLine(voltage).opts(color="black", line_width=1.0) curve = curve * text * line if ana_type == "fit": mid = hv.Curve([*middle_line]).opts(color="red", line_width=1.5) right = hv.Curve([*right_line]).opts(color="blue", line_width=1.0) curve = curve * text * line * mid * right curve.opts(ylim=(min(y) - 3 * min(y) / 20, max(y) + max(y) / 10), **kwargs) return curve
def cross_hair_info(x, y): text = hv.Text(x + 0.05, y, "%.3f %.3f %.3f" % (x, y, img[x, y]), halign="left", valign="bottom") return hv.HLine(y) * hv.VLine(x) * text
def plot_flatband(self, file, ana_type, interpol): '''plot function for both "derivative" and "fit" analysis''' x, y = self.data[file][ana_type]["dataframe"]['x'], self.data[file][ ana_type]["dataframe"]['y'] curve = hv.Curve(zip(x, y), kdims=self.measurements[1], vdims=self.measurements[3]) text_str = "Flatband Voltage: " + str( self.data[file][ana_type]["flatband"] ) + "\nAnalysis Type: " + ana_type + "\nInterpolated: " + str(interpol) text = hv.Text(x.max() * (3 / 4), y.max() * (3 / 4), text_str, fontsize=20) line = hv.VLine(self.data[file][ana_type]["flatband"]).opts( color="black", line_width=1.0) curve = curve * text * line if ana_type == "fit": curve = curve * text * line * self.data[file]["fit"]["lines"][ 0] * self.data[file]["fit"]["lines"][1] curve.opts(**self.config["MOS_CV"].get("General", {}), ylim=(y.min() - 3 * y.min() / 20, y.max() + y.max() / 10)) if self.PlotDict["All"] is None: self.PlotDict["All"] = curve else: self.PlotDict["All"] = self.PlotDict["All"] + curve
def __post_init__(self): """ :return: """ data = self.spectral_cube.data self.ds = hv.Dataset((np.arange(data.shape[2]), np.arange( data.shape[1]), np.arange(data.shape[0]), data), [self.spectral_axis_name, 'x', 'y'], 'Cube') # maybe PolyEdit as well # polys = hv.Polygons([hv.Box(int(self.image_width / 2), int(self.image_height / 2), int(self.image_height / 2))]) # self.box_stream = streams.PolyEdit(source=polys) polys = hv.Polygons([]) self.box_stream = streams.BoxEdit(source=polys) hlines = hv.HoloMap({i: hv.VLine(i) for i in range(data.shape[2])}, 'wavelengths') dmap = hv.DynamicMap(self.roi_curves, streams=[self.box_stream]) im = self.ds.to(hv.Image, ['x', 'y'], dynamic=True) self.layout = (im * polys + dmap * hlines).opts( opts.Image(cmap=self.color_map, width=self.image_width, height=self.image_height), opts.Curve(width=650, height=450, framewise=True), opts.Polygons(fill_alpha=0.2, line_color='white'), opts.VLine(color='black'))
def interpol(self, df, xaxis, yaxis): xnew, ynew = self.interpolated_axis(df, xaxis, yaxis) capa_interp_plot = self.add_single_plots(xnew, ynew, "Capacity") # Build derivatives of the interpolated data firstdev_interp = self.build_first_derivative(xnew, ynew) derivative_interpolation_plot = self.add_single_plots( xnew, firstdev_interp, "derivative" ) seconddev_interp = self.build_second_derivative(xnew, ynew) secondderivative_interp_plot = self.add_single_plots( xnew, seconddev_interp, "derivative2" ) # Find the flatband-voltage through the maximum value of the first derivative item_max = firstdev_interp.argmax() voltage_value_of_max_firstder = xnew[item_max] max_firstder_plot = hv.VLine(voltage_value_of_max_firstder).opts(line_width=1.0) fbvoltage_firstderivative.append(voltage_value_of_max_firstder) return ( capa_interp_plot, derivative_interpolation_plot, secondderivative_interp_plot, max_firstder_plot, voltage_value_of_max_firstder, )
def update_vlines(self, x1: float, x2: float, stroke_count: int, data: Optional[np.ndarray] = None): if None in [x1, x2]: x1, x2 = self.vlines_positions xs, ys, _ = data ids1 = np.argmin((xs - x1)**2) ids2 = np.argmin((xs - x2)**2) ones = np.ones_like(xs[ids1]) points1 = hv.Points(data=(ones * x1, ys[ids1])).opts(color=orange1) points2 = hv.Points(data=(ones * x2, ys[ids2])).opts(color=orange2) vline1 = hv.VLine(x=x1).opts(color=orange1) vline2 = hv.VLine(x=x2).opts(color=orange2) return vline1 * vline2 * points1 * points2
def _holoviews_get_metrics(self, color_map: dict = {}, label_map: dict = {}): """ Creates holoviews plot for every not node specific metric over time Returns: holoviews.HoloMap: holoviews object representing plot """ metric_names = [ name for name in next(iter( self._calculated_networks.values())).graph.keys() ] curve_dict = {} for metric_name in metric_names: name = label_map.get(metric_name, metric_name) curve_dict[name] = hv.Curve( (list(self._calculated_networks.keys()), list( map(lambda x: x.graph[metric_name], self._calculated_networks.values()))), kdims='Time', vdims='Value') if metric_name in color_map: curve_dict[name].opts(color=color_map[metric_name]) ndoverlay = hv.NdOverlay(curve_dict) distribution = hv.HoloMap({i: (ndoverlay * hv.VLine(i)).relabel(group='Metrics') for i in self._calculated_networks.keys()}, kdims='Time')\ .opts(width=400, height=400, padding=0.1) return distribution
def marker(x, y): x_dim = {image.kdims[0].label: x} y_dim = {image.kdims[1].label: y} crosssection1 = image.sample(**x_dim).opts(norm=dict(framewise=True)) crosssection1y = image.sample(**y_dim).opts(norm=dict(framewise=True)) return hv.Layout(image * hv.VLine(x) * hv.HLine(y) + crosssection1 + crosssection1y).cols(2).opts(norm=dict(axiwise=True))
def cultural_build_tribute_plot(self): # Limits the target raise bounds when ploting the charts self.bounds_target_raise() df_hatch_params_to_plot = self.output_scenarios() # Drop NaN rows df_hatch_params_to_plot = df_hatch_params_to_plot.dropna() with pd.option_context('mode.chained_assignment', None): df_hatch_params_to_plot['Cultural Build Tribute'] = df_hatch_params_to_plot['Cultural Build Tribute'].mul(100) cultural_build_tribute_plot = df_hatch_params_to_plot.hvplot.area(title='Cultural Build Tribute (%)', x='Total XDAI Raised', y='Cultural Build Tribute', xformatter='%.0f', yformatter='%.1f', hover=True, ylim=(0, 100), xlim=self.config_bounds['min_max_raise']['xlim'] ).opts(axiswise=True) try: #cultural_build_tribute_target = df_hatch_params_to_plot.loc[df_hatch_params_to_plot['Total XDAI Raised'] == self.target_raise]['Cultural Build Tribute'].values[0] cultural_build_tribute_target = df_hatch_params_to_plot[df_hatch_params_to_plot['Total XDAI Raised'] >= self.target_raise].iloc[0]['Cultural Build Tribute'] except: cultural_build_tribute_target = 0 with param.edit_constant(self): self.target_cultural_build_tribute = round(cultural_build_tribute_target, 2) return cultural_build_tribute_plot * hv.VLine(self.target_raise).opts(color='#E31212') * hv.HLine(cultural_build_tribute_target).opts(color='#E31212')
def load_indices(Index): #scatter = hv.Scatter(multi_df[Index], kdims = ['JDK_RS_ratio', 'JDK_RS_momentum']) scatter = hv.Scatter(multi_df[Index], kdims = ['JDK_RS_momentum']) ##Colors explicit_mapping = {'Leading': 'green', 'Lagging': 'yellow', 'Weakening': 'red', 'Improving': 'blue'} ##Plot Joining all together scatter = scatter.opts(opts.Scatter(tools=['hover'], height = 500, width=500, size = 10, xlim = x_range, ylim = y_range, color = 'Quadrant', cmap=explicit_mapping, )) ##Line connecting the dots #curve = hv.Curve(multi_df[Index], kdims = ['JDK_RS_ratio', 'JDK_RS_momentum']) curve = hv.Curve(multi_df[Index], kdims = [ 'JDK_RS_momentum']) curve = curve.opts(opts.Curve(color = 'black', line_width = 1)) ##Vertical and Horizontal Lines vline = hv.VLine(100).opts(color = 'black', line_width = 1) hline = hv.HLine(100).opts(color = 'black', line_width = 1) #All Together full_scatter = scatter * vline * hline * curve full_scatter = full_scatter.opts(legend_cols= True) return full_scatter
def plot_batch_y(ds, i): x_past, y_past, x_future, y_future = ds.get_rows(i) y = pd.concat([y_past, y_future]) p = hv.Scatter(y) now = y_past.index[-1] p *= hv.VLine(now).relabel('now').opts(color='red') return p
def impact_hours_rewards(self): expected_raise = self.total_impact_hours * self.raise_horizon if expected_raise > self.maximum_raise: expected_raise = self.maximum_raise # self.param['maximum_raise'].bounds = (expected_raise, expected_raise * 10) # self.param['maximum_raise'].step = expected_raise / 10 # if self.target_raise > self.maximum_raise: # self.target_raise = self.maximum_raise # self.param['target_raise'].bounds = (self.minimum_raise, self.maximum_raise) # self.param['target_raise'].step = self.maximum_raise / 100 x = np.linspace(self.minimum_raise, self.maximum_raise) R = self.maximum_impact_hour_rate m = self.raise_horizon H = self.total_impact_hours y = [R * (x / (x + m * H)) for x in x] df = pd.DataFrame([x, y]).T df.columns = ['Total XDAI Raised', 'Impact Hour Rate'] try: expected_impact_hour_rate = df[ df['Total XDAI Raised'] > expected_raise].iloc[0]['Impact Hour Rate'] except: expected_impact_hour_rate = df['Impact Hour Rate'].max() try: target_impact_hour_rate = df[ df['Total XDAI Raised'] > self.target_raise].iloc[0]['Impact Hour Rate'] except: target_impact_hour_rate = df['Impact Hour Rate'].max() impact_hours_plot = df.hvplot.area(title='Expected and Target Raise', x='Total XDAI Raised', xformatter='%.0f', hover=True) return impact_hours_plot * hv.VLine(expected_raise) * hv.HLine( expected_impact_hour_rate) * hv.VLine( self.target_raise) * hv.HLine(target_impact_hour_rate)
def redeemable(self): df_hatch_params = self.output_scenarios() # Drop NaN rows df_hatch_params_to_plot = df_hatch_params.dropna() df_hatch_params_to_plot['Redeemable'] = df_hatch_params_to_plot['Redeemable'] * 100 redeemable_plot = df_hatch_params_to_plot.hvplot.area(title='Redeemable (%)', x='Total XDAI Raised', y='Redeemable', xformatter='%.0f', yformatter='%.1f', hover=True, ylim=(0, 100), xlim=(0,1000)).opts(axiswise=True) redeemable_target = 100 * df_hatch_params[df_hatch_params_to_plot['Total XDAI Raised'] ==self.target_raise].iloc[0]['Redeemable'] return redeemable_plot * hv.VLine(self.target_raise).opts(color='#E31212') * hv.HLine(redeemable_target).opts(color='#E31212')
def curves_data_US(year=1971): oil_z2 = oil.loc[oil.country == 'United States', 'NY.GDP.PETR.RT.ZS'].iloc[::-1] oil_z2 = oil_z2 - oil_z2.iloc[0] money_z2 = money.loc[money.country == 'United States', 'FM.LBL.BMNY.GD.ZS'].iloc[::-1] money_z2 = money_z2 - money_z2.iloc[0] z_2 = oil_z2.iloc[year - 1971] - 10 z_1 = -money_z2.iloc[year - 1971] - 10 as_eq = pd.DataFrame([P(), AS(P=P(), Z_2=0)], index=['Price-Level', 'Real Output']).T ad_eq = pd.DataFrame([P(), AD(P=P(), Z_1=0)], index=['Price-Level', 'Real Output']).T as_shock = pd.DataFrame([P(), AS(P=P(), Z_2=z_2 + 10)], index=['Price-Level', 'Real Output']).T ad_shock = pd.DataFrame([P(), AD(P=P(), Z_1=z_1 + 10)], index=['Price-Level', 'Real Output']).T result = findIntersection(lambda x: AS(P=x, Z_2=z_2 + 10), lambda x: AD(P=x, Z_1=-z_1 - 10), 0.0) r = result + 1e-4 if result == 0 else result plot = hv.Curve(as_eq, vdims='Price-Level',kdims='Real Output').options(alpha=0.2, color='#1BB3F5') *\ hv.Curve(ad_eq, vdims='Price-Level',kdims='Real Output').options(alpha=0.2, color='orange') *\ hv.Curve(as_shock, vdims='Price-Level',kdims='Real Output', label='AS').options(alpha=1, color='#1BB3F5') *\ hv.Curve(ad_shock, vdims='Price-Level',kdims='Real Output', label='AD').options(alpha=1, color='orange') *\ hv.VLine(-result[0]).options(color='black', alpha=0.2, line_width=1) *\ hv.HLine(AD(P=-r[0], Z_1=z_1+10)).options(color='black', alpha=0.2, line_width=1) gdp_mean = gdp.loc[gdp.country == 'United States', 'NY.GDP.PCAP.KD'].iloc[0] gdp_iqr = iqr(gdp.loc[gdp.country == 'United States', 'NY.GDP.PCAP.KD']) gdp_plot_US = gdp.loc[gdp.country=='United States',:].iloc[::-1,:].hvplot.line(x='year', y='NY.GDP.PCAP.KD', title='GDP per capita growth (constant 2010 US$)') *\ hv.VLine(year).options(color='black') * pd.DataFrame([[(AD(P=-r[0], Z_1=-z_1-10))*gdp_iqr*0.3+gdp_mean*4, year]], columns=['Real Output', 'year']).hvplot.scatter(y='Real Output', x='year',color='red') return plot.options(xticks=[0], yticks=[0], title_format="US Short-Run AS-AD Model") + gdp_plot_US
def _timetable(self, x, y): if self.solutions.empty: return (hv.Points((0, 0)).opts(alpha=0) * hv.Text( 0, 0, 'No Journeys Found').opts(color='firebrick')).opts( xlim=(-1, 1), xaxis=None, yaxis=None, show_frame=False, toolbar=None) stop_time = self.stop_time * 10**3 time_delta = stop_time - self.solutions['start_time'].min() boxes_opts = { 'color': 'color', 'line_width': 0, 'tools': [ HoverTool( tooltips=[('From', '@station_name'), ('To', '@station_name_stop'), ('Departure Time', '@departure'), ('Arrival Time', '@arrival'), ('Travel Type', '@transport_type'), ( 'Line', '@line_text'), ('Trip', '@trip_id')]) ], } opts = { 'height': int(self.solutions['path'].max() + 3) * 50, 'width': 600, 'ylim': (-1, self.solutions['path'].max() + 2), 'xlim': (self.solutions['start_time'].min() - time_delta * 0.1, stop_time + time_delta * 0.1), 'hooks': [datetime_ticks], 'yaxis': None, 'show_frame': False, 'xlabel': '', 'toolbar': None, 'active_tools': [] } boxes = hv.Rectangles( self.line_aggregate, ['start_time', 'y_min', 'stop_time', 'y_max'], [ 'color', 'station_name', 'station_name_stop', 'departure', 'arrival', 'transport_type', 'trip_id', 'line_text' ]).opts(**boxes_opts) text = self._timetable_text() stop_line = hv.VLine(stop_time).opts(line_width=1, line_color='red') return (boxes * text * stop_line).opts(**opts)
def plot_batch_x(ds, i): """Plot input features""" x_past, y_past, x_future, y_future = ds.get_rows(i) x = pd.concat([x_past, x_future]) p = hv.NdOverlay({ col: hv.Curve(x[col]) for col in x.columns }, kdims='column') now = y_past.index[-1] p *= hv.VLine(now).relabel('now').opts(color='red') return p
def plot(*args): xs = [ table.value.index[x] for xs, table in zip(args, tables) for x in xs ] return hv.Overlay([ hv.VLine(x).opts( backend='bokeh', line_dash='dashed', ) for x in xs ])
def find_voltage(df, x, ana_type): '''returns voltage and: for Ana 1 fit line, for Ana 2/3 line to mark voltage''' if ana_type == "Ana 1": df = df[df.dy == df.dy.max()] inflection_x, inflection_y, slope = df['x'].iloc[0], df['y'].iloc[0], df['dy'].iloc[0] d = inflection_y - slope * inflection_x voltage = -d / slope # y = kx + d --> x = (y-d)/k with x = 0 fit_line = [[0, d], [x[-1], x[-1] * slope + d]] fit_line = hv.Curve(fit_line).opts(color="red", line_width=1.5) return voltage, fit_line elif ana_type == "Ana 2": df = df[df.dy == df.dy.max()] voltage = df['x'].iloc[0] line = hv.VLine(voltage).opts(color="black", line_width=1.0) return voltage, line elif ana_type == "Ana 3": df = df[df.dy == df.dy.min()] voltage = df['x'].iloc[0] line = hv.VLine(voltage).opts(color="black", line_width=1.0) return voltage, line
def AS_AD(country="South Africa", year=1980): z_22 = oilrents.loc[((oilrents.country == country) & (oilrents.year == year)), ["NY.GDP.PETR.RT.ZS"]].fillna(0).reset_index( drop=True).iloc[0, 0] z_11 = bmoney.loc[((oilrents.country == country) & (oilrents.year == year)), ["FM.LBL.BMNY.GD.ZS"]].fillna(0).reset_index( drop=True).iloc[0, 0] as_eq = pd.DataFrame([P(), AS(pas=P(), Z_2=0)], index=["Price_Level", "Real Output"]).T ad_eq = pd.DataFrame([P(), AD(pad=P(), Z_1=0)], index=["Price_Level", "Real Output"]).T as_shock = pd.DataFrame([P(), AS(pas=P(), Z_2=z_22)], index=["Price_Level", "Real Output"]).T ad_shock = pd.DataFrame([P(), AD(pad=P(), Z_1=z_11)], index=["Price_Level", "Real Output"]).T result = findIntersection(lambda x: AS(pas=x, Z_2=z_22), lambda x: AD(pad=x, Z_1=-z_11), 0.0) r = result + 1e-4 if result == 0 else result as_ad_plot = hv.Curve(as_eq, vdims="Price_Level", kdims="Real Output").options(alpha=0.2, color='#1BB3F5') *\ hv.Curve(ad_eq, vdims="Price_Level", kdims="Real Output").options(alpha=0.2, color='orange') *\ hv.Curve(as_shock, vdims="Price_Level", kdims="Real Output", label='AS').options(alpha=1, color='#1BB3F5') *\ hv.Curve(ad_shock, vdims="Price_Level", kdims="Real Output", label='AD').options(alpha=1, color='orange') *\ hv.VLine(-result[0]).options(alpha=0.2, color='black', line_width=1) *\ hv.HLine(AS(pas=-r[0], Z_2=-z_22)).options(line_width=1, alpha=0.2, color='black') gdp_plot = gdp.loc[gdp.country==country].hvplot.line(y="NY.GDP.PCAP.KD", x="year") *\ pd.DataFrame([[AS(pas=-r[0], Z_2=z_22)*0.1*gdp4_iqr_max[country], year]], columns=['GDP', 'YEAR'])\ .hvplot.scatter(y="GDP", x='YEAR', color="red")*hv.VLine(year) return as_ad_plot + gdp_plot
def plot_train_history(history): """ Plot the train and validation loss and accuracy :param history: the output of tf.keras.Model.fit :returns: hv.Layout """ ds = hv.Dataset(pd.DataFrame(history.history), kdims=[('index', 'epoch')]) loss = ds.to(hv.Curve, vdims=['loss'], label='Train') * \ ds.to(hv.Curve, vdims=['val_loss'], label='Validation') accuracy = ds.to(hv.Curve, vdims=['accuracy'], label='Train') * \ ds.to(hv.Curve, vdims=['val_accuracy'], label='Validation') best_epoch = hv.VLine(np.argmin(history.history['val_loss'])).opts( color='black', line_dash='dashed', line_width=1) return (loss + accuracy).opts( hv.opts.Curve(width=400, height=400, tools=['hover'])) * best_epoch
def _plot_signals(self, task, test, failures): ana = self.trace.ana( task=task, backend='bokeh', ) fig = (ana.load_tracking.plot_task_signals( signals=['util', 'enqueued', 'ewma']) * ana.rta.plot_phases() * hv.Overlay([ hv.VLine(x).options( alpha=0.5, color='red', ) for x in failures ])).options(title='UtilConvergence debug plot', ) self._save_debug_plot(fig, name=f'util_est_{test}') return fig
def update_control_vlines(self, x1: float, x2: float, stroke_count: int, data): if None in [x1, x2]: x1, x2 = self.vlines_positions xs, _, cov = data xmin, xmax = np.min(xs), np.max(xs) bounds = (xmin, xmin, xmax, xmax) hline = hv.VLine(x=x1).opts(color=orange1) vline = hv.HLine(y=x2).opts(color=orange2) self.vlines_positions = (x1, x2) image = hv.Image(np.rot90(cov), bounds=bounds) points_3 = hv.Points([(x1, x1), (x2, x2), (x2, x1)]).opts(line_color=blue) point = hv.Points([(x1, x2)]).opts(fill_color=orange1, line_color="white") return image * hline * vline * points_3 * point
def background(func, size=(500, 500)): """ Given the ODE y'=f(x,y), bg,vec,xaxis_line,yaxis_line = background() returns a grayscale image of the slopes y', a vector field representation of the slopes, and a set of axis lines for -5<x<5, -5<y<5 """ # compute the data vals = np.linspace(-5, 5, num=150) X, Y = np.meshgrid(vals, vals) clines = func(X, Y) # f(x,y) theta = np.arctan2(clines, 1) # angle of the slope y' at x,y # Obtain the vector field (subsample the grid) h, w = size vf_opts = dict(size_index=3, height=h, width=w, xticks=9, yticks=9, alpha=0.3, muted_alpha=0.05) vec_field = hv.VectorField( (vals[::3], vals[::3], theta[::3, ::3], 0 * clines[::3, ::3] + 1), label='vector_field').options(**vf_opts) # Normalize the given array so that it can be used with the RGB element's alpha channel def norm(arr): arr = (arr - arr.min()) return arr / arr.max() normXY = norm(clines) img_field = hv.RGB( (vals, vals, normXY, normXY, normXY, 0*clines+0.1), vdims=['R','G','B','A'] )\ .options(width=size[0], height=size[1], shared_axes=False) # finally, we add the axes as VLine, HLine and return an array of the plot Elements hv_opts = dict(color='k', alpha=0.8, line_width=1.5) return [ img_field, vec_field, hv.HLine(0).options(**hv_opts), hv.VLine(0).options(**hv_opts) ]
def __call__(self, skyplots, **params): self.p = param.ParamOverrides(self, params) pointer = hv.streams.PointerXY(x=0, y=0) cross_opts = dict(style={'line_width': 1, 'color': 'black'}) cross_dmap = hv.DynamicMap(lambda x, y: (hv.VLine(x).opts(**cross_opts) * hv.HLine(y).opts(**cross_opts)), streams=[pointer]) plots = [] for s in skyplots: if self.p.crosshair: plot = (s*cross_dmap).relabel(s.label) else: plot = s plots.append(plot) return hv.Layout(plots)
def plot_annotations(self, **kwargs): flag = [ str(i) == str(self.mission_id) for i in self.annotations.mission_id.values ] rows = self.annotations[flag].iterrows() plots = [] # We remember the first double-click and draw a vertical line if we expect another click to happen if self.pending_start: plots.append(hv.VLine(self.pending_start).opts(line_dash="dashed")) plots.extend([ hv.VSpan(r["start_clock_ms"], r["end_clock_ms"]).opts( color=color_dict.get(r["classification"], "yellow")) #* #hv.Text((r["start_clock_ms"]+r["end_clock_ms"])/2,0.9,str(r["classification"])).opts(color="red") for ix, r in rows ]) return hv.Overlay(plots)