Exemplo n.º 1
0
 def test_offset(self):
     crs = ccrs.Sinusoidal()
     crs_offset = ccrs.Sinusoidal(false_easting=1234, false_northing=-4321)
     other_args = {'ellps=WGS84', 'lon_0=0.0', 'x_0=1234', 'y_0=-4321'}
     check_proj_params('sinu', crs_offset, other_args)
     assert tuple(np.array(crs.x_limits) + 1234) == crs_offset.x_limits
     assert tuple(np.array(crs.y_limits) - 4321) == crs_offset.y_limits
Exemplo n.º 2
0
 def test_offset(self):
     crs = ccrs.Sinusoidal()
     crs_offset = ccrs.Sinusoidal(false_easting=1234, false_northing=-4321)
     expected = ('+ellps=WGS84 +proj=sinu +lon_0=0.0 +x_0=1234 '
                 '+y_0=-4321 +no_defs')
     assert_equal(crs_offset.proj4_init, expected)
     assert_equal(tuple(np.array(crs.x_limits) + 1234), crs_offset.x_limits)
     assert_equal(tuple(np.array(crs.y_limits) - 4321), crs_offset.y_limits)
Exemplo n.º 3
0
def test_pretty_plot():

    image = os.path.join(root_path.test_root, '00_testdata', 'plot',
        'ESACCI-SOILMOISTURE-L3S-SSMV-COMBINED-20100701000000-fv04.5.nc')
    ds = Dataset(image)
    dat = ds.variables['sm'][:]
    dat = dat.filled(np.nan).flatten()
    _, resampled_lons, resampled_lats, _  = SMECV_Grid_v052(None).get_grid_points()

    index =pd.MultiIndex.from_arrays(np.array([resampled_lats, resampled_lons]),
                                     names=['lats', 'lons'])
    df = pd.DataFrame(index=index, data={'sm': dat}).dropna()

    f, imax, im = cp_map(df, 'sm', resxy=(0.25,0.25), cbrange=(0,50.), veg_mask=True,
                         cmap=cm_sm, projection=ccrs.Sinusoidal(),
                         title='Overloaded Plot with too much Information',
                         ocean=True, land='grey', gridspace=(60,20), states=True,
                         borders=True,  llc=(-179.9999, -90.), urc=(179.9999, 90),
                         cb_label='ESA CCI SM [$m^3/m^3$]', cb_labelsize=7, scale_factor=100,
                         grid_label_loc='0111', coastline_size='110m', cb_extend='both',
                         cb_ext_label_min='DRY', cb_ext_label_max='WET', cb_loc='right')

    out_dir = tempfile.mkdtemp()
    try:
        filename = 'pretty_plot.png'
        f.savefig(os.path.join(out_dir, 'pretty_plot.png'), dpi=200)
        assert os.path.isfile(os.path.join(out_dir, filename))
    finally:
        shutil.rmtree(out_dir)
Exemplo n.º 4
0
    def __init__(self, src_cube, tgt_grid_cube, method, projection=None):
        """
        Create a regridder for conversions between the source
        and target grids.

        Args:

        * src_cube:
            The :class:`~iris.cube.Cube` providing the source points.
        * tgt_grid_cube:
            The :class:`~iris.cube.Cube` providing the target grid.
        * method:
            Either 'linear' or 'nearest'.
        * projection:
            The projection in which the interpolation is performed. If None, a
            PlateCarree projection is used. Defaults to None.

        """
        # Validity checks.
        if not isinstance(src_cube, iris.cube.Cube):
            raise TypeError("'src_cube' must be a Cube")
        if not isinstance(tgt_grid_cube, iris.cube.Cube):
            raise TypeError("'tgt_grid_cube' must be a Cube")

        # Snapshot the state of the target cube to ensure that the regridder
        # is impervious to external changes to the original source cubes.
        self._tgt_grid = snapshot_grid(tgt_grid_cube)

        # Check the target grid units.
        for coord in self._tgt_grid:
            self._check_units(coord)

        # Whether to use linear or nearest-neighbour interpolation.
        if method not in ('linear', 'nearest'):
            msg = 'Regridding method {!r} not supported.'.format(method)
            raise ValueError(msg)
        self._method = method

        src_x_coord, src_y_coord = get_xy_coords(src_cube)
        if src_x_coord.coord_system != src_y_coord.coord_system:
            raise ValueError("'src_cube' lateral geographic coordinates have "
                             "differing coordinate sytems.")
        if src_x_coord.coord_system is None:
            raise ValueError("'src_cube' lateral geographic coordinates have "
                             "no coordinate sytem.")
        tgt_x_coord, tgt_y_coord = get_xy_dim_coords(tgt_grid_cube)
        if tgt_x_coord.coord_system != tgt_y_coord.coord_system:
            raise ValueError("'tgt_grid_cube' lateral geographic coordinates "
                             "have differing coordinate sytems.")
        if tgt_x_coord.coord_system is None:
            raise ValueError("'tgt_grid_cube' lateral geographic coordinates "
                             "have no coordinate sytem.")

        if projection is None:
            globe = src_x_coord.coord_system.as_cartopy_globe()
            projection = ccrs.Sinusoidal(globe=globe)
        self._projection = projection
 def test_nearest_sinusoidal(self):
     crs = ccrs.Sinusoidal()
     res = self.src.regrid(self.global_grid,
                           ProjectedUnstructuredNearest(crs))
     self.assertArrayShapeStats(res, (1, 6, 73, 96),
                                315.891358296,
                                11.000639227,
                                rtol=1e-8)
     self.assertArrayShapeStats(res[:, 0], (1, 73, 96), 299.99993826,
                                3.9223839688e-5)
Exemplo n.º 6
0
    def test_eccentric_globe(self):
        globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500,
                           ellipse=None)
        crs = ccrs.Sinusoidal(globe=globe)
        other_args = {'a=1000', 'b=500', 'lon_0=0.0', 'x_0=0.0', 'y_0=0.0'}
        check_proj_params('sinu', crs, other_args)

        assert_almost_equal(np.array(crs.x_limits),
                            [-3141.59, 3141.59], decimal=2)
        assert_almost_equal(np.array(crs.y_limits),
                            [-1216.60, 1216.60], decimal=2)
Exemplo n.º 7
0
    def test_default(self):
        crs = ccrs.Sinusoidal()
        other_args = {'ellps=WGS84', 'lon_0=0.0', 'x_0=0.0', 'y_0=0.0'}
        check_proj_params('sinu', crs, other_args)

        assert_almost_equal(np.array(crs.x_limits),
                            [-20037508.3428, 20037508.3428],
                            decimal=4)
        assert_almost_equal(np.array(crs.y_limits),
                            [-10001965.7293, 10001965.7293],
                            decimal=4)
Exemplo n.º 8
0
    def test_central_longitude(self, lon):
        crs = ccrs.Sinusoidal(central_longitude=lon)
        other_args = {'ellps=WGS84', f'lon_0={lon}', 'x_0=0.0', 'y_0=0.0'}
        check_proj_params('sinu', crs, other_args)

        assert_almost_equal(np.array(crs.x_limits),
                            [-20037508.3428, 20037508.3428],
                            decimal=4)
        assert_almost_equal(np.array(crs.y_limits),
                            [-10001965.7293, 10001965.7293],
                            decimal=4)
Exemplo n.º 9
0
    def __create_plot_objects(self):
        """
        Create plot objects
        """
        years_fmt = mdates.DateFormatter('%Y')

        # Get projection from first data variable
        for key in self.ts.data.data_vars:
            proj4_string = getattr(self.ts.data, key).crs
            break

        # If projection is Sinusoidal
        srs = get_projection(proj4_string)
        if srs.GetAttrValue('PROJECTION') == 'Sinusoidal':
            globe=ccrs.Globe(ellipse=None,
                semimajor_axis=6371007.181,
                semiminor_axis=6371007.181)

            self.projection = ccrs.Sinusoidal(globe=globe)
        else:
            globe = ccrs.Globe(ellipse='WGS84')
            self.projection = ccrs.Mollweide(globe=globe)

        # Figure
        self.fig = plt.figure(figsize=(11.0, 6.0))

        # subplot2grid((rows,cols), (row,col)
        # Left, right and climatology plots
        self.left_p = plt.subplot2grid((4, 4), (0, 0), rowspan=2,
                projection=self.projection)
        self.right_p = plt.subplot2grid((4, 4), (0, 1), rowspan=2,
                sharex=self.left_p, sharey=self.left_p,
                projection=self.projection)

        if self.projection is not None:
            for _axis in [self.left_p, self.right_p]:
                _axis.coastlines(resolution='10m', color='white')
                _axis.add_feature(cfeature.BORDERS, edgecolor='white')
                _axis.gridlines()

        self.climatology = plt.subplot2grid((4, 4), (2, 0),
                rowspan=2, colspan=2)

        # Time series plot
        self.observed = plt.subplot2grid((4, 4), (0, 2), colspan=2)
        self.observed.xaxis.set_major_formatter(years_fmt)

        self.trend_p = plt.subplot2grid((4, 4), (1, 2), colspan=2,
                sharex=self.observed)
        self.seasonal_p = plt.subplot2grid((4, 4), (2, 2), colspan=2,
                sharex=self.observed)
        self.resid_p = plt.subplot2grid((4, 4), (3, 2), colspan=2,
                sharex=self.observed)
