예제 #1
0
    def _regrid_to_target(self, cube: Cube, target_grid: Cube,
                          regridded_title: Optional[str]) -> Cube:
        """
        Regrid cube to target_grid, inherit grid attributes and update title

        Args:
            cube:
                Cube to be regridded
            target_grid:
                Data on the target grid. If regridding with mask, this cube
                should contain land-sea mask data to be used in adjusting land
                and sea points after regridding.
            regridded_title:
                New value for the "title" attribute to be used after
                regridding. If not set, a default value is used.

        Returns:
            Regridded cube with updated attributes
        """
        regridder = Linear(extrapolation_mode=self.extrapolation_mode)
        if "nearest" in self.regrid_mode:
            regridder = Nearest(extrapolation_mode=self.extrapolation_mode)
        cube = cube.regrid(target_grid, regridder)

        if self.REGRID_REQUIRES_LANDMASK[self.regrid_mode]:
            cube = self._adjust_landsea(cube, target_grid)

        # identify grid-describing attributes on source cube that need updating
        required_grid_attributes = [
            attr for attr in cube.attributes if attr in MOSG_GRID_ATTRIBUTES
        ]
        # update attributes if available on target grid, otherwise remove
        for key in required_grid_attributes:
            if key in target_grid.attributes:
                cube.attributes[key] = target_grid.attributes[key]
            else:
                cube.attributes.pop(key)

        cube.attributes["title"] = (MANDATORY_ATTRIBUTE_DEFAULTS["title"]
                                    if regridded_title is None else
                                    regridded_title)

        return cube
예제 #2
0
    def __init__(self, extrapolation_mode="nanmask", vicinity_radius=25000.0):
        """
        Initialise class

        Args:
            extrapolation_mode (str):
                Mode to use for extrapolating data into regions
                beyond the limits of the source_data domain.
                Available modes are documented in
                `iris.analysis <https://scitools.org.uk/iris/docs/latest/iris/
                iris/analysis.html#iris.analysis.Nearest>`_
                Defaults to "nanmask".
            vicinity_radius (float):
                Distance in metres to search for a sea or land point.
        """
        self.input_land = None
        self.nearest_cube = None
        self.output_land = None
        self.output_cube = None
        self.regridder = Nearest(extrapolation_mode=extrapolation_mode)
        self.vicinity = OccurrenceWithinVicinity(vicinity_radius)
예제 #3
0
class TestCubeRegridNearest(MixinCheckingCode, tests.IrisTest):
    scheme = Nearest(extrapolation_mode='extrapolate')

    def regrid(self, src_cube, dst_cube, **kwargs):
        return src_cube.regrid(dst_cube, scheme=self.scheme)
예제 #4
0
    def _regrid_to_target(
        self,
        cube: Cube,
        target_grid: Cube,
        regridded_title: Optional[str],
        regrid_mode: str,
    ) -> Cube:
        """
        Regrid cube to target_grid, inherit grid attributes and update title

        Args:
            cube:
                Cube to be regridded
            target_grid:
                Data on the target grid. If regridding with mask, this cube
                should contain land-sea mask data to be used in adjusting land
                and sea points after regridding.
            regridded_title:
                New value for the "title" attribute to be used after
                regridding. If not set, a default value is used.
            regrid_mode:
                "bilinear","nearest","nearest-with-mask",
                "nearest-2","nearest-with-mask-2","bilinear-2","bilinear-with-mask-2"

        Returns:
            Regridded cube with updated attributes.
        """
        if regrid_mode in (
                "nearest-with-mask",
                "nearest-with-mask-2",
                "bilinear-with-mask-2",
        ):
            if self.landmask_name not in self.landmask_source_grid.name():
                msg = "Expected {} in input_landmask cube but found {}".format(
                    self.landmask_name, repr(self.landmask_source_grid))
                warnings.warn(msg)

            if self.landmask_name not in target_grid.name():
                msg = "Expected {} in target_grid cube but found {}".format(
                    self.landmask_name, repr(target_grid))
                warnings.warn(msg)

        # basic categories (1) Iris-based (2) new nearest based  (3) new bilinear-based
        if regrid_mode in ("bilinear", "nearest", "nearest-with-mask"):
            if "nearest" in regrid_mode:
                regridder = Nearest(extrapolation_mode=self.extrapolation_mode)
            else:
                regridder = Linear(extrapolation_mode=self.extrapolation_mode)
            cube = cube.regrid(target_grid, regridder)

            # Iris regridding is used, and then adjust if land_sea mask is considered
            if self.REGRID_REQUIRES_LANDMASK[regrid_mode]:
                cube = AdjustLandSeaPoints(
                    vicinity_radius=self.landmask_vicinity,
                    extrapolation_mode=self.extrapolation_mode,
                )(cube, self.landmask_source_grid, target_grid)

        # new version of nearest/bilinear option with/without land-sea mask
        elif regrid_mode in (
                "nearest-2",
                "nearest-with-mask-2",
                "bilinear-2",
                "bilinear-with-mask-2",
        ):
            cube = RegridWithLandSeaMask(
                regrid_mode=regrid_mode,
                vicinity_radius=self.landmask_vicinity)(
                    cube, self.landmask_source_grid, target_grid)

        # identify grid-describing attributes on source cube that need updating
        required_grid_attributes = [
            attr for attr in cube.attributes if attr in MOSG_GRID_ATTRIBUTES
        ]

        # update attributes if available on target grid, otherwise remove
        for key in required_grid_attributes:
            if key in target_grid.attributes:
                cube.attributes[key] = target_grid.attributes[key]
            else:
                cube.attributes.pop(key)

        cube.attributes["title"] = (MANDATORY_ATTRIBUTE_DEFAULTS["title"]
                                    if regridded_title is None else
                                    regridded_title)

        return cube
