How to use regionmask - 10 common examples

To help you get started, we’ve selected a few regionmask 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 mathause / regionmask / regionmask / core / _geopandas.py View on Github external
def _construct_abbrevs(geodataframe, names):
    """Construct unique abbreviations based on geodataframe.names."""
    if names is None:
        raise ValueError(
            "names is None, but should be a valid column name of"
            "geodataframe, choose from {}".format(geodataframe.columns)
        )
    abbrevs = []
    names = _maybe_get_column(geodataframe, names)
    names = names.str.replace(r"[(\[\]).]", "")
    names = names.str.replace("[/-]", " ")
    abbrevs = names.str.split(" ").map(lambda x: "".join([y[:3] for y in x]))
    abbrevs = _enumerate_duplicates(abbrevs)
    return abbrevs
github mathause / regionmask / regionmask / core / mask.py View on Github external
def _mask_rasterize_split(lon, lat, polygons, numbers, fill=np.NaN, **kwargs):

    split_point = _find_splitpoint(lon)
    lon_l, lon_r = lon[:split_point], lon[split_point:]

    mask_l = _mask_rasterize(lon_l, lat, polygons, numbers=numbers)
    mask_r = _mask_rasterize(lon_r, lat, polygons, numbers=numbers)

    return np.hstack((mask_l, mask_r))
github mathause / regionmask / regionmask / defined_regions / natural_earth.py View on Github external
names = _maybe_get_column(df, names)
    abbrevs = _maybe_get_column(df, abbrevs)
    coords = _maybe_get_column(df, coords)

    # create one MultiPolygon of all Polygons (used for land)
    if combine_coords:
        from shapely import geometry

        coords = [geometry.MultiPolygon([p for p in coords])]

    # make sure numbers is a list
    numbers = np.array(numbers)

    source = "http://www.naturalearthdata.com"

    return Regions(
        coords, numbers=numbers, names=names, abbrevs=abbrevs, name=title, source=source
    )
github mathause / regionmask / regionmask / core / regions.py View on Github external
return _mask(
            outlines=outlines,
            regions_is_180=self.lon_180,
            numbers=self.numbers,
            lon_or_obj=lon_or_obj,
            lat=lat,
            lon_name=lon_name,
            lat_name=lat_name,
            method=method,
            xarray=xarray,
            wrap_lon=wrap_lon,
        )


# add the plotting methods
Regions.plot = _plot
Regions.plot_regions = _plot_regions


class Regions_cls(Regions):
    def __init__(
        self, name, numbers, names, abbrevs, outlines, centroids=None, source=""
    ):
        """
        Parameters
        ----------
        name : string
            Name of the collection of regions.
        numbers : list of int
            List of numerical indices for every region.
        names : dict of string
            Long name of each region. Must be accessible as names[number].
github mathause / regionmask / regionmask / core / regions.py View on Github external
lon_or_obj=lon_or_obj,
            lat=lat,
            lon_name=lon_name,
            lat_name=lat_name,
            method=method,
            xarray=xarray,
            wrap_lon=wrap_lon,
        )


# add the plotting methods
Regions.plot = _plot
Regions.plot_regions = _plot_regions


class Regions_cls(Regions):
    def __init__(
        self, name, numbers, names, abbrevs, outlines, centroids=None, source=""
    ):
        """
        Parameters
        ----------
        name : string
            Name of the collection of regions.
        numbers : list of int
            List of numerical indices for every region.
        names : dict of string
            Long name of each region. Must be accessible as names[number].
        abbrevs : dict of string
            List of abbreviations of each region. Must be accessible as
            abbrevs[number].
        outlines : List of Nx2 float array of vertices, Polygon, MultiPolygon
github mathause / regionmask / regionmask / core / regions.py View on Github external
outlines=outlines,
            regions_is_180=self.lon_180,
            numbers=self.numbers,
            lon_or_obj=lon_or_obj,
            lat=lat,
            lon_name=lon_name,
            lat_name=lat_name,
            method=method,
            xarray=xarray,
            wrap_lon=wrap_lon,
        )