Exemplo n.º 10
0
    def test_default(self):
        crs = ccrs.Sinusoidal()
        expected = ('+ellps=WGS84 +proj=sinu +lon_0=0.0 '
                    '+x_0=0.0 +y_0=0.0 +no_defs')
        assert_equal(crs.proj4_init, expected)

        assert_almost_equal(np.array(crs.x_limits),
                            [-20037508.3428, 20037508.3428],
                            decimal=4)
        assert_almost_equal(np.array(crs.y_limits),
                            [-10001965.7293, 10001965.7293],
                            decimal=4)
Exemplo n.º 11
0
    def test_eccentric_globe(self):
        globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500,
                           ellipse=None)
        crs = ccrs.Sinusoidal(globe=globe)
        expected = ('+a=1000 +b=500 +proj=sinu +lon_0=0.0 +x_0=0.0 '
                    '+y_0=0.0 +no_defs')
        assert_equal(crs.proj4_init, expected)

        assert_almost_equal(np.array(crs.x_limits),
                            [-3141.59, 3141.59], decimal=2)
        assert_almost_equal(np.array(crs.y_limits),
                            [-1216.60, 1216.60], decimal=2)
Exemplo n.º 12
0
def plot(family_locations,
         resources,
         maximum=3650000000.0,
         hexes=[],
         color_schema={}) -> None:
    plt.gcf().set_size_inches(30, 30)
    ax = plt.axes(projection=ccrs.Sinusoidal(-98))

    if resources is not None:
        raise NotImplementedError

    ax.coastlines("50m")
    ax.set_extent((hexgrid.AMERICAS.w, hexgrid.AMERICAS.e, hexgrid.AMERICAS.s,
                   hexgrid.AMERICAS.n))

    G, xyz = connect_agents(family_locations)

    new_color_schema = {}
    # for community in G.community_label_propagation():
    # for community in G.community_infomap():
    for community in G.community_fastgreedy().as_clustering():
        pos = numpy.array([(xyz[n][0], xyz[n][1]) for n in community])
        s = [xyz[n][2] for n in community]
        mean = numpy.mean(pos, axis=0)
        closest = numpy.inf
        for location, popsize in color_schema:
            dist = numpy.linalg.norm(mean - location) + abs(
                numpy.log(
                    (popsize + 1) / (len(community) + 1))) / numpy.log(1.04)
            if dist > 20:
                continue
            if dist < closest:
                closest = dist
                reference = location, popsize
        if numpy.isfinite(closest):
            color = color_schema.pop(reference)
        else:
            color = numpy.random.random(3)

        new_color_schema[tuple(mean), len(community)] = color

        ax.scatter(*pos.T,
                   s=s,
                   c=[color],
                   alpha=0.2,
                   edgecolors=None,
                   transform=ccrs.Geodetic())

    for key in list(color_schema):
        color_schema.pop(key)
    color_schema.update(new_color_schema)
Exemplo n.º 13
0
    def on_pbOverlay_click(self):
        """
        EXPERIMENTAL
        Overlay a specific geometry on maps
        """
        fname = open_file_dialog(dialog_type = 'open_specific',
                data_format = 'Shapefile',
                extension = 'shp')

        # If there is no selection
        if fname == '':
            return None

        # If file does not exists
        if os.path.exists(fname) is False:
            return None

        # Open file
        spatial_reference = self.get_shapefile_spatial_reference(fname)

        # Get projection from first data variable
        for key in self.ts.data.data_vars:
            proj4_string = getattr(self.ts.data, key).crs
            break

        # If projection is Sinusoidal
        srs = get_projection(proj4_string)
        if srs.GetAttrValue('PROJECTION') == 'Sinusoidal':
            # Get ellipsoid/datum parameters
            globe=ccrs.Globe(ellipse=None,
                semimajor_axis=spatial_reference.GetSemiMajor(),
                semiminor_axis=spatial_reference.GetSemiMinor())

            self.shapefile_projection = ccrs.Sinusoidal(globe=globe)
            #ccrs.CRS(spatial_reference.ExportToProj4())
        else:
            globe = ccrs.Globe(ellipse='WGS84')
            self.shapefile_projection = ccrs.Mollweide(globe=globe)

        try:
            shape_feature = ShapelyFeature(cReader(fname).geometries(),
                self.shapefile_projection, facecolor='none')

            for _axis in [self.left_p, self.right_p]:
                _axis.add_feature(shape_feature,
                        edgecolor='gray')
        except:
            return None

        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
Exemplo n.º 14
0
def proj_grid(lon_0, lat_0, dx, nx, ny, bearing, dy=None):
    """
    Define a regular grid over geographical space.

    Parameters
    ----------
    lon_0, lat_0: float
        PlateCarree coordinates of mean grid position.
    dx, dy: float
        Horizontal and vertical resolutions in meters.
    nx, ny: int
        Horizontal and vertical number of grid points.
    bearing: float
        Compass orientation of horizontal dimension.

    Returns
    -------
    2D array
        Horizontal and vertical grid coordinates.
    cartopy.crs
        Coordinate reference system in which grid is defined.

    """
    def _crs2crs(x, y, target, origin=ccrs.PlateCarree()):
        """
        Using the version in convert results in a circular import.
        """
        x, y = np.array([x, x]), np.array([y, y])
        transformed = target.transform_points(origin, x, y)
        x_dest, y_dest = transformed[0, 0], transformed[0, 1]
        return x_dest, y_dest

    # Default to equal spacing in both directions
    dy = dy or dx

    # Get equal area projection
    pj_sine = ccrs.Sinusoidal(central_longitude=lon_0)
    x_g = np.arange(0, (nx + 1) * dx, dx)
    y_g = np.arange(0, (ny + 1) * dy, dy)
    XG, YG = np.meshgrid(x_g, y_g)

    # Set to required center
    x_0, y_0 = _crs2crs(lon_0, lat_0, pj_sine)

    XG = XG - XG.mean() + x_0
    YG = YG - YG.mean() + y_0

    # Rotate
    XG, YG = rotate_frame(XG, YG, (90 - bearing) * np.pi / 180, inplace=True)

    return XG, YG, pj_sine
Exemplo n.º 15
0
def show_proj(latitudes, longitudes, angle, extent, proj, label=''):
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.collections as mplcollections
    from matplotlib.patches import Circle
    import cartopy.crs as ccrs
    from math import degrees as to_deg
    # Ustawianie kolorów
    colors = np.linspace(0, 1, num=5)
    if extent == None:
        extent = [0, 0, 0, 0]
    # Ustawianie rzutowania
    if proj == 'orto':
        bmap = ccrs.Orthographic(
            central_longitude=((extent[0] + extent[1]) / 2),
            central_latitude=((extent[2] + extent[3]) / 2))
    if proj == 'albers':
        bmap = ccrs.AlbersEqualArea(central_longitude=0)
    if proj == 'sinus':
        bmap = ccrs.Sinusoidal(central_longitude=((extent[0] + extent[1]) / 2))
    if proj == 'merc':
        bmap = ccrs.Mercator(central_longitude=((extent[0] + extent[1]) / 2))
    if proj == 'plate':
        bmap = ccrs.PlateCarree(central_longitude=((extent[0] + extent[1]) /
                                                   2))

    ax = plt.axes(projection=bmap)
    ax.set_global()
    ax.coastlines()
    ax.gridlines()
    if not extent == [0, 0, 0, 0]:
        ax.set_extent(extent)

    # Ładowanie kół opisujących maksymalną widoczność
    patches = []
    for i in range(len(latitudes)):
        patches.append(
            Circle((latitudes[i], longitudes[i]), radius=to_deg(angle[i])))

    collection = mplcollections.PatchCollection(patches,
                                                transform=ccrs.PlateCarree())
    # Rysowanie
    collection.set_array(colors)
    ax.add_collection(collection)
    ax.set_title(label)
    plt.savefig('CircleTest.png', dpi=100)
    plt.show()
    return ()
