Beispiel #1
0
    def test_matplotlib_contour_to_geojson(self):
        latrange, lonrange, Z = self.create_grid_data()
        config = ContourPlotConfig(level_lower=0, level_upper=202,
                                   unit='[unit]')

        figure = plt.figure()
        ax = figure.add_subplot(111)
        contours = ax.contour(
            lonrange, latrange, Z,
            levels=config.levels,
            cmap=config.colormap
        )

        contourf = ax.contourf(
            lonrange, latrange, Z,
            levels=config.levels,
            cmap=config.colormap
        )

        ndigits = 3
        geojsoncontour.contour_to_geojson(
            contour=contours,
            geojson_filepath=self.geojson_file,
            contour_levels=config.levels,
            min_angle_deg=config.min_angle_between_segments,
            ndigits=ndigits,
            unit=config.unit
        )
        geojsoncontour.contourf_to_geojson(
            contourf=contourf,
            geojson_filepath=self.geojson_file_contourf,
            contour_levels=config.levels,
            min_angle_deg=config.min_angle_between_segments,
            ndigits=ndigits,
            unit=config.unit
        )
        geojsoncontour.contourf_to_multipolygeojson(
            contourf=contourf,
            geojson_filepath=self.geojson_file_multipoly,
            contour_levels=config.levels,
            min_angle_deg=config.min_angle_between_segments,
            ndigits=ndigits,
            unit=config.unit
        )
        self.assertTrue(os.path.exists(self.geojson_file))
        self.assertTrue(filecmp.cmp(self.benchmark_geojson_file, self.geojson_file))
        os.remove(self.geojson_file)

        self.assertTrue(os.path.exists(self.geojson_file_contourf))
        self.assertTrue(filecmp.cmp(self.benchmark_geojson_file_contourf, self.geojson_file_contourf))
        os.remove(self.geojson_file_contourf)

        self.assertTrue(os.path.exists(self.geojson_file_multipoly))
        self.assertTrue(filecmp.cmp(self.benchmark_geojson_file_multipoly, self.geojson_file_multipoly))
        os.remove(self.geojson_file_multipoly)
Beispiel #2
0
 def test_matplotlib_contourf_to_geojson(self):
     contourf = self.create_contourf()
     ndigits = 3
     geojsoncontour.contourf_to_geojson(
         contourf=contourf,
         geojson_filepath=self.geojson_file_multipoly,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit
     )
     self.assertTrue(os.path.exists(self.geojson_file_multipoly))
     self.assertTrue(filecmp.cmp(self.benchmark_geojson_file_multipoly, self.geojson_file_multipoly))
     os.remove(self.geojson_file_multipoly)
Beispiel #3
0
 def test_matplotlib_contourf_to_geojson(self):
     contourf = self.create_contourf()
     ndigits = 3
     geojsoncontour.contourf_to_geojson(
         contourf=contourf,
         geojson_filepath=self.geojson_file_multipoly,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit)
     self.assertTrue(os.path.exists(self.geojson_file_multipoly))
     self.assertTrue(
         filecmp.cmp(self.benchmark_geojson_file_multipoly,
                     self.geojson_file_multipoly))
     os.remove(self.geojson_file_multipoly)
Beispiel #4
0
def generate_layer_distance(tmp_map,
                            X,
                            Y,
                            Z,
                            ll=0,
                            ul=300,
                            cmap_name='seismic',
                            levels=30):
    contourf = plt.contourf(X,
                            Y,
                            Z,
                            levels,
                            cmap=cmap_name,
                            alpha=1,
                            vmin=ll,
                            vmax=ul,
                            linestyles='dashed')
    # Convert matplotlib contourf to geojson
    geojson = geojsoncontour.contourf_to_geojson(contourf=contourf,
                                                 stroke_width=0)

    fg_dist = folium.FeatureGroup(name="Distance", show=False)
    tmp_map.add_child(fg_dist)

    # Plot the contour plot on folium
    folium.GeoJson(
        geojson,
        style_function=lambda x: {
            # 'weight': x['properties']['stroke-width'],
            'fillColor': x['properties']['fill'],
            'opacity': 0.5,  # does not work
            'weight': 0.4
        }).add_to(fg_dist)

    return tmp_map
