def show(self, **kwargs): width = kwargs.get("width", 800) height = kwargs.get("height", 600) opts.defaults(opts.WMTS(width=width, height=height)) tile = gv.WMTS("https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png") ps = [tile] # external ds = self._obj.loc["line0"] ds = ds.append(ds.iloc[0]).reset_index(drop=True) dland = ds.loc[ds.tag == "land"] dland_ = np.split(dland, np.flatnonzero(np.diff(dland.index) != 1) + 1) for seg in dland_: ps.append( seg.hvplot.paths(x="lon", y="lat", geo=True, color="brown")) dwater = ds.loc[ds.tag == "open"] dwater_ = np.split(dwater, np.flatnonzero(np.diff(dwater.index) != 1) + 1) for seg in dwater_: ps.append( seg.hvplot.paths(x="lon", y="lat", geo=True, color="blue")) # islands for line in self._obj.index.levels[0][1:]: ds = self._obj.loc[line] ds = ds.append(ds.iloc[0]).reset_index(drop=True) ps.append( ds.hvplot.paths(x="lon", y="lat", geo=True, color="green")) return hv.Overlay(ps)
def elevation_max(dataset: xr.Dataset): #extract data x, y, simplices = extract_grid(dataset) w = dataset z = dataset.elev.max(dim='time').values # create panel objects xyz_points = pd.DataFrame(dict(longitude=x, latitude=y, elevation=z)) points = hv.Points(xyz_points, kdims=["longitude", "latitude"], vdims="elevation") trimesh = hv.TriMesh((simplices, points)) opts.defaults(opts.WMTS(width=1200, height=900)) datashaded_trimesh = (rasterize(trimesh, aggregator='mean').opts(colorbar=True, cmap='Viridis', clim=(z.min(), z.max()), clabel='meters', tools=["hover"])) tiles = gv.WMTS('https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png') layout = tiles * datashaded_trimesh t0 = pd.to_datetime(w.time.values.min()).strftime(format='%Y-%m-%d:%H') t1 = pd.to_datetime(w.time.values.max()).strftime(format='%Y-%m-%d:%H') header = get_header( title="## Maximum forecasted elevation between {} and {}".format( t0, t1)) disclaimer = get_disclaimer() return pn.Column(header, layout, disclaimer)
def covid_viewer_v2(ds): ''' covid viewer, for actives_vs_beds ''' opts.defaults( opts.Curve(tools=['hover'], width=800, height = 600, ylabel='') ) logtog = pn.widgets.Toggle(name='Log (Y-axis)', button_type='default', value=False) xlim=(np.datetime64('2020-03-01'), np.datetime64('2020-03-25')) hv_ds = hv.Dataset(ds, ['date', 'place'], ['active_per_beds']) avb = hv_ds.to(hv.Curve, 'date', 'active_per_beds').overlay('place').opts( legend_position='top_left', shared_axes=True, ylim=(0, 0.13), xlim=xlim, title='Severe Cases per Open Hospital Bed') avb_log = hv_ds.to(hv.Curve, 'date', 'active_per_beds').overlay('place').opts( legend_position='top_left', shared_axes=True, logy=True, ylim=(1e-6, 10), xlim=xlim, title='Severe Cases per Open Hospital Bed (Log Scale)') max_line = hv.HLine(1).opts( opts.HLine(color='red', line_width=6), opts.Points(color='#D3D3D3')) # layout = (avb_log) # layout.opts( # opts.Curve(width=400, height=300, framewise=True)) # pn_layout = pn.pane.HoloViews(layout) # return pn.Row(logtog, pn_layout) return avb
def hvplot(self): # noqa F811 opts.defaults( opts.Overlay( width=self.width, height=self.height, active_tools=["wheel_zoom"] ) ) return self._hvplot_trajectory(self.data)
def elevation_max(data_dir: pathlib.Path): # load data grid_path = data_dir / "grid.npz" elevation_max_path = data_dir / "elevation.max.npz" x, y, simplices = load_grid_from_disk(grid_path) z = load_elevation_from_disk(elevation_max_path) # create panel objects xyz_points = pd.DataFrame(dict(x=x, y=y, z=z)) points = hv.Points(xyz_points, kdims=["x", "y"], vdims="z") trimesh = hv.TriMesh((simplices, points)) opts.defaults(opts.WMTS(width=1200, height=900)) datashaded_trimesh = (rasterize(trimesh, aggregator='mean').opts(colorbar=True, cmap='Viridis', clim=(z.min(), z.max()), clabel='meters', tools=["hover"])) tiles = gv.WMTS('https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png') layout = tiles * datashaded_trimesh header = get_header(title="## Max elevation for the next 72 hours") disclaimer = get_disclaimer() return pn.Column(header, layout, disclaimer)
def contourf(self, var='depth', it=None, **kwargs): x = kwargs.get('x', self._obj.SCHISM_hgrid_node_x[:].values) y = kwargs.get('y', self._obj.SCHISM_hgrid_node_y[:].values) try: t = kwargs.get('t', self._obj.time.values) except: pass tri3 = kwargs.get( 'tri3', self._obj.SCHISM_hgrid_face_nodes.values[:, :3].astype(int)) z = kwargs.get('z', self._obj[var].values[it, :].flatten()) nodes = pd.DataFrame({ 'longitude': x, 'latitude': y, '{}'.format(var): z }) elems = pd.DataFrame(tri3, columns=['a', 'b', 'c']) opts.defaults(opts.WMTS(width=800, height=400)) tiles = gv.WMTS( 'https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png') points = gv.operation.project_points( gv.Points(nodes, vdims=['{}'.format(var)])) trimesh = gv.TriMesh((elems, points)) return tiles * rasterize(trimesh, aggregator='mean').opts( colorbar=True, cmap='Viridis', padding=.1, tools=['hover'])
def grid(self, tiles=False, **kwargs): x = kwargs.get("x", self._obj.SCHISM_hgrid_node_x[:].values) y = kwargs.get("y", self._obj.SCHISM_hgrid_node_y[:].values) tes = kwargs.get("tri3", self._obj.SCHISM_hgrid_face_nodes.values) width = kwargs.get("width", 800) height = kwargs.get("height", 600) opts.defaults(opts.WMTS(width=width, height=height)) tile = gv.WMTS("https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png") nodes = pd.DataFrame({"longitude": x, "latitude": y}) points = gv.operation.project_points(gv.Points(nodes)) if tes.shape[1] == 3: elems = pd.DataFrame(tes, columns=["a", "b", "c"]) trimesh = gv.TriMesh((elems, points)).edgepaths if tiles: return tile * datashade( trimesh, precompute=True, cmap=["black"]) else: return datashade(trimesh, precompute=True, cmap=["green"]).opts(width=width, height=height) else: # there are quads elems = pd.DataFrame(tes, columns=["a", "b", "c", "d"]) quads = elems.loc[~elems.d.isna()].copy() quads = quads.reset_index(drop=True) ap = nodes.loc[quads.a, ["longitude", "latitude"]] bp = nodes.loc[quads.b, ["longitude", "latitude"]] cp = nodes.loc[quads.c, ["longitude", "latitude"]] dp = nodes.loc[quads.d, ["longitude", "latitude"]] quads["ap"] = ap.values.tolist() quads["bp"] = bp.values.tolist() quads["cp"] = cp.values.tolist() quads["dp"] = dp.values.tolist() q = gv.Polygons([ quads.loc[i, ["ap", "bp", "cp", "dp"]].tolist() for i in range(quads.shape[0]) ]).options(fill_alpha=0, line_color="black") triangles = elems.loc[elems.d.isna()] trimesh = gv.TriMesh((triangles, points)).edgepaths g1 = datashade(trimesh, precompute=True, cmap=["black"]) if tiles: return tile * g1 * q else: return g1 * q
def draw_holoviews_graphs(graph_dict): # use first key to determine default settings first_key = list(graph_dict.keys())[0] molecule, ksize, log2sketchsize = first_key hv.extension('bokeh') defaults = dict(width=400, height=400, padding=0.1) hv.opts.defaults(opts.EdgePaths(**defaults), opts.Graph(**defaults), opts.Nodes(**defaults)) kdims = [ hv.Dimension(('molecule', "molecule"), default=molecule), hv.Dimension(('ksize', "k-mer size"), default=ksize), hv.Dimension(('log2_num_hashes', "$\log_2$ num hashes"), default=log2sketchsize), ] kwargs = dict(width=800, height=800, xaxis=None, yaxis=None) opts.defaults(opts.Nodes(**kwargs), opts.Graph(**kwargs)) kwargs = dict(node_size=10, edge_line_width=1, cmap='Set2', node_color=dim("species"), node_line_color='gray', width=600, height=600, xaxis=None, yaxis=None) holomap = hv.HoloMap(graph_dict, kdims=kdims) holomap.opts(opts.Graph(**kwargs)) return holomap
def contourf(self, var="depth", it=None, tiles=False, **kwargs): x = kwargs.get("x", self._obj.SCHISM_hgrid_node_x[:].values) y = kwargs.get("y", self._obj.SCHISM_hgrid_node_y[:].values) try: t = kwargs.get("t", self._obj.time.values) except: pass tes = kwargs.get("tri3", self._obj.SCHISM_hgrid_face_nodes.values[:, :4]) # sort out quads try: mask = np.isnan(tes)[:, 3] tr3 = tes[mask][:, :3] tr3_ = quads_to_tris(tes[~mask]) if tr3_: tri3 = np.append(tr3, tr3_, axis=0).astype(int) else: tri3 = tr3.astype(int) except: tri3 = tes.astype(int) if tri3.min() > 0: tri3 = tri3 - 1 z = kwargs.get("z", self._obj[var].values[it, :].flatten()) nodes = pd.DataFrame({ "longitude": x, "latitude": y, "{}".format(var): z }) elems = pd.DataFrame(tri3, columns=["a", "b", "c"]) width = kwargs.get("width", 800) height = kwargs.get("height", 600) opts.defaults(opts.WMTS(width=width, height=height)) tile = gv.WMTS("https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png") points = gv.operation.project_points( gv.Points(nodes, vdims=["{}".format(var)])) trimesh = gv.TriMesh((elems, points)) if tiles: return tile * rasterize(trimesh, aggregator="mean").opts( colorbar=True, cmap="Viridis", padding=0.1, tools=["hover"]) else: return rasterize(trimesh, aggregator="mean").opts( colorbar=True, cmap="Viridis", padding=0.1, tools=["hover"], width=width, height=height, )
def __init__(self, directory, selected_cols, columns, files): self.db_file = os.path.join(directory, "experiment.db") self.directory = directory self.all_cols = columns self.columns = [] self.selected = list(selected_cols) self.files = files self.exps = {} opts.defaults(opts.Points(fontsize={'title': 18, 'labels': 18}))
def hvplot(self): opts.defaults(opts.Overlay(width=self.width, height=self.height, active_tools=['wheel_zoom'])) for traj in self.data.trajectories: overlay = self._hvplot_trajectory(traj) if self.overlay: self.overlay = self.overlay * overlay else: self.overlay = overlay self.hvplot_tiles = False # has to be removed after the first iteration, otherwise tiles will cover trajectories! return self.overlay
def grid(self, tiles=False, **kwargs): x = kwargs.get('x',self._obj.SCHISM_hgrid_node_x[:].values) y = kwargs.get('y',self._obj.SCHISM_hgrid_node_y[:].values) tes = kwargs.get('tri3',self._obj.SCHISM_hgrid_face_nodes.values) width = kwargs.get('width', 800) height = kwargs.get('height', 600) opts.defaults(opts.WMTS(width=width, height=height)) tile = gv.WMTS('https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png') nodes = pd.DataFrame({'longitude':x,'latitude':y}) points = gv.operation.project_points(gv.Points(nodes)) if tes.shape[1] == 3 : elems = pd.DataFrame(tes, columns=['a', 'b', 'c']) trimesh=gv.TriMesh((elems, points)).edgepaths if tiles: return tile * datashade(trimesh, precompute=True, cmap=['black']) else: return datashade(trimesh, precompute=True, cmap=['green']).opts(width=width,height=height) else: # there are quads elems = pd.DataFrame(tes, columns=['a', 'b', 'c', 'd']) quads = elems.loc[~elems.d.isna()].copy() quads = quads.reset_index(drop=True) ap = nodes.loc[quads.a,['longitude','latitude']] bp = nodes.loc[quads.b,['longitude','latitude']] cp = nodes.loc[quads.c,['longitude','latitude']] dp = nodes.loc[quads.d,['longitude','latitude']] quads['ap'] = ap.values.tolist() quads['bp'] = bp.values.tolist() quads['cp'] = cp.values.tolist() quads['dp'] = dp.values.tolist() q = gv.Polygons([quads.loc[i,['ap','bp','cp','dp']].tolist() for i in range(quads.shape[0])]).options(fill_alpha=0, line_color='black') triangles = elems.loc[elems.d.isna()] trimesh=gv.TriMesh((triangles, points)).edgepaths g1 = datashade(trimesh, precompute=True, cmap=['black']) if tiles : return tile * g1 * q else: return g1 * q
def frames(self,var='depth', tiles=False, **kwargs): x = kwargs.get('x',self._obj.SCHISM_hgrid_node_x[:].values) y = kwargs.get('y',self._obj.SCHISM_hgrid_node_y[:].values) try: t = kwargs.get('t',self._obj.time.values) except: pass tes = kwargs.get('tri3',self._obj.SCHISM_hgrid_face_nodes.values[:,:4]) # sort out quads try: mask = np.isnan(tes)[:,3] tr3 = tes[mask][:,:3] tr3_ = quads_to_tris(tes[~mask]) if tr3_ : tri3 = np.append(tr3,tr3_,axis=0).astype(int) else: tri3 = tr3.astype(int) except: tri3 = tes.astype(int) times=kwargs.get('times',self._obj.time.values) z = kwargs.get('z',self._obj[var].values[0,:].flatten()) zmin = self._obj[var].values.min() zmax = self._obj[var].values.max() nodes = pd.DataFrame({'longitude':x,'latitude':y, '{}'.format(var):z}) elems = pd.DataFrame(tri3, columns=['a', 'b', 'c']) width = kwargs.get('width', 800) height = kwargs.get('height', 600) opts.defaults(opts.WMTS(width=width, height=height)) tile = gv.WMTS('https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png') points = gv.operation.project_points(gv.Points(nodes, vdims=['{}'.format(var)])) trimesh = gv.TriMesh((elems, points)) def time_mesh(time): points.data[var] = self._obj[var].sel(time=time).values return gv.TriMesh((elems, points))#, crs=ccrs.GOOGLE_MERCATOR) meshes = hv.DynamicMap(time_mesh, kdims=['Time']).redim.values(Time=times) imesh = rasterize(meshes, aggregator='mean').opts(cmap='viridis', colorbar=True, padding=.1, tools=['hover'], clim=(zmin, zmax)) if tiles: return hv.output(tile*imesh, holomap='scrubber', fps=1) else: return hv.output(imesh.opts(width=width,height=height), holomap='scrubber', fps=1)
def elevation(dataset: xr.Dataset): # extract data z = dataset x, y, simplices = extract_grid(dataset) # create panel objects xyz_points = pd.DataFrame( dict(longitude=x, latitude=y, elevation=z.elev.isel(time=0).values)) points = hv.Points(xyz_points, kdims=["longitude", "latitude"], vdims="elevation") opts.defaults(opts.WMTS(width=1200, height=900)) def time_mesh(time): points.data.elevation = z.elev.sel(time=time).values return hv.TriMesh((simplices, points)) #, crs=ccrs.GOOGLE_MERCATOR) meshes = hv.DynamicMap(time_mesh, kdims='Time').redim.values(Time=z.time.values) datashaded_trimesh = (rasterize(meshes, aggregator='mean').opts( colorbar=True, cmap='Viridis', clim=(z.elev.values.min(), z.elev.values.max()), clabel='meters', tools=["hover"])) tiles = gv.WMTS('https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png') t_widget = pn.widgets.Select() @pn.depends(t_widget) def t_plot(time): return tiles * datashaded_trimesh tref_ = pd.to_datetime(z.time.values.min()) - pd.to_timedelta('1H') tref = tref_.strftime(format='%Y-%m-%d:%H') header = get_header( title="## Hourly sea level for 72 hours based on the {} forecast". format(tref)) text = ''' # USAGE Use the toolbox on the right to zoom in/out. ''' footer = pn.Row(pn.pane.Markdown(text)) disclaimer = get_disclaimer() return pn.Column(header, t_plot, footer, disclaimer)
def __init__(self, path, ping_file_path, speed_test_file_path): self.path = path self.ping_file_path = ping_file_path self.speed_test_file_name = speed_test_file_path # Define default layout of graphs hv.extension('bokeh') opts.defaults( opts.Bars(xrotation=45, tools=['hover']), opts.BoxWhisker(width=700, xrotation=30, box_fill_color=Palette('Category20')), opts.Curve(width=700, tools=['hover']), opts.GridSpace(shared_yaxis=True), opts.Scatter(width=700, height=500, color=Palette('Category20'), size=dim('growth')+5, tools=['hover'],alpha=0.5, cmap='Set1'), opts.NdOverlay(legend_position='left')) if os.path.isdir(os.path.join(self.path, "webpage","figures")) is False: os.mkdir(os.path.join(self.path, "webpage","figures")) print("Path 'figures' created successfully") else: print("Path 'figures' initialized") # Load basic configurations config = configparser.ConfigParser() try: config.read('./modules/config_a.ini') # Get values from configuration file self.upper_acceptable_ping_bound = float(config['DEFAULT']['upper_acceptable_ping_bound']) self.upper_ping_issue_bound = float(config['DEFAULT']['upper_ping_issue_bound']) self.acceptable_network_speed = float(config['DEFAULT']['acceptable_network_speed']) except: # In case no config-file is found or another reading error occured print("Configuration file not found/readable.") print("Creating a new configuration file.") # Creating new file with standard values config['DEFAULT'] = {'upper_acceptable_ping_bound': '10', 'upper_ping_issue_bound': '99999', 'acceptable_network_speed': '16'} with open('config_a.ini', 'w') as configfile: config.write(configfile) print("New configuration file was created. Running on default parameters, please restart for changes.") #set default values to continue with program self.upper_acceptable_ping_bound = float(config['DEFAULT']['upper_acceptable_ping_bound']) self.upper_ping_issue_bound = float(config['DEFAULT']['upper_ping_issue_bound']) self.acceptable_network_speed = float(config['DEFAULT']['acceptable_network_speed'])
def frames(self, var='depth', **kwargs): x = kwargs.get('x', self._obj.SCHISM_hgrid_node_x[:].values) y = kwargs.get('y', self._obj.SCHISM_hgrid_node_y[:].values) try: t = kwargs.get('t', self._obj.time.values) except: pass tri3 = kwargs.get( 'tri3', self._obj.SCHISM_hgrid_face_nodes.values[:, :3].astype(int)) times = kwargs.get('times', self._obj.time.values) z = kwargs.get('z', self._obj[var].values[0, :].flatten()) nodes = pd.DataFrame({ 'longitude': x, 'latitude': y, '{}'.format(var): z }) elems = pd.DataFrame(tri3, columns=['a', 'b', 'c']) opts.defaults(opts.WMTS(width=800, height=400)) tiles = gv.WMTS( 'https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png') points = gv.operation.project_points( gv.Points(nodes, vdims=['{}'.format(var)])) trimesh = gv.TriMesh((elems, points)) def time_mesh(time): points.data[var] = self._obj[var].sel(time=time).values return gv.TriMesh((elems, points)) #, crs=ccrs.GOOGLE_MERCATOR) meshes = hv.DynamicMap(time_mesh, kdims=['Time']).redim.values(Time=times) imesh = rasterize(meshes, aggregator='mean').opts(cmap='viridis', colorbar=True, padding=.1, tools=['hover']) return hv.output(tiles * imesh, holomap='scrubber', fps=1)
def covid_viewer(ds): ''' covid viewer, start with MRE view backbone? ''' opts.defaults( opts.Curve(tools=['hover'], width=600, ylabel='') ) logtog = pn.widgets.Toggle(name='Log (Y-axis)', button_type='default', value=False) xlim=(np.datetime64('2020-02-10'), np.datetime64('2020-03-25')) hv_ds = hv.Dataset(ds, ['date', 'country'], ['confirmed', 'dead', 'recovered']) confirmed = hv_ds.to(hv.Curve, 'date', 'confirmed').overlay('country').opts( legend_position='top_left', shared_axes=False, ylim=(-ds.confirmed.values.max()*0.1, ds.confirmed.values.max()*1.1), xlim=xlim, title='Confirmed') confirmed_log = hv_ds.to(hv.Curve, 'date', 'confirmed').overlay('country').opts( legend_position='top_left', shared_axes=False, logy=True, ylim=(1, ds.confirmed.values.max()*2), xlim=xlim, title='Confirmed (Log)') dead = hv_ds.to(hv.Curve, 'date', 'dead').overlay('country').opts( legend_position='top_left', shared_axes=False, ylim=(-ds.dead.values.max()*0.1, ds.dead.values.max()*1.1), xlim=xlim, title='Dead') dead_log = hv_ds.to(hv.Curve, 'date', 'dead').overlay('country').opts( legend_position='top_left', shared_axes=False, logy=True, ylim=(0.1, ds.dead.values.max()*2), xlim=xlim, title='Dead (Log)') recovered = hv_ds.to(hv.Curve, 'date', 'recovered').overlay('country').opts( legend_position='top_left', shared_axes=False, ylim=(-ds.recovered.values.max()*0.1, ds.recovered.values.max()*1.1), xlim=xlim, title='Recovered') recovered_log = hv_ds.to(hv.Curve, 'date', 'recovered').overlay('country').opts( legend_position='top_left', shared_axes=False, logy=True, ylim=(0.1, ds.recovered.values.max()*2), xlim=xlim, title='Recovered (Log)') layout = (confirmed + confirmed_log + dead + dead_log + recovered + recovered_log).cols(2) layout.opts( opts.Curve(width=400, height=250, framewise=True)) # pn_layout = pn.pane.HoloViews(layout) # return pn.Row(logtog, pn_layout) return layout
def elevation(data_dir: pathlib.Path): # load data grid_path = data_dir / "grid.npz" elevation_path = data_dir / "elevation.nc" x, y, simplices = load_grid_from_disk(grid_path) z = get_dataset(elevation_path) # create panel objects xyz_points = pd.DataFrame(dict(x=x, y=y, z=z.elev.isel(time=0).values)) points = hv.Points(xyz_points, kdims=["x", "y"], vdims="z") opts.defaults(opts.WMTS(width=1200, height=900)) def time_mesh(time): points.data.z = z.elev.sel(time=time).values return hv.TriMesh((simplices, points)) #, crs=ccrs.GOOGLE_MERCATOR) meshes = hv.DynamicMap(time_mesh, kdims='Time').redim.values(Time=z.time.values) datashaded_trimesh = (rasterize(meshes, aggregator='mean').opts( colorbar=True, cmap='Viridis', clim=(z.elev.values.min(), z.elev.values.max()), clabel='meters', tools=["hover"])) tiles = gv.WMTS('https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png') t_widget = pn.widgets.Select() @pn.depends(t_widget) def t_plot(time): return tiles * datashaded_trimesh header = get_header(title="## Time Steps") text = ''' # USAGE Use the toolbox on the right to zoom in/out. ''' footer = pn.Row(pn.pane.Markdown(text)) disclaimer = get_disclaimer() return pn.Column(header, t_plot, footer, disclaimer)
def grid(self, **kwargs): x = kwargs.get('x', self._obj.SCHISM_hgrid_node_x[:].values) y = kwargs.get('y', self._obj.SCHISM_hgrid_node_y[:].values) tri3 = kwargs.get( 'tri3', self._obj.SCHISM_hgrid_face_nodes.values[:, :3].astype(int)) opts.defaults(opts.WMTS(width=800, height=400)) tiles = gv.WMTS( 'https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png') nodes = pd.DataFrame({'longitude': x, 'latitude': y}) elems = pd.DataFrame(tri3, columns=['a', 'b', 'c']) points = gv.operation.project_points(gv.Points(nodes)) trimesh = gv.TriMesh((elems, points)).edgepaths return tiles * datashade(trimesh, precompute=True, cmap=['black'])
def contourf(self, var='depth', it=None, tiles=False, **kwargs): x = kwargs.get('x',self._obj.SCHISM_hgrid_node_x[:].values) y = kwargs.get('y',self._obj.SCHISM_hgrid_node_y[:].values) try: t = kwargs.get('t',self._obj.time.values) except: pass tes = kwargs.get('tri3',self._obj.SCHISM_hgrid_face_nodes.values[:,:4]) # sort out quads try: mask = np.isnan(tes)[:,3] tr3 = tes[mask][:,:3] tr3_ = quads_to_tris(tes[~mask]) if tr3_ : tri3 = np.append(tr3,tr3_,axis=0).astype(int) else: tri3 = tr3.astype(int) except: tri3 = tes.astype(int) z = kwargs.get('z',self._obj[var].values[it,:].flatten()) nodes = pd.DataFrame({'longitude':x,'latitude':y, '{}'.format(var):z}) elems = pd.DataFrame(tri3, columns=['a', 'b', 'c']) width = kwargs.get('width', 800) height = kwargs.get('height', 600) opts.defaults(opts.WMTS(width=width, height=height)) tile = gv.WMTS('https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png') points = gv.operation.project_points(gv.Points(nodes, vdims=['{}'.format(var)])) trimesh = gv.TriMesh((elems, points)) if tiles: return tile * rasterize(trimesh, aggregator='mean').opts(colorbar=True, cmap='Viridis', padding=.1, tools=['hover']) else: return rasterize(trimesh, aggregator='mean').opts(colorbar=True, cmap='Viridis', padding=.1, tools=['hover'],width=width,height=height)
def generateGraph(): df = processCSVMatrix(file) names = df.columns # submatrix for quicker development if (len(names) > 150): df = df.head(150)[names[0:150]] # set defaults for HoloViews extension('bokeh') renderer('bokeh').webgl = True defaults = dict(width=400, height=400, padding=0.1) opts.defaults(opts.EdgePaths(**defaults), opts.Graph(**defaults), opts.Nodes(**defaults)) G = from_pandas_adjacency(df) graph = Graph.from_networkx(G, circular_layout).opts(directed=False, width=600, height=600, arrowhead_length=0.0005) # Make a panel and widgets with param for choosing a layout return pn.Column(graph)
def plot_segregation(adata, save=False, filename=None): """Plot gabaergic and glutamaterig cell populations""" import holoviews as hv from holoviews import opts import pandas as pd hv.extension("matplotlib") df = pd.DataFrame(adata.uns["ligands"]).loc[["GABA", "L-glutamic acid" ]].stack().reset_index() df.columns = ["ligand", "cluster", "value"] df = df.sort_values(by="cluster", axis=0) opts.defaults( opts.Bars(stacked=True, xrotation=90, legend_position="right", ylabel="Ligand score")) bars = hv.Bars(df, kdims=["cluster", "ligand"]) if save is True: hv.save(bars, filename) return bars
def _plot_overlay(elevation, shadows): ''' ''' shadows = hv.Dataset( (np.arange(shadows.shape[2]), np.arange( shadows.shape[0]), np.arange(shadows.shape[1]), shadows), ['Time', 'x', 'y'], 'Shadows') elevation = hv.Dataset((np.arange( elevation.shape[0]), np.arange(elevation.shape[1]), elevation), ['x', 'y'], 'Elevation') opts.defaults( opts.Image('elevation', cmap='viridis', invert_yaxis=True), opts.Image('shadows', cmap='binary', invert_yaxis=True, alpha=0.7), opts.Overlay(show_legend=False)) elevation = elevation.to(hv.Image, ['x', 'y'], group='elevation') shadows = shadows.to(hv.Image, ['x', 'y'], group='shadows') return elevation * shadows
def setLibrary(library='bokeh'): ## Use Bokeh by default if (library == 'bokeh'): hv.extension('bokeh') hv.archive.auto(filename_formatter="{obj:.7}") ## For notebooks opts.defaults( opts.Scatter(tools=['hover'], width=700, height=700, padding=0.05), opts.HeatMap(tools=['hover'], width=700, height=700, labelled=[], xrotation=45, colorbar=True, cmap=('Blues'))) # opts.HeatMap(tools=['hover'], width=700, height=700, labelled=[], # xrotation=45, colorbar=True, cmap=('Blues'))) ## The library that Bokeh uses to export to SVG is not longer supported ## and so cannot be exported to SVG elif (library == 'matplotlib'): hv.extension('matplotlib') hv.output(fig='svg') opts.defaults( opts.Scatter(fig_size=300, padding=0.05), opts.HeatMap(fig_size=300, labelled=[], xrotation=45, colorbar=True, cmap=('Blues'))) else: raise NotImplementedError("Unknown plotting library.")
# Now we switch to holoviews to render the plot # Specify the plot render to use hv.extension('bokeh') hv.output(size=300) # Chord diagram with interactive components edgeList = edges[['Source', 'Target', 'weight']] # Within the holoviews dataset object we define kdim and vdims # Kdims are the independent variables which is Id in this example # Vdims are dependent variables cent_value and rank_value # By defining these here were can use them when creating the graph nodeDS = hv.Dataset(nodes_extended, 'Id', ['cent_value', 'rank_value']) # Coloured interactive chord diagram with node size determined by Vdims kwargs = dict(width=300, height=300, xaxis=None, yaxis=None) opts.defaults(opts.Nodes(**kwargs), opts.Graph(**kwargs)) graph = hv.Graph((edgeList, nodeDS), label='GoT season 1') graph.opts(cmap='Category20', edge_cmap='Category20', node_size='cent_value', edge_line_width=1, node_color=dim('Id').str(), edge_color=dim('Source').str()) graph.opts( opts.Chord(inspection_policy='nodes', tools=['hover'], edge_hover_line_color='green', node_hover_fill_color='red')) hv.save(graph, 'node_size_chord.html')
import panel as pn from bokeh.document import Document from holoviews import opts from panel.pane import HoloViews, Markdown from panel.template.fast.list import FastListDarkTheme, FastListTemplate from panel.tests.template.fast.test_fast_grid_template import ( INFO, _create_hvplot, _fast_button_card, _sidebar_items) ACCENT_COLOR = "#D2386C" opts.defaults(opts.Ellipse(line_width=3, color=ACCENT_COLOR)) def test_template_theme_parameter(): template = FastListTemplate(title="Fast", theme="dark") # Not '#3f3f3f' which is for the Vanilla theme doc = template.server_doc(Document()) assert doc.theme._json['attrs']['Figure'][ 'background_fill_color'] == "#181818" assert isinstance(template._get_theme(), FastListDarkTheme) def test_accepts_colors_by_name(): template = FastListTemplate( accent_base_color="red", header_background="green", header_color="white",
def animationFunction(trackData): hvData = hv.Dataset(trackData) kdims = ['MappedFixationPointX', 'MappedFixationPointY'] vdims = ['FixationDuration', 'user', 'StimuliName'] hvtracking = hvData.to(hv.Points, kdims, vdims, 'user_index') opts.defaults( opts.Points(alpha=0.8, line_color='black', cmap='Set1', width=600, height=450, color='user', size=dim('FixationDuration') * 0.03, tools=['hover'], title='DBL Animation', invert_yaxis=True, show_grid=True)) # Define custom widgets def animate_update(): user_index = animation_slider.value + 1 if user_index > end: user_index = start animation_slider.value = user_index # Update the holoviews plot by calling update with the user index. def slider_update(attrname, old, new): hvplot.update((new, )) callback_id = None def animate(): global callback_id print('animate() ', trackData.head()) # This always shows the old stimuli if button.label == '► Play': button.label = '❚❚ Pause' callback_id = doc.add_periodic_callback(animate_update, 600) else: button.label = '► Play' callback_id = doc.remove_periodic_callback(callback_id) start, end = hvData.range('user_index') animation_slider = Slider(start=start, end=end, value=0, step=1, title="User Index") animation_slider.on_change('value', slider_update) button = Button(label='► Play Animation', width=80) button.on_click(animate) doc = curdoc() hvplot = renderer.get_plot(hvtracking, doc) hvplot.update((1, )) plot = layout([[hvplot.state], [button, animation_slider]]) return plot
def frames(self, var="depth", tiles=False, **kwargs): x = kwargs.get("x", self._obj.SCHISM_hgrid_node_x[:].values) y = kwargs.get("y", self._obj.SCHISM_hgrid_node_y[:].values) try: t = kwargs.get("t", self._obj.time.values) except: pass tes = kwargs.get("tri3", self._obj.SCHISM_hgrid_face_nodes.values[:, :4]) # sort out quads try: mask = np.isnan(tes)[:, 3] tr3 = tes[mask][:, :3] tr3_ = quads_to_tris(tes[~mask]) if tr3_: tri3 = np.append(tr3, tr3_, axis=0).astype(int) else: tri3 = tr3.astype(int) except: tri3 = tes.astype(int) times = kwargs.get("times", self._obj.time.values) z = kwargs.get("z", self._obj[var].values[0, :].flatten()) zmin = self._obj[var].values.min() zmax = self._obj[var].values.max() nodes = pd.DataFrame({ "longitude": x, "latitude": y, "{}".format(var): z }) elems = pd.DataFrame(tri3, columns=["a", "b", "c"]) width = kwargs.get("width", 800) height = kwargs.get("height", 600) opts.defaults(opts.WMTS(width=width, height=height)) tile = gv.WMTS("https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png") points = gv.operation.project_points( gv.Points(nodes, vdims=["{}".format(var)])) trimesh = gv.TriMesh((elems, points)) def time_mesh(time): points.data[var] = self._obj[var].sel(time=time).values return gv.TriMesh((elems, points)) # , crs=ccrs.GOOGLE_MERCATOR) meshes = hv.DynamicMap(time_mesh, kdims=["Time"]).redim.values(Time=times) imesh = rasterize(meshes, aggregator="mean").opts(cmap="viridis", colorbar=True, padding=0.1, tools=["hover"], clim=(zmin, zmax)) if tiles: return hv.output(tile * imesh, holomap="scrubber", fps=1) else: return hv.output(imesh.opts(width=width, height=height), holomap="scrubber", fps=1)
def curve_defaults(cls, **kwargs): return opts.defaults( opts.Curve(**_dict_merge(kwargs, cls.DEFAULT_PLOT_OPTS)))
def point_defaults(cls, **kwargs): return opts.defaults( opts.Points(**_dict_merge(kwargs, cls.DEFAULT_POINT_OPTS)))
""" import numpy as np import holoviews as hv import dask.dataframe as dd from holoviews import opts from holoviews.operation.datashader import aggregate renderer = hv.renderer('bokeh') # Set plot and style options opts.defaults( opts.Curve(xaxis=None, yaxis=None, show_grid=False, show_frame=False, color='orangered', framewise=True, width=100), opts.Image(width=800, height=400, shared_axes=False, logz=True, xaxis=None, yaxis=None, axiswise=True), opts.HLine(color='white', line_width=1), opts.Layout(shared_axes=False), opts.VLine(color='white', line_width=1)) # Read the parquet file df = dd.read_parquet('./data/nyc_taxi_wide.parq').persist() # Declare points points = hv.Points(df, kdims=['pickup_x', 'pickup_y'], vdims=[]) # Use datashader to rasterize and linked streams for interactivity agg = aggregate(points, link_inputs=True, x_sampling=0.0001, y_sampling=0.0001) pointerx = hv.streams.PointerX(x=np.mean(points.range('pickup_x')), source=points) pointery = hv.streams.PointerY(y=np.mean(points.range('pickup_y')), source=points) vline = hv.DynamicMap(lambda x: hv.VLine(x), streams=[pointerx])