# add the plotting methods
Regions.plot = _plot
Regions.plot_regions = _plot_regions


class Regions_cls(Regions):
    def __init__(
        self, name, numbers, names, abbrevs, outlines, centroids=None, source=""
    ):
        """
        Parameters
        ----------
        name : string
            Name of the collection of regions.
        numbers : list of int
            List of numerical indices for every region.
        names : dict of string
            Long name of each region. Must be accessible as names[number].
        abbrevs : dict of string
github mathause / regionmask / regionmask / core / regions.py View on Github external
from shapely.geometry import Polygon

            numbers = [1, 2]
            names = {1:'Unit Square1', 2: 'Unit Square2'}
            abbrevs = {1:'uSq1', 2:'uSq2'}
            poly = {1: Polygon(outl1), 2: Polygon(outl2)}

            r = Regions(outlines, numbers, names, abbrevs, name)

            # arguments are now optional
            r = Regions(outlines)

        """

        super(Regions, self).__init__()

        if numbers is None:
            numbers = range(len(outlines))

        if not _is_numeric(numbers):
            raise ValueError("'numbers' must be numeric")

        outlines = _maybe_to_dict(numbers, outlines)

        names = _sanitize_names_abbrevs(numbers, names, "Region")
        abbrevs = _sanitize_names_abbrevs(numbers, abbrevs, "r")

        regions = dict()

        for n in numbers:
            regions[n] = _OneRegion(n, names[n], abbrevs[n], outlines[n])
github mathause / regionmask / regionmask / core / regions.py View on Github external
def lon_180(self):
        """if the regions extend from -180 to 180
        """
        lon_min = self.bounds_global[0]
        lon_max = self.bounds_global[2]

        return _is_180(lon_min, lon_max)
github mathause / regionmask / regionmask / core / _geopandas.py View on Github external
def _prepare_gdf_for_mask(geodataframe, method, numbers):

    from geopandas import GeoDataFrame, GeoSeries

    if not isinstance(geodataframe, (GeoDataFrame, GeoSeries)):
        raise TypeError("input must be a geopandas 'GeoDataFrame' or 'GeoSeries'")

    if method == "legacy":
        raise ValueError("method 'legacy' not supported in 'mask_geopandas'")

    lon_min = geodataframe.bounds["minx"].min()
    lon_max = geodataframe.bounds["maxx"].max()
    is_180 = _is_180(lon_min, lon_max)

    polygons = geodataframe.geometry.tolist()

    if numbers is not None:
        numbers = geodataframe[numbers]
        _check_missing(numbers, "numbers")
        _check_duplicates(numbers, "numbers")
    else:
        numbers = geodataframe.index.values

    return polygons, is_180, numbers
github mathause / regionmask / regionmask / core / mask.py View on Github external
internal function to create a mask
    """

    if not _is_numeric(numbers):
        raise ValueError("'numbers' must be numeric")

    lat_orig = lat

    lon, lat = _extract_lon_lat(lon_or_obj, lat, lon_name, lat_name)

    lon = np.asarray(lon)
    lat = np.asarray(lat)

    # automatically detect whether wrapping is necessary
    if wrap_lon is None:
        grid_is_180 = _is_180(lon.min(), lon.max())

        wrap_lon = not regions_is_180 == grid_is_180

    lon_orig = lon.copy()
    if wrap_lon:
        lon = _wrapAngle(lon, wrap_lon)

    if method not in (None, "rasterize", "shapely", "legacy"):
        msg = "Method must be None or one of 'rasterize', 'shapely', or 'legacy'."
        raise ValueError(msg)

    if method is None:
        method = _determine_method(lon, lat)
    elif method == "rasterize":
        method = _determine_method(lon, lat)
        if "rasterize" not in method: