def _create_hvplot(): # Generate some data cl1 = np.random.normal(loc=2, scale=0.2, size=(200, 200)) cl2x = np.random.normal(loc=-2, scale=0.6, size=200) cl2y = np.random.normal(loc=-2, scale=0.1, size=200) cl3 = np.random.normal(loc=0, scale=1.5, size=(400, 400)) # Create an overlay of points and ellipses clusters = (hv.Points(cl1).opts(color="blue") * hv.Points( (cl2x, cl2y)).opts(color="green") * hv.Points(cl3).opts(color="#FDDC22")) plot = clusters * hv.Ellipse(2, 2, 2) * hv.Ellipse(-2, -2, (4, 2)) return plot
def _create_hvplot(): # Generate some data cl1 = np.random.normal(loc=2, scale=0.2, size=(200, 200)) cl2x = np.random.normal(loc=-2, scale=0.6, size=200) cl2y = np.random.normal(loc=-2, scale=0.1, size=200) cl3 = np.random.normal(loc=0, scale=1.5, size=(400, 400)) # Create an overlay of points and ellipses clusters = (hv.Points(cl1).opts(color="blue") * hv.Points( (cl2x, cl2y)).opts(color="green") * hv.Points(cl3).opts(color="#FDDC22")) plot = (clusters * hv.Ellipse(2, 2, 2).opts(ellipse_opts) * hv.Ellipse(-2, -2, (4, 2)).opts(ellipse_opts)) return pn.Column( pn.pane.Markdown("## HoloViews Plot"), pn.pane.HoloViews(plot, sizing_mode="stretch_both"), sizing_mode="stretch_both", )
def plot_stimulus(obj, **args): spatial = args.get('spatial', False) bin = args.get('bin', float('Inf')) if np.isinf(bin): bins = np.array([0, obj.duration]) num = 1 else: bins = np.r_[0:obj.duration + bin / 1000.:bin / 1000.] num = bins.size - 1 if not spatial: grid = args.get('grid', False) hm = dict() tmin = np.min(obj.trace) tmax = np.max(obj.trace) for t in range(num): if num == 1: d = {i:hv.Curve((obj.time,obj.trace[i]))\ for i in range(obj.trace.shape[0])} else: d = {i:hv.Curve((obj.time,obj.trace[i]))*\ hv.Curve([(bins[t+1],tmin),(bins[t+1],tmax)]) for i in range(obj.trace.shape[0])} if grid: hvobj = hv.NdLayout(d) else: hvobj = hv.NdOverlay(d) hm[t] = hvobj hvobj = hv.HoloMap(hm, kdims='Time bin [' + str(bin) + ' ms]').collate() else: sur = args.get('surface', hand_surface) mid = (bins[1:] + bins[:-1]) / 2. d = np.array([np.interp(mid,obj.time,obj.trace[i])\ for i in range(obj.trace.shape[0])]) d = (d - np.min(d)) d = 1 - d / np.max(d) hm = dict() locs = sur.hand2pixel(obj.location) rad = obj.pin_radius * sur.pxl_per_mm for t in range(num): p = hv.Polygons( [{ ('x', 'y'): hv.Ellipse(locs[l, 0], locs[l, 1], 2 * rad).array(), 'z': d[l, t] } for l in range(obj.location.shape[0])], vdims='z').opts( plot=dict(color_index='z', aspect='equal'), style=dict(linewidth=0., line_width=0.01)).options(cmap='fire') hm[t] = p hvobj = hv.HoloMap(hm, kdims='Time bin [' + str(bin) + ' ms]') return hvobj
def generate_single_plot(comet_api, SOPT, STR="r", COPT="sgd", E=1, project="emnist-s"): clr = "Client Learning Rate (log10)" slr = "Server Learning Rate (log10)" exps = get_experiments(comet_api, SOPT, STR, COPT, E, project) slrv = exp_params2list(exps, "SERVER_LEARNING_RATE", float) clrv = exp_params2list(exps, "CLIENT_LEARNING_RATE", float) acc = exp_metrics2list(exps, "last_avg_acc", float) df = pd.DataFrame({ slr: np.log10(slrv), clr: np.log10(clrv), "Accuracy": acc }) i = df["Accuracy"].idxmax() m = df.iloc[i] return ( hv.HeatMap(df, kdims=[clr, slr]).opts(colorbar=True, cmap="viridis") * hv.Ellipse(m[clr], m[slr], 0.5)).opts(fig_inches=10)
def circle_fit(self): xCtr, yCtr, r, _ = cf.least_squares_circle(self.points_data.values) return hv.Ellipse(xCtr, yCtr, 2 * r).opts(color="red")
def Pitch(height, width): height, width = height, width line_color, pitch_color, pitch_linewidth = "black", "white", 1 lin = np.linspace(0, np.pi / 2, 200) def corners(t, x, y, r, theta): return (x + r * np.cos(t + theta), y + r * np.sin(t + theta), t) def int_angles(radius, h, k, line_y): """ Calculate the intersection angles of the arc above the D-boxes Parameters: radius (float): Radius of the arc h(float): x coordinate of the centre of the arc k(float): y coordiante of the centre of the arc line_y(float): y coordinate of the D-box or the line to be intersected by the arc Returns: theta1(float): First intersection angle theta2(float): Second intersection angle """ x1 = h + np.sqrt(radius**2 - (line_y - k)**2) x2 = h - np.sqrt(radius**2 - (line_y - k)**2) theta1 = np.arccos((x1 - h) / radius) theta2 = np.pi - theta1 return theta1, theta2 theta1, theta2 = int_angles(0.075 * height, width / 2, 0.1 * height, 0.15 * height) lin2 = np.linspace(theta1, theta2, 200) def boxarcs(t, x, y, r, theta): return (x + r * np.cos(t + theta), y + r * np.sin(t + theta), t) #Pitch outline matchpitch = hv.Curve([(0, 0), (0, height)]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(0, height), (width, height) ]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(width, height), (width, 0)]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(width, 0), (0, 0)]).opts(color=line_color) #Halfline matchpitch = matchpitch * hv.Curve([(0, height / 2), (width, height / 2) ]).opts(color=line_color) #Bottom Penalty Area matchpitch = matchpitch * hv.Curve([(.225 * width, 0), (.225 * width, .15 * height) ]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(.225 * width, .15 * height), (.775 * width, .15 * height) ]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(.775 * width, .15 * height), (.775 * width, 0) ]).opts(color=line_color) #Top Penalty Area matchpitch = matchpitch * hv.Curve([(.225 * width, height), (.225 * width, .85 * height) ]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(.225 * width, .85 * height), (.775 * width, .85 * height) ]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(.775 * width, .85 * height), (.775 * width, height) ]).opts(color=line_color) #Bottom 6 yard Box matchpitch = matchpitch * hv.Curve([(.375 * width, 0), (.375 * width, 0.05 * height) ]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(.375 * width, 0.05 * height), (.625 * width, 0.05 * height) ]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(.625 * width, 0.05 * height), (.625 * width, 0) ]).opts(color=line_color) #Top 6 yard Box matchpitch = matchpitch * hv.Curve([(.375 * width, height), (.375 * width, .95 * height) ]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(.375 * width, .95 * height), (.625 * width, .95 * height) ]).opts(color=line_color) matchpitch = matchpitch * hv.Curve([(.625 * width, .95 * height), (.625 * width, height) ]).opts(color=line_color) #Prepare Circles #Center circle and kickoff spot matchpitch = matchpitch * hv.Ellipse( width / 2, height / 2, 2 * .076 * height).opts(color=line_color) matchpitch = matchpitch * hv.Points( (width / 2, height / 2)).opts(color=line_color, size=5) #Bottom Penalty Spot matchpitch = matchpitch * hv.Points( (width / 2, 0.1 * height)).opts(color=line_color, size=5) #Top Penalty Spot matchpitch = matchpitch * hv.Points( (width / 2.0, .9 * height)).opts(color=line_color, size=5) #Bottom left corner matchpitch = matchpitch * hv.Path([corners(lin, 0, 0, 0.025 * height, 0) ]).opts(color=line_color) #Bottom right corner matchpitch = matchpitch * hv.Path([ corners(lin, width, 0, 0.025 * height, np.pi / 2) ]).opts(color=line_color) #Top left corner matchpitch = matchpitch * hv.Path([ corners(lin, 0, height, 0.025 * height, 3.0 * np.pi / 2) ]).opts(color=line_color) #Top right corner matchpitch = matchpitch * hv.Path([ corners(lin, width, height, 0.025 * height, np.pi) ]).opts(color=line_color) #Bottom box arc matchpitch = matchpitch * hv.Path([ boxarcs(lin2, width / 2, 0.1 * height, 0.075 * height, 0) ]).opts(color=line_color) #Top box arc matchpitch = matchpitch * hv.Path([ boxarcs(lin2, width / 2, 0.9 * height, 0.075 * height, np.pi) ]).opts(color=line_color) xl = -10 xr = width + 10 yb = -10 yt = height + 10 w = 2.5 * (xr - xl) h = 2.5 * (yt - yb) matchpitch.opts(width=w, height=h, xlim=(xl, xr), ylim=(yb, yt), data_aspect=1, xaxis=None, yaxis=None) return matchpitch
def view(self): if self.lsd is None: return panel.pane.Markdown("No data selected.") try: if self.intercylinder_only: name = "ringmap_intercyl" else: name = "ringmap" container = self.data.load_file(self.revision, self.lsd, name) except DataError as err: return panel.pane.Markdown( f"Error: {str(err)}. Please report this problem." ) # Index map for ra (x-axis) index_map_ra = container.index_map["ra"] axis_name_ra = "RA [degrees]" # Index map for sin(ZA)/sin(theta) (y-axis) index_map_el = container.index_map["el"] axis_name_el = "sin(\u03B8)" # Apply data selections sel_beam = np.where(container.index_map["beam"] == self.beam)[0] sel_freq = np.where( [f[0] for f in container.index_map["freq"]] == self.frequency )[0] if self.polarization == self.mean_pol_text: sel_pol = np.where( (container.index_map["pol"] == "XX") | (container.index_map["pol"] == "YY") )[0] rmap = np.squeeze(container.map[sel_beam, sel_pol, sel_freq]) rmap = np.nanmean(rmap, axis=0) else: sel_pol = np.where(container.index_map["pol"] == self.polarization)[0] rmap = np.squeeze(container.map[sel_beam, sel_pol, sel_freq]) if self.flag_mask: rmap = np.where(self._flags_mask(container.index_map["ra"]), np.nan, rmap) if self.weight_mask: try: rms = np.squeeze(container.rms[sel_pol, sel_freq]) except IndexError: logger.error( f"rms dataset of ringmap file for rev {self.revision} lsd " f"{self.lsd} is missing [{sel_pol}, {sel_freq}] (polarization, " f"frequency). rms has shape {container.rms.shape}" ) self.weight_mask = False else: rmap = np.where(self._weights_mask(rms), np.nan, rmap) # Set flagged data to nan rmap = np.where(rmap == 0, np.nan, rmap) if self.crosstalk_removal: # The mean of an all-nan slice (masked?) is nan. We don't need a warning about that. with warnings.catch_warnings(): warnings.filterwarnings("ignore", r"All-NaN slice encountered") rmap -= np.nanmedian(rmap, axis=0) if self.template_subtraction: try: rm_stack = self.data.load_file_from_path( self._stack_path, ccontainers.RingMap ) except DataError as err: return panel.pane.Markdown( f"Error: {str(err)}. Please report this problem." ) # The stack file has all polarizations, so we can't reuse sel_pol if self.polarization == self.mean_pol_text: stack_sel_pol = np.where( (rm_stack.index_map["pol"] == "XX") | (rm_stack.index_map["pol"] == "YY") )[0] else: stack_sel_pol = np.where( rm_stack.index_map["pol"] == self.polarization )[0] try: rm_stack = np.squeeze(rm_stack.map[sel_beam, stack_sel_pol, sel_freq]) except IndexError as err: logger.error( f"map dataset of ringmap stack file " f"is missing [{sel_beam}, {stack_sel_pol}, {sel_freq}] (beam, polarization, " f"frequency). map has shape {rm_stack.map.shape}:\n{err}" ) self.template_subtraction = False else: if self.polarization == self.mean_pol_text: rm_stack = np.nanmean(rm_stack, axis=0) # FIXME: this is a hack. remove when rinmap stack file fixed. rmap -= rm_stack.reshape(rm_stack.shape[0], -1, 2).mean(axis=-1) if self.transpose: rmap = rmap.T index_x = index_map_ra index_y = index_map_el axis_names = [axis_name_ra, axis_name_el] xlim, ylim = self.ylim, self.xlim else: index_x = index_map_el index_y = index_map_ra axis_names = [axis_name_el, axis_name_ra] xlim, ylim = self.xlim, self.ylim img = hv.Image( (index_x, index_y, rmap), datatype=["image", "grid"], kdims=axis_names, ).opts( clim=self.colormap_range, logz=self.logarithmic_colorscale, cmap=process_cmap("inferno", provider="matplotlib"), colorbar=True, xlim=xlim, ylim=ylim, ) if self.serverside_rendering is not None: # set colormap cmap_inferno = copy.copy(matplotlib_cm.get_cmap("inferno")) cmap_inferno.set_under("black") cmap_inferno.set_bad("lightgray") # Set z-axis normalization (other possible values are 'eq_hist', 'cbrt'). if self.logarithmic_colorscale: normalization = "log" else: normalization = "linear" # datashade/rasterize the image img = self.serverside_rendering( img, cmap=cmap_inferno, precompute=True, x_range=xlim, y_range=ylim, normalization=normalization, ) if self.mark_moon: # Put a ring around the location of the moon if it transits on this day eph = skyfield_wrapper.ephemeris # Start and end times of the CSD st = csd_to_unix(self.lsd.lsd) et = csd_to_unix(self.lsd.lsd + 1) moon_time, moon_dec = chime.transit_times( eph["moon"], st, et, return_dec=True ) if len(moon_time): lunar_transit = unix_to_csd(moon_time[0]) lunar_dec = moon_dec[0] lunar_ra = (lunar_transit % 1) * 360.0 lunar_za = np.sin(np.radians(lunar_dec - 49.0)) if self.transpose: img *= hv.Ellipse(lunar_ra, lunar_za, (5.5, 0.15)) else: img *= hv.Ellipse(lunar_za, lunar_ra, (0.04, 21)) if self.mark_day_time: # Calculate the sun rise/set times on this sidereal day # Start and end times of the CSD start_time = csd_to_unix(self.lsd.lsd) end_time = csd_to_unix(self.lsd.lsd + 1) times, rises = chime.rise_set_times( skyfield_wrapper.ephemeris["sun"], start_time, end_time, diameter=-10, ) sun_rise = 0 sun_set = 0 for t, r in zip(times, rises): if r: sun_rise = (unix_to_csd(t) % 1) * 360 else: sun_set = (unix_to_csd(t) % 1) * 360 # Highlight the day time data opts = { "color": "grey", "alpha": 0.5, "line_width": 1, "line_color": "black", "line_dash": "dashed", } if self.transpose: if sun_rise < sun_set: img *= hv.VSpan(sun_rise, sun_set).opts(**opts) else: img *= hv.VSpan(self.ylim[0], sun_set).opts(**opts) img *= hv.VSpan(sun_rise, self.ylim[1]).opts(**opts) else: if sun_rise < sun_set: img *= hv.HSpan(sun_rise, sun_set).opts(**opts) else: img *= hv.HSpan(self.ylim[0], sun_set).opts(**opts) img *= hv.HSpan(sun_rise, self.ylim[1]).opts(**opts) img.opts( # Fix height, but make width responsive height=self.height, responsive=True, shared_axes=True, bgcolor="lightgray", ) return panel.Row(img, width_policy="max")