Beispiel #5
0
def runmodel(input_date):
    date = (pd.to_datetime(input_date)).date()
    modelfilename = 'data/lin_model.sav'
    scalerfilename = 'data/lin_scaler.sav'
    lin = pickle.load(open(modelfilename, 'rb'))
    scaler = pickle.load(open(scalerfilename, 'rb'))
    testX = build_input(date)
    testx = testX[['TL1', 'Tmin', 'Tmax', 'd_lm', 'sqrt_dw', 'sqrt_dp']]
    X = scaler.transform(testx)
    Y = lin.predict(X)
    l = len(Y)
    for i in range(l):
        if Y[i] < 0:
            Y[i] = 0
    smallY = Y.reshape(101, 101)
    #    y5 = ndimage.zoom(smallY, 5)

    NN = np.genfromtxt("data/nans100.csv", delimiter=',').transpose()
    TT = np.multiply(smallY, NN)
    xx = np.linspace(min(testX['lon']), max(testX['lon']), 101)
    yy = np.linspace(min(testX['lat']), max(testX['lat']), 101)

    colors = ['darkgreen', 'green', 'yellow', 'orange', 'red', 'darkred']
    vmin = 0
    vmax = 50
    levels = len(colors)
    cfig = plt.contourf(xx,
                        yy,
                        TT,
                        levels,
                        alpha=1.0,
                        colors=colors,
                        linestyles='None',
                        vmin=vmin,
                        vmax=vmax)
    geojson = geojsoncontour.contourf_to_geojson(contourf=cfig,
                                                 min_angle_deg=0.0,
                                                 ndigits=5,
                                                 stroke_width=0.5,
                                                 fill_opacity=1.0)
    geomap = folium.Map(location=[41.89, -87.64],
                        zoom_start=13,
                        tiles="stamenterrain")
    folium.GeoJson(geojson,
                   style_function=lambda x: {
                       'color': x['properties']['stroke'],
                       'weight': x['properties']['stroke-width'],
                       'fillColor': x['properties']['fill'],
                       'fillOpacity': 0.65
                   }).add_to(geomap)
    plugins.Fullscreen(position='topright',
                       force_separate_button=True).add_to(geomap)
    fname = 'static/' + str(dt.datetime.now()) + '.html'
    geomap.save(f'flaskapp/' + fname)
    return fname
def netcdf_to_geojson(ncfile, var, fourth_dim=None):
    realpath = os.path.realpath(ncfile)
    name, ext = os.path.splitext(realpath)
    X, Y, Z, levels, unit = setup(ncfile, var)
    figure = plt.figure()
    ax = figure.add_subplot(111)
    for t in range(len(Z.time)):
        third = Z.isel(time=t)
        position = 0
        if len(third.dims) == 3:
            position = len(getattr(third, third.dims[0])) - 1
            third = third[position, ]
        # local min max
        levels = np.linspace(start=np.nanmin(third),
                             stop=np.nanmax(third),
                             num=20)
        contourf = ax.contourf(X, Y, third, levels=levels, cmap=plt.cm.viridis)
        geojsoncontour.contourf_to_geojson(
            contourf=contourf,
            geojson_filepath='{}_{}_t{}_{}.geojson'.format(
                name, var, t, position),
            ndigits=3,
            min_angle_deg=None,
            unit=unit)
Beispiel #7
0
def contour_ice(dataarray):
    """Contour xarray dataarray of ice cover to geojson"""
    contours = dataarray.plot.contourf(vmin=0, vmax=100, levels=5)
    ice_json = json.loads(contourf_to_geojson(contourf=contours))
    print(ice_json['type'])
    # Remove land polygons
    rm_feats = [
        f for f in ice_json['features'] if f['properties']['title'] == '<0.00 '
    ]
    for rm in rm_feats:
        ice_json['features'].remove(rm)
    print([
        np.array(f['geometry']['coordinates']).shape
        for f in ice_json['features']
    ])
    geodf_ice = gpd.GeoDataFrame.from_features(ice_json)
    return geodf_ice
def add_layer(df,text,cc): 
    if cc == 1:
        colors = ["#FFFFFF","#CCCCFF", "#AAAAFF", "#6666FF","#0000FF"]
    elif cc == 2:
        colors = ["#FFFFFF","#FFCCCC", "#FFAAAA", "#FF6666","#FF0000"] 
    elif cc == 3:
        colors = ["#FFFFFF","#CCFFCC", "#AAFFAA", "#66FF66","#00FF00"] 
    polygon = Polygon(tw)
    lons = np.asarray(df.long.tolist())
    lats = np.asarray(df.lat.tolist())
    data = np.asarray(df.EI.tolist())
    grid_space = 0.05
    global grid_lon, grid_lat
    grid_lon = np.arange(lons.min()-0.1, lons.max()+0.1, grid_space) 
    grid_lat = np.arange(lats.min()-0.1, lats.max()+0.1, grid_space)
    OK = OrdinaryKriging(lons, lats, data, variogram_model='gaussian', verbose=False, enable_plotting=False,nlags=20)
    global z_mesh,x_mesh,y_mesh
    z_mesh, ss1 = OK.execute('grid', grid_lon, grid_lat)
    x_mesh, y_mesh = np.meshgrid(grid_lon, grid_lat)
    shp = x_mesh.shape
    mtw = np.zeros(shp,dtype=np.float)
    for i in range(shp[0]):
        for j in range(shp[1]):
            point = Point(x_mesh[i][j], y_mesh[i][j])
            if not polygon.contains(point):
                mtw[i][j] = 1        
    z_mesh = np.ma.masked_where(mtw == 1, z_mesh)    
    contourf = plt.contourf(x_mesh, y_mesh, z_mesh, levels=[-0.2,0.01,0.1,0.2,0.6,1.2], alpha=0.9, colors=colors, linestyles='None', vmin=-0.2, vmax=1.2)
    global geojson
    geojson = geojsoncontour.contourf_to_geojson(
        contourf=contourf,
        min_angle_deg=3.0,
        ndigits=5,
        stroke_width=1,
        fill_opacity=0.5)
#     geoj = folium.GeoJson(
#         geojson,
#         style_function=lambda x: {
#             'color':     x['properties']['stroke'],
#             'weight':    x['properties']['stroke-width'],
#             'fillColor': x['properties']['fill'],
#             'opacity':   0.6,
#         })
    geoj = 'none'
    return geoj,geojson
Beispiel #9
0
    def get_geojsons(self):
        data_grids = self.__datagrid.get_data_grids()
        result = []
        for data_grid in data_grids:
            X = data_grid['X']
            Y = data_grid['Y']
            Z = data_grid['Z']

            if self.__method == 'Изолинии':
                contour = pylab.contour(
                    X, Y, Z, cmap=self.__create_colourmap())
                result.append({
                    'geojson': geojsoncontour.contour_to_geojson(contour, stroke_width=0.5),
                    'leadTime': data_grid['leadTime']
                })
            if self.__method == 'Контур с подписями':
                contourf = pylab.contourf(
                    X, Y, Z, cmap=self.__create_colourmap())
                result.append({
                    'geojson': geojsoncontour.contourf_to_geojson(contourf, stroke_width=0.5),
                    'leadTime': data_grid['leadTime']
                })
        return result
