def triGraph(*args): dots = [[1, 200], [200, 1], [200, 100], [30, 20]] tris = [[0, 1, 2, 30], [3, 1, 2, 10]] res = hv.TriMesh((tris, verts), label=(variable)).options(filled=True) return res
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 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 triGraph(*args): global n, n4, tris, xrData, verts, variable, freedims n1 = [] n2 = [] n3 = [] selectors = {} idx = 0 for d in freedims: # WORKAROUND because Holoview is not working with a kdim with name "height" # See issue if d == "hi": selectors["height"] = args[idx] else: selectors[d] = args[idx] idx = idx + 1 if n is None: xrData = xr.open_dataset(getURL(), decode_cf=False) verts = np.column_stack( (xrData.clon_bnds.stack(z=('vertices', 'ncells')), xrData.clat_bnds.stack(z=('vertices', 'ncells')))) #not so performant f = 180 / math.pi for v in verts: v[0] = v[0] * f v[1] = v[1] * f l = len(xrData.clon_bnds) n1 = np.arange(l) n2 = n1 + l n3 = n2 + l n4 = np.column_stack((n1, n2, n3)) n = np.column_stack((n4, getattr(xrData, variable).isel(selectors))) verts = pd.DataFrame(verts, columns=['Longitude', 'Latitude']) tris = pd.DataFrame(n, columns=['v0', 'v1', 'v2', "var"], dtype=np.float64) tris['v0'] = tris["v0"].astype(np.int32) tris['v1'] = tris["v1"].astype(np.int32) tris['v2'] = tris["v2"].astype(np.int32) else: tris["var"] = getattr(xrData, variable).isel(selectors) print('vertices:', len(verts), 'triangles:', len(tris)) res = hv.TriMesh((tris, verts), label=(variable)).options(filled=True) return res
def buildTrimesh(self, *args): """ Function that builds up the TriMesh-Graph Args: Take multiple arguments. A value for every free dimension. Returns: The TriMesh-Graph object """ if self.dataUpdate == True: selectors = self.buildSelectors(args) self.logger.info("Selectors: " + str(selectors)) if self.aggDim == "None" or self.aggFn == "None": self.logger.info("No aggregation") self.tris["var"] = self.stub.GetTris( nc_pb2.TrisRequest(filename=self.url, variable=self.variable, alt=selectors[self.heightDim], time=selectors['time'], dom=self.dom)).data else: if self.aggFn == "mean": self.logger.info("mean aggregation with %s" % self.aggDim) self.tris["var"] = self.stub.GetTrisAgg( nc_pb2.TrisAggRequest(filename=self.url, variable=self.variable, aggregateFunction=0, dom=self.dom)).data elif self.aggFn == "sum": self.logger.info("sum aggregation %s" % self.aggDim) self.tris["var"] = self.stub.GetTrisAgg( nc_pb2.TrisAggRequest(filename=self.url, variable=self.variable, aggregateFunction=1, time=selectors['time'], dom=self.dom)).data else: self.logger.error( "Unknown Error! AggFn not None, mean, sum") # Apply unit factor = 1 self.tris["var"] = self.tris["var"] * factor res = hv.TriMesh((self.tris, self.verts), label=(self.title)) return res
def grid(data_dir: pathlib.Path): # load data grid_path = data_dir / "grid.npz" x, y, simplices = load_grid_from_disk(grid_path) # create panel objects xy_points = pd.DataFrame(dict(x=x, y=y)) points = hv.Points(xy_points, kdims=["x", "y"]) trimesh = hv.TriMesh((simplices, points)).edgepaths datashaded_trimesh = (datashade(trimesh, precompute=True, cmap=['black']).opts(width=1200, height=900, tools=["hover"])) tiles = gv.WMTS('https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png') layout = tiles * datashaded_trimesh header = get_header(title="## Mesh") disclaimer = get_disclaimer() return pn.Column(header, layout, disclaimer)
def triGraph(h): global n, n4, tris, xrData, verts, variable, freedims print("Called with %d" % h) n1 = [] n2 = [] n3 = [] #selectors = {"height":h,"time":Time} if n is None: xrData = xr.open_dataset(getURL(), decode_cf=False) verts = np.column_stack( (xrData.clon_bnds.stack(z=('vertices', 'ncells')), xrData.clat_bnds.stack(z=('vertices', 'ncells')))) #not so performant f = 180 / math.pi for v in verts: v[0] = v[0] * f v[1] = v[1] * f l = len(xrData.clon_bnds) n1 = np.arange(l) n2 = n1 + l n3 = n2 + l n4 = np.column_stack((n1, n2, n3)) n = np.column_stack((n4, getattr(xrData, variable).isel(height=h, time=0))) verts = pd.DataFrame(verts, columns=['Longitude', 'Latitude']) tris = pd.DataFrame(n, columns=['v0', 'v1', 'v2', "var"], dtype=np.float64) tris['v0'] = tris["v0"].astype(np.int32) tris['v1'] = tris["v1"].astype(np.int32) tris['v2'] = tris["v2"].astype(np.int32) else: tris["var"] = getattr(xrData, variable).isel(height=h, time=0) print('vertices:', len(verts), 'triangles:', len(tris)) res = hv.TriMesh((tris, verts), label=(variable)).options(filled=True) return res
def gen_trimesh(value): if value == 'M2 Elevation Amplitude': z = nc['Amp'][0, :] elif value == 'S2 Elevation Amplitude': z = nc['Amp'][1, :] elif value == 'N2 Elevation Amplitude': z = nc['Amp'][2, :] elif value == 'O1 Elevation Amplitude': z = nc['Amp'][3, :] elif value == 'K1 Elevation Amplitude': z = nc['Amp'][4, :] else: z = -nc['depth'][:] v = np.vstack((u['nodes']['x'], u['nodes']['y'], z)).T verts = pd.DataFrame(v, columns=['x', 'y', 'z']) points = gv.operation.project_points(gv.Points(verts, vdims=['z'])) label = '{} (m)'.format(value) return hv.TriMesh((tris, points), label=label)
class Unstructured2D(Unstructured): tri_mesh = param.ClassSelector(default=hv.TriMesh(data=()), class_=hv.TriMesh) def __init__(self, **params): super(Unstructured2D, self).__init__(**params) def view_elements(self, agg='any', line_color='black', cmap='black'): """ Method to display the mesh as wireframe elements""" if self.elements_toggle: # return datashade(self.tri_mesh.edgepaths.opts(line_color=line_color), aggregator=agg, # precompute=True, cmap=cmap) return datashade( self.tri_mesh.edgepaths.opts( opts.TriMesh(edge_cmap='yellow', edge_color='yellow'))) else: return hv.Curve([]) def view_elevation(self): """ Method to display the mesh as continuous color contours""" if self.elevation_toggle: return rasterize(self.tri_mesh, aggregator=ds.mean('z'), precompute=True) else: return hv.Curve([]) def view_mesh(self, agg='any', line_color='black', cmap='black'): elements = self.view_elements(agg=agg, line_color=line_color, cmap=cmap) elevation = self.view_elevation() return elevation * elements
def grid(dataset: xr.Dataset): # extract data x, y, simplices = extract_grid(dataset) # create panel objects xy_points = pd.DataFrame(dict(longitude=x, latitude=y)) points = hv.Points(xy_points, kdims=["longitude", "latitude"]) trimesh = hv.TriMesh((simplices, points)).edgepaths datashaded_trimesh = ( datashade(trimesh, precompute=True, cmap=['black']).opts(width=1200, height=900) #, tools=["hover"]) ) tiles = gv.WMTS('https://b.tile.openstreetmap.org/{Z}/{X}/{Y}.png') layout = tiles * datashaded_trimesh header = get_header(title="## Mesh") disclaimer = get_disclaimer() text = ''' # USAGE Use the toolbox on the right to zoom in/out. ''' footer = pn.Row(pn.pane.Markdown(text)) return pn.Column(header, layout, footer, disclaimer)
def time_mesh(time): points.data.z = z.elev.sel(time=time).values return hv.TriMesh((simplices, points)) #, crs=ccrs.GOOGLE_MERCATOR)
def plotter_2D_test_histogram(name): # IMPORTING AND FOMRATTING DATA # ===| open root demo file with pedestal and noise values |=== t = uproot.open("Data/CalibTree.root")["calibTree"] #padData = t.pandas.df("Pedestals", flatten = False) padData = t.array(name) # ===| pad plane plane meta data |=== d = pd.read_csv("Data/pad_plane_data.txt", sep='\t') # ===| fuction to prepare input root demo file for plotting |=== [vcor, vtri] = configureData(padData, d) # PLOTTING hd.shade.cmap = [ '#FBFCBF', '#FD9F6C', '#DD4968', '#8C2980', '#3B0F6F', '#000003' ] cvs = ds.Canvas(plot_height=400, plot_width=400) trim = hv.TriMesh((vtri, hv.Points(vcor, vdims='za'))).opts(show_grid=True) trim2 = hv.TriMesh((vtri, hv.Points(vcor, vdims='zc'))).opts(show_grid=True) trim.opts(colorbar=True) trim.opts(cmap='Blues') trimesh = hd.datashade(trim, aggregator=ds.mean('za'), precompute=True, link_inputs=False) trimesh2 = hd.datashade(trim2, aggregator=ds.mean('zc'), precompute=True, link_inputs=False) trimesh.opts(height=450, width=450, show_grid=False, xaxis=None, yaxis=None) trimesh2.opts(height=450, width=450, show_grid=False, xaxis=None, yaxis=None) # ADDING INTERACTIVITY # Small hover tool tooltips_small = [("X:", "$x"), ("Y:", "$y"), ("Value:", "NaN")] hover_small = HoverTool(tooltips=tooltips_small) dynamic = hv.util.Dynamic(hd.aggregate(trim, width=30, height=30, streams=[RangeXY]), operation=hv.QuadMesh) \ .opts(tools=[hover_small], alpha=0, hover_alpha=0, hover_line_color='black',hover_line_alpha=0) # Sector select hover tool sector_edge_phi = np.linspace(0, np.pi * 2, 19) sector_edge_r = np.array([850, 2530]) Phi, R = np.meshgrid(sector_edge_phi, sector_edge_r) Qx = np.cos(Phi) * np.abs(R) Qy = np.sin(Phi) * np.abs(R) Z = np.linspace(0, 17, 18).reshape(1, 18) #Z = Z*0 hover_data = dict(x=Qx, y=Qy, z=Z) tooltips_a = [("Side", "A"), ("Sector", "@z")] tooltips_c = [("Side", "C"), ("Sector", "@z")] hover_a = HoverTool(tooltips=tooltips_a) hover_c = HoverTool(tooltips=tooltips_c) qmesh_a = hv.QuadMesh(hover_data)\ .opts(tools=[hover_a,'tap'], alpha=0, hover_fill_alpha=0.1, hover_color='white', hover_line_color='black',hover_line_alpha=1) qmesh_c = hv.QuadMesh(hover_data)\ .opts(tools=[hover_c], alpha=0, hover_fill_alpha=0.1, hover_color='white', hover_line_color='black',hover_line_alpha=1) # CREATING OUTPUT tpc_plot_a = trimesh * qmesh_a * hv.Text(0, 0, 'A', fontsize=40) tpc_plot_c = trimesh2 * qmesh_c * hv.Text(0, 0, 'C', fontsize=40) final_layout = (tpc_plot_a + tpc_plot_c).opts(merge_tools=False) return final_layout