Exemple #1
0
 def test_aux_coord_fail_mixed_dims(self):
     # Check behaviour with an aux-coord mapped over both interpolation and
     # non-interpolation dims : not supported.
     cube = self.test_cube
     cube.add_aux_coord(AuxCoord([[111, 112, 113, 114],
                                  [211, 212, 213, 214]],
                                 long_name='aux_0x'),
                        (0, 2))
     msg = ('Coord aux_0x at one x-y position has the shape.*'
            'instead of being a single point')
     with self.assertRaisesRegexp(ValueError, msg):
         interpolate(cube, self.single_sample_point, method='nearest')
Exemple #2
0
 def test_single_point_same_cube(self):
     # Check exact result matching for a single point.
     cube = self.test_cube
     result = interpolate(cube, self.single_sample_point, method='nearest')
     # Check that the result is a single trajectory point, exactly equal to
     # the expected part of the original data.
     self.assertEqual(result.shape[-1], 1)
     result = result[..., 0]
     expected = cube[:, self.single_point_iy, self.single_point_ix]
     self.assertEqual(result, expected)
Exemple #3
0
    def test_aux_coord_noninterpolation_dim(self):
        # Check exact result with an aux-coord mapped to an uninterpolated dim.
        cube = self.test_cube
        cube.add_aux_coord(DimCoord([17, 19], long_name='aux0'), 0)

        # The result cube should exactly equal a single source point.
        result = interpolate(cube, self.single_sample_point, method='nearest')
        self.assertEqual(result.shape[-1], 1)
        result = result[..., 0]
        expected = cube[:, self.single_point_iy, self.single_point_ix]
        self.assertEqual(result, expected)
Exemple #4
0
    def test_aux_coord_one_interp_dim(self):
        # Check exact result with an aux-coord over one interpolation dims.
        cube = self.test_cube
        cube.add_aux_coord(AuxCoord([11, 12, 13, 14], long_name='aux_x'),
                           2)

        # The result cube should exactly equal a single source point.
        result = interpolate(cube, self.single_sample_point, method='nearest')
        self.assertEqual(result.shape[-1], 1)
        result = result[..., 0]
        expected = cube[:, self.single_point_iy, self.single_point_ix]
        self.assertEqual(result, expected)
Exemple #5
0
 def test_metadata(self):
     # Check exact result matching for a single point, with additional
     # attributes and cell-methods.
     cube = self.test_cube
     cube.attributes['ODD_ATTR'] = 'string-value-example'
     cube.add_cell_method(iris.coords.CellMethod('mean', 'area'))
     result = interpolate(cube, self.single_sample_point, method='nearest')
     # Check that the result is a single trajectory point, exactly equal to
     # the expected part of the original data.
     self.assertEqual(result.shape[-1], 1)
     result = result[..., 0]
     expected = cube[:, self.single_point_iy, self.single_point_ix]
     self.assertEqual(result, expected)
    def test_aux_coord_both_interp_dims(self):
        # Check exact result with an aux-coord over both interpolation dims.
        cube = self.test_cube
        cube.add_aux_coord(
            AuxCoord([[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34]],
                     long_name='aux_xy'), (1, 2))

        # The result cube should exactly equal a single source point.
        result = interpolate(cube, self.single_sample_point, method='nearest')
        self.assertEqual(result.shape[-1], 1)
        result = result[..., 0]
        expected = cube[:, self.single_point_iy, self.single_point_ix]
        self.assertEqual(result, expected)
Exemple #7
0
 def test_metadata(self):
     # Check exact result matching for a single point, with additional
     # attributes and cell-methods.
     cube = self.test_cube
     cube.attributes["ODD_ATTR"] = "string-value-example"
     cube.add_cell_method(iris.coords.CellMethod("mean", "area"))
     result = interpolate(cube, self.single_sample_point, method="nearest")
     # Check that the result is a single trajectory point, exactly equal to
     # the expected part of the original data.
     self.assertEqual(result.shape[-1], 1)
     result = result[..., 0]
     expected = cube[:, self.single_point_iy, self.single_point_ix]
     self.assertEqual(result, expected)
Exemple #8
0
    def test_multi_point_same_cube(self):
        # Check an exact result for multiple points.
        cube = self.test_cube
        # Use latitude selection to recreate a whole row of the original cube.
        sample_points = [('longitude', [-180, -90, 0, 90]),
                         ('latitude', [0, 0, 0, 0])]
        result = interpolate(cube, sample_points, method='nearest')

        # The result should be identical to a single latitude section of the
        # original, but with modified coords (latitude has 4 repeated zeros).
        expected = cube[:, 1, :]
        # Result 'longitude' is now an aux coord.
        co_x = expected.coord('longitude')
        expected.remove_coord(co_x)
        expected.add_aux_coord(co_x, 1)
        # Result 'latitude' is now an aux coord containing 4*[0].
        expected.remove_coord('latitude')
        co_y = AuxCoord([0, 0, 0, 0],
                        standard_name='latitude', units='degrees')
        expected.add_aux_coord(co_y, 1)
        self.assertEqual(result, expected)
Exemple #9
0
    def test_multi_point_same_cube(self):
        # Check an exact result for multiple points.
        cube = self.test_cube
        # Use latitude selection to recreate a whole row of the original cube.
        sample_points = [('longitude', [-180, -90, 0, 90]),
                         ('latitude', [0, 0, 0, 0])]
        result = interpolate(cube, sample_points, method='nearest')

        # The result should be identical to a single latitude section of the
        # original, but with modified coords (latitude has 4 repeated zeros).
        expected = cube[:, 1, :]
        # Result 'longitude' is now an aux coord.
        co_x = expected.coord('longitude')
        expected.remove_coord(co_x)
        expected.add_aux_coord(co_x, 1)
        # Result 'latitude' is now an aux coord containing 4*[0].
        expected.remove_coord('latitude')
        co_y = AuxCoord([0, 0, 0, 0],
                        standard_name='latitude',
                        units='degrees')
        expected.add_aux_coord(co_y, 1)
        self.assertEqual(result, expected)
Exemple #10
0
 def test_unknown_method(self):
     cube = iris.tests.stock.simple_2d()
     sample_point = [('x', 2.8)]
     msg = 'Unhandled interpolation.*linekar'
     with self.assertRaisesRegex(ValueError, msg):
         interpolate(cube, sample_point, method="linekar")
Exemple #11
0
 def test_derived_coord(self):
     cube = iris.tests.stock.realistic_4d()
     sample_pts = [('altitude', [0, 10, 50])]
     msg = "'altitude'.*derived coordinates are not allowed"
     with self.assertRaisesRegex(ValueError, msg):
         interpolate(cube, sample_pts, 'nearest')
Exemple #12
0
# Create attribute constraint based on name of column
attConstraint = iris.AttributeConstraint(**{'Name':name})

# Load data into a cube
cube = iris.load_cube(workdir+'/'+filename, attConstraint)

#----------------------
# Option 1: Specify the trajectory by listing all the latitudes and
# longitudes along it
sample_points = [('latitude', [52, 54, 56, 58]),
                 ('longitude', [-20, -15, -10, -5])]

# Extract the data at the trajectory points by linearly interpolating
# from the nearest points
interpolated_cube = trajectory.interpolate(cube, sample_points)

# Plot
# Choose the coordinates to be shown on the x and y-axis, these are passed to
# contourf as coords = [x-coord, y-coord]
altitude = interpolated_cube.coord('altitude')
latitude = interpolated_cube.coord('latitude')

cf = iplt.contourf(interpolated_cube, coords=[latitude, altitude])
plt.xlabel(latitude.name().title() + ' (' + str(latitude.units) + ')')
plt.ylabel(altitude.name().title() + ' (' + str(altitude.units) + ')')
plt.title(interpolated_cube.name() + ' (' + str(interpolated_cube.units) + ')')
cb = plt.colorbar(cf, orientation='vertical', shrink=0.7, format='%.1e')

plt.show()
Exemple #13
0
 def test_unknown_method(self):
     cube = iris.tests.stock.simple_2d()
     sample_point = [('x', 2.8)]
     msg = 'Unhandled interpolation.*linekar'
     with self.assertRaisesRegexp(ValueError, msg):
         interpolate(cube, sample_point, method="linekar")
Exemple #14
0
 def test_derived_coord(self):
     cube = iris.tests.stock.realistic_4d()
     sample_pts = [('altitude', [0, 10, 50])]
     msg = "'altitude'.*derived coordinates are not allowed"
     with self.assertRaisesRegexp(ValueError, msg):
         interpolate(cube, sample_pts, 'nearest')
