How to use the salem.utils function in salem

To help you get started, we’ve selected a few salem examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github fmaussion / salem / salem / sio.py View on Github external
def _lonlat_grid_from_dataset(ds):
    """Seek for longitude and latitude coordinates."""

    # Do we have some standard names as variable?
    vns = ds.variables.keys()
    xc = utils.str_in_list(vns, utils.valid_names['x_dim'])
    yc = utils.str_in_list(vns, utils.valid_names['y_dim'])

    # Sometimes there are more than one coordinates, one of which might have
    # more dims (e.g. lons in WRF files): take the first one with ndim = 1:
    x = None
    for xp in xc:
        if len(ds.variables[xp].shape) == 1:
            x = xp
    y = None
    for yp in yc:
        if len(ds.variables[yp].shape) == 1:
            y = yp
    if (x is None) or (y is None):
        return None

    # OK, get it
github fmaussion / salem / salem / grids.py View on Github external
def _netcdf_lonlat_grid(nc):
    """Seek for longitude and latitude coordinates."""

    # Do we have some standard names as vaiable?
    vns = nc.variables.keys()
    lon = utils.str_in_list(vns, utils.valid_names['lon_var'])
    lat = utils.str_in_list(vns, utils.valid_names['lat_var'])
    if (lon is None) or (lat is None):
        return None

    # OK, get it
    lon = nc.variables[lon][:]
    lat = nc.variables[lat][:]
    if len(lon.shape) != 1:
        raise RuntimeError('Coordinates not of correct shape')

    # Make the grid
    dx = lon[1]-lon[0]
    dy = lat[1]-lat[0]
    args = dict(nxny=(lon.shape[0], lat.shape[0]), proj=wgs84, dxdy=(dx, dy))
    args['corner'] = (lon[0], lat[0])
    return gis.Grid(**args)
github fmaussion / salem / salem / sio.py View on Github external
xarray_obj = xarray_obj.to_dataset(name='var')
            try:  # maybe there was already some georef
                xarray_obj.attrs['pyproj_srs'] = xarray_obj['var'].pyproj_srs
            except:
                pass

        self.grid = grid_from_dataset(xarray_obj)
        if self.grid is None:
            raise RuntimeError('dataset Grid not understood.')

        dn = xarray_obj.dims.keys()
        self.x_dim = utils.str_in_list(dn, utils.valid_names['x_dim'])[0]
        self.y_dim = utils.str_in_list(dn, utils.valid_names['y_dim'])[0]
        dim = utils.str_in_list(dn, utils.valid_names['t_dim'])
        self.t_dim = dim[0] if dim else None
        dim = utils.str_in_list(dn, utils.valid_names['z_dim'])
        self.z_dim = dim[0] if dim else None
github fmaussion / salem / salem / datasets.py View on Github external
# surely not the smartest way to do but should be enough for now
        mc = (np.mean(lon), np.mean(lat))
        zoom = 20
        while zoom >= 0:
            grid = gis.googlestatic_mercator_grid(center_ll=mc, nx=size_x,
                                                  ny=size_y, zoom=zoom,
                                                  scale=scale)
            dx, dy = grid.transform(lon, lat, maskout=True)
            if np.any(dx.mask):
                zoom -= 1
            else:
                break

        if 'key' not in kwargs:
            if API_KEY is None:
                with open(utils.get_demo_file('.api_key'), 'r') as f:
                    API_KEY = f.read().replace('\n', '')
            kwargs['key'] = API_KEY

        GoogleCenterMap.__init__(self, center_ll=mc, size_x=size_x,
                                 size_y=size_y, zoom=zoom, scale=scale,
                                 maptype=maptype, use_cache=use_cache, **kwargs)
github fmaussion / salem / salem / graphics.py View on Github external
a multiplicating factor controlling the y size of the bounding box
            (trial and error works best for this one)
        bbox_kwargs : dict
            kwarg to pass to set_geometry() for the bounding box (e.g.
            facecolor, alpha, etc...)
        kwargs : dict
            any kwarg accepted by ``set_geometry``. Defaults are put on
            ``color``, ``linewidth``, ``text``, ``text_kwargs``... But you can
            do whatever you want
        """

        x0, x1, y0, y1 = self.grid.extent

        # Find a sensible length for the scale
        if length is None:
            length = utils.nice_scale(x1 - x0, maxlen=maxlen)

        if location is None:
            location = (0.96 - length/2/(x1 - x0), 0.04)

        # scalebar center location in proj coordinates
        sbcx, sbcy = x0 + (x1 - x0) * location[0], y0 + (y1 - y0) * location[1]

        # coordinates for the scalebar
        line = LineString(([sbcx - length/2, sbcy], [sbcx + length/2, sbcy]))
        # Of the bounding box
        bbox = [[sbcx - length / 2 * bbox_dx, sbcy - length / 4 * bbox_dy],
                [sbcx - length / 2 * bbox_dx, sbcy + length / 4 * bbox_dy],
                [sbcx + length / 2 * bbox_dx, sbcy + length / 4 * bbox_dy],
                [sbcx + length / 2 * bbox_dx, sbcy - length / 4 * bbox_dy],
                ]
github fmaussion / salem / salem / datasets.py View on Github external
def _img(self):
        """Download the image."""
        if self.use_cache:
            return utils.joblib_read_img_url(self.googleurl.generate_url())
        else:
            from matplotlib.image import imread
            fd = urlopen(self.googleurl.generate_url())
            return imread(io.BytesIO(fd.read()))
github fmaussion / salem / salem / datasets.py View on Github external
and that the data provider decided to tag the date as the center of
        the month (stupid)
        """

        self._nc = netCDF4.Dataset(file)
        self._nc.set_auto_mask(False)
        self.variables = self._nc.variables
        if grid is None:
            grid = sio.grid_from_dataset(self._nc)
            if grid is None:
                raise RuntimeError('File grid not understood')
        if time is None:
            time = sio.netcdf_time(self._nc, monthbegin=monthbegin)
        dn = self._nc.dimensions.keys()
        try:
            self.x_dim = utils.str_in_list(dn, utils.valid_names['x_dim'])[0]
            self.y_dim = utils.str_in_list(dn, utils.valid_names['y_dim'])[0]
        except IndexError:
            raise RuntimeError('File coordinates not understood')
        dim = utils.str_in_list(dn, utils.valid_names['t_dim'])
        self.t_dim = dim[0] if dim else None
        dim = utils.str_in_list(dn, utils.valid_names['z_dim'])
        self.z_dim = dim[0] if dim else None

        GeoDataset.__init__(self, grid, time=time)
github fmaussion / salem / salem / graphics.py View on Github external
the image to plot
        crs : Grid
            the image reference system
        interp : str, default 'nearest'
            'nearest', 'linear', or 'spline'
        natural_earth : str
           'lr', 'mr' or 'hr' (low res, medium or high res)
           natural earth background img
        """

        if natural_earth is not None:
            from matplotlib.image import imread
            with warnings.catch_warnings():
                # DecompressionBombWarning
                warnings.simplefilter("ignore")
                img = imread(utils.get_natural_earth_file(natural_earth))
            ny, nx = img.shape[0], img.shape[1]
            dx, dy = 360. / nx, 180. / ny
            grid = Grid(nxny=(nx, ny), dxdy=(dx, -dy), x0y0=(-180., 90.),
                        pixel_ref='corner').center_grid
            return self.set_rgb(img, grid, interp='linear')

        if (len(img.shape) != 3) or (img.shape[-1] not in [3, 4]):
            raise ValueError('img should be of shape (y, x, 3) or (y, x, 4)')

        # Unefficient but by far easiest right now
        out = []
        for i in range(img.shape[-1]):
            out.append(self._check_data(img[..., i], crs=crs, interp=interp))
        self._rgb = np.dstack(out)
github fmaussion / salem / salem / datasets.py View on Github external
self._nc = netCDF4.Dataset(file)
        self._nc.set_auto_mask(False)
        self.variables = self._nc.variables
        if grid is None:
            grid = sio.grid_from_dataset(self._nc)
            if grid is None:
                raise RuntimeError('File grid not understood')
        if time is None:
            time = sio.netcdf_time(self._nc, monthbegin=monthbegin)
        dn = self._nc.dimensions.keys()
        try:
            self.x_dim = utils.str_in_list(dn, utils.valid_names['x_dim'])[0]
            self.y_dim = utils.str_in_list(dn, utils.valid_names['y_dim'])[0]
        except IndexError:
            raise RuntimeError('File coordinates not understood')
        dim = utils.str_in_list(dn, utils.valid_names['t_dim'])
        self.t_dim = dim[0] if dim else None
        dim = utils.str_in_list(dn, utils.valid_names['z_dim'])
        self.z_dim = dim[0] if dim else None

        GeoDataset.__init__(self, grid, time=time)