Ejemplo n.º 1
0
    def create_geojson(self,
                       filepath,
                       min_zoom=0,
                       max_zoom=12,
                       stroke_width=1,
                       levels=[],
                       norm=None):
        figure = Figure(frameon=False)
        FigureCanvas(figure)
        ax = figure.add_subplot(111)
        # contours = plt.contourf(lonrange, latrange, Z, levels=levels, cmap=plt.cm.plasma)
        contours = ax.contour(self.lonrange,
                              self.latrange,
                              self.Z,
                              levels=levels,
                              norm=norm,
                              cmap=plt.cm.jet,
                              linewidths=3)

        ndigits = len(str(int(1.0 / self.config.stepsize_deg))) + 1
        logger.info('converting contour to geojson file: ' + filepath)
        geojsoncontour.contour_to_geojson(
            contour=contours,
            geojson_filepath=filepath,
            contour_levels=levels,
            min_angle_deg=self.config.min_angle_between_segments,
            ndigits=ndigits,
            unit='min',
            stroke_width=stroke_width)
Ejemplo n.º 2
0
    def create_geojson(self, filepath, stroke_width=1, levels=[], norm=None):
        figure = Figure(frameon=False)
        FigureCanvas(figure)
        ax = figure.add_subplot(111)
        colormap = plt.cm.jet
        contours = ax.contourf(self.lonrange,
                               self.latrange,
                               self.Z,
                               levels=levels,
                               cmap=colormap)
        contours = ax.contour(self.lonrange,
                              self.latrange,
                              self.Z,
                              levels=levels,
                              norm=norm,
                              cmap=colormap,
                              linewidths=1)

        ndigits = len(str(int(1.0 / self.config.stepsize_deg))) + 1
        geojsoncontour.contour_to_geojson(
            contour=contours,
            geojson_filepath=filepath,
            contour_levels=levels,
            min_angle_deg=self.config.min_angle_between_segments,
            ndigits=ndigits,
            unit='min',
            stroke_width=stroke_width)
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
 def test_matplotlib_contour_to_geojson_none_min_angle(self):
     contours = self.create_contour()
     ndigits = 3
     geojsoncontour.contour_to_geojson(contour=contours,
                                       geojson_filepath=self.geojson_file,
                                       min_angle_deg=None,
                                       ndigits=ndigits,
                                       unit=self.config.unit,
                                       stroke_width=5)
     self.assertTrue(os.path.exists(self.geojson_file))
     os.remove(self.geojson_file)
Ejemplo n.º 5
0
    def create_contour_json(self, filepath):
        logger.info('START: create contour json tiles')
        zoomfactor = 2.0
        self.Z = scipy.ndimage.zoom(self.Z, zoom=zoomfactor, order=1)
        self.lonrange = scipy.ndimage.zoom(self.lonrange, zoom=zoomfactor, order=1)
        self.latrange = scipy.ndimage.zoom(self.latrange, zoom=zoomfactor, order=1)

        figure = Figure(frameon=False)
        FigureCanvas(figure)
        ax = figure.add_subplot(111)
        contours = ax.contour(
            self.lonrange, self.latrange, self.Z,
            levels=self.config.levels,
            cmap=self.config.colormap,
            norm=self.config.norm
        )
        figure.clear()

        ndigits = 4
        logger.info('converting contour to geojson')
        geojsoncontour.contour_to_geojson(
            contour=contours,
            geojson_filepath=filepath + '.geojson',
            contour_levels=self.config.levels,
            min_angle_deg=self.config.min_angle_between_segments,
            ndigits=ndigits,
            unit=self.config.unit,
            stroke_width=1
        )

        world_bounding_box_filepath = 'data/world_bounding_box.geojson'
        assert os.path.exists(world_bounding_box_filepath)

        togeojsontiles.geojson_to_mbtiles(
            filepaths=[filepath + '.geojson', world_bounding_box_filepath],
            tippecanoe_dir=TIPPECANOE_DIR,
            mbtiles_file='out.mbtiles',
            minzoom=0,
            maxzoom=5,
            full_detail=10,
            lower_detail=9,
            min_detail=7
        )

        logger.info('converting mbtiles to geojson-tiles')
        togeojsontiles.mbtiles_to_geojsontiles(
            tippecanoe_dir=TIPPECANOE_DIR,
            tile_dir=os.path.join(filepath, 'tiles/'),
            mbtiles_file='out.mbtiles',
        )
        logger.info('DONE: create contour json tiles')
Ejemplo n.º 6
0
 def test_matplotlib_contour_to_geojson(self):
     contours = self.create_contour()
     ndigits = 3
     geojsoncontour.contour_to_geojson(
         contour=contours,
         geojson_filepath=self.geojson_file,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit,
         stroke_width=5
     )
     self.assertTrue(os.path.exists(self.geojson_file))
     self.assertTrue(filecmp.cmp(self.benchmark_geojson_file, self.geojson_file))
     os.remove(self.geojson_file)
Ejemplo n.º 7
0
 def test_matplotlib_contour_to_geojson(self):
     contours = self.create_contour()
     ndigits = 3
     geojsoncontour.contour_to_geojson(
         contour=contours,
         geojson_filepath=self.geojson_file,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit,
         stroke_width=5)
     self.assertTrue(os.path.exists(self.geojson_file))
     self.assertTrue(
         filecmp.cmp(self.benchmark_geojson_file, self.geojson_file))
     os.remove(self.geojson_file)
Ejemplo n.º 8
0
    def create_geojson(self,
                       filepath,
                       stroke_width=1,
                       levels=[],
                       norm=None,
                       overwrite=False):
        if not overwrite and os.path.exists(filepath):
            logger.error('Output file ' + filepath +
                         ' already exists. Will not override.')
            return

        figure = Figure(frameon=False)
        FigureCanvas(figure)
        ax = figure.add_subplot(111)
        # contours = plt.contourf(lonrange, latrange, Z, levels=levels, cmap=plt.cm.plasma)
        contours = ax.contour(self.lonrange,
                              self.latrange,
                              self.Z,
                              levels=levels,
                              norm=norm,
                              cmap=plt.cm.jet,
                              linewidths=3)

        ndigits = len(str(int(1.0 / self.config.stepsize_deg))) + 1
        logger.info('converting contour to geojson file: ' + filepath)
        geojsoncontour.contour_to_geojson(
            contour=contours,
            geojson_filepath=filepath,
            contour_levels=levels,
            min_angle_deg=self.config.min_angle_between_segments,
            ndigits=ndigits,
            unit='min',
            stroke_width=stroke_width)

        cbar = figure.colorbar(contours, format='%d', orientation='horizontal')
        cbar.set_label('Travel time [minutes]')
        # cbar.set_ticks(self.config.colorbar_ticks)
        ax.set_visible(False)
        figure.savefig(
            filepath.replace('.geojson', '') + "_colorbar.png",
            dpi=90,
            bbox_inches='tight',
            pad_inches=0,
            transparent=True,
        )
Ejemplo n.º 9
0
 def test_return_string_if_destination_file_not_provided(self):
     contours = self.create_contour()
     ndigits = 3
     result = geojsoncontour.contour_to_geojson(
         contour=contours,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit,
         stroke_width=5)
     self.assertTrue(isinstance(result, str))
Ejemplo n.º 10
0
 def test_contour_to_geojson_extra_properties(self):
     contour = self.create_contour()
     ndigits = 3
     geojson_properties = {
         'description': 'A description',
         'stroke-opacity': 1.0
     }
     geojsoncontour.contour_to_geojson(
         contour=contour,
         geojson_filepath=self.geojson_properties_file,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit,
         stroke_width=5,
         geojson_properties=geojson_properties
     )
     self.assertTrue(os.path.exists(self.geojson_properties_file))
     self.assertTrue(filecmp.cmp(self.benchmark_geojson_properties_file, self.geojson_properties_file))
     os.remove(self.geojson_properties_file)
Ejemplo n.º 11
0
 def test_contour_to_geojson_extra_properties(self):
     contour = self.create_contour()
     ndigits = 3
     geojson_properties = {
         'description': 'A description',
         'stroke-opacity': 1.0
     }
     geojsoncontour.contour_to_geojson(
         contour=contour,
         geojson_filepath=self.geojson_properties_file,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit,
         stroke_width=5,
         geojson_properties=geojson_properties)
     self.assertTrue(os.path.exists(self.geojson_properties_file))
     self.assertTrue(
         filecmp.cmp(self.benchmark_geojson_properties_file,
                     self.geojson_properties_file))
     os.remove(self.geojson_properties_file)
Ejemplo n.º 12
0
 def test_return_string_if_destination_file_not_provided(self):
     contours = self.create_contour()
     ndigits = 3
     result = geojsoncontour.contour_to_geojson(
         contour=contours,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit,
         stroke_width=5
     )
     self.assertTrue(isinstance(result, str))
Ejemplo n.º 13
0
def weimer(request):
    tmstpd = request.GET.get('tmstp')
    mod = request.GET.get('mod')
    data_to_query = tmstpd
    # url = 'https://geomagnet.ru/weimer_api/?type=epot&tmstp=2015-03-17-23:15'
    url = 'https://geomagnet.ru/weimer_api/?type=epot&tmstp=' + data_to_query
    logo = urllib.request.urlopen(url).read()
    fff = logo
    if (str(json.loads(fff))[2] == 'e'):
        url = 'https://geomagnet.ru/weimer_api/?type=epot&tmstp=2021-02-01-05:21'
        logo = urllib.request.urlopen(url).read()
        fff = logo
    arr = []
    for line in fff.decode().splitlines():
        s = line.strip()
        arr.append(s)
    j = json.loads(''.join(arr))
    arr1 = []
    data = j['coordinates']
    for k in range(1, len(data)):
        arr_ = []
        if (str(data[k][2]) != '0' and str(data[k][2]) != '1'
                and str(data[k][2]) != '2'):
            arr_.append(int(data[k][2]))
            arr_.append(float(data[k][1]))
            arr_.append(float(data[k][0]))
            arr1.append(arr_)
    arr1 = np.array(arr1)
    d = arr1
    import matplotlib.tri as tri
    z = d[:, 0]
    x = d[:, 2]
    y = d[:, 1]
    xi = np.sort(np.unique(x))
    yi = np.sort(np.unique(y))
    from scipy.ndimage.filters import gaussian_filter
    triang = tri.Triangulation(x, y)
    interpolator = tri.LinearTriInterpolator(triang, z)
    Xi, Yi = np.meshgrid(xi, yi)
    zi = interpolator(Xi, Yi)
    zi = gaussian_filter(zi, sigma=.7)
    levels = 20  # len(np.unique(z))
    contour = plt.contour(xi,
                          yi,
                          zi,
                          levels=levels,
                          cmap=plt.cm.jet,
                          extend='both')  #
    geojson = geojsoncontour.contour_to_geojson(contour=contour,
                                                stroke_width=10)
    return HttpResponse(geojson)
Ejemplo n.º 14
0
 def test_return_python_object_if_serialize_argument_false(self):
     contours = self.create_contour()
     ndigits = 3
     result = geojsoncontour.contour_to_geojson(
         serialize=False,
         geojson_filepath=self.geojson_file,
         strdump=True,
         contour=contours,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit,
         stroke_width=5)
     self.assertTrue(isinstance(result, dict))
     self.assertEqual(result["type"], "FeatureCollection")
Ejemplo n.º 15
0
def plot_kde(map, data, limits, name, cmap):

    lat_min, lat_max, lon_min, lon_max = limits

    ##### GET KDES
    bandwidth = 5e-4
    kde = KernelDensity(kernel='gaussian',
                        bandwidth=bandwidth,
                        metric='haversine',
                        atol=0.1)
    kde.fit(np.pi / 180.0 * data[['lat', 'lon']])

    x = np.linspace(lon_min, lon_max, 500)
    y = np.linspace(lat_min, lat_max, 200)
    lon, lat = np.meshgrid(x, y)

    score = np.exp(
        kde.score_samples(
            np.pi / 180.0 *
            np.array([lat.reshape(-1), lon.reshape(-1)]).T))
    score = score.reshape(lon.shape) / 25e6

    ##### SET CMAP WITH ALPHA
    mycmap = cmap(np.arange(cmap.N))
    mycmap[:, -1] = np.linspace(0, 0.9, cmap.N)
    mycmap = ListedColormap(mycmap)

    ##### CREATE CONTOUR THROUGH MPL
    contour = plt.contour(lon, lat, score, 30, cmap=mycmap)

    ##### CONVERT  CONTOUR TO GEOJSON OBJECT
    geojson = geojsoncontour.contour_to_geojson(
        contour=contour,
        min_angle_deg=1.0,
        ndigits=10,
        stroke_width=2,
        #fill_opacity=0.8
    )

    ##### ADD GEOJSON OBJECT TO PLOT
    folium.GeoJson(
        geojson,
        style_function=lambda x: {
            'color': x['properties']['stroke'],
            'weight': x['properties']['stroke-width'],
            #'fillColor': None,#x['properties']['fill'],
            'opacity': 1.0,
            #'fillOpacity': 0.0,
        }).add_to(folium.FeatureGroup(name=name).add_to(map))
Ejemplo n.º 16
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
        )

        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
        )
        self.assertTrue(os.path.exists(self.geojson_file))
        self.assertTrue(filecmp.cmp(self.benchmark_geojson_file, self.geojson_file))
        os.remove(self.geojson_file)
Ejemplo n.º 17
0
 def test_return_python_object_if_serialize_argument_false(self):
     contours = self.create_contour()
     ndigits = 3
     result = geojsoncontour.contour_to_geojson(
         serialize=False,
         geojson_filepath=self.geojson_file,
         strdump=True,
         contour=contours,
         min_angle_deg=self.config.min_angle_between_segments,
         ndigits=ndigits,
         unit=self.config.unit,
         stroke_width=5
     )
     self.assertTrue(isinstance(result, dict))
     self.assertEqual(result["type"], "FeatureCollection")
Ejemplo n.º 18
0
def store_bathy_contours(
    contour_file='contours.geojson',
    levels=[0, 100, 500, 1000, 2000, 3000],
):
    """ Store bathymetric contours as a geojson
    The geojson may be used for folium plots
    """
    # Create contour data lon_range, lat_range, Z
    depth = -xr.open_dataset(_bathy_file)['elevation']
    contours = depth.plot.contour(levels=levels, cmap='gray_r')

    # Convert matplotlib contour to geojson
    from geojsoncontour import contour_to_geojson
    contours_geojson = contour_to_geojson(
        contour=contours,
        geojson_filepath=os.path.join(bathy_dir, contour_file),
        ndigits=3,
        unit='m',
    )
Ejemplo n.º 19
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
# numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
# Return evenly spaced numbers over a specified interval.
# num = number of samples to generate
contourIntervals = {
  # "1": numpy.linspace(start = 0, stop = 150, num = n_contours["1"]),
  # "2": numpy.linspace(start = 0, stop = 150, num = n_contours["2"]),
  # "3": numpy.linspace(start = 0, stop = 150, num = n_contours["3"]),
  # "5": numpy.linspace(start = 0, stop = 150, num = n_contours["5"]),
  "10": numpy.linspace(start = 0, stop = 150, num = n_contours["10"])
}

# plot contour
for interval in contourIntervals:
  contour_grey = ax.contour(lonRange, latRange, pm25Value,\
    levels = contourIntervals[interval],\
    cmap = None,\
    colors = "black"\
  )

  ### Convert matplotlib contour to geojson
  geojsoncontour.contour_to_geojson(
    contour = contour_grey,
    geojson_filepath = DIR + 'data/pm25Contour_grey_' + interval + '.geojson',
    min_angle_deg = 10.0,
    ndigits = 3,
    stroke_width = 2,
    unit = "μg/m^3"
  )

end = time.time()
logger.info("pm2.5 contour geojson completes: %f" % (end - start))
import geojsoncontour as gjc
import matplotlib.cm as cm

#plt.clf()
monitorData = []
lat = []
lon = []
level = []

with open( "180502-HexbinNoise.txt") as tsvFile:
    next(tsvFile)
    next(tsvFile)#skip header
    fileReader = csv.DictReader(tsvFile, delimiter='\t')
    for row in fileReader:
        monitorData.append(dict(row))
    for monitor in monitorData:
        lat.append(float(monitor['Latitude']))
        lon.append(float(monitor['Longitude']))
        level.append(float(monitor['DNL 24 hr']))
        
ax = plt.figure(figsize=(12,8)).add_subplot(111)
contour = ax.tricontour(lon, lat, level, 200, linewidths=2, extend='neither', cmap=cm.nipy_spectral)
plt.colorbar(contour, shrink=1.2, extend='neither', extendrect='true', orientation='vertical', drawedges='false')
# Default contour converison settings
gjc.contour_to_geojson(
    contour=contour,
    geojson_filepath='noiseMap.geojson',
    min_angle_deg=10.0,
    ndigits=4,
    unit='m'
)
Ejemplo n.º 22
0
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 = 10
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)
contour = ax.contour(lonrange, latrange, Z, levels=levels, cmap=plt.cm.jet)