Exemple #15
0
def extract_vert_section(cube, pnts):
    """
    Extract vertical slice of a cube

    Assume cube's dims: (..., y, x)
    """
    sample_count = pnts['sample_count']
    zcoord = cube.coord(axis='z', dim_coords=True)
    zspan = int(zcoord.points[0]), int(zcoord.points[-1])
    if 'x' in pnts and 'y' in pnts:
        # Grid indices (no interpolation needed)
        if len(pnts['x']) == 2 and len(pnts['y']) == 2:
            if ((pnts['x'] == pnts['x'][0]).all() and
               not (pnts['y'] == pnts['y'][0]).all()):
                # X const, Y varies
                xslice = pnts['x'][0]
                if pnts['y'][0] < pnts['y'][1]:
                    stride = 1
                else:
                    stride = -1
                yslice = slice(*pnts['y'], stride)
                sect_info = dict(v=zcoord.name(),
                                 h='y_axis_ind',
                                 label='z{}-{}y{}-{}x{}'.format(*zspan,
                                                                *pnts['y'],
                                                                pnts['x'][0]))
            elif ((pnts['y'] == pnts['y'][0]).all() and
                  not (pnts['x'] == pnts['x'][0]).all()):
                # Y const, X varies
                yslice = pnts['y'][0]
                if pnts['x'][0] < pnts['x'][1]:
                    stride = 1
                else:
                    stride = -1
                xslice = slice(*pnts['x'], stride)
                sect_info = dict(v=zcoord.name(),
                                 h='x_axis_ind',
                                 label='z{}-{}y{}x{}-{}'.format(*zspan,
                                                                pnts['y'][0],
                                                                *pnts['x']))
            sect = cube[..., yslice, xslice]
        else:
            _msg = (f'Only 2 point pairs is allowed for grid indices option'
                    ',\n{pnts} are given')
            raise NotYetImplementedError(_msg)
    elif 'lon' in pnts and 'lat' in pnts:
        # Lon / lat coordinates
        cs = cube.coord_system()
        xcoord = cube.coord(axis='x', dim_coords=True)
        ycoord = cube.coord(axis='y', dim_coords=True)
        xp, yp = xcoord.points, ycoord.points
        if (xp > 180).any():
            xp = xp - 360

        if isinstance(cs, (iris.coord_systems.RotatedGeogCS, )):
            # Rotated coordinate system
            # Use iris interpolation along a trajectory
            nplat = cs.grid_north_pole_latitude
            nplon = cs.grid_north_pole_longitude
            waypoints = []
            for ilon, ilat in zip(pnts['lon'], pnts['lat']):
                waypoints.append({'longitude': ilon, 'latitude': ilat})
            if sample_count == 'auto':
                _x, _y = [], []
                for ilon, ilat in zip(pnts['lon'], pnts['lat']):
                    _ilon, _ilat = rotate_pole(np.asarray(ilon),
                                               np.asarray(ilat),
                                               nplon, nplat)
                    _x.append(np.argmin(abs(xp - _ilon[0])))
                    _y.append(np.argmin(abs(yp - _ilat[0])))
                sample_count = int(((np.diff(_x)**2 +
                                     np.diff(_y)**2)**0.5).sum())
            else:
                assert isinstance(sample_count, int)

            traj = trajectory.Trajectory(waypoints, sample_count=sample_count)
            lon = np.array([d['longitude'] for d in traj.sampled_points])
            lat = np.array([d['latitude'] for d in traj.sampled_points])
            rlon, rlat = iris.analysis.cartography.rotate_pole(lon, lat,
                                                               nplon, nplat)
            sampled_points = [(xcoord.name(), rlon),
                              (ycoord.name(), rlat)]

            sect = trajectory.interpolate(cube, sampled_points)
            _add_real_lonlat(sect, lon, lat)

            latspan = pnts['lat'][0], pnts['lat'][-1]
            lonspan = pnts['lon'][0], pnts['lon'][-1]
            sect_info = dict(v=zcoord.name(),
                             h='index',
                             label='z{}-{}lat{}-{}lon{}-{}'.format(*zspan,
                                                                   *latspan,
                                                                   *lonspan))

        elif isinstance(cs, (None, iris.coord_systems.GeogCS)):
            # Rectangular grid
            if len(pnts['lon']) == 2 and len(pnts['lat']) == 2:
                if ((pnts['lon'] == pnts['lon'][0]).all() and
                   not (pnts['lat'] == pnts['lat'][0]).all()):
                    # X const, Y varies
                    xslice = np.argmin(abs(xp - pnts['lon'][0]))
                    yslice = slice(*[np.argmin(abs(yp - i))
                                     for i in pnts['lat']])

                elif ((pnts['lat'] == pnts['lat'][0]).all() and
                      not (pnts['lon'] == pnts['lon'][0]).all()):
                    # Y const, X varies
                    yslice = np.argmin(abs(yp - pnts['lat'][0]))
                    xslice = slice(*[np.argmin(abs(xp - i))
                                     for i in pnts['lon']])
                sect = cube[..., yslice, xslice]
                sect_info = {}  # TODO
            else:
                # Diagonal
                raise NotYetImplementedError()
        else:
            raise NotYetImplementedError(f"Can't deal with "
                                          "{cube.coord_system()}")

    sect.attributes['sect_info'] = sect_info
    sect.attributes['sect_info']['pnts'] = pnts
    return sect