Beispiel #10
0
    def __init__(self,
                 df,
                 bw_method=None,
                 weights=None,
                 alpha=0.4,
                 grid=100,
                 number_of_levels=100,
                 ignore_levels=1,
                 cmap=None,
                 epsg=3857,
                 padding=5000.):
        """Computes the KDE for a given dataset and creates the heatmap.

        Parameters:
            df (object): A dataframe with geometries and optionally weights.
            bw_method (string, optional): The method used to calculate the estimator bandwidth. This can be ‘scott’, ‘silverman’, a scalar constant or a callable. See https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html
            weights (string): The attribute name of the weights in the dataframe.
            alpha (float): The alpha blending value, between 0 (transparent)
                and 1 (opaque) (default: 0.4).
            grid (int): The number of points in the grid (default: 100).
            number_of_levels (int): The number of levels in the generated heatmap (default: 100).
            ignore_levels (int): The number of first levels to ignore (default: 1).
            cmap (obect|string): A matplotlib Colormap instance or registered colormap name.
                The colormap maps the level values to colors.
                (default: A custom colormap blue-green-red weighted to the right.)
            epsg (int): The EPSG code to reproject the geometries (default: 3857).
            padding (float, optional): Padding around the MBR in meters.
        """
        self.df = df
        self.weights = weights
        self.alpha = alpha
        self.number_of_levels = number_of_levels
        self.ignore_levels = ignore_levels
        self.epsg = epsg

        # Create the data
        pois = df.centroid()
        if epsg is not None:
            pois.geometry.to_crs(epsg)
        data = pg.get_coordinates(pois.geometry.to_pygeos().values())
        xmin, ymin = data.min(axis=0) - padding
        xmax, ymax = data.max(axis=0) + padding

        m1, m2 = data.T
        x, y = np.mgrid[xmin:xmax:grid * 1j, ymin:ymax:grid * 1j]
        positions = np.vstack([x.ravel(), y.ravel()])
        values = np.vstack([m1, m2])

        # Calculate the bandwidth
        if bw_method is None and weights is None:
            std = m1.std(ddof=1)
            n = len(m1)
            iqr = stats.iqr(m1)
            bw_method = 0.9 * (min(std, iqr / 1.34) * n**(-0.2)) / std
        elif bw_method is None and weights is not None:
            bw_method = 'scotts'

        # Compute Kernel Density Estimation and levels
        kde = stats.gaussian_kde(values,
                                 bw_method=bw_method,
                                 weights=df[weights])
        levels = np.reshape(kde(positions).T, x.shape)

        # Create the colormap
        if cmap is None:
            colors = [
                '#0000ff', '#00ff00', '#20e000', '#40c000', '#60a000',
                '#808000', '#a06000', '#c04000', '#e02000', '#ff0000'
            ]
            cmap = LinearSegmentedColormap.from_list('BuGrRd', colors, N=100)

        # Create the filled contour
        fig, ax = plt.subplots()
        cset = ax.contourf(x,
                           y,
                           levels,
                           number_of_levels,
                           cmap=cmap,
                           alpha=alpha,
                           antialiased=True)
        plt.close(fig)

        # Extract the geojson from contour
        for i in range(0, ignore_levels):
            del cset.collections[i]
        geojson = geojsoncontour.contourf_to_geojson(contourf=cset,
                                                     ndigits=3,
                                                     fill_opacity=alpha)
        geojson = loads(geojson)
        # Transform to EPSG:4326
        geojson = gpd.GeoDataFrame.from_features(
            geojson['features'], crs="epsg:3857").to_crs(epsg=4326).to_json()
        # Store computed values
        self.kde = kde
        self.grid = (x, y)
        self.cmap = cmap
        self.geojson = loads(geojson)
        self._levels = levels
sigma = [5, 5]
z_mesh = sp.ndimage.filters.gaussian_filter(z_mesh, sigma, mode='constant')

contourf = plt.contourf(x_mesh,
                        y_mesh,
                        z_mesh,
                        levels,
                        alpha=0.5,
                        colors=colors,
                        linestyles='None',
                        vmin=vmin,
                        vmax=vmax)

geojson = geojsoncontour.contourf_to_geojson(contourf=contourf,
                                             min_angle_deg=3.0,
                                             ndigits=5,
                                             stroke_width=1,
                                             fill_opacity=0.5)

geomap = folium.Map(
    [data.latitude.mean(), data.longitude.mean()],
    zoom_start=10,
    tiles="cartodbpositron")

folium.GeoJson(geojson,
               style_function=lambda x: {
                   'color': x['properties']['stroke'],
                   'weight': x['properties']['stroke-width'],
                   'fillColor': x['properties']['fill'],
                   'opacity': 0.6,
               }).add_to(geomap)