# Convert matplotlib contour to geojson
geojsoncontour.contour_to_geojson(
    contour=contour,
    geojson_filepath='out.geojson',
    contour_levels=levels,
    min_angle_deg=10.0,
    ndigits=3,
    unit='m'
)
Ejemplo n.º 23
0
def contour(lon, lat, data, time_str, timerange_str, **kwargs):
    """Contour 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 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
        Contour levels to plot.
    linewidths: list, array
        Linewidths corresponding to each contour level
    colors : color string (hexademicals)
        Colors corresponding to each contour 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')
    if levels is not None and colors is not None:
        c = ax.contour(lon, lat, data, levels, colors=colors)
    else:
        c = ax.contour(lon, lat, data)
    geojson = json.loads(
        geojsoncontour.contour_to_geojson(contour=c, ndigits=2))

    out = []
    out.append('Title: %s %s\n' % (plotinfo, time_str))
    out.append('RefreshSeconds: 60\n')
    out.append('TimeRange: %s\n' % (timerange_str))
    for feature in geojson['features']:
        coords = feature['geometry']['coordinates']
        level = '%s' % (feature['properties']['level-value'])
        idx = feature['properties']['level-index']
        if int(levels[idx]) == int(float(level)):
            try:
                lws = list(kwargs['linewidths'])
                linewidth = lws[idx]
            except:
                linewidth = kwargs['linewidths']
        else:
            linewidth = 1

        rgb = hex2rgb(feature['properties']['stroke'])
        out.append('Color: %s 255\n' % (' '.join(rgb)))
        out.append('Line: %s, 0, "%s"\n' % (linewidth, level))
        for coord in coords:
            out.append(' %s, %s\n' % (coord[1], coord[0]))
        out.append('End:\n\n')
    plt.close(fig)
    return out
Ejemplo n.º 24
0
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 = 10
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)
contour = ax.contour(lonrange, latrange, Z, levels=levels, cmap=plt.cm.jet)

# Convert matplotlib contour to geojson
geojsoncontour.contour_to_geojson(contour=contour,
                                  geojson_filepath='out.geojson',
                                  contour_levels=levels,
                                  min_angle_deg=10.0,
                                  ndigits=3,
                                  unit='m')
Ejemplo n.º 25
0
def test(request):
    tmstpd = request.GET.get('tmstp')
    mod = request.GET.get('mod')
    data_to_query = tmstpd
    just_date = tmstpd[0:10]
    date1 = time.strptime(just_date, "%Y-%m-%d")
    date2 = time.strptime('2020-10-30', "%Y-%m-%d")
    if (mod == 'w'):
        #
        # url = 'https://geomagnet.ru/weimer_api/?type=epot&tmstp='+data_to_query
        url = 'https://geomagnet.ru/weimer_api/?type=epot&tmstp=2021-01-24-20:02'
        logo = urllib.request.urlopen(url).read()
        fff = logo
        arr = []
        for line in fff.decode().splitlines():
            s = line.strip()
            arr.append(s)
        j = json.loads(''.join(arr))
        arr1 = []
        data = j['coordinates']
        for k in range(1, len(data)):
            arr_ = []
            arr_.append(int(data[k][2]))
            arr_.append(float(data[k][1]))
            arr_.append(float(data[k][0]))
            arr1.append(arr_)
        arr1 = np.array(arr1)
        d = arr1
        import matplotlib.tri as tri
        z = d[:, 0]
        x = d[:, 2]
        y = d[:, 1]
        xi = np.sort(np.unique(x))
        yi = np.sort(np.unique(y))
        from scipy.ndimage.filters import gaussian_filter
        triang = tri.Triangulation(x, y)
        interpolator = tri.LinearTriInterpolator(triang, z)
        Xi, Yi = np.meshgrid(xi, yi)
        zi = interpolator(Xi, Yi)
        zi = gaussian_filter(zi, sigma=.7)
        levels = len(np.unique(z))
        contour = plt.contour(xi,
                              yi,
                              zi,
                              levels=levels,
                              cmap=plt.cm.jet,
                              extend='both')  #
        geojson = geojsoncontour.contour_to_geojson(contour=contour,
                                                    stroke_width=10)
        return HttpResponse(geojson)
        ###
    #
    else:
        longi = [i * 0.3515625 - 180 for i in range(1025)]
        lati = [j * 0.3515625 - 90 for j in range(513)]
        ctr = 0
        ct = 0
        #    data_to_query = tmstpd
        #    just_date = tmstpd[0:10]
        #    date1 = time.strptime(just_date, "%Y-%m-%d")
        #    date2 = time.strptime('2020-10-30', "%Y-%m-%d")
        typ = 'new'
        if (date1 >= date2):
            typ = 'new'
        else:
            typ = 'old'

        if typ == 'new':
            # return redirect('/getdata?type=aurora&dt='+data_to_query)
            # url = '/getdata?type=aurora&dt='+data_to_query
            # logo = urllib.request.urlopen(url).read();
            # fff = logo;
            # arr = [];
            # for line in fff.decode().splitlines():
            #     s=line.strip()
            #     arr.append(s)
            # j = json.loads(''.join(arr));
            j = getdata('aurora', data_to_query)
            if j is None:
                return JsonResponse(None, safe=False)
            arr1 = []
            data = j['coordinates']
            for k in range(1, len(data)):
                arr_ = []
                if (str(data[k][2]) != '0' and str(data[k][2]) != '1'
                        and str(data[k][2]) != '2'):
                    arr_.append(int(data[k][2]))
                    arr_.append(float(data[k][1]))
                    arr_.append(float(data[k][0]))
                    arr1.append(arr_)
            arr1 = np.array(arr1)
            d = arr1
            import matplotlib.tri as tri
            z = d[:, 0]
            x = d[:, 2]
            y = d[:, 1]
            xi = np.sort(np.unique(x))
            yi = np.sort(np.unique(y))
            from scipy.ndimage.filters import gaussian_filter
            triang = tri.Triangulation(x, y)
            interpolator = tri.LinearTriInterpolator(triang, z)
            Xi, Yi = np.meshgrid(xi, yi)
            zi = interpolator(Xi, Yi)
            zi = gaussian_filter(zi, sigma=.7)
            levels = len(np.unique(z))
            contour = plt.contour(xi,
                                  yi,
                                  zi,
                                  levels=levels,
                                  cmap=plt.cm.jet,
                                  extend='both')  #
            geojson = geojsoncontour.contour_to_geojson(contour=contour,
                                                        stroke_width=10)
            return HttpResponse(geojson)

        if typ == 'old':
            logo = getdata('aurora', data_to_query)
            # url = '/getdata?type=aurora&dt='+data_to_query
            # logo = urllib.request.urlopen(url).read();
            fff = logo
            arr = []
            for line in fff.splitlines():
                if (ctr == 1025):
                    ctr = 0
                    ct += 1
                if '#' in line.decode():
                    continue
                s = line.split()
                for k in range(1, len(s), 3):
                    ciqw = 0
                    if ((s[k - 1]) == '0' or (s[k - 1]) == '1'
                            or (s[k - 1]) == '2'):
                        continue
                    arr_ = []
                    arr_.append(float(s[k - 1]))
                    arr_.append((lati[ct]))
                    arr_.append((longi[k - 1]))
                    arr.append(arr_)
                ct += 1
            arr = np.array(arr)
            contour_data = pd.DataFrame({
                'category': arr[..., 0],
                'latitude': arr[..., 1],
                'longitude': arr[..., 2]
            })
            Z = contour_data.pivot_table(index='longitude',
                                         columns='latitude',
                                         values='category').T.values
            X_unique = np.sort(contour_data['longitude'].unique())
            Y_unique = np.sort(contour_data['latitude'].unique())
            X, Y = np.meshgrid(X_unique, Y_unique)
            n_contours = 50  # contour_data['category'].nunique()#40
            levels = np.linspace(start=0, stop=100, num=n_contours)
            contour = plt.contour(X, Y, Z, levels=levels, cmap=plt.cm.jet)
            geojson = geojsoncontour.contour_to_geojson(
                contour=contour,
                min_angle_deg=1.0,
                ndigits=1,
                stroke_width=2,
            )
            return HttpResponse(geojson)