Exemplo n.º 16
0
    def on_pbOverlay_click(self):
        """
        EXPERIMENTAL
        Overlay a specific geometry on maps
        """
        fname = open_file_dialog(dialog_type = 'open_specific',
                data_format = 'Shapefile',
                extension = 'shp')

        # If there is no selection
        if fname == '':
            return None

        # If file does not exists
        if os.path.exists(fname) is False:
            return None

        # Open file
        spatial_reference = self.get_shapefile_spatial_reference(fname)

        # Get ellipsoid/datum parameters
        globe=ccrs.Globe(ellipse=None,
                semimajor_axis=spatial_reference.GetSemiMajor(),
                semiminor_axis=spatial_reference.GetSemiMinor())

        self.shapefile_projection = ccrs.Sinusoidal(globe=globe)
            #ccrs.CRS(spatial_reference.ExportToProj4())

        from IPython import embed ; ipshell = embed()

        try:
            shape_feature = ShapelyFeature(cReader(fname).geometries(),
                self.shapefile_projection, facecolor='none')

            for _axis in [self.ax]:
                _axis.add_feature(shape_feature,
                        edgecolor='gray')
        except:
            return None

        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
Exemplo n.º 17
0
    def __create_plot_objects(self):
        """
        Create plot objects
        """
        # Get projection from first data variable
        for key in self.qa_analytics.ts.data.data_vars:
            proj4_string = getattr(self.qa_analytics.ts.data, key).crs
            break

        # If projection is Sinusoidal
        srs = get_projection(proj4_string)
        if srs.GetAttrValue('PROJECTION') == 'Sinusoidal':
            globe=ccrs.Globe(ellipse=None,
                semimajor_axis=6371007.181,
                semiminor_axis=6371007.181)

            self.projection = ccrs.Sinusoidal(globe=globe)
        else:
            globe = ccrs.Globe(ellipse='WGS84')
            self.projection = ccrs.Mollweide(globe=globe)

        # Figure
        self.fig = plt.figure(figsize=(8.0, 7.0))

        # Left plot
        self.left_p = plt.subplot2grid((2, 2), (0, 0), colspan=1,
                projection=self.projection)

        # Right plot
        self.right_p = plt.subplot2grid((2, 2), (0, 1), colspan=1,
                sharex=self.left_p, sharey=self.left_p,
                projection=self.projection)

        if self.projection is not None:
            for _axis in [self.left_p, self.right_p]:
                _axis.coastlines(resolution='10m', color='white')
                _axis.add_feature(cfeature.BORDERS, edgecolor='white')
                _axis.gridlines()

        # Time series plot
        self.ts_p = plt.subplot2grid((2, 2), (1, 0), colspan=2)
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

plt.figure(figsize=(6.0101, 3))
ax = plt.axes(projection=ccrs.Sinusoidal())
ax.coastlines(resolution='110m')
ax.gridlines()
Exemplo n.º 19
0
def plot_map(ds: xr.Dataset,
             var: VarName.TYPE = None,
             indexers: DictLike.TYPE = None,
             time: TimeLike.TYPE = None,
             region: PolygonLike.TYPE = None,
             projection: str = 'PlateCarree',
             central_lon: float = 0.0,
             title: str = None,
             properties: DictLike.TYPE = None,
             file: str = None) -> Figure:
    """
    Create a geographic map plot for the variable given by dataset *ds* and variable name *var*.

    Plots the given variable from the given dataset on a map with coastal lines.
    In case no variable name is given, the first encountered variable in the
    dataset is plotted. In case no *time* is given, the first time slice
    is taken. It is also possible to set extents of the plot. If no extents
    are given, a global plot is created.

    The plot can either be shown using pyplot functionality, or saved,
    if a path is given. The following file formats for saving the plot
    are supported: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg,
    svgz, tif, tiff

    :param ds: the dataset containing the variable to plot
    :param var: the variable's name
    :param indexers: Optional indexers into data array of *var*. The *indexers* is a dictionary
           or a comma-separated string of key-value pairs that maps the variable's dimension names
           to constant labels. e.g. "layer=4".
    :param time: time slice index to plot, can be a string "YYYY-MM-DD" or an integer number
    :param region: Region to plot
    :param projection: name of a global projection, see http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html
    :param central_lon: central longitude of the projection in degrees
    :param title: an optional title
    :param properties: optional plot properties for Python matplotlib,
           e.g. "bins=512, range=(-1.5, +1.5)"
           For full reference refer to
           https://matplotlib.org/api/lines_api.html and
           https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.contourf.html
    :param file: path to a file in which to save the plot
    :return: a matplotlib figure object or None if in IPython mode
    """
    if not isinstance(ds, xr.Dataset):
        raise NotImplementedError(
            'Only gridded datasets are currently supported')

    var_name = None
    if not var:
        for key in ds.data_vars.keys():
            var_name = key
            break
    else:
        var_name = VarName.convert(var)
    var = ds[var_name]

    time = TimeLike.convert(time)
    indexers = DictLike.convert(indexers) or {}
    properties = DictLike.convert(properties) or {}

    extents = None
    region = PolygonLike.convert(region)
    if region:
        lon_min, lat_min, lon_max, lat_max = region.bounds
        if not _check_bounding_box(lat_min, lat_max, lon_min, lon_max):
            raise ValueError(
                'Provided plot extents do not form a valid bounding box '
                'within [-180.0,+180.0,-90.0,+90.0]')
        extents = [lon_min, lon_max, lat_min, lat_max]

    # See http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#
    if projection == 'PlateCarree':
        proj = ccrs.PlateCarree(central_longitude=central_lon)
    elif projection == 'LambertCylindrical':
        proj = ccrs.LambertCylindrical(central_longitude=central_lon)
    elif projection == 'Mercator':
        proj = ccrs.Mercator(central_longitude=central_lon)
    elif projection == 'Miller':
        proj = ccrs.Miller(central_longitude=central_lon)
    elif projection == 'Mollweide':
        proj = ccrs.Mollweide(central_longitude=central_lon)
    elif projection == 'Orthographic':
        proj = ccrs.Orthographic(central_longitude=central_lon)
    elif projection == 'Robinson':
        proj = ccrs.Robinson(central_longitude=central_lon)
    elif projection == 'Sinusoidal':
        proj = ccrs.Sinusoidal(central_longitude=central_lon)
    elif projection == 'NorthPolarStereo':
        proj = ccrs.NorthPolarStereo(central_longitude=central_lon)
    elif projection == 'SouthPolarStereo':
        proj = ccrs.SouthPolarStereo(central_longitude=central_lon)
    else:
        raise ValueError('illegal projection: "%s"' % projection)

    figure = plt.figure(figsize=(8, 4))
    ax = plt.axes(projection=proj)
    if extents:
        ax.set_extent(extents)
    else:
        ax.set_global()

    ax.coastlines()
    var_data = _get_var_data(var,
                             indexers,
                             time=time,
                             remaining_dims=('lon', 'lat'))
    var_data.plot.contourf(ax=ax, transform=proj, **properties)

    if title:
        ax.set_title(title)

    figure.tight_layout()

    if file:
        figure.savefig(file)

    return figure if not in_notebook() else None