예제 #5
0
 def test_default(self):
     scheme = Nearest()
     self.assertEqual(scheme.extrapolation_mode, "extrapolate")
예제 #6
0
 def test_invalid(self):
     with self.assertRaisesRegex(ValueError, "Extrapolation mode"):
         Nearest("bogus")
예제 #7
0
def create_scheme(mode=None):
    kwargs = {}
    if mode is not None:
        kwargs["extrapolation_mode"] = mode
    return Nearest(**kwargs)
예제 #8
0
# Stock cube - global grid extents (degrees).
_LAT_MIN = -90.0
_LAT_MAX = 90.0
_LAT_RANGE = _LAT_MAX - _LAT_MIN
_LON_MIN = 0.0
_LON_MAX = 360.0
_LON_RANGE = _LON_MAX - _LON_MIN

# A cached stock of standard horizontal target grids.
_CACHE = dict()

# Supported point interpolation schemes.
POINT_INTERPOLATION_SCHEMES = {
    'linear': Linear(extrapolation_mode='mask'),
    'nearest': Nearest(extrapolation_mode='mask'),
}

# Supported horizontal regridding schemes.
HORIZONTAL_SCHEMES = {
    'linear': Linear(extrapolation_mode='mask'),
    'linear_extrapolate': Linear(extrapolation_mode='extrapolate'),
    'nearest': Nearest(extrapolation_mode='mask'),
    'area_weighted': AreaWeighted(),
    'unstructured_nearest': UnstructuredNearest(),
}

# Supported vertical interpolation schemes.
VERTICAL_SCHEMES = ('linear', 'nearest',
                    'linear_horizontal_extrapolate_vertical',
                    'nearest_horizontal_extrapolate_vertical')
예제 #9
0
 def test_invalid(self):
     with self.assertRaisesRegexp(ValueError, 'Extrapolation mode'):
         Nearest('bogus')
               two_pt_close=od(lons=[10, 11], lats=[10, 11]),
               two_pt_far=od(lons=[10, -170], lats=[50, -50]),
               twenty_pt_far=od(lons=lons, lats=lats))
        for name, coords in d.items():

            data = pyaerocom.GriddedData()
            data._init_testdata_default()
            num = len(coords['lats'])
            sample_points = [('latitude', coords['lats']),
                             ('longitude', coords['lons'])]
            print("Current: {}, (#={})".format(name, num))
            t0 = time()
            data.interpolate(sample_points)
            dt = time() - t0
            print("Elapsed time: {:.3f} s".format(dt))
            times.append(dt)

        from iris.analysis import Nearest

        data = pyaerocom.GriddedData()
        data._init_testdata_default()

        scheme = Nearest()
        t0 = time()
        coords, points = zip(*sample_points)
        interp = scheme.interpolator(data.grid, coords)
        t1 = time()
        interp(points, collapse_scalar=True)
        print("Create interpolator: {:.3f} s".format(t1 - t0))
        print("Total: {:.3f} s".format(time() - t0))