Esempio n. 1
0
def mapPoint(id=11):

    #bbox
    minx, maxx, miny, maxy = boundingBox(nahalal_basin)

    current_pnt = gv.Points(smp_pnt.query("id=={}".format(id)))
    pnts = gv.Points(smp_pnt, vdims=["id", "description"])
    basin = gv.Contours(nahalal_basin)

    # hovertool
    hover = HoverTool(tooltips=[("Point #",
                                 "@id"), ("Description", '@description')])

    points_map = ((
        gts.EsriImagery.opts(alpha=0.4) * gts.OSM.opts(alpha=0.4) *
        basin.opts(color='chocolate', line_width=2, alpha=.5) *
        gv.Path(kishon).opts(line_width=3.5,
                             alpha=0.4,
                             line_color="darkblue",
                             line_dash="dashed") *
        gv.Path(nahalal).opts(line_width=2.5, alpha=0.4, line_color="blue") *
        gv.Path(nahalal_sub).opts(
            line_width=2, line_dash="dashdot", alpha=0.4, line_color="blue") *
        pnts.opts(size=13, alpha=0.6, tools=[hover]) *
        current_pnt.opts(size=20, color="purple")
        # * gv.Contours(interest_zone).opts(alpha=0)
    ).opts(width=500,
           height=375,
           fontsize={
               'labels': labels_fsize,
               'xticks': tick_fsize,
               'yticks': tick_fsize
           }).redim.range(Longitude=(minx, maxx), Latitude=(miny, maxy)))

    return points_map
Esempio n. 2
0
 def inner(departure_lat, departure_lon, arrival_lat, arrival_lon):
     opts = {
         'xaxis': None,
         'yaxis': None,
         'responsive': True,
         'active_tools': ['wheel_zoom']
     }
     departure_station_id = closest_station(self.stations,
                                            departure_lat,
                                            departure_lon)
     arrival_station_id = closest_station(self.stations, arrival_lat,
                                          arrival_lon)
     unselected_stations = self.stations.loc[
         ~self.stations['station_id'].
         isin([departure_station_id, arrival_station_id])]
     departure_station = self.stations.loc[[departure_station_id]]
     arrival_station = self.stations.loc[[arrival_station_id]]
     unselected = gv.Points(
         unselected_stations, ['lat', 'lon'],
         ['station_name']).opts(tools=[self.unselected_hover])
     departure = gv.Points(departure_station, ['lat', 'lon'],
                           ['station_name']).opts(
                               tools=[self.departure_hover],
                               size=5,
                               color='black')
     arrival = gv.Points(arrival_station, ['lat', 'lon'],
                         ['station_name']).opts(
                             tools=[self.arrival_hover],
                             size=5,
                             color='red')
     return (self.tiles * unselected * departure * arrival).opts(**opts)
Esempio n. 3
0
    def plotthis(datetime, regions='Whole_East_Coast'):
        dat = datetime
        # datetostr=result.strftime("%Y%b%d%H")
        dt = parse(str(dat))
        yr = dt.year
        mn = dt.month
        d = dt.day
        hr = dt.hour
        mi = dt.minute

        if hr < 10:

            hr = '0' + str(hr)
        else:
            d = str(d)
            hr = str(hr)
        if int(d) < 10:
            d = '0' + str(d)
        else:
            d = str(d)
        varname = 'Steepn_' + str(yr) + '0' + str(mn) + str(
            d) + '_' + hr + '0000'

        x = Xp.flatten()
        y = Yp.flatten()
        z = datamat[varname]

        if regions is 'Odisha':
            z = np.where(((Xp >= 85) & (Xp <= 88) & (Yp >= 19) & (Yp <= 22)),
                         z, np.nan).flatten()
        elif regions is 'Andra_Pradesh':
            z = np.where(((Xp >= 79) & (Xp <= 85) & (Yp >= 13) & (Yp <= 19)),
                         z, np.nan).flatten()
        elif regions is 'Tamil_Nadu':
            z = np.where(((Xp >= 77) & (Xp <= 83) & (Yp >= 7) & (Yp <= 14)), z,
                         np.nan).flatten()
        elif regions is 'Whole_East_Coast':
            z = z.flatten()

        else:
            #         data = get_data4region(data,**odisha)
            z = z.flatten()

        # z = z.flatten()
        Longitude = x
        Latitude = y
        HS = z

        pts = np.stack((Longitude, Latitude, HS)).T
        verts = pd.DataFrame(np.stack((Longitude, Latitude, HS)).T,
                             columns=['Longitude', 'Latitude', 'HS'])

        # openStreet Background.
        tri_sub = tri_new.apply(lambda x: x - 1)
        ggpoints = gv.Points(verts, vdims=['HS'])
        ggsubraster = rasterize(gv.TriMesh((tri_sub, gv.Points(verts))))

        tri = gv.TriMesh((tri_sub, gv.Points(verts)))

        return tri
Esempio n. 4
0
def geoview_flat_plot(region_da, time_sel=0, level_sel=False, wide_chile=True):
    
    if type(level_sel) is int:
        da = region_da.isel(level=level_sel)
    else:
        da = region_da
    
    gv_ds = gv.Dataset(da.isel(time=time_sel))
    plot = gv_ds.to(gv.Image,  ['lon', 'lat'], 't', 'time').opts(cmap='viridis', 
                                                                colorbar=True)
    extras = []
    if wide_chile:
        easter_island_text = gv.Text(-104.360481, -24.104671, 'Easter Island').opts(color='white')
        easter_island_point = gv.Points([(-109.360481, -27.104671)]).opts(color='red')

        easter = easter_island_point * easter_island_text

        falkland_islands_text = gv.Text(-49.563412, -56.820557, 'Falklands').opts(color='white')
        falkland_islands_point = gv.Points([(-51.563412, -59.820557)]).opts(color='red')

        falkland = falkland_islands_point * falkland_islands_text
        
        extras.append(easter * falkland)
    
    plot = contours(plot, filled=True, overlaid=True)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        
        final_plot = plot * gf.coastline
        for extra in extras:
            final_plot *= extra
        gv.output(final_plot)
Esempio n. 5
0
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
Esempio n. 6
0
    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
Esempio n. 7
0
def geodframe_to_geoviews(obj, geo_type, crs):
    """Converts the geometry in a GeoPandas GeoDataFrame into a list formatted for Geoviews
        only accepts one data type per object

        Parameters
        ----------
        obj - geopandas geodataframe with geometry column of shapely objects
        geo_type - string - type of geometry to extract from gdf 'point' or 'polygon'.
            Only one geometry type can be extracted from a gdf
        crs - cartopy.crs projection
        """

    if geo_type is 'point':
        data = [item.coords for item in obj.geometry]
        element = gv.Points(data, crs=crs)
        for col in obj.columns:
            if col is not 'geometry':
                element = element.add_dimension(col, 0, obj[col], True)

    elif geo_type is 'polygon':
        data = [item.coords for item in obj.geometry.boundary]
        element = gv.Polygons(data, crs=crs)
        for col in obj.columns:
            if col is not 'geometry':
                element = element.add_dimension(col, 0, obj[col], True)
    else:
        raise IOError('Shapely geometry type {} not supported'.format(
            obj.geometryType()))

    return element
Esempio n. 8
0
    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 industry_size_map(data_list, data_values_list, industry_col):
    for ind, data_df in enumerate(data_list):
        renderer = gv.renderer('bokeh')
        gv_points = gv.Points(data_df, ['longitude', 'latitude'],
                              [industry_col, 'YeshuvAtarSvivatiMenifa'])
        data_df.rename(columns={industry_col: ""})
        tooltips = [("Amount", "@" + industry_col),
                    ("Location", '@YeshuvAtarSvivatiMenifa')]
        hover = HoverTool(tooltips=tooltips)
        # map_plot =gvts.CartoLight.options(width=500, height=800, xaxis=None, yaxis=None, show_grid=False) * gv_points
        map_plot = (gvts.CartoLight * gv_points).opts(
            opts.Points(width=400,
                        height=700,
                        alpha=0.3,
                        hover_line_color='black',
                        color=color_looper_bokeh(ind),
                        line_color='black',
                        xaxis=None,
                        yaxis=None,
                        tools=[hover],
                        size=dim(industry_col) * 10,
                        hover_fill_color=None,
                        hover_fill_alpha=0.5))
        dir = save_geoviews(map_plot=map_plot,
                            file_name="map " + industry_col + "-" +
                            data_values_list[ind],
                            renderer=renderer,
                            output_folder="Output_files")
Esempio n. 10
0
    def getGeoElementFromData(self, data,vdims=None):

        arrayGeomType = data.geom_type.unique()

        for geomType in arrayGeomType:

            data = data[data['geometry'].apply(lambda x: x.geom_type == geomType)]

            if geomType in POINT:
                geomNdOverlay = gv.Points(data, vdims=vdims,crs=ccrs.GOOGLE_MERCATOR,  group=POINT[0])


            elif geomType in LINESTRING:
                data['geometry'] = data.simplify(SOFT_SIMPLIFY, True)
                geomNdOverlay = gv.Path(data, vdims=vdims,crs=ccrs.GOOGLE_MERCATOR, group=LINESTRING[0])

            elif geomType in MULTILINESTRING:
                data['geometry'] = data.simplify(SOFT_SIMPLIFY, True)
                geomNdOverlay = gv.Path(data, vdims=vdims, crs=ccrs.GOOGLE_MERCATOR,
                                        group=MULTILINESTRING[0])
            elif geomType in POLYGONE:
                data['geometry'] = data.simplify(STRONG_SIMPLIFY, True)
                geomNdOverlay = gv.Polygons(data, vdims=vdims, crs=ccrs.GOOGLE_MERCATOR,  group=POLYGONE[0])

            elif geomType in MULTIPOLYGONE:
                data['geometry'] = data.simplify(STRONG_SIMPLIFY, True)
                geomNdOverlay = gv.Polygons(data, vdims=vdims, crs=ccrs.GOOGLE_MERCATOR,
                                            group=MULTIPOLYGONE[0])
            elif geomType in GEOMETRYCOLLECTION:
                data = data.explode()
                geomNdOverlay = GeomUtil.getGeoElementFromData(self,data=data)
            else:
                return None

        return geomNdOverlay.opts(tools=['hover', 'tap'])
Esempio n. 11
0
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
Esempio n. 12
0
def plotthis(z, regions='w'):

    if regions is 'O':
        z = np.where(((x >= 2) & (x <= 3) & (y >= 51) & (y <= 52)), z,
                     np.nan).flatten()

    elif regions is 'A':
        z = np.where(((x >= 3) & (x <= 4) & (y >= 54) & (y <= 57)), z,
                     np.nan).flatten()

    elif regions is 'T':
        z = np.where(((x >= 0) & (x <= 3) & (y >= 51) & (y <= 57)), z,
                     np.nan).flatten()

    #         else:
    #         #         data = get_data4region(data,**odisha)
    #             z=z.flatten()
    print("lx:", len(x), "ly:", len(y), "lz:", len(z))
    print("z", z)
    verts = pd.DataFrame(np.stack((x, y, z)).T, columns=['X', 'Y', 'Z'])

    # #openStreet Background.
    # tri_sub = cf.apply(lambda x: x - 1)
    # tri_sub=tri_sub[:10]

    tri = gv.TriMesh((triangles, gv.Points(verts)))

    return tri
Esempio n. 13
0
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
Esempio n. 14
0
def get_trimesh(
    dataset: xr.Dataset,
    longitude_var: str,
    latitude_var: str,
    elevation_var: str,
    simplices_var: str,
    time_var: str,
    timestamp: str | pd.Timestamp,
) -> gv.TriMesh:
    simplices = dataset[simplices_var].values
    columns = [longitude_var, latitude_var, elevation_var]
    if timestamp == "MAXIMUM":
        points_df = dataset.max(time_var)[columns].to_dataframe()
    elif timestamp == "MINIMUM":
        points_df = dataset.min(time_var)[columns].to_dataframe()
    else:
        points_df = dataset.sel(
            {time_var:
             timestamp})[columns].to_dataframe().drop(columns=time_var)
    points_df = points_df.reset_index(drop=True)
    points_gv = gv.Points(points_df,
                          kdims=[longitude_var, latitude_var],
                          vdims=elevation_var)
    trimesh = gv.TriMesh((simplices, points_gv))
    return trimesh
Esempio n. 15
0
 def reproject_points(self):
     """Method to set the mesh points as gv points (projected if necessary)"""
     # reproject the points
     self.mesh_points = gv.operation.project_points(
         gv.Points(self.verts[['x', 'y', 'z']],
                   vdims=['z'],
                   crs=self.projection.get_crs()),
         projection=ccrs.GOOGLE_MERCATOR)
Esempio n. 16
0
def pick_points_from_basemap_tiles(tiles, utm_zone=None):

    if utm_zone == None:
        location = gv.Points([], vdims="vertices")

    else:
        location = gv.Points([], vdims="vertices", crs=ccrs.UTM(utm_zone))

    point_stream = PointDraw(source=location)
    base_map = (tiles * location).opts(
        opts.Points(width=500,
                    height=500,
                    size=12,
                    color='black',
                    tools=["hover"]))
    app = pn.panel(base_map)
    return app, point_stream
Esempio n. 17
0
    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,
            )
Esempio n. 18
0
 def _load(self):
     self.scatter = pd.read_csv(self.filepath,
                                sep=',',
                                names=['x', 'y', 'z'])
     self.scatter_pts = gv.Points(data=self.scatter,
                                  crs=self.scatter_projection.get_crs(),
                                  vdims=['z'],
                                  kdims=['x', 'y'])
     self.scatter_toggle = True
Esempio n. 19
0
def update_map_val(attr, old, new):
    global selection, vizual, gvplot, hvplot, heatmap, feats, points, world_map, temp_feats
    max_cur_feature = loc_feats[choice.value].max()
    min_cur_feature = loc_feats[choice.value].min()
    new_loc_feats = temp_feats.loc[(temp_feats[choice.value] <= new[1])
                                   & (temp_feats[choice.value] >= new[0])]
    feats = gv.Dataset(new_loc_feats,
                       kdims=['Longitude', 'Latitude', choice.value])
    points = feats.to(gv.Points, ['Longitude', 'Latitude'], [choice.value])
    if len(new_loc_feats) <= 20000:
        world_map = gv.Points(points).options(
            'Points',
            size=5,
            cmap='viridis',
            colorbar=True,
            tools=TOOLS,
            color_index=2,
            width=900,
            height=800,
            colorbar_opts={'scale_alpha': 0.5},
            fill_alpha=0.5,
            line_alpha=0.5)
    else:
        world_map = decimate(gv.Points(points), max_samples=20000).options(
            'Points',
            size=5,
            cmap='viridis',
            colorbar=True,
            tools=TOOLS,
            color_index=2,
            width=900,
            height=800,
            colorbar_opts={'scale_alpha': 0.5},
            fill_alpha=0.5,
            line_alpha=0.5)
    selection = hv.streams.Selection1D(source=world_map)
    heatmap = hv.DynamicMap(selected_points, streams=[selection])
    box = hv.streams.BoundsXY(source=world_map)
    zoom = hv.DynamicMap(test_bounds, streams=[box])
    hvplot = renderer.get_plot(heatmap, curdoc())
    gvplot = renderer.get_plot(world_map, curdoc())
    bvplot = renderer.get_plot(zoom, curdoc())
    vizual.children[1].children = [gvplot.state, hvplot.state, bvplot.state]
Esempio n. 20
0
    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
Esempio n. 21
0
    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 createOverlay(self,**kwargs):

        traceP = kwargs.get("traceParam")
        data = traceP.data
        label  = kwargs.get("label")
        self.param.variable_taille_point.objects = traceP.listeEntier
        self.param.variable_couleur.objects = data.columns

        if not self.variable_taille_point:
            self.silently = True
            self.variable_taille_point = traceP.listeEntier[0]

        if not self.variable_couleur:
            self.silently = True
            self.variable_couleur = traceP.listeEntier[0]


        vdims = traceP.listeEntier
        kdims = list(data.columns)[5:-1]

        size = self.variable_taille_point

        arrayGeomType = data.geom_type.unique()

        for geomType in arrayGeomType:

            data = data[data['geometry'].apply(lambda x: x.geom_type == geomType)]

            if geomType in POINT:
                geomNdOverlay = gv.Points(data, vdims=vdims, crs=crs.GOOGLE_MERCATOR, label=label, group=POINT[0], id=traceP.trace.id).options(size=dim(size).norm()*45)

            ## Convertir les autres géometry en barycentre
            elif geomType in POLYGONE:
                data['geometry'] = data.simplify(STRONG_SIMPLIFY,True)
                geomNdOverlay =  gv.Polygons(data,vdims=vdims, crs=crs.GOOGLE_MERCATOR,label=label, group=POLYGONE[0])

            elif geomType in LINESTRING:
                data['geometry'] = data.simplify(SOFT_SIMPLIFY, True)
                geomNdOverlay = gv.Path(data, crs=crs.GOOGLE_MERCATOR,label=label, group=LINESTRING[0])

            elif geomType in MULTILINESTRING:
                data['geometry'] = data.simplify(SOFT_SIMPLIFY, True)
                geomNdOverlay = gv.Path(data, crs=crs.GOOGLE_MERCATOR, label=label, group=MULTILINESTRING[0])

            elif geomType in MULTIPOLYGONE:
                data['geometry'] = data.simplify(STRONG_SIMPLIFY,True)
                geomNdOverlay =  gv.Polygons(data, vdims=vdims, crs=crs.GOOGLE_MERCATOR,label=label, group=MULTIPOLYGONE[0])
            else:
                geomNdOverlay = None


        overlay = hv.Overlay([geomNdOverlay.opts(tools=['hover', 'tap'],color=self.variable_couleur, cmap='Category20')])

        return overlay
Esempio n. 23
0
 def callback(self, data):
     if (self.display == 'Probability of train delay'):
         layout = gv.Points(data,
                            vdims=[
                                'color', 'displaysize', 'name',
                                'waittime_str', 'delay_prob', 'MTAdelay',
                                'inboundtrain', 'inbound_from'
                            ]).opts(tools=[SubwayMap.hover_delays],
                                    size='displaysize',
                                    color='color')
     #elif(self.display == 'Time since last train'):
     else:
         layout = gv.Points(data,
                            vdims=[
                                'waittimecolor', 'waittimedisplaysize',
                                'name', 'waittime_str', 'delay_prob',
                                'MTAdelay'
                            ]).opts(tools=[SubwayMap.hover_waittime],
                                    size='waittimedisplaysize',
                                    color='waittimecolor')
     return layout
Esempio n. 24
0
    def get_plot_point(x, y):
        if None not in [x, y]:
            add_remove_pts(x, y, data, dataset, fmt)

        if ((x is None) or (y is None)) and len(data.xys) == 0:
            xys = [(data.x0, data.y0)]
            hpoint = gv.Points(xys).opts(show_legend=False, visible=False)
            htext = gv.HoloMap({
                i: gv.Text(*xy, '{}'.format(i + 1)).opts(show_legend=False,
                                                         visible=False)
                for i, xy in enumerate(xys)
            }).overlay()
        else:
            xys = data.xys
            hpoint = gv.Points(xys).opts(color='r', size=3, show_legend=False)
            htext = gv.HoloMap({
                i: gv.Text(*xy, '{}'.format(i + 1)).opts(show_legend=False,
                                                         color='k',
                                                         fontsize=3)
                for i, xy in enumerate(xys)
            }).overlay()
        return hpoint * htext
Esempio n. 25
0
def update_map(attr, old, new):
    global selection, vizual, gvplot, hvplot, heatmap, feats, points, world_map, range_slider, controls3, max_cur_feature, min_cur_feature, temp_feats
    max_cur_feature = temp_feats[choice.value].max()
    min_cur_feature = temp_feats[choice.value].min()
    range_slider = RangeSlider(start=min_cur_feature,
                               end=max_cur_feature,
                               value=(min_cur_feature, max_cur_feature),
                               step=(max_cur_feature - min_cur_feature) / 20,
                               title="Feature_range")
    range_slider.on_change('value', update_map_val)
    controls3 = widgetbox([range_slider], width=250)
    new_loc_feats = temp_feats.loc[
        (temp_feats[choice.value] < range_slider.value[1])
        & (temp_feats[choice.value] > range_slider.value[0])]
    feats = gv.Dataset(new_loc_feats, kdims=['Longitude', 'Latitude', new])
    points = feats.to(gv.Points, ['Longitude', 'Latitude'], [new])
    if len(new_loc_feats) <= 20000:
        world_map = gv.Overlay(tiles * points).options(
            'Points',
            size=5,
            cmap='viridis',
            colorbar=True,
            tools=TOOLS,
            color_index=2,
            width=900,
            height=800,
            global_extent=True,
            colorbar_opts={'scale_alpha': 0.5},
            fill_alpha=0.5,
            line_alpha=0.5)
    else:
        world_map = decimate(gv.Points(points), max_samples=20000).options(
            'Points',
            size=5,
            cmap='viridis',
            colorbar=True,
            tools=TOOLS,
            color_index=2,
            width=900,
            height=800,
            global_extent=True,
            colorbar_opts={'scale_alpha': 0.5},
            fill_alpha=0.5,
            line_alpha=0.5)
    selection = hv.streams.Selection1D(source=world_map)
    heatmap = hv.DynamicMap(selected_points, streams=[selection])
    zoom = hv.DynamicMap(test_bounds, streams=[box])
    hvplot = renderer.get_plot(heatmap, curdoc())
    gvplot = renderer.get_plot(world_map, curdoc())
    bvplot = renderer.get_plot(zoom, curdoc())
    vizual.children[1].children = [gvplot.state, hvplot.state, bvplot.state]
Esempio n. 26
0
    def create_mesh(self):
        # Add refine points
        points = self.annot.point_stream.element

        refine_points = []
        for x, y, s in zip(*(points.dimension_values(i) for i in range(3))):
            if s:
                refine_points.append(
                    xmsmesh.meshing.RefinePoint(create_mesh_point=True,
                                                point=(x, y, 0),
                                                size=float(s)))

            else:
                print('refine point {}, {} skipped due to missing size value'.
                      format(x, y))

        input_polygon = []

        # add each polygon to the input data
        for ply in self.annot.poly_stream.element.split(datatype='dataframe'):
            # add an additional dimension as zeros (for required dimensionality)
            poly_data = np.hstack((ply[['Longitude', 'Latitude']].values,
                                   np.zeros((len(ply['Latitude']), 1))))
            # instantiate the redistribution class
            rdp = xmsmesh.meshing.PolyRedistributePts()
            # set the node distance
            rdp.set_constant_size_func(
                self.node_spacing)  # create_constant_size_function
            # run the redistribution function
            outdata = rdp.redistribute(poly_data)

            # convert the polygon to an 'input polygon'
            input_polygon.append(
                xmsmesh.meshing.PolyInput(outside_polygon=outdata))

        # add the input polygons as polygons to the mesher class
        self.mesh_io = xmsmesh.meshing.MultiPolyMesherIo(
            poly_inputs=input_polygon, refine_points=refine_points)

        # Generate Mesh
        succeded, errors = xmsmesh.meshing.mesh_utils.generate_mesh(
            mesh_io=self.mesh_io)

        # convert the xms data format into dataframes
        pts, self.cells = xmsmesh_to_dataframe(self.mesh_io.points,
                                               self.mesh_io.cells)

        # convert the pts df into a hv Points class
        self.vert_points = gv.Points(pts,
                                     vdims=['z'],
                                     crs=ccrs.GOOGLE_MERCATOR)
Esempio n. 27
0
def plotPowerPlants(df):
    # size marker according to gross power output
    iMaxSize = 30
    iMinSize = 10
    df["size"] = (df["Bruttoleistung"] - df["Bruttoleistung"].min()) / \
                 (df["Bruttoleistung"].max() - df["Bruttoleistung"].min()) * \
                 (iMaxSize - iMinSize) + iMinSize

    # convert datetime to string
    df["date"] = df["Inbetriebnahmedatum"].dt.strftime("%Y-%m-%d")

    # define tooltips
    tt = [
        ("Name", "@Name"),
        ("Address", "@Standort, @Bundesland, @Land"),
        ("Commissioning date", "@date"),
        ("Type", "@Einheittyp"),
        ("Gross generation", "@Bruttoleistung MW"),
    ]
    hover_tool = bokeh.models.HoverTool(tooltips=tt)

    # choose background tiles
    overlay = gv.tile_sources.Wikipedia

    # markers will be colored according to Einheittyp
    groups = df["Einheittyp"].unique()
    colors = {
        "Wasser": palette[0],
        "Biomasse": palette[2],
        "Windeinheit": palette[4],
    }

    # create geoviews point objects
    for group in groups:
        df_group = df.loc[
            df["Einheittyp"] == group,
            ["Name", "Standort", "Bundesland", "Land", "date",
             "Einheittyp", "Bruttoleistung", "Laengengrad", "Breitengrad", "size"]
        ]
        points = gv.Points(df_group, ["Laengengrad", "Breitengrad"], label=group).options(
            aspect=2, responsive=True, tools=[hover_tool], size="size", active_tools=['wheel_zoom'],
            fill_alpha=0.6, fill_color=colors[group], line_color="white",
        )
        overlay = (overlay * points)

    # hide group when clicking on legend
    overlay.options(click_policy="hide", clone=False)

    # return figure
    return overlay
Esempio n. 28
0
def create_map(indices_meses):
    df_filtrado = filtrar_por_indice(df_total, meses, indices_meses)

    df_agregado = df_filtrado.groupby("nacionalidad").size().reset_index()
    df_agregado.columns = ["nacionalidad", "conteo"]

    df_map = df_agregado.merge(countries_df,
                               how="inner",
                               left_on=["nacionalidad"],
                               right_on=["country_spanish"])

    df_map["tamaño"] = scale_size(df_map["conteo"], 10, 60).astype("int")

    hover_points = HoverTool(
        tooltips=[("Nacionalidad",
                   "@{nacionalidad}"), ("Nº Clienes", "@{conteo}")])

    points = gv.Points(df_map,
                       kdims=["Capital Longitude", "Capital Latitude"],
                       vdims=["nacionalidad", "conteo", "tamaño"])

    points.opts(size="tamaño",
                padding=0.1,
                color="nacionalidad",
                cmap=["#00497c"],
                fill_alpha=0.8,
                hover_fill_alpha=1.0,
                line_color="white",
                line_width=2,
                show_legend=False,
                tools=[hover_points])

    #tiles = gv.tile_sources.WMTS("https://b.basemaps.cartocdn.com/light_nolabels/{Z}/{X}/{Y}@2x.png", name="Carto_light_Nolabels")
    tiles = gv.tile_sources.WMTS(
        "https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{Z}/{X}/{Y}@2x.png",
        name="Alidade_Smooth_Dark")

    map = tiles * points

    map_bokeh = renderer.get_plot(map).state
    map_bokeh.toolbar.autohide = True
    map_bokeh.height = 400
    map_bokeh.width = 780
    map_bokeh.sizing_mode = "scale_both"

    return map_bokeh
Esempio n. 29
0
def make_temporal_vel_pair_point_obj(date):
    ttt = date.astype('datetime64[D]')
    kdims = ["Longitude", "Latitude"]
    vdims = [("e_max", "Velocity changes (%)"), "Pairname"]
    opts = dict(color='e_max',
                cmap="jet_r",
                size=5,
                tools=["hover"],
                marker='s')
    opts.update(opts1)
    temporal_vel_pair_point_obj = gv.Points(data_mid_point_pair[ttt],
                                            kdims=kdims,
                                            vdims=vdims,
                                            crs=ccrs.PlateCarree())
    temporal_vel_pair_point_obj = temporal_vel_pair_point_obj.opts(**opts)
    print("make_temporal_vel_pair_point_obj {}".format(date))
    return (temporal_vel_pair_point_obj)
Esempio n. 30
0
    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)