Exemplo n.º 20
0
def get_map_projection(
        proj_name,
        central_longitude=0.0,
        central_latitude=0.0,
        false_easting=0.0,
        false_northing=0.0,
        globe=None,
        standard_parallels=(20.0, 50.0),
        scale_factor=None,
        min_latitude=-80.0,
        max_latitude=84.0,
        true_scale_latitude=None,
        latitude_true_scale=None,  ### BOTH
        secant_latitudes=None,
        pole_longitude=0.0,
        pole_latitude=90.0,
        central_rotated_longitude=0.0,
        sweep_axis='y',
        satellite_height=35785831,
        cutoff=-30,
        approx=None,
        southern_hemisphere=False,
        zone=15):  #### numeric UTM zone

    proj_name = proj_name.lower()

    if (proj_name == 'albersequalarea'):
        proj = ccrs.AlbersEqualArea(central_longitude=central_longitude,
                                    central_latitude=central_latitude,
                                    false_easting=false_easting,
                                    false_northing=false_northing,
                                    globe=globe,
                                    standard_parallels=standard_parallels)
    elif (proj_name == 'azimuthalequidistant'):
        proj = ccrs.AzimuthalEquidistant(central_longitude=central_longitude,
                                         central_latitude=central_latitude,
                                         false_easting=false_easting,
                                         false_northing=false_northing,
                                         globe=globe)
    elif (proj_name == 'equidistantconic'):
        proj = ccrs.EquidistantConic(central_longitude=central_longitude,
                                     central_latitude=central_latitude,
                                     false_easting=false_easting,
                                     false_northing=false_northing,
                                     globe=globe,
                                     standard_parallels=standard_parallels)
    elif (proj_name == 'lambertconformal'):
        proj = ccrs.LambertConformal(
            central_longitude=-96.0,  ##########
            central_latitude=39.0,  ##########
            false_easting=false_easting,
            false_northing=false_northing,
            globe=globe,
            secant_latitudes=None,
            standard_parallels=None,  ## default: (33,45)
            cutoff=cutoff)
    elif (proj_name == 'lambertcylindrical'):
        proj = ccrs.LambertCylindrical(central_longitude=central_longitude)
    elif (proj_name == 'mercator'):
        proj = ccrs.Mercator(central_longitude=central_longitude,
                             min_latitude=min_latitude,
                             max_latitude=max_latitude,
                             latitude_true_scale=latitude_true_scale,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe,
                             scale_factor=None)  #########
    elif (proj_name == 'miller'):
        proj = ccrs.Miller(central_longitude=central_longitude, globe=globe)
    elif (proj_name == 'mollweide'):
        proj = ccrs.Mollweide(central_longitude=central_longitude,
                              false_easting=false_easting,
                              false_northing=false_northing,
                              globe=globe)
    elif (proj_name == 'orthographic'):
        proj = ccrs.Orthographic(central_longitude=central_longitude,
                                 central_latitude=central_latitude,
                                 globe=globe)
    elif (proj_name == 'robinson'):
        proj = ccrs.Robinson(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'sinusoidal'):
        proj = ccrs.Sinusoidal(central_longitude=central_longitude,
                               false_easting=false_easting,
                               false_northing=false_northing,
                               globe=globe)
    elif (proj_name == 'stereographic'):
        proj = ccrs.Stereographic(central_latitude=central_latitude,
                                  central_longitude=central_longitude,
                                  false_easting=false_easting,
                                  false_northing=false_northing,
                                  globe=globe,
                                  true_scale_latitude=true_scale_latitude,
                                  scale_factor=scale_factor)
    elif (proj_name == 'transversemercator'):
        proj = ccrs.TransverseMercator(
            central_longitude=central_longitude,
            central_latitude=central_latitude,
            false_easting=false_easting,
            false_northing=false_northing,
            globe=globe,
            scale_factor=1.0,  ##########
            approx=approx)
    elif (proj_name == 'utm'):
        proj = ccrs.UTM(zone,
                        southern_hemisphere=southern_hemisphere,
                        globe=globe)
    elif (proj_name == 'interruptedgoodehomolosine'):
        proj = ccrs.InterruptedGoodeHomolosine(
            central_longitude=central_longitude, globe=globe)
    elif (proj_name == 'rotatedpole'):
        proj = ccrs.RotatedPole(
            pole_longitude=pole_longitude,
            pole_latitude=pole_latitude,
            globe=globe,
            central_rotated_longitude=central_rotated_longitude)
    elif (proj_name == 'osgb'):
        proj = ccrs.OSGB(approx=approx)
    elif (proj_name == 'europp'):
        proj = ccrs.EuroPP
    elif (proj_name == 'geostationary'):
        proj = ccrs.Geostationary(central_longitude=central_longitude,
                                  satellite_height=satellite_height,
                                  false_easting=false_easting,
                                  false_northing=false_northing,
                                  globe=globe,
                                  sweep_axis=sweep_axis)
    elif (proj_name == 'nearsideperspective'):
        proj = ccrs.NearsidePerspective(central_longitude=central_longitude,
                                        central_latitude=central_latitude,
                                        satellite_height=satellite_height,
                                        false_easting=false_easting,
                                        false_northing=false_northing,
                                        globe=globe)
    elif (proj_name == 'eckerti'):
        proj = ccrs.EckertI(central_longitude=central_longitude,
                            false_easting=false_easting,
                            false_northing=false_northing,
                            globe=globe)
    elif (proj_name == 'eckertii'):
        proj = ccrs.EckertII(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'eckertiii'):
        proj = ccrs.EckertIII(central_longitude=central_longitude,
                              false_easting=false_easting,
                              false_northing=false_northing,
                              globe=globe)
    elif (proj_name == 'eckertiv'):
        proj = ccrs.EckertIV(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'eckertv'):
        proj = ccrs.EckertV(central_longitude=central_longitude,
                            false_easting=false_easting,
                            false_northing=false_northing,
                            globe=globe)
    elif (proj_name == 'eckertvi'):
        proj = ccrs.EckertVI(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'equalearth'):
        proj = ccrs.EqualEarth(central_longitude=central_longitude,
                               false_easting=false_easting,
                               false_northing=false_northing,
                               globe=globe)
    elif (proj_name == 'gnomonic'):
        proj = ccrs.Gnomonic(central_latitude=central_latitude,
                             central_longitude=central_longitude,
                             globe=globe)
    elif (proj_name == 'lambertazimuthalequalarea'):
        proj = ccrs.LambertAzimuthalEqualArea(
            central_longitude=central_longitude,
            central_latitude=central_latitude,
            globe=globe,
            false_easting=false_easting,
            false_northing=false_northing)
    elif (proj_name == 'northpolarstereo'):
        proj = ccrs.NorthPolarStereo(central_longitude=central_longitude,
                                     true_scale_latitude=true_scale_latitude,
                                     globe=globe)
    elif (proj_name == 'osni'):
        proj = ccrs.OSNI(approx=approx)
    elif (proj_name == 'southpolarstereo'):
        proj = ccrs.SouthPolarStereo(central_longitude=central_longitude,
                                     true_scale_latitude=true_scale_latitude,
                                     globe=globe)
    else:
        # This is same as "Geographic coordinates"
        proj = ccrs.PlateCarree(central_longitude=central_longitude,
                                globe=globe)

    return proj
Exemplo n.º 21
0
    def _plot(self, qa_analytics, cmap='viridis', dpi=72):
        """
        From the TATSSI QA Analytics object plots:
          - Percentage of data available
          - Maximum gap length
        """
        uic.loadUi('plot.ui', self)

        # Get projection from first data variable
        for key in qa_analytics.ts.data.data_vars:
            proj4_string = getattr(qa_analytics.ts.data, key).crs
            break

        # If projection is Sinusoidal
        srs = get_projection(proj4_string)
        if srs.GetAttrValue('PROJECTION') == 'Sinusoidal':
            globe=ccrs.Globe(ellipse=None,
                semimajor_axis=6371007.181,
                semiminor_axis=6371007.181)

            proj = ccrs.Sinusoidal(globe=globe)
        else:
            globe = ccrs.Globe(ellipse='WGS84')
            proj = ccrs.Mollweide(globe=globe)

        fig, (ax, bx) = plt.subplots(1, 2, figsize=(16, 9.6),
                #sharex=True, sharey=True, tight_layout=True, dpi=dpi,
                sharex=True, sharey=True, dpi=dpi,
                subplot_kw=dict(projection=proj))

        if proj is not None:
            for _axis in [ax, bx]:
                _axis.coastlines(resolution='10m', color='white')
                _axis.add_feature(cfeature.BORDERS, edgecolor='white')
                _axis.gridlines()

        qa_analytics.pct_data_available.plot.imshow(
                ax=ax, cmap=cmap,
                cbar_kwargs={'orientation':'horizontal',
                             'pad' : 0.005},
                transform=proj
        )

        ax.set_frame_on(False)
        ax.axis('off')
        ax.set_aspect('equal')
        ax.title.set_text('% of data available')

        qa_analytics.max_gap_length.plot.imshow(
                ax=bx, cmap=cmap,
                cbar_kwargs={'orientation':'horizontal',
                             'pad' : 0.005},
                transform=proj
        )

        bx.set_frame_on(False)
        bx.axis('off')
        bx.set_aspect('equal')
        bx.title.set_text('Max gap-length')

        # Set plot on the plot widget
        self.plotWidget = FigureCanvas(fig)
        lay = QtWidgets.QVBoxLayout(self.content_plot)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(self.plotWidget)

        # Add toolbar
        font = QFont()
        font.setPointSize(12)

        toolbar = NavigationToolbar(self.plotWidget, self)
        toolbar.setFont(font)

        self.addToolBar(QtCore.Qt.BottomToolBarArea, toolbar)

        # Needed in order to use a tight layout with Cartopy axes
        fig.canvas.draw()
        plt.tight_layout()
Exemplo n.º 22
0
def set_of_photos(hrit_files,
                  central_lat,
                  central_lon,
                  elevation,
                  time,
                  dpi,
                  photo_path,
                  all_lines=False,
                  load_photo=['VIS006']):
    """Return path of photo
    Parameters
    ----------
    parameter_name : parameter_type
        Quick description of it.
    Returns
    -------
    photos: array
        Array of saved on disc files.

    """
    # Loading decompressed previously photos
    from satpy import Scene
    import numpy as np
    # from glob import glob
    import matplotlib.pyplot as plt
    from satpy import find_files_and_readers
    from datetime import datetime
    import cartopy.crs as ccrs
    import matplotlib as mpl
    mpl.rcParams['figure.dpi'] = dpi
    # load_photo = 'VIS006'

    first = 0
    last = len(time) - 1
    # print(len(time),last)

    yearF, monthF, dayF, hourF, minuteF, secondF = time[first].tt_calendar()
    yearL, monthL, dayL, hourL, minuteL, secondL = time[last].tt_calendar()
    # IT IS NOT WORKING FIND SOLUTION - Adding a minute in case there is only one point on map
    if len(time) == 1:
        time[last].tt = time[last].tt + 1 / 3600
        yearL, monthL, dayL, hourL, minuteL, secondL = time[last].tt_calendar()
        # print("udalosie")

    # print(yearF, monthF, dayF, hourF, minuteF, secondF )
    # print(yearL, monthL, dayL, hourL, minuteL, secondL)
    # time[0].tt_calendar()[0]
    files = find_files_and_readers(base_dir=hrit_files,
                                   start_time=datetime(yearF, monthF, dayF,
                                                       hourF, minuteF),
                                   end_time=datetime(yearL, monthL, dayL,
                                                     hourL, minuteL),
                                   reader='seviri_l1b_hrit')
    scn = Scene(filenames=files)
    load_photo = scn.available_dataset_names()
    # HRV does not work properly
    load_photo.remove('HRV')
    # print(load_photo)
    # print(scn.available_dataset_names())

    div = 30
    name_img = []
    for photo_type in load_photo:
        # print(photo_type)
        scn.load([photo_type])
        # print(scn)
        for i in range(len(time)):
            new_scn = scn
            # print(new_scn)
            crs = new_scn[photo_type].attrs['area'].to_cartopy_crs()
            y, x = polygon_surrounding_sat(central_lat[i], central_lon[i],
                                           elevation[i], div)
            extent = calculate_extent(x, y)
            ax = plt.axes(
                projection=ccrs.Sinusoidal(central_lon[i], central_lat[i]))
            ax.set_extent(extent)

            if (all_lines):
                ax.gridlines()
                ax.coastlines(resolution='50m', color='red')
                ax.coastlines()

            # ax.gridlines()
            # ax.set_global()
            plt.imshow(new_scn[photo_type],
                       transform=crs,
                       extent=crs.bounds,
                       origin='upper',
                       cmap='gray')
            # cbar = plt.colorbar()
            # cbar.set_label("Kelvin")
            # plt.imsave('imsave.png', im, cmap='gray')
            name = photo_path + photo_type + "_" + time[i].utc_iso() + '.png'
            plt.savefig(name, dpi=dpi)
            name_img = np.append(name_img, name)

    return (name_img)
Exemplo n.º 23
0
def photo_of_area(hrit_files,
                  central_lat,
                  central_lon,
                  elevation,
                  time,
                  dpi,
                  photo_path,
                  load_photo='VIS006',
                  all_lines=True):
    """Return path of photo
    Parameters
    ----------
    parameter_name : parameter_type
        Quick description of it.
    Returns
    -------
    photos: array
        Array of saved on disc files.

    """
    # Loading decompressed previously photos
    from satpy import Scene
    # from glob import glob
    import matplotlib.pyplot as plt
    from satpy import find_files_and_readers
    from datetime import datetime
    import cartopy.crs as ccrs
    import matplotlib as mpl
    mpl.rcParams['figure.dpi'] = dpi
    # load_photo = 'VIS006'

    first = 0
    last = len(time) - 1
    # print(len(time),last)

    yearF, monthF, dayF, hourF, minuteF, secondF = time[first].tt_calendar()
    yearL, monthL, dayL, hourL, minuteL, secondL = time[last].tt_calendar()
    # IT IS NOT WORKING FIND SOLUTION - Adding a minute in case there is only one point on map
    if (len(time) == 1):
        time[last].tt = time[last].tt + 1 / 3600
        yearL, monthL, dayL, hourL, minuteL, secondL = time[last].tt_calendar()
        # print("udalosie")

    # print(yearF, monthF, dayF, hourF, minuteF, secondF )
    # print(yearL, monthL, dayL, hourL, minuteL, secondL)
    time[0].tt_calendar()[0]
    files = find_files_and_readers(base_dir=hrit_files,
                                   start_time=datetime(yearF, monthF, dayF,
                                                       hourF, minuteF),
                                   end_time=datetime(yearL, monthL, dayL,
                                                     hourL, minuteL),
                                   reader='seviri_l1b_hrit')
    scn = Scene(filenames=files)

    scn.load([load_photo])
    new_scn = scn
    crs = new_scn[load_photo].attrs['area'].to_cartopy_crs()

    div = 30
    y, x = polygon_surrounding_sat(central_lat, central_lon, elevation, div)
    extent = calculate_extent(x, y)
    ax = plt.axes(projection=ccrs.Sinusoidal(central_lon, central_lat))
    ax.set_extent(extent)

    if (all_lines):
        ax.gridlines()
        ax.coastlines(resolution='50m', color='red')
        ax.coastlines()

    # ax.gridlines()
    # ax.set_global()
    plt.imshow(new_scn[load_photo],
               transform=crs,
               extent=crs.bounds,
               origin='upper',
               cmap='gray')
    # cbar = plt.colorbar()
    # cbar.set_label("Kelvin")
    # plt.imsave('imsave.png', im, cmap='gray')
    name_img = photo_path + load_photo + "_" + datetime(
        yearF, monthF, dayF, hourF, minuteF).__str__() + '.png'
    plt.savefig(name_img, dpi=dpi)
    # print(name_img)

    return name_img
Exemplo n.º 24
0
    def to_cartopy_proj(self):
        """
        Creates a `cartopy.crs.Projection` instance from PROJ4 parameters.

        Returns
        -------
        cartopy.crs.projection
            Cartopy projection representing the projection of the spatial reference system.

        """
        proj4_params = self.to_proj4_dict()
        proj4_name = proj4_params.get('proj')
        central_longitude = proj4_params.get('lon_0', 0.)
        central_latitude = proj4_params.get('lat_0', 0.)
        false_easting = proj4_params.get('x_0', 0.)
        false_northing = proj4_params.get('y_0', 0.)
        scale_factor = proj4_params.get('k', 1.)
        standard_parallels = (proj4_params.get('lat_1', 20.),
                              proj4_params.get('lat_2', 50.))

        if proj4_name == 'longlat':
            ccrs_proj = ccrs.PlateCarree(central_longitude)
        elif proj4_name == 'aeqd':
            ccrs_proj = ccrs.AzimuthalEquidistant(central_longitude,
                                                  central_latitude,
                                                  false_easting,
                                                  false_northing)
        elif proj4_name == 'merc':
            ccrs_proj = ccrs.Mercator(central_longitude,
                                      false_easting=false_easting,
                                      false_northing=false_northing,
                                      scale_factor=scale_factor)
        elif proj4_name == 'eck1':
            ccrs_proj = ccrs.EckertI(central_longitude, false_easting,
                                     false_northing)
        elif proj4_name == 'eck2':
            ccrs_proj = ccrs.EckertII(central_longitude, false_easting,
                                      false_northing)
        elif proj4_name == 'eck3':
            ccrs_proj = ccrs.EckertIII(central_longitude, false_easting,
                                       false_northing)
        elif proj4_name == 'eck4':
            ccrs_proj = ccrs.EckertIV(central_longitude, false_easting,
                                      false_northing)
        elif proj4_name == 'eck5':
            ccrs_proj = ccrs.EckertV(central_longitude, false_easting,
                                     false_northing)
        elif proj4_name == 'eck6':
            ccrs_proj = ccrs.EckertVI(central_longitude, false_easting,
                                      false_northing)
        elif proj4_name == 'aea':
            ccrs_proj = ccrs.AlbersEqualArea(central_longitude,
                                             central_latitude, false_easting,
                                             false_northing,
                                             standard_parallels)
        elif proj4_name == 'eqdc':
            ccrs_proj = ccrs.EquidistantConic(central_longitude,
                                              central_latitude, false_easting,
                                              false_northing,
                                              standard_parallels)
        elif proj4_name == 'gnom':
            ccrs_proj = ccrs.Gnomonic(central_longitude, central_latitude)
        elif proj4_name == 'laea':
            ccrs_proj = ccrs.LambertAzimuthalEqualArea(central_longitude,
                                                       central_latitude,
                                                       false_easting,
                                                       false_northing)
        elif proj4_name == 'lcc':
            ccrs_proj = ccrs.LambertConformal(
                central_longitude,
                central_latitude,
                false_easting,
                false_northing,
                standard_parallels=standard_parallels)
        elif proj4_name == 'mill':
            ccrs_proj = ccrs.Miller(central_longitude)
        elif proj4_name == 'moll':
            ccrs_proj = ccrs.Mollweide(central_longitude,
                                       false_easting=false_easting,
                                       false_northing=false_northing)
        elif proj4_name == 'stere':
            ccrs_proj = ccrs.Stereographic(central_latitude,
                                           central_longitude,
                                           false_easting,
                                           false_northing,
                                           scale_factor=scale_factor)
        elif proj4_name == 'ortho':
            ccrs_proj = ccrs.Orthographic(central_longitude, central_latitude)
        elif proj4_name == 'robin':
            ccrs_proj = ccrs.Robinson(central_longitude,
                                      false_easting=false_easting,
                                      false_northing=false_northing)
        elif proj4_name == 'sinus':
            ccrs_proj = ccrs.Sinusoidal(central_longitude, false_easting,
                                        false_northing)
        elif proj4_name == 'tmerc':
            ccrs_proj = ccrs.TransverseMercator(central_longitude,
                                                central_latitude,
                                                false_easting, false_northing,
                                                scale_factor)
        else:
            err_msg = "Projection '{}' is not supported.".format(proj4_name)
            raise ValueError(err_msg)

        return ccrs_proj
Exemplo n.º 25
0
def show_overall(hrit_files,
                 central_lat,
                 central_lon,
                 elevation,
                 time,
                 dpi,
                 photo_path,
                 all_lines=False,
                 pro='PlateCarree',
                 load_photo=['VIS006'],
                 save=False):
    """Return path of photo
    Parameters
    ----------
    pro : string
        PlateCarree
        Sinusoidal
    Returns
    -------
    photos: array
        Array of saved on disc files.

    """
    from satpy.scene import Scene
    from satpy import find_files_and_readers
    from datetime import datetime
    import cartopy.crs as ccrs
    import cartopy.feature as cfeature
    import numpy as np
    # %matplotlib inline
    import matplotlib.pyplot as plt

    ### START - CALCULATES OVERALL EXTENT ###
    div = 30
    x, y = [], []
    for i in range(len(central_lat)):
        y_temp, x_temp = polygon_surrounding_sat(central_lat[i],
                                                 central_lon[i], elevation[i],
                                                 div)
        x = np.append(x, x_temp)
        y = np.append(y, y_temp)

    extent = calculate_extent(x, y)
    ### END - CALCULATES OVERALL EXTENT ###

    first = 0
    last = len(time) - 1

    yearF, monthF, dayF, hourF, minuteF, secondF = time[first].tt_calendar()
    yearL, monthL, dayL, hourL, minuteL, secondL = time[last].tt_calendar()
    if len(time) == 1:
        time[last].tt = time[last].tt + 1 / 3600
        yearL, monthL, dayL, hourL, minuteL, secondL = time[last].tt_calendar()

    # print(yearF, monthF, dayF, hourF, minuteF, secondF )
    # print(yearL, monthL, dayL, hourL, minuteL, secondL)
    # time[0].tt_calendar()[0]
    files = find_files_and_readers(base_dir=hrit_files,
                                   start_time=datetime(yearF, monthF, dayF,
                                                       hourF, minuteF),
                                   end_time=datetime(yearL, monthL, dayL,
                                                     hourL, minuteL),
                                   reader='seviri_l1b_hrit')
    scn = Scene(filenames=files)
    scn.load(load_photo)
    new_scn = scn
    crs = new_scn[load_photo[0]].attrs['area'].to_cartopy_crs()
    # ax = plt.axes(projection=crs)
    central_lon, central_lat = (extent[0] + extent[1]) / 2, (extent[2] +
                                                             extent[3]) / 2

    if pro == 'PlateCarree':
        ax = plt.axes(projection=ccrs.PlateCarree())
        pro_name = '_PlateCarree_'
        ax.set_global()
    if pro == 'Sinusoidal':
        ax = plt.axes(projection=ccrs.Sinusoidal(central_lon, central_lat))
        ax.set_extent(extent)
        pro_name = '_Sinusoidal_'

    if all_lines:
        ax.coastlines(color='red')
        ax.gridlines(color='red')
        ax.add_feature(cfeature.BORDERS, color='red')
        pro_name = pro_name + 'lines_'

    plt.imshow(new_scn[load_photo[0]],
               transform=crs,
               extent=crs.bounds,
               origin='upper',
               cmap='gray')

    if save:
        if isinstance(load_photo[0], float):
            photo_type = str(load_photo[0])
        else:
            photo_type = load_photo[0]
        name = photo_path + photo_type + pro_name + '_{date:%Y-%m-%d_%H_%M_%S}.png'.format(
            date=scn.start_time)
        plt.savefig(name, dpi=dpi)
    if not save:
        plt.show()

    return ()
Exemplo n.º 26
0
    def projection(self):
        if self.proj is None:
            return ccrs.PlateCarree()

        proj_dict = ast.literal_eval(self.proj)
        user_proj = proj_dict.pop("proj")
        if user_proj == 'PlateCarree':
            self.xylim_supported = True
            return ccrs.PlateCarree(**proj_dict)
        elif user_proj == 'AlbersEqualArea':
            return ccrs.AlbersEqualArea(**proj_dict)
        elif user_proj == 'AzimuthalEquidistant':
            return ccrs.AzimuthalEquidistant(**proj_dict)
        elif user_proj == 'EquidistantConic':
            return ccrs.EquidistantConic(**proj_dict)
        elif user_proj == 'LambertConformal':
            return ccrs.LambertConformal(**proj_dict)
        elif user_proj == 'LambertCylindrical':
            return ccrs.LambertCylindrical(**proj_dict)
        elif user_proj == 'Mercator':
            return ccrs.Mercator(**proj_dict)
        elif user_proj == 'Miller':
            return ccrs.Miller(**proj_dict)
        elif user_proj == 'Mollweide':
            return ccrs.Mollweide(**proj_dict)
        elif user_proj == 'Orthographic':
            return ccrs.Orthographic(**proj_dict)
        elif user_proj == 'Robinson':
            return ccrs.Robinson(**proj_dict)
        elif user_proj == 'Sinusoidal':
            return ccrs.Sinusoidal(**proj_dict)
        elif user_proj == 'Stereographic':
            return ccrs.Stereographic(**proj_dict)
        elif user_proj == 'TransverseMercator':
            return ccrs.TransverseMercator(**proj_dict)
        elif user_proj == 'UTM':
            return ccrs.UTM(**proj_dict)
        elif user_proj == 'InterruptedGoodeHomolosine':
            return ccrs.InterruptedGoodeHomolosine(**proj_dict)
        elif user_proj == 'RotatedPole':
            return ccrs.RotatedPole(**proj_dict)
        elif user_proj == 'OSGB':
            self.xylim_supported = False
            return ccrs.OSGB(**proj_dict)
        elif user_proj == 'EuroPP':
            self.xylim_supported = False
            return ccrs.EuroPP(**proj_dict)
        elif user_proj == 'Geostationary':
            return ccrs.Geostationary(**proj_dict)
        elif user_proj == 'NearsidePerspective':
            return ccrs.NearsidePerspective(**proj_dict)
        elif user_proj == 'EckertI':
            return ccrs.EckertI(**proj_dict)
        elif user_proj == 'EckertII':
            return ccrs.EckertII(**proj_dict)
        elif user_proj == 'EckertIII':
            return ccrs.EckertIII(**proj_dict)
        elif user_proj == 'EckertIV':
            return ccrs.EckertIV(**proj_dict)
        elif user_proj == 'EckertV':
            return ccrs.EckertV(**proj_dict)
        elif user_proj == 'EckertVI':
            return ccrs.EckertVI(**proj_dict)
        elif user_proj == 'EqualEarth':
            return ccrs.EqualEarth(**proj_dict)
        elif user_proj == 'Gnomonic':
            return ccrs.Gnomonic(**proj_dict)
        elif user_proj == 'LambertAzimuthalEqualArea':
            return ccrs.LambertAzimuthalEqualArea(**proj_dict)
        elif user_proj == 'NorthPolarStereo':
            return ccrs.NorthPolarStereo(**proj_dict)
        elif user_proj == 'OSNI':
            return ccrs.OSNI(**proj_dict)
        elif user_proj == 'SouthPolarStereo':
            return ccrs.SouthPolarStereo(**proj_dict)
Exemplo n.º 27
0
def animate_map(ds: xr.Dataset,
                var: VarName.TYPE = None,
                animate_dim: str = 'time',
                interval: int = 200,
                true_range: bool = False,
                indexers: DictLike.TYPE = None,
                region: PolygonLike.TYPE = None,
                projection: str = 'PlateCarree',
                central_lon: float = 0.0,
                title: str = None,
                contour_plot: bool = False,
                cmap_params: DictLike.TYPE = None,
                plot_properties: DictLike.TYPE = None,
                file: str = None,
                monitor: Monitor = Monitor.NONE) -> HTML:
    """
    Create a geographic map animation for the variable given by dataset *ds* and variable name *var*.

    Creates an animation of the given variable from the given dataset on a map with coastal lines.
    In case no variable name is given, the first encountered variable in the
    dataset is animated.
    It is also possible to set extents of the animation. If no extents
    are given, a global animation is created.

    The following file formats for saving the animation are supported: html

    :param ds: the dataset containing the variable to animate
    :param var: the variable's name
    :param animate_dim: Dimension to animate, if none given defaults to time.
    :param interval: Delay between frames in milliseconds. Defaults to 200.
    :param true_range: If True, calculates colormap and colorbar configuration parameters from the
    whole dataset. Can potentially take a lot of time. Defaults to False, in which case the colormap
    is calculated from the first frame.
    :param indexers: Optional indexers into data array of *var*. The *indexers* is a dictionary
           or a comma-separated string of key-value pairs that maps the variable's dimension names
           to constant labels. e.g. "layer=4".
    :param region: Region to animate
    :param projection: name of a global projection, see http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html
    :param central_lon: central longitude of the projection in degrees
    :param title: an optional title
    :param contour_plot: If true plot a filled contour plot of data, otherwise plots a pixelated colormesh
    :param cmap_params: optional additional colormap configuration parameters,
           e.g. "vmax=300, cmap='magma'"
           For full reference refer to
           http://xarray.pydata.org/en/stable/generated/xarray.plot.contourf.html
    :param plot_properties: optional plot properties for Python matplotlib,
           e.g. "bins=512, range=(-1.5, +1.5)"
           For full reference refer to
           https://matplotlib.org/api/lines_api.html and
           https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.contourf.html
    :param file: path to a file in which to save the animation
    :param monitor: A progress monitor.
    :return: An animation in HTML format
    """
    if not isinstance(ds, xr.Dataset):
        raise NotImplementedError('Only gridded datasets are currently supported')

    var_name = None
    if not var:
        for key in ds.data_vars.keys():
            var_name = key
            break
    else:
        var_name = VarName.convert(var)

    try:
        var = ds[var_name]
    except KeyError:
        raise ValidationError('Provided variable name "{}" does not exist in the given dataset'.format(var_name))

    indexers = DictLike.convert(indexers) or {}
    properties = DictLike.convert(plot_properties) or {}
    cmap_params = DictLike.convert(cmap_params) or {}

    extents = None
    bounds = handle_plot_polygon(region)
    if bounds:
        lon_min, lat_min, lon_max, lat_max = bounds
        extents = [lon_min, lon_max, lat_min, lat_max]

    if len(ds.lat) < 2 or len(ds.lon) < 2:
        # Matplotlib can not plot datasets with less than these dimensions with
        # contourf and pcolormesh methods
        raise ValidationError('The minimum dataset spatial dimensions to create a map'
                              ' plot are (2,2)')

    # See http://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html#
    if projection == 'PlateCarree':
        proj = ccrs.PlateCarree(central_longitude=central_lon)
    elif projection == 'LambertCylindrical':
        proj = ccrs.LambertCylindrical(central_longitude=central_lon)
    elif projection == 'Mercator':
        proj = ccrs.Mercator(central_longitude=central_lon)
    elif projection == 'Miller':
        proj = ccrs.Miller(central_longitude=central_lon)
    elif projection == 'Mollweide':
        proj = ccrs.Mollweide(central_longitude=central_lon)
    elif projection == 'Orthographic':
        proj = ccrs.Orthographic(central_longitude=central_lon)
    elif projection == 'Robinson':
        proj = ccrs.Robinson(central_longitude=central_lon)
    elif projection == 'Sinusoidal':
        proj = ccrs.Sinusoidal(central_longitude=central_lon)
    elif projection == 'NorthPolarStereo':
        proj = ccrs.NorthPolarStereo(central_longitude=central_lon)
    elif projection == 'SouthPolarStereo':
        proj = ccrs.SouthPolarStereo(central_longitude=central_lon)
    else:
        raise ValidationError('illegal projection: "%s"' % projection)

    figure = plt.figure(figsize=(8, 4))
    ax = plt.axes(projection=proj)
    if extents:
        ax.set_extent(extents, ccrs.PlateCarree())
    else:
        ax.set_global()

    ax.coastlines()

    if not animate_dim:
        animate_dim = 'time'

    indexers[animate_dim] = var[animate_dim][0]

    var_data = get_var_data(var, indexers, remaining_dims=('lon', 'lat'))

    with monitor.starting("animate", len(var[animate_dim]) + 3):
        if true_range:
            data_min, data_max = _get_min_max(var, monitor=monitor)
        else:
            data_min, data_max = _get_min_max(var_data, monitor=monitor)

        cmap_params = determine_cmap_params(data_min, data_max, **cmap_params)
        plot_kwargs = {**properties, **cmap_params}

        # Plot the first frame to set-up the axes with the colorbar properly
        # transform keyword is for the coordinate our data is in, which in case of a
        # 'normal' lat/lon dataset is PlateCarree.
        if contour_plot:
            var_data.plot.contourf(ax=ax, transform=ccrs.PlateCarree(), subplot_kws={'projection': proj},
                                   add_colorbar=True, **plot_kwargs)
        else:
            var_data.plot.pcolormesh(ax=ax, transform=ccrs.PlateCarree(), subplot_kws={'projection': proj},
                                     add_colorbar=True, **plot_kwargs)
        if title:
            ax.set_title(title)
        figure.tight_layout()
        monitor.progress(1)

        def run(value):
            ax.clear()
            if extents:
                ax.set_extent(extents, ccrs.PlateCarree())
            else:
                ax.set_global()
            ax.coastlines()
            indexers[animate_dim] = value
            var_data = get_var_data(var, indexers, remaining_dims=('lon', 'lat'))
            var_data.plot.contourf(ax=ax, transform=ccrs.PlateCarree(), subplot_kws={'projection': proj},
                                   add_colorbar=False, **plot_kwargs)
            if title:
                ax.set_title(title)
            monitor.progress(1)
            return ax
        anim = animation.FuncAnimation(figure, run, [i for i in var[animate_dim]],
                                       interval=interval, blit=False, repeat=False)
        anim_html = anim.to_jshtml()

        # Prevent the animation for running after it's finished
        del anim

        # Delete the rogue temp-file
        try:
            os.remove('None0000000.png')
        except FileNotFoundError:
            pass

        if file:
            with open(file, 'w') as outfile:
                outfile.write(anim_html)
                monitor.progress(1)

    return HTML(anim_html)
Exemplo n.º 28
0
def set_proj(projection='Robinson', proj_default=True):
    """ Set the projection for Cartopy.
    
    Parameters
    ----------
    
    projection : string
        the map projection. Available projections:
        'Robinson' (default), 'PlateCarree', 'AlbertsEqualArea',
        'AzimuthalEquidistant','EquidistantConic','LambertConformal',
        'LambertCylindrical','Mercator','Miller','Mollweide','Orthographic',
        'Sinusoidal','Stereographic','TransverseMercator','UTM',
        'InterruptedGoodeHomolosine','RotatedPole','OSGB','EuroPP',
        'Geostationary','NearsidePerspective','EckertI','EckertII',
        'EckertIII','EckertIV','EckertV','EckertVI','EqualEarth','Gnomonic',
        'LambertAzimuthalEqualArea','NorthPolarStereo','OSNI','SouthPolarStereo'
    proj_default : bool
        If True, uses the standard projection attributes from Cartopy.
        Enter new attributes in a dictionary to change them. Lists of attributes
        can be found in the Cartopy documentation: 
            https://scitools.org.uk/cartopy/docs/latest/crs/projections.html#eckertiv
    
    Returns
    -------
        proj : the Cartopy projection object
        
    See Also
    --------
    pyleoclim.utils.mapping.map_all : mapping function making use of the projection
    
    """
    if proj_default is not True and type(proj_default) is not dict:
        raise TypeError(
            'The default for the projections should either be provided' +
            ' as a dictionary or set to True')

    # Set the projection
    if projection == 'Robinson':
        if proj_default is True:
            proj = ccrs.Robinson()
        else:
            proj = ccrs.Robinson(**proj_default)
    elif projection == 'PlateCarree':
        if proj_default is True:
            proj = ccrs.PlateCarree()
        else:
            proj = ccrs.PlateCarree(**proj_default)
    elif projection == 'AlbersEqualArea':
        if proj_default is True:
            proj = ccrs.AlbersEqualArea()
        else:
            proj = ccrs.AlbersEqualArea(**proj_default)
    elif projection == 'AzimuthalEquidistant':
        if proj_default is True:
            proj = ccrs.AzimuthalEquidistant()
        else:
            proj = ccrs.AzimuthalEquidistant(**proj_default)
    elif projection == 'EquidistantConic':
        if proj_default is True:
            proj = ccrs.EquidistantConic()
        else:
            proj = ccrs.EquidistantConic(**proj_default)
    elif projection == 'LambertConformal':
        if proj_default is True:
            proj = ccrs.LambertConformal()
        else:
            proj = ccrs.LambertConformal(**proj_default)
    elif projection == 'LambertCylindrical':
        if proj_default is True:
            proj = ccrs.LambertCylindrical()
        else:
            proj = ccrs.LambertCylindrical(**proj_default)
    elif projection == 'Mercator':
        if proj_default is True:
            proj = ccrs.Mercator()
        else:
            proj = ccrs.Mercator(**proj_default)
    elif projection == 'Miller':
        if proj_default is True:
            proj = ccrs.Miller()
        else:
            proj = ccrs.Miller(**proj_default)
    elif projection == 'Mollweide':
        if proj_default is True:
            proj = ccrs.Mollweide()
        else:
            proj = ccrs.Mollweide(**proj_default)
    elif projection == 'Orthographic':
        if proj_default is True:
            proj = ccrs.Orthographic()
        else:
            proj = ccrs.Orthographic(**proj_default)
    elif projection == 'Sinusoidal':
        if proj_default is True:
            proj = ccrs.Sinusoidal()
        else:
            proj = ccrs.Sinusoidal(**proj_default)
    elif projection == 'Stereographic':
        if proj_default is True:
            proj = ccrs.Stereographic()
        else:
            proj = ccrs.Stereographic(**proj_default)
    elif projection == 'TransverseMercator':
        if proj_default is True:
            proj = ccrs.TransverseMercator()
        else:
            proj = ccrs.TransverseMercator(**proj_default)
    elif projection == 'TransverseMercator':
        if proj_default is True:
            proj = ccrs.TransverseMercator()
        else:
            proj = ccrs.TransverseMercator(**proj_default)
    elif projection == 'UTM':
        if proj_default is True:
            proj = ccrs.UTM()
        else:
            proj = ccrs.UTM(**proj_default)
    elif projection == 'UTM':
        if proj_default is True:
            proj = ccrs.UTM()
        else:
            proj = ccrs.UTM(**proj_default)
    elif projection == 'InterruptedGoodeHomolosine':
        if proj_default is True:
            proj = ccrs.InterruptedGoodeHomolosine()
        else:
            proj = ccrs.InterruptedGoodeHomolosine(**proj_default)
    elif projection == 'RotatedPole':
        if proj_default is True:
            proj = ccrs.RotatedPole()
        else:
            proj = ccrs.RotatedPole(**proj_default)
    elif projection == 'OSGB':
        if proj_default is True:
            proj = ccrs.OSGB()
        else:
            proj = ccrs.OSGB(**proj_default)
    elif projection == 'EuroPP':
        if proj_default is True:
            proj = ccrs.EuroPP()
        else:
            proj = ccrs.EuroPP(**proj_default)
    elif projection == 'Geostationary':
        if proj_default is True:
            proj = ccrs.Geostationary()
        else:
            proj = ccrs.Geostationary(**proj_default)
    elif projection == 'NearsidePerspective':
        if proj_default is True:
            proj = ccrs.NearsidePerspective()
        else:
            proj = ccrs.NearsidePerspective(**proj_default)
    elif projection == 'EckertI':
        if proj_default is True:
            proj = ccrs.EckertI()
        else:
            proj = ccrs.EckertI(**proj_default)
    elif projection == 'EckertII':
        if proj_default is True:
            proj = ccrs.EckertII()
        else:
            proj = ccrs.EckertII(**proj_default)
    elif projection == 'EckertIII':
        if proj_default is True:
            proj = ccrs.EckertIII()
        else:
            proj = ccrs.EckertIII(**proj_default)
    elif projection == 'EckertIV':
        if proj_default is True:
            proj = ccrs.EckertIV()
        else:
            proj = ccrs.EckertIV(**proj_default)
    elif projection == 'EckertV':
        if proj_default is True:
            proj = ccrs.EckertV()
        else:
            proj = ccrs.EckertV(**proj_default)
    elif projection == 'EckertVI':
        if proj_default is True:
            proj = ccrs.EckertVI()
        else:
            proj = ccrs.EckertVI(**proj_default)
    elif projection == 'EqualEarth':
        if proj_default is True:
            proj = ccrs.EqualEarth()
        else:
            proj = ccrs.EqualEarth(**proj_default)
    elif projection == 'Gnomonic':
        if proj_default is True:
            proj = ccrs.Gnomonic()
        else:
            proj = ccrs.Gnomonic(**proj_default)
    elif projection == 'LambertAzimuthalEqualArea':
        if proj_default is True:
            proj = ccrs.LambertAzimuthalEqualArea()
        else:
            proj = ccrs.LambertAzimuthalEqualArea(**proj_default)
    elif projection == 'NorthPolarStereo':
        if proj_default is True:
            proj = ccrs.NorthPolarStereo()
        else:
            proj = ccrs.NorthPolarStereo(**proj_default)
    elif projection == 'OSNI':
        if proj_default is True:
            proj = ccrs.OSNI()
        else:
            proj = ccrs.OSNI(**proj_default)
    elif projection == 'OSNI':
        if proj_default is True:
            proj = ccrs.SouthPolarStereo()
        else:
            proj = ccrs.SouthPolarStereo(**proj_default)
    else:
        raise ValueError('Invalid projection type')

    return proj
Exemplo n.º 29
0
sia_a = add_cyclic_point(sia_a)
sih_a = add_cyclic_point(sih_a)

land_mask_a = add_cyclic_point(land_mask)

land_mask_a2 = np.where(land_mask_a == 1, 1, np.nan)

######################################################
#
# PART 1:  COLOR FILL CONTOURS
#
#%%######################################################

plt.close('all')
fig = plt.figure(num=1, figsize=(14, 7))
ax = plt.axes(projection=ccrs.Sinusoidal(central_longitude=-60))

vmax = 2.3
vmax = 2.0

mp.rcParams['axes.linewidth'] = .05
mp.rcParams['lines.linewidth'] = .05
mp.rcParams['patch.linewidth'] = .05


cnt = plt.contourf(lons_a, lats_a, np.zeros(land_mask_a2.shape), levels=2,\
               transform=ccrs.PlateCarree(),vmin=-1,vmax=0,colors='black')

# This is the fix for the white lines between contour levels
for c in cnt.collections:
    c.set_edgecolor("face")
Exemplo n.º 30
0
    def _plot(self, data_array):
        """
        From the TATSSI Time Series Generator object plots the
        extent of data with coastline and political division
        """
        # Get projection from first data variable
        proj4_string = data_array.crs

        # If projection is Sinusoidal
        srs = get_projection(proj4_string)
        if srs.GetAttrValue('PROJECTION') == 'Sinusoidal':
            globe=ccrs.Globe(ellipse=None,
                semimajor_axis=6371007.181,
                semiminor_axis=6371007.181)

            proj = ccrs.Sinusoidal(globe=globe)
        else:
            proj = None

        self.fig, self.ax = plt.subplots(1, 1, figsize=(8, 8),
                subplot_kw=dict(projection=proj))

        self.extent = self.ax.get_extent()

        if proj is not None:
            try:
                cfeature.BORDERS.geometries()
                self.ax.coastlines(resolution='50m', color='black')
                self.ax.add_feature(cfeature.BORDERS, edgecolor='black')
            except urllib.error.URLError:
                pass

            # Gridlines
            self.ax.gridlines()

        # Make all values NaN
        # data_array = (data_array.astype(np.float32) * np.nan)
        # Plot
        data_array[0].plot.imshow(
                ax=self.ax, add_colorbar=False, cmap='viridis',
                transform=proj
        )

        self.ax.set_frame_on(False)
        self.ax.axis('off')
        self.ax.set_aspect('equal')
        self.ax.title.set_text('')

        # Set plot on the plot widget
        self.plotWidget = FigureCanvas(self.fig)
        lay = QtWidgets.QVBoxLayout(self.content_plot)
        lay.setContentsMargins(0, 40, 0, 0)
        lay.addWidget(self.plotWidget)

        # Add toolbar
        font = QFont()
        font.setPointSize(10)

        toolbar = NavigationToolbar(self.plotWidget, self)
        toolbar.setFont(font)

        self.addToolBar(QtCore.Qt.BottomToolBarArea, toolbar)

        # Needed in order to use a tight layout with Cartopy axes
        self.fig.canvas.draw()
        plt.tight_layout()