Beispiel #12
0
def generate_layer_gradient_slope(base_map,
                                  X,
                                  Y,
                                  ll=0,
                                  ul=20,
                                  cmap_name='Reds',
                                  levels=30):
    # compute gradient
    X_1d = X.flatten()
    Y_1d = Y.flatten()
    elevation = []
    for i in trange(0, len(X_1d)):
        # https://www.opentopodata.org/api/
        topo_url = f"http://localhost:5000/v1/eudem25m?locations={Y_1d[i]},{X_1d[i]}&interpolation=cubic"
        response = requests.get(topo_url)
        data_topo = response.json()
        elevation.append(data_topo['results'][0]['elevation'])

    # https://medium.com/ai-in-plain-english/introduction-to-digital-elevation-map-processing-visualization-in-python-4bb7aa65f2b1
    elevation_array = np.array(elevation)
    elevation_2d = elevation_array.reshape(
        np.unique(X_1d).size,
        np.unique(Y_1d).size)
    dx, dy = np.gradient(elevation_2d)
    grad_tot = np.hypot(dx, dy)

    contourf_gradient = plt.contourf(X,
                                     Y,
                                     grad_tot,
                                     levels,
                                     cmap=cmap_name,
                                     alpha=1,
                                     vmin=ll,
                                     vmax=ul,
                                     linestyles='dashed')
    # Convert matplotlib contourf to geojson
    geojson_gradient = geojsoncontour.contourf_to_geojson(
        contourf=contourf_gradient, stroke_width=0)

    fg_grad = folium.FeatureGroup(name="Gradient", show=False)
    base_map.add_child(fg_grad)

    folium.GeoJson(
        geojson_gradient,
        style_function=lambda x: {
            # 'weight': x['properties']['stroke-width'],
            'fillColor': x['properties']['fill'],
            'opacity': 0.5,  # does not work
            'weight': 0.4
        }).add_to(fg_grad)

    # compute slope

    slopes = np.degrees(np.arctan(np.hypot(dy, dx)))
    min_slope = np.ceil(np.min(slopes))
    max_slope = np.ceil(np.max(slopes))
    contourf_slopes = plt.contourf(X,
                                   Y,
                                   slopes,
                                   levels,
                                   cmap=cmap_name,
                                   alpha=1,
                                   vmin=min_slope,
                                   vmax=max_slope,
                                   linestyles='dashed')
    # Convert matplotlib contourf to geojson
    geojson_slopes = geojsoncontour.contourf_to_geojson(
        contourf=contourf_slopes, stroke_width=0)

    fg_slope = folium.FeatureGroup(name="Slopes [deg]", show=False)
    base_map.add_child(fg_slope)

    folium.GeoJson(
        geojson_slopes,
        style_function=lambda x: {
            # 'weight': x['properties']['stroke-width'],
            'fillColor': x['properties']['fill'],
            'opacity': 0.5,  # does not work
            'weight': 0.4
        }).add_to(fg_slope)

    return base_map
import numpy
import matplotlib.pyplot as plt
import geojsoncontour

# Create lat and lon vectors and grid data
grid_size = 1.0
latrange = numpy.arange(-90.0, 90.0, grid_size)
lonrange = numpy.arange(-180.0, 180.0, grid_size)
X, Y = numpy.meshgrid(lonrange, latrange)
Z = numpy.sqrt(X * X + Y * Y)

n_contours = 20
levels = numpy.linspace(start=0, stop=100, num=n_contours)

# Create a contour plot plot from grid (lat, lon) data
figure = plt.figure()
ax = figure.add_subplot(111)
contourf = ax.contourf(lonrange, latrange, Z, levels=levels, cmap=plt.cm.jet)

# Convert matplotlib contourf to geojson
geojson = geojsoncontour.contourf_to_geojson(
    contourf=contourf,
    min_angle_deg=3.0,
    ndigits=3,
    stroke_width=2,
    fill_opacity=0.5
)

print(geojson)
Beispiel #14
0
def contourf(lon, lat, data, time_str, timerange_str, **kwargs):
    """Contour-filled plot using geojsoncontour.

    Parameters:
    -----------
    lon : array
        2-D array of longitudes. Must be same shape as data
    lat : array
        2-D array of latitudes. Must be same shape as data
    data : array [N, M]
        Values over which contour fill is drawn
    time_str : string
        Valid time for this plot. Included in the placefile title
    timerange_str : string
        Valid time range over which to display in GR

    Other Parameters:
    -----------------
    levels : list, array
        Number and positions of the contour lines / regions
    colors : color string (hexademicals)
        Colors corresponding to each contour-fill level
    plotinfo : string
        Brief description of the plot

    Returns:
    --------
    out : list
        List of strings, each corresponding to a new line for the placefile
    """

    fig = plt.figure()
    ax = fig.add_subplot(111)

    levels = kwargs.get('levels')
    colors = kwargs.get('colors')
    plotinfo = kwargs.get('plotinfo', 'None')

    c = ax.contourf(lon, lat, data, levels, colors=colors)
    geojson = json.loads(
        geojsoncontour.contourf_to_geojson(contourf=c, ndigits=8))

    out = []
    out.append('Title: %s Filled Contour %s\n' % (plotinfo, time_str))
    out.append('RefreshSeconds: 60\n')
    out.append('TimeRange: %s\n' % (timerange_str))
    for feature in geojson['features']:
        rgb = hex2rgb(feature['properties']['fill'])
        groups = feature['geometry']['coordinates']
        for group in groups:
            out.append('Polygon:\n')
            first_line = True
            for item in group[0]:
                if first_line:
                    COLOR = '%s, %s\n' % (', '.join(rgb), ALPHA)
                else:
                    COLOR = ''
                out.append(' %s, %s, %s\n' % (item[1], item[0], COLOR))
                first_line = False
            out.append('End:\n')
            out.append('\n')
    plt.close(fig)
    return out
Beispiel #15
0
def build_geojson_contours(data, ax: Axes, manifest: dict):

    ax.clear()

    z = data
    x = z.mesh2d_face_x[:len(z)]
    y = z.mesh2d_face_y[:len(z)]

    variable_name = z.name

    # capture date and convert to datetime
    dt = datetime64_to_datetime(z.time)

    # set title on figure
    ax.set_title(dt.isoformat())

    # build json file name output
    file_name = '{}.json'.format(dt.isoformat())

    # convert to numpy arrays
    z = z.values
    x = x.values
    y = y.values

    # build grid constraints
    xi = np.linspace(np.floor(x.min()), np.ceil(x.max()), GRID_SIZE)
    yi = np.linspace(np.floor(y.min()), np.ceil(y.max()), GRID_SIZE)

    # build delaunay triangles
    triang = tri.Triangulation(x, y)

    # build a list of the triangle coordinates
    tri_coords = []
    for i in range(len(triang.triangles)):
        tri_coords.append(
            tuple(zip(x[triang.triangles[i]], y[triang.triangles[i]])))

    # filter out large triangles
    large_triangles = [
        i for i, t in enumerate(tri_coords)
        if circum_radius(*t) > MAX_CIRCUM_RADIUS
    ]
    mask = [i in large_triangles for i, _ in enumerate(triang.triangles)]
    triang.set_mask(mask)

    # interpolate values from triangle data and build a mesh of data
    interpolator = tri.LinearTriInterpolator(triang, z)
    Xi, Yi = np.meshgrid(xi, yi)
    zi = interpolator(Xi, Yi)

    contourf = ax.contourf(xi, yi, zi, LEVELS, cmap=plt.cm.jet)

    # create output directory if it doesn't exist
    output_path = '/tmp/{}'.format(variable_name)
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    # convert matplotlib contourf to geojson
    geojsoncontour.contourf_to_geojson(
        contourf=contourf,
        min_angle_deg=3.0,
        ndigits=5,
        stroke_width=2,
        fill_opacity=0.5,
        geojson_filepath=os.path.join(output_path, file_name),
    )

    # update the manifest with the geojson output
    manifest_entry = {
        'date': dt.isoformat(),
        'path': os.path.join(variable_name, file_name),
    }
    if variable_name not in manifest:
        manifest[variable_name] = {'geojson': []}
    manifest[variable_name]['geojson'].append(manifest_entry)

    return contourf
Beispiel #16
0
geojson = {}

for i, month in enumerate(data.time_stamps()):
    date = str(month).split('T')[0]
    datamon = nparr[i]
    contour = ax.contourf(lons,
                          lats,
                          datamon,
                          transform=proj,
                          cmap=cm,
                          levels=levels,
                          extend='max')

    result = geojsoncontour.contourf_to_geojson(contourf=contour,
                                                ndigits=2,
                                                unit='m')

    geojson[date] = eval(result)

#set the legend in one key
import matplotlib
geojson['legend'] = {
    'colors':
    list([matplotlib.colors.to_hex(rgba) for rgba in cm._lut][0:len(levels)]),
    'levels':
    list(levels)
}

