def request_basemap_tiles( lon, lat, dx, dy, url='https://mt1.google.com/vt/lyrs=s&x={X}&y={Y}&z={Z}', utm=False): if utm == False: extents = (lon - dx, lat - dy, lon + dx, lat + dy) tiles = gv.WMTS(url, extents=extents) location = gv.Points([], vdims="vertices") point_stream = PointDraw(source=location) tiles = gv.WMTS(url, extents=extents) return tiles else: u = utm.from_latlon(lat, lon) utm_lon = u[0] utm_lat = u[1] utm_zone = u[2] utm_zone_code = u[3] extents = utm_lon - dx, utm_lat - dy, utm_lon + dx, utm_lat + dy tiles = gv.WMTS(url, extents=extents, crs=ccrs.UTM(utm_zone)) return tiles, utm_zone
def __defineMap(self): """define a backgound map tile source""" from bokeh.models import WMTSTileSource url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' wmts = WMTSTileSource(url=url) mapTiles = gv.WMTS(wmts) return mapTiles
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 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 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 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 pick_heading_from_map(image_file_name, camera_center_lon, camera_center_lat, dx=0.015, dy=0.015): # Google Satellite tiled basemap imagery url url = 'https://mt1.google.com/vt/lyrs=s&x={X}&y={Y}&z={Z}' # TODO # # allow large images to be plotted or force resampling to thumbnail # # load the image with xarray and plot with hvplot to handle larger images img, subplot_width, subplot_height = hv_plot_raster(image_file_name) # create the extent of the bounding box extents = (camera_center_lon - dx, camera_center_lat - dy, camera_center_lon + dx, camera_center_lat + dy) # run the tile server tiles = gv.WMTS(url, extents=extents) points = gv.Points( [(camera_center_lon, camera_center_lat, 'camera_center')], vdims='location') point_stream = hv.streams.PointDraw(source=points) base_map = (tiles * points).opts( opts.Points(width=subplot_width, height=subplot_height, size=10, color='black', tools=["hover"])) row = pn.Row(img, base_map) server = row.show(threaded=True) condition = True while condition == True: try: if len(point_stream.data['x']) == 2: server.stop() condition = False except: pass projected = gv.operation.project_points(point_stream.element, projection=ccrs.PlateCarree()) df = projected.dframe() df['location'] = ['camera_center', 'flight_direction'] heading_lon = df.x[1] heading_lat = df.y[1] heading = hsfm.geospatial.calculate_heading(camera_center_lon, camera_center_lat, heading_lon, heading_lat) return heading
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 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 change_basemap(**kw): print("change_basemap: " + str(kw)) url = kw['url'] alpha = kw["alpha"] tiles = gv.WMTS(url).options(global_extent=True, height=400, width=700, alpha=alpha) return tiles * boxes
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 bbox_selector(metadata_csv=None, metadata_csv_lon_column='Longitude', metadata_csv_lat_column='Latitude', bounds=(-124.5, 40, -108, 50), basemap_url=None): ''' Draw bounding box (hold shift) on basemap and return vertices. Select bounding box to delete. ''' OpenTopoMap = 'https://tile.opentopomap.org/{Z}/{X}/{Y}.png' OpenStreetMap = 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png' GoogleHybrid = 'https://mt1.google.com/vt/lyrs=y&x={X}&y={Y}&z={Z}' GoogleSatellite = 'https://mt1.google.com/vt/lyrs=s&x={X}&y={Y}&z={Z}' GoogleRoad = 'https://mt1.google.com/vt/lyrs=m&x={X}&y={Y}&z={Z}' GoogleTerrain = 'http://mt0.google.com/vt/lyrs=p&hl=en&x={X}&y={Y}&z={Z}' GoogleTerrainOnly = 'http://mt0.google.com/vt/lyrs=t&hl=en&x={X}&y={Y}&z={Z}' ESRIImagery = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' Wikimedia = 'https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png' print('Toggle Box Edit Tool and hold shift to draw bounding box.') if not basemap_url: url = GoogleSatellite basemap = gv.WMTS(url, extents=bounds).opts(aspect=1, frame_height=500) if metadata_csv: df = pd.read_csv(metadata_csv) df = df.loc[(df[metadata_csv_lat_column] < bounds[3]) & (df[metadata_csv_lat_column] > bounds[1]) & (df[metadata_csv_lon_column] > bounds[0]) & (df[metadata_csv_lon_column] < bounds[2])].reset_index( drop=True) coords = list( zip(df[metadata_csv_lon_column].values, df[metadata_csv_lat_column].values)) points = gv.Points(coords).opts(size=10, frame_height=500) else: points = gv.Points({}).opts(size=10, frame_height=500) box_poly = gv.Polygons([{}]).opts( opts.Polygons(fill_alpha=0, line_color='yellow', line_width=3, selection_fill_color='red')) box_stream = BoxEdit(source=box_poly) return basemap * points * box_poly, box_stream
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 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 make_view(self, x_range=None, y_range=None, **kwargs): options = dict(width=800, height=475, xaxis=None, yaxis=None) map_tiles = gv.WMTS(tiles['ESRI']).opts(style=dict(alpha=self.alpha), plot=options) points = hv.Points(nyc_taxi, kdims=[self.plot + '_x', self.plot + '_y'], vdims=['passenger_count']) selected = points.select(passenger_count=self.passengers) taxi_trips = datashade(selected, x_sampling=1, y_sampling=1, width=800, height=475, cmap=inferno, dynamic=False) return map_tiles * taxi_trips
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 plot_map(data, label, agg_data, agg_name, cmap): url = "http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{Z}/{Y}/{X}.png" geomap = gv.WMTS(url) points = hv.Points(gv.Dataset(data, kdims=['x', 'y'], vdims=[agg_name])) agg = datashade(points, element_type=gv.Image, aggregator=agg_data, cmap=cmap) zip_codes = dynspread(agg, threshold=T, max_px=PX) hover = hv.util.Dynamic(rasterize(points, aggregator=agg_data, width=50, height=25, streams=[RangeXY]), operation=hv.QuadMesh) hover = hover.options(cmap=cmap) img = geomap * zip_codes * hover img = img.relabel(label) return img
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 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)
import dask.dataframe as dd import holoviews as hv import geoviews as gv from bokeh.models import WMTSTileSource from holoviews.operation.datashader import datashade url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' wmts = WMTSTileSource(url=url) # 1. Instead of using hv.extension, declare that we are using Bokeh and grab the renderer renderer = hv.renderer('bokeh') # 2. Declare points and datashade them ddf = dd.read_csv('../data/nyc_taxi.csv', usecols=['pickup_x', 'pickup_y']).persist() shaded = datashade(hv.Points(ddf)) # Set some plot options app = gv.WMTS(wmts) * shaded.opts(plot=dict(width=800, height=600)) # 3. Instead of Jupyter's automatic rich display, render the object as a bokeh document doc = renderer.server_doc(app) doc.title = 'HoloViews Bokeh App'
def callback(self): return (gv.WMTS(self.tile_server) * gv.tile_sources.StamenLabels())
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)
from bokeh.models import WMTSTileSource from holoviews.operation.datashader import datashade, aggregate, shade shade.cmap = fire hv.extension('bokeh') renderer = hv.renderer('bokeh').instance(mode='server') # Load data ddf = dd.read_parquet(os.path.join(os.path.dirname(__file__),'..','..','..','data','nyc_taxi_wide.parq')).persist() from bokeh.models import WMTSTileSource url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' wmts = gv.WMTS(WMTSTileSource(url=url)) stream = hv.streams.Stream.define('HourSelect', hour=0)() points = hv.Points(ddf, kdims=['dropoff_x', 'dropoff_y']) dmap = hv.util.Dynamic(points, operation=lambda obj, hour: obj.select(dropoff_hour=hour).relabel('Hour of Day: %d' % hour), streams=[stream]) # Apply aggregation aggregated = aggregate(dmap, link_inputs=True, streams=[hv.streams.RangeXY], width=1200, height=600) # Shade the data class ColormapPicker(hv.streams.Stream): colormap = param.ObjectSelector(default=cm_n["fire"], objects=cm_n.values()) cmap_picker = ColormapPicker(rename={'colormap': 'cmap'}, name='') shaded = shade(aggregated, link_inputs=True, streams=[cmap_picker])
import os import holoviews as hv, geoviews as gv, param, parambokeh, dask.dataframe as dd, cartopy.crs as crs from holoviews.operation.datashader import datashade from holoviews.streams import RangeXY from colorcet import cm_n hv.extension('bokeh', logo=False) df = dd.read_parquet( os.path.join(os.path.dirname(__file__), '..', '..', 'data', 'osm-1billion.snappy.parq')).persist() url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' map_tiles = gv.WMTS(url, crs=crs.GOOGLE_MERCATOR) opts1 = dict(width=1000, height=600, xaxis=None, yaxis=None, bgcolor='black', show_grid=False) opts2 = dict(width=1000, height=600, x_sampling=1, y_sampling=1, dynamic=False) class OSMExplorer(hv.streams.Stream): alpha = param.Magnitude(default=0.75, doc="Map opacity") colormap = param.ObjectSelector(default=cm_n["fire"], objects=cm_n.values()) def make_view(self, x_range, y_range, **kwargs):
def get_tiles() -> gv.Tiles: tiles = gv.WMTS("http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png") return tiles
# Apply datashading to census data x_range, y_range = ((-13884029.0, -7453303.5), (2818291.5, 6335972.0)) # Continental USA shade_defaults = dict(x_range=x_range, y_range=y_range, x_sampling=10, y_sampling=10, width=1200, height=682, color_key=color_key, aggregator=ds.count_cat('race'),) shaded = datashade(census_points, **shade_defaults) shapefile = {'state_house': 'cb_2016_48_sldl_500k', 'state_senate': 'cb_2016_48_sldu_500k', 'us_house': 'cb_2015_us_cd114_5m'} # Define tile source tile_url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' tiles = gv.WMTS(WMTSTileSource(url=tile_url)) DIVISION_ID_RE = { 'state_house': re.compile(r'ocd-division/country:us/state:[a-z]{2}/sldl:([0-9]+)'), 'state_senate': re.compile(r'ocd-division/country:us/state:[a-z]{2}/sldu:([0-9]+)'), 'us_house': re.compile(r'ocd-division/country:us/state:[a-z]{2}/cd:([0-9]+)'), 'county': re.compile(r'ocd-division/country:us/state:[a-z]{2}/county:[^\/]+/council_district:([0-9]+)'), 'city_council': re.compile(r'ocd-division/country:us/state:[a-z]{2}/place:[^\/]+/council_district:([0-9]+)'), } # engine = create_engine('mysql+mysqlconnector://atxhackathon:atxhackathon@atxhackathon.chs2sgrlmnkn.us-east-1.rds.amazonaws.com:3306/atxhackathon', echo=False) # cnx = engine.raw_connection() # vtd_data = pd.read_sql('SELECT * FROM vtd2016preselection', cnx)
# EC2015 data in netCDF form, accessed via OPeNDAP. # Here we use a UGRID-ized version of http://tds.renci.org:8080/thredds/dodsC/DataLayers/Tides/ec2015_tidaldb/f53.nc.html url = 'http://gamone.whoi.edu/thredds/dodsC/usgs/vault0/models/tides/ec2015/f53.ncml' nc = netCDF4.Dataset(url) # Use gridgeo to get mesh from UGRID compliant dataset u = ugrid(nc) tris = pd.DataFrame(u['faces'].astype('int'), columns=['v0', 'v1', 'v2']) # In[7]: dpdown.observe(on_change) # In[8]: tiles = gv.WMTS( 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' ) dynamic_trimesh = hv.DynamicMap(gen_trimesh, streams=[value_stream]) plot = tiles * rasterize( dynamic_trimesh, aggregator=ds.mean('z'), precompute=True) # In[9]: get_ipython().run_line_magic( 'opts', "Image [colorbar=True clipping_colors={'NaN': (0, 0, 0, 0)}] (cmap=palettable.cubehelix.perceptual_rainbow_16.mpl_colormap)" ) get_ipython().run_line_magic('opts', 'WMTS [width=700 height=400]') plot # In[10]: