Пример #1
0
    def test_different_dims(self):
        # Source data
        source_nx = 100
        source_ny = 100
        source_x = np.linspace(-180.0, 180.0,
                               source_nx).astype(np.float64)
        source_y = np.linspace(-90, 90.0,
                               source_ny).astype(np.float64)
        source_x, source_y = np.meshgrid(source_x, source_y)
        data = np.arange(source_nx * source_ny,
                         dtype=np.int32).reshape(source_ny, source_nx)
        source_cs = ccrs.Geodetic()

        # Target grids (different shapes)
        target_x_shape = (23, 45)
        target_y_shape = (23, 44)
        target_x = np.arange(reduce(operator.mul, target_x_shape),
                             dtype=np.float64).reshape(target_x_shape)
        target_y = np.arange(reduce(operator.mul, target_y_shape),
                             dtype=np.float64).reshape(target_y_shape)
        target_proj = ccrs.PlateCarree()

        # Attempt regrid
        with pytest.raises(ValueError):
            im_trans.regrid(data, source_x, source_y, source_cs,
                            target_proj, target_x, target_y)
Пример #2
0
    def test_different_dims(self):
        # Source data
        source_nx = 100
        source_ny = 100
        source_x = np.linspace(-180.0, 180.0,
                               source_nx).astype(np.float64)
        source_y = np.linspace(-90, 90.0,
                               source_ny).astype(np.float64)
        source_x, source_y = np.meshgrid(source_x, source_y)
        data = np.arange(source_nx * source_ny,
                         dtype=np.int32).reshape(source_ny, source_nx)
        source_cs = ccrs.Geodetic()

        # Target grids (different shapes)
        target_x_shape = (23, 45)
        target_y_shape = (23, 44)
        target_x = np.arange(reduce(operator.mul, target_x_shape),
                             dtype=np.float64).reshape(target_x_shape)
        target_y = np.arange(reduce(operator.mul, target_y_shape),
                             dtype=np.float64).reshape(target_y_shape)
        target_proj = ccrs.PlateCarree()

        # Attempt regrid
        with self.assertRaises(ValueError):
            im_trans.regrid(data, source_x, source_y, source_cs,
                            target_proj, target_x, target_y)
Пример #3
0
    def test_array_dims(self):
        # Source data
        source_nx = 100
        source_ny = 100
        source_x = np.linspace(-180.0, 180.0, source_nx).astype(np.float64)
        source_y = np.linspace(-90, 90.0, source_ny).astype(np.float64)
        source_x, source_y = np.meshgrid(source_x, source_y)
        data = np.arange(source_nx * source_ny,
                         dtype=np.int32).reshape(source_ny, source_nx)
        source_cs = ccrs.Geodetic()

        # Target grid
        target_nx = 23
        target_ny = 45
        target_proj = ccrs.PlateCarree()
        target_x, target_y, extent = im_trans.mesh_projection(
            target_proj, target_nx, target_ny)

        # Perform regrid
        new_array = im_trans.regrid(data, source_x, source_y, source_cs,
                                    target_proj, target_x, target_y)

        # Check dimensions of return array
        self.assertEqual(new_array.shape, target_x.shape)
        self.assertEqual(new_array.shape, target_y.shape)
        self.assertEqual(new_array.shape, (target_ny, target_nx))
Пример #4
0
def test_gridding_data_outside_projection():
    # Data which exists outside the standard projection e.g. [0, 360] rather
    # than [-180, 180].
    target_prj = ccrs.PlateCarree()
    # create 3 data points
    lats = np.array([65, 10, -45])
    lons = np.array([120, 180, 240])
    data = np.array([1, 2, 3])
    data_trans = ccrs.Geodetic()

    target_x, target_y, extent = img_trans.mesh_projection(target_prj, 8, 4)

    image = img_trans.regrid(data,
                             lons,
                             lats,
                             data_trans,
                             target_prj,
                             target_x,
                             target_y,
                             mask_extrapolated=True)

    # The expected image. n.b. on a map the data is reversed in the y axis.
    expected = np.array([[3, 3, 3, 3, 3, 2, 2, 2], [3, 3, 3, 3, 1, 1, 2, 2],
                         [3, 3, 3, 3, 1, 1, 1, 2], [3, 3, 3, 1, 1, 1, 1, 1]],
                        dtype=np.float64)

    expected_mask = np.array(
        [[True, True, True, True, True, True, True, True],
         [False, False, True, True, True, True, False, False],
         [False, False, True, True, True, True, False, False],
         [True, True, True, True, True, True, True, True]])

    assert_array_equal([-180, 180, -90, 90], extent)
    assert_array_equal(expected, image)
    assert_array_equal(expected_mask, image.mask)
Пример #5
0
def test_griding_data_outside_projection():
    # Data which exists outside the standard projection e.g. [0, 360] rather
    # than [-180, 180].
    target_prj = ccrs.PlateCarree()
    # create 3 data points
    lats = np.array([65, 10, -45])
    lons = np.array([120, 180, 240])
    data = np.array([1, 2, 3])
    data_trans = ccrs.Geodetic()

    target_x, target_y, extent = img_trans.mesh_projection(target_prj, 8, 4)

    image = img_trans.regrid(data, lons, lats, data_trans, target_prj,
                             target_x, target_y,
                             mask_extrapolated=True)

    # The expected image. n.b. on a map the data is reversed in the y axis.
    expected = np.array(
        [[3, 3, 3, 3, 3, 3, 3, 3],
         [3, 3, 3, 3, 3, 1, 2, 2],
         [2, 2, 3, 1, 1, 1, 1, 2],
         [1, 1, 1, 1, 1, 1, 1, 1]], dtype=np.float64)

    expected_mask = np.array(
        [[True, True, True, True, True, True, True, True],
         [False, False, True, True, True, True, False, False],
         [False, False, True, True, True, True, False, False],
         [True, True, True, True, True, True, True, True]])

    assert_array_equal([-180, 180, -90, 90], extent)
    assert_array_equal(expected, image)
    assert_array_equal(expected_mask, image.mask)
Пример #6
0
    def test_array_dims(self):
        # Source data
        source_nx = 100
        source_ny = 100
        source_x = np.linspace(-180.0,
                               180.0,
                               source_nx).astype(np.float64)
        source_y = np.linspace(-90, 90.0, source_ny).astype(np.float64)
        source_x, source_y = np.meshgrid(source_x, source_y)
        data = np.arange(source_nx * source_ny,
                         dtype=np.int32).reshape(source_ny, source_nx)
        source_cs = ccrs.Geodetic()

        # Target grid
        target_nx = 23
        target_ny = 45
        target_proj = ccrs.PlateCarree()
        target_x, target_y, extent = im_trans.mesh_projection(target_proj,
                                                              target_nx,
                                                              target_ny)

        # Perform regrid
        new_array = im_trans.regrid(data, source_x, source_y, source_cs,
                                    target_proj, target_x, target_y)

        # Check dimensions of return array
        self.assertEqual(new_array.shape, target_x.shape)
        self.assertEqual(new_array.shape, target_y.shape)
        self.assertEqual(new_array.shape, (target_ny, target_nx))
Пример #7
0
    def data(self, da, projection):
        """"""

        # Reproject the data
        if projection and (da[self.xname].ndim == 2):

            projection = getattr(cartopy.crs, projection)()

            # Set the central longitude (if applicable)
            if self.c_lon:
                try:
                    projection = projection.__class__(central_longitude=self.c_lon)
                except:
                    pass

            # TODO: Need to detect and add cyclic point insertion
            x, y = img_transform.mesh_projection(projection, nx=self.nx, ny=self.ny)[:2]
            field = img_transform.regrid(da.to_masked_array(), da[self.xname].values, da[self.yname].values,
                                         self.ref_crs, projection, x, y)

            plt.gcf().add_subplot(self.subplot, projection=projection)

        # Subsample the data and plot on grid coords
        else:
            # NOTE: Assume here that dims are (y, x); I don't think auto-transpose happens in mpl so should be
            # obvious from figure if this assumption is wrong
            da = da[slice(None, None, max(1, da.shape[0] / self.ny)),
                    slice(None, None, max(1, da.shape[1] / self.nx))]
            x = da[self.xname]
            y = da[self.yname]
            field = da.to_masked_array()

            plt.gcf().add_subplot(self.subplot)

        return x, y, field
Пример #8
0
def test_regrid_image():
    # Source data
    fname = os.path.join(config["repo_data_dir"], 'raster', 'natural_earth',
                         '50-natural-earth-1-downsampled.png')
    nx = 720
    ny = 360
    source_proj = ccrs.PlateCarree()
    source_x, source_y, _ = im_trans.mesh_projection(source_proj, nx, ny)
    data = plt.imread(fname)
    # Flip vertically to match source_x/source_y orientation
    data = data[::-1]

    # Target grid
    target_nx = 300
    target_ny = 300
    target_proj = ccrs.InterruptedGoodeHomolosine(emphasis='land')
    target_x, target_y, target_extent = im_trans.mesh_projection(
        target_proj, target_nx, target_ny)

    # Perform regrid
    new_array = im_trans.regrid(data, source_x, source_y, source_proj,
                                target_proj, target_x, target_y)

    # Plot
    fig = plt.figure(figsize=(10, 10))
    gs = mpl.gridspec.GridSpec(nrows=4, ncols=1, hspace=1.5, wspace=0.5)
    # Set up axes and title
    ax = fig.add_subplot(gs[0], projection=target_proj)
    ax.imshow(new_array, origin='lower', extent=target_extent)
    ax.coastlines()
    # Plot each color slice (tests masking)
    cmaps = {'red': 'Reds', 'green': 'Greens', 'blue': 'Blues'}
    for i, color in enumerate(['red', 'green', 'blue']):
        ax = fig.add_subplot(gs[i + 1], projection=target_proj)
        ax.imshow(new_array[:, :, i],
                  extent=target_extent,
                  origin='lower',
                  cmap=cmaps[color])
        ax.coastlines()

    # Tighten up layout
    gs.tight_layout(fig)
    return fig
Пример #9
0
def test_regrid_image():
    # Source data
    fname = os.path.join(config["repo_data_dir"], 'raster', 'natural_earth',
                         '50-natural-earth-1-downsampled.png')
    nx = 720
    ny = 360
    source_proj = ccrs.PlateCarree()
    source_x, source_y, _ = im_trans.mesh_projection(source_proj, nx, ny)
    data = plt.imread(fname)
    # Flip vertically to match source_x/source_y orientation
    data = data[::-1]

    # Target grid
    target_nx = 300
    target_ny = 300
    target_proj = ccrs.InterruptedGoodeHomolosine()
    target_x, target_y, target_extent = im_trans.mesh_projection(target_proj,
                                                                 target_nx,
                                                                 target_ny)

    # Perform regrid
    new_array = im_trans.regrid(data, source_x, source_y, source_proj,
                                target_proj, target_x, target_y)

    # Plot
    fig = plt.figure(figsize=(10, 10))
    gs = matplotlib.gridspec.GridSpec(nrows=4, ncols=1,
                                      hspace=1.5, wspace=0.5)
    # Set up axes and title
    ax = plt.subplot(gs[0], frameon=False, projection=target_proj)
    plt.imshow(new_array, origin='lower', extent=target_extent)
    ax.coastlines()
    # Plot each colour slice (tests masking)
    cmaps = {'red': 'Reds', 'green': 'Greens', 'blue': 'Blues'}
    for i, colour in enumerate(['red', 'green', 'blue']):
        ax = plt.subplot(gs[i + 1], frameon=False, projection=target_proj)
        ax.set_title(colour)
        plt.imshow(new_array[:, :, i], extent=target_extent, origin='lower',
                   cmap=cmaps[colour])
        ax.coastlines()

    # Tighten up layout
    gs.tight_layout(plt.gcf())
Пример #10
0
def test_griding_data():
    target_prj = ccrs.PlateCarree()
    # create 3 data points
    lats = np.array([45, 20, -45])
    lons = np.array([-90, 90, 0])
    data = np.array([1, 2, 3])
    data_trans = ccrs.Geodetic()

    target_x, target_y, extent = img_trans.mesh_projection(target_prj, 8, 4)

    image = img_trans.regrid(data, lons, lats, data_trans, target_prj,
                             target_x, target_y)

    # The expected image. n.b. on a map the data is reversed in the y axis.
    expected = np.array(
        [[3., 3., 3., 3., 3., 3., 3., 3.], [1., 1., 3., 3., 3., 2., 2., 2.],
         [1., 1., 1., 1., 2., 2., 2., 2.], [1., 1., 1., 1., 1., 2., 2., 1.]],
        dtype=np.float64)

    assert_array_equal([-180, 180, -90, 90], extent)
    assert_array_equal(expected, image)
Пример #11
0
def test_griding_data():
    target_prj = ccrs.PlateCarree()
    # create 3 data points
    lats = np.array([45, 20, -45])
    lons = np.array([-90, 90, 0])
    data = np.array([1, 2, 3])
    data_trans = ccrs.Geodetic()

    target_x, target_y, extent = img_trans.mesh_projection(target_prj, 8, 4)

    image = img_trans.regrid(data, lons, lats, data_trans, target_prj,
                             target_x, target_y)

    # The expected image. n.b. on a map the data is reversed in the y axis.
    expected = np.array([[3., 3., 3., 3., 3., 3., 3., 3.],
                         [1., 1., 3., 3., 3., 2., 2., 2.],
                         [1., 1., 1., 1., 2., 2., 2., 2.],
                         [1., 1., 1., 1., 1., 2., 2., 1.]], dtype=np.float64)

    assert_array_equal([-180,  180,  -90,   90], extent)
    assert_array_equal(expected, image)