#write the file
import json
Beispiel #17
0
def plotDataHTML(df_plot, departamento, ciudad):
    minlat = np.min(df_plot['lat'])
    maxlat = np.max(df_plot['lat'])
    minlon = np.min(df_plot['long'])
    maxlon = np.max(df_plot['long'])

    lon = df_plot['long']
    lat = df_plot['lat']
    meanlon = np.mean(lon)
    meanlat = np.mean(lat)
    stdlon = np.std(lon)
    stdlat = np.std(lat)

    pro = df_plot['Prob']
    ngrid_lon = 200
    ngrid_lat = 200

    yi = np.linspace(minlat, maxlat, ngrid_lat)
    xi = np.linspace(minlon, maxlon, ngrid_lon)

    triang = tri.Triangulation(lon, lat)
    interpolator = tri.LinearTriInterpolator(triang, pro)
    Xi, Yi = np.meshgrid(xi, yi)
    zi = interpolator(Xi, Yi)
    vmin = np.min(pro)
    vmax = np.max(pro)

    sigma = [5, 5]
    z_mesh = sp.ndimage.filters.gaussian_filter(zi, sigma, mode='constant')

    colors = [
        'blue', 'royalblue', 'navy', 'pink', 'mediumpurple', 'darkorchid',
        'plum', 'm', 'mediumvioletred', 'palevioletred', 'crimson', 'magenta',
        'pink', 'red', 'yellow', 'orange', 'brown', 'green', 'darkgreen'
    ]
    levels = len(colors)
    cm = branca.colormap.LinearColormap(colors, vmin=vmin,
                                        vmax=vmax).to_step(levels)

    contf = plt.contourf(Xi,
                         Yi,
                         z_mesh,
                         levels,
                         alpha=0.5,
                         colors=colors,
                         linestyles='None',
                         vmin=vmin,
                         vmax=vmax)

    geojson = geojsoncontour.contourf_to_geojson(contourf=contf,
                                                 min_angle_deg=3.0,
                                                 ndigits=5,
                                                 stroke_width=1,
                                                 fill_opacity=0.1)

    geomap = folium.Map(location=[np.mean(lat), np.mean(lon)],
                        zoom_start=12,
                        tiles="OpenStreetMap")

    folium.GeoJson(geojson,
                   style_function=lambda x: {
                       'color': x['properties']['stroke'],
                       'weight': x['properties']['stroke-width'],
                       'fillColor': x['properties']['fill'],
                       'opacity': 0.5,
                   }).add_to(geomap)

    folium.Circle(location=[minlat, minlon],
                  radius=100,
                  color='crimson',
                  fill=True,
                  fill_color='crimson').add_to(geomap)

    folium.Circle(location=[maxlat, maxlon],
                  radius=100,
                  color='crimson',
                  fill=True,
                  fill_color='crimson').add_to(geomap)
    cm.caption = 'Probability'
    geomap.add_child(cm)
    plugins.Fullscreen(position='topright',
                       force_separate_button=True).add_to(geomap)
    geomap.save('Mapa' + departamento + '-' + ciudad + '.html')
    return ('Mapa' + departamento + '-' + ciudad + '.html')


#plotDataHTML(prepareData(dataPath,departamento,ciudad,sexo,edad,mes,dia,hora))
Beispiel #18
0
    ax = figure.add_subplot(111)
    contourf = ax.contourf(lon, lat, ssh[num], levels=levels, cmap=plt.cm.coolwarm, extend='both')
    contourf_trend = ax.contourf(lon, lat, ssh[num] + trend, levels=levels, cmap=plt.cm.coolwarm, extend='both')
    cbar = plt.colorbar(contourf, ticks=ticks)
    plt.title('Example')
    plt.show()
    geojsonProps = {"time": int(time[num])*1000}
    out_file_name = '-' + str(len(time) - num) + '.geojson'
    out_file_name_trend = '-' + str(len(time) - num) + 'trend.geojson'
    print(int(time[num])*1000)
    # # Convert matplotlib contour to geojson
    geojsoncontour.contourf_to_geojson(
        contourf=contourf,
        geojson_filepath=out_file_name,
        ndigits=1,
        min_angle_deg=7,
        stroke_width=1,
        unit='cm',
        fill_opacity=1.0,
        geojson_properties=geojsonProps
    )
    geojsoncontour.contourf_to_geojson(
        contourf=contourf_trend,
        geojson_filepath=out_file_name_trend,
        ndigits=1,
        min_angle_deg=7,
        stroke_width=1,
        unit='cm',
        fill_opacity=1.0,
        geojson_properties=geojsonProps
    )
Beispiel #19
0
def draw_KDE_Map(i_data,i_geo_map,g1,cl):
    geomap=i_geo_map
    #Using Kernel Density Estimation
    X = i_data[['Longitude', 'Latitude']].values
    kde = KernelDensity(kernel='gaussian', bandwidth=0.01)
    kde.fit(X)
    print("Generating KDE score")
    log_dens = kde.score_samples(X)
    
    #Genrating KDE Contours
    # Setup
    debug     = False
    # Setup colormap
    colors = cl
    vmin   = log_dens.min()
    vmax   =log_dens.max()
    levels = len(colors)
    cm     = branca.colormap.LinearColormap(colors, vmin=vmin, vmax=vmax).to_step(levels)
    #The original data
    x_orig = np.asarray(i_data['Longitude'].values.tolist())
    y_orig = np.asarray(i_data['Latitude'].values.tolist())
    z_orig = np.asarray(log_dens.tolist())
    # Make a grid
    x_arr          = np.linspace(np.min(x_orig), np.max(x_orig), 500)
    y_arr          = np.linspace(np.min(y_orig), np.max(y_orig), 500)
    x_mesh, y_mesh = np.meshgrid(x_arr, y_arr)
    # Grid the values
    z_mesh = griddata((x_orig, y_orig), z_orig, (x_mesh, y_mesh), method='linear')
    # Gaussian filter the grid to make it smoother
    sigma = [7,7]
    z_mesh = sp.ndimage.filters.gaussian_filter(z_mesh, sigma, mode='constant')
    # Create the contour
    contourf = plt.contourf(x_mesh, y_mesh, z_mesh, levels, alpha=0.5, colors=colors, linestyles='None', vmin=vmin, vmax=vmax)
 
    # Convert matplotlib contourf to geojson
    geojson = geojsoncontour.contourf_to_geojson(
        contourf=contourf,
        min_angle_deg=3.0,
        ndigits=5,
        stroke_width=1,
        fill_opacity=1)

    # Plot the contour plot on folium
    g1.add_child(folium.GeoJson(
        geojson,
        style_function=lambda x: {
            'color':     x['properties']['stroke'],
            'weight':    x['properties']['stroke-width'],
            'fillColor': x['properties']['fill'],
            'opacity':   0.5,
        }))
    
    geomap.add_child(feature_group)
    geomap.add_child(g1)
    #folium.LayerControl().add_to(geomap)
    
    # Add the colormap to the folium map
    cm.caption = 'Kernel Density'
    geomap.add_child(cm)
    
    # Fullscreen mode
    plugins.Fullscreen(position='topright', force_separate_button=True).add_to(geomap)
    display(geomap)
    #geomap.save(f'folium_contour_temperature_map.html')
    
    return(geomap)
Beispiel #20
0
                         cmap=cm,
                         levels=levels,
                         extend='max')

# Convert matplotlib contour to geojson
import geojsoncontour
geojson = {}
keys = [
    '2010-01-15', '2010-02-15', '2010-03-15', '2010-04-15', '2010-05-15',
    '2010-06-15', '2010-07-15', '2010-08-15', '2010-09-15', '2010-10-15',
    '2010-11-15', '2010-12-15'
]
for i in np.arange(np.shape(data_year)[0]):
    geojson[keys[i]] = eval(
        geojsoncontour.contourf_to_geojson(contourf=csf[i],
                                           ndigits=2,
                                           unit='m'))

#set the legend in one key
import matplotlib
geojson['legend'] = {
    'colors':
    list([matplotlib.colors.to_hex(rgba) for rgba in cm._lut][0:len(levels)]),
    'levels':
    list(levels)
}

#write the file
import json
fn = var + '_Column_' + modid + '.geojson'
with open(fn, 'w') as f:
Beispiel #21
0
    dist= np.sqrt((E-x)**2 + (N-y)**2 + (H-z)**2)
    Lp = Lw - 20*np.log10(dist)-8
    return Lp

x = np.linspace(Eas-1000, Eas+1000, 10)
y = np.linspace(Nor-1000, Nor+1000, 10)

X, Y = np.meshgrid(x, y)
Z = f(Eas, Nor, Altura, X, Y, Hmap, Lw)
Lat, Lon  = utm.to_latlon(x, y, Zone, Num)
fig, ax = plt.subplots()
cs = ax.contourf(Lon, Lat, Z)


cbar = fig.colorbar(cs)

plt.show()

geojson = geojsoncontour.contourf_to_geojson(
    contourf=cs,
    ndigits=3,
    unit='m'
)
#print (geojson)

with open('myfile1.geojson', 'w') as f:
   f.write(geojson)
f.close()