Ejemplo n.º 1
0
    def gradient(self, chi, truncation=None):
        """Computes the vector gradient of a scalar field on the sphere.

        **Argument:**

        *chi*
            A scalar field. It must be a `~iris.cube.Cube`
            with the same latitude and longitude dimensions as the
            vector wind components that initialized the `VectorWind`
            instance.

        **Optional argument:**

        *truncation*
            Truncation limit (triangular truncation) for the spherical
            harmonic computation.

        **Returns:**

        *uchi*, *vchi*
            The zonal and meridional components of the vector gradient
            respectively.

        **Examples:**

        Compute the vector gradient of absolute vorticity::

            avrt = w.absolutevorticity()
            avrt_zonal, avrt_meridional = w.gradient(avrt)

        Compute the vector gradient of absolute vorticity and apply
        spectral truncation at triangular T13::

            avrt = w.absolutevorticity()
            avrt_zonalT13, avrt_meridionalT13 = w.gradient(avrt, truncation=13)

        """
        if type(chi) is not Cube:
            raise TypeError('scalar field must be an iris cube')
        name = chi.name()
        lat, lat_dim = _dim_coord_and_dim(chi, 'latitude')
        lon, lon_dim = _dim_coord_and_dim(chi, 'longitude')
        apiorder, reorder = self._get_apiorder_reorder(chi, lat_dim, lon_dim)
        chi = chi.copy()
        chi.transpose(apiorder)
        ishape = chi.shape
        coords = chi.dim_coords
        chi = chi.data.reshape(chi.shape[:2] + (np.prod(chi.shape[2:]),))
        uchi, vchi = self._api.gradient(chi, truncation=truncation)
        uchi = uchi.reshape(ishape)
        vchi = vchi.reshape(ishape)
        uchi = Cube(uchi,
                    dim_coords_and_dims=zip(coords, range(uchi.ndim)))
        vchi = Cube(vchi,
                    dim_coords_and_dims=zip(coords, range(vchi.ndim)))
        uchi.transpose(reorder)
        vchi.transpose(reorder)
        uchi.long_name = 'zonal_gradient_of_{!s}'.format(name)
        vchi.long_name = 'meridional_gradient_of_{!s}'.format(name)
        return uchi, vchi
Ejemplo n.º 2
0
Archivo: stock.py Proyecto: js297/iris
def simple_2d(with_bounds=True):
    """
    Returns an abstract, two-dimensional, optionally bounded, cube.

    >>> print(simple_2d())
    thingness                           (bar: 3; foo: 4)
         Dimension coordinates:
              bar                           x       -
              foo                           -       x

    >>> print(repr(simple_2d().data))
    [[ 0  1  2  3]
     [ 4  5  6  7]
     [ 8  9 10 11]]


    """
    cube = Cube(np.arange(12, dtype=np.int32).reshape((3, 4)))
    cube.long_name = 'thingness'
    cube.units = '1'
    y_points = np.array([  2.5,   7.5,  12.5])
    y_bounds = np.array([[0, 5], [5, 10], [10, 15]], dtype=np.int32)
    y_coord = iris.coords.DimCoord(y_points, long_name='bar', units='1', bounds=y_bounds if with_bounds else None)
    x_points = np.array([ -7.5,   7.5,  22.5,  37.5])
    x_bounds = np.array([[-15, 0], [0, 15], [15, 30], [30, 45]], dtype=np.int32)
    x_coord = iris.coords.DimCoord(x_points, long_name='foo', units='1', bounds=x_bounds if with_bounds else None)

    cube.add_dim_coord(y_coord, 0)
    cube.add_dim_coord(x_coord, 1)
    return cube
Ejemplo n.º 3
0
def simple_1d(with_bounds=True):
    """
    Returns an abstract, one-dimensional cube.

    >>> print simple_1d()
    thingness                           (foo: 11)
         Dimension coordinates:
              foo                           x

    >>> print `simple_1d().data`
    [ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10]

    """
    cube = Cube(np.arange(11, dtype=np.int32))
    cube.long_name = 'thingness'
    cube.units = '1'
    points = np.arange(11, dtype=np.int32) + 1
    bounds = np.column_stack(
        [np.arange(11, dtype=np.int32),
         np.arange(11, dtype=np.int32) + 1])
    coord = iris.coords.DimCoord(points,
                                 long_name='foo',
                                 units='1',
                                 bounds=bounds)
    cube.add_dim_coord(coord, 0)
    return cube
Ejemplo n.º 4
0
def simple_2d(with_bounds=True):
    """
    Returns an abstract, two-dimensional, optionally bounded, cube.

    >>> print(simple_2d())
    thingness                           (bar: 3; foo: 4)
         Dimension coordinates:
              bar                           x       -
              foo                           -       x

    >>> print(repr(simple_2d().data))
    [[ 0  1  2  3]
     [ 4  5  6  7]
     [ 8  9 10 11]]


    """
    cube = Cube(np.arange(12, dtype=np.int32).reshape((3, 4)))
    cube.long_name = 'thingness'
    cube.units = '1'
    y_points = np.array([2.5,   7.5,  12.5])
    y_bounds = np.array([[0, 5], [5, 10], [10, 15]], dtype=np.int32)
    y_coord = DimCoord(y_points, long_name='bar', units='1',
                       bounds=y_bounds if with_bounds else None)
    x_points = np.array([ -7.5,   7.5,  22.5,  37.5])
    x_bounds = np.array([[-15, 0], [0, 15], [15, 30], [30, 45]],
                        dtype=np.int32)
    x_coord = DimCoord(x_points, long_name='foo', units='1',
                       bounds=x_bounds if with_bounds else None)

    cube.add_dim_coord(y_coord, 0)
    cube.add_dim_coord(x_coord, 1)
    return cube
Ejemplo n.º 5
0
def empty_3d_cube_aps3(data, name=None, unit=None, stash=None, **kwargs):
    """
    Prepare some iris cubes at APS3 grids for testing
    """
    if data is None:
        data = np.empty([6, 6])

    cube = Cube(data)

    time = AuxCoord([0], 'time', units='hours since epoch')

    latitude = DimCoord([6.26953125, 6.38671875, 6.50390625, 6.62109375,
                         6.73828125, 6.85546875, 6.97265625, 7.08984375],
                        standard_name='latitude', units='degrees')

    longitude = DimCoord([81.12304688, 81.29882812, 81.47460938,
                          81.65039062, 81.82617188, 82.00195312],
                         standard_name='longitude', units='degrees')

    cube.add_dim_coord(latitude, 0)
    cube.add_dim_coord(longitude, 1)
    cube.add_aux_coord(time)

    if name:
        cube.long_name = name
    if unit:
        cube.units = unit
    if stash:
        cube.attributes['STASH'] = stash

    return cube
Ejemplo n.º 6
0
def empty_3d_cube_aps2(data, name=None, unit=None, stash=None, **kwargs):
    """
    Prepare some iris cubes at APS2 grids for testing
    """
    if data is None:
        data = np.empty([2, 2])

    cube = Cube(data)

    time = AuxCoord([0], 'time', units='hours since epoch')

    latitude = DimCoord([6.328125, 6.5625, 6.796875, 7.03125],
                        standard_name='latitude', units='degrees')

    longitude = DimCoord([81.211053, 81.562616, 81.914179],
                         standard_name='longitude', units='degrees')

    cube.add_dim_coord(latitude, 0)
    cube.add_dim_coord(longitude, 1)
    cube.add_aux_coord(time)

    if name:
        cube.long_name = name
    if unit:
        cube.units = unit
    if stash:
        cube.attributes['STASH'] = stash

    return cube
Ejemplo n.º 7
0
def test_derive_noop():
    """Test derivation when it is not necessary."""
    alb = Cube([1.])
    alb.var_name = 'alb'
    alb.long_name = 'albedo at the surface'
    alb.units = 1

    cube = derive([alb], alb.var_name, alb.long_name, alb.units)

    assert cube is alb
Ejemplo n.º 8
0
def test_derive_noop():

    alb = Cube([1.])
    alb.var_name = 'alb'
    alb.long_name = 'albedo at the surface'
    alb.units = 1

    cube = derive([alb], alb.var_name, alb.long_name, alb.units)

    print(cube)
    assert cube is alb
Ejemplo n.º 9
0
def simple_3d_w_multidim_coords(with_bounds=True):
    """
    Returns an abstract, two-dimensional, optionally bounded, cube.

    >>> print simple_3d_w_multidim_coords()
    thingness                           (wibble: 2; *ANONYMOUS*: 3; *ANONYMOUS*: 4)
         Dimension coordinates:
              wibble                           x               -               -
         Auxiliary coordinates:
              bar                              -               x               x
              foo                              -               x               x

    >>> print simple_3d_w_multidim_coords().data
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]

    """
    cube = Cube(np.arange(24, dtype=np.int32).reshape((2, 3, 4)))
    cube.long_name = 'thingness'
    cube.units = '1'

    y_points = np.array([[2.5, 7.5, 12.5, 17.5],
                         [10., 17.5, 27.5, 42.5],
                         [15., 22.5, 32.5, 50.]])
    y_bounds = np.array([[[0, 5], [5, 10], [10, 15], [15, 20]],
                         [[5, 15], [15, 20], [20, 35], [35, 50]],
                         [[10, 20], [20, 25], [25, 40], [40, 60]]],
                        dtype=np.int32)
    y_coord = iris.coords.AuxCoord(points=y_points, long_name='bar',
                                   units='1',
                                   bounds=y_bounds if with_bounds else None)
    x_points = np.array([[-7.5, 7.5, 22.5, 37.5],
                         [-12.5, 4., 26.5, 47.5],
                         [2.5, 14., 36.5, 44.]])
    x_bounds = np.array([[[-15, 0], [0, 15], [15, 30], [30, 45]],
                         [[-25, 0], [0, 8], [8, 45], [45, 50]],
                         [[-5, 10], [10, 18],  [18, 55], [18, 70]]],
                        dtype=np.int32)
    x_coord = iris.coords.AuxCoord(points=x_points, long_name='foo',
                                   units='1',
                                   bounds=x_bounds if with_bounds else None)
    wibble_coord = iris.coords.DimCoord(np.array([10., 30.],
                                                 dtype=np.float32),
                                        long_name='wibble', units='1')

    cube.add_dim_coord(wibble_coord, [0])
    cube.add_aux_coord(y_coord, [1, 2])
    cube.add_aux_coord(x_coord, [1, 2])
    return cube
Ejemplo n.º 10
0
def simple_3d_w_multidim_coords(with_bounds=True):
    """
    Returns an abstract, two-dimensional, optionally bounded, cube.

    >>> print simple_3d_w_multidim_coords()
    thingness                           (wibble: 2; *ANONYMOUS*: 3; *ANONYMOUS*: 4)
         Dimension coordinates:
              wibble                           x               -               -
         Auxiliary coordinates:
              bar                              -               x               x
              foo                              -               x               x

    >>> print simple_3d_w_multidim_coords().data
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]

    """
    cube = Cube(np.arange(24, dtype=np.int32).reshape((2, 3, 4)))
    cube.long_name = 'thingness'
    cube.units = '1'

    y_points = np.array([[2.5, 7.5, 12.5, 17.5], [10., 17.5, 27.5, 42.5],
                         [15., 22.5, 32.5, 50.]])
    y_bounds = np.array([[[0, 5], [5, 10], [10, 15], [15, 20]],
                         [[5, 15], [15, 20], [20, 35], [35, 50]],
                         [[10, 20], [20, 25], [25, 40], [40, 60]]],
                        dtype=np.int32)
    y_coord = iris.coords.AuxCoord(points=y_points,
                                   long_name='bar',
                                   units='1',
                                   bounds=y_bounds if with_bounds else None)
    x_points = np.array([[-7.5, 7.5, 22.5, 37.5], [-12.5, 4., 26.5, 47.5],
                         [2.5, 14., 36.5, 44.]])
    x_bounds = np.array([[[-15, 0], [0, 15], [15, 30], [30, 45]],
                         [[-25, 0], [0, 8], [8, 45], [45, 50]],
                         [[-5, 10], [10, 18], [18, 55], [18, 70]]],
                        dtype=np.int32)
    x_coord = iris.coords.AuxCoord(points=x_points,
                                   long_name='foo',
                                   units='1',
                                   bounds=x_bounds if with_bounds else None)
    wibble_coord = iris.coords.DimCoord(np.array([10., 30.], dtype=np.float32),
                                        long_name='wibble',
                                        units='1')

    cube.add_dim_coord(wibble_coord, [0])
    cube.add_aux_coord(y_coord, [1, 2])
    cube.add_aux_coord(x_coord, [1, 2])
    return cube
Ejemplo n.º 11
0
def covariance_map(pcs, field, ddof=1):
    """Covariance between PCs and a field.

    Computes maps of the covariance between each PC and the given
    field at each grid point.

    Given a set of PCs contained in a `~iris.cube.Cube` (e.g., as output
    from `eofs.iris.Eof.pcs`) and a field with a time dimension
    contained in a `iris.cube.Cube`, one covariance map per PC is
    computed.

    The field must have the same length time dimension as the PCs. Any
    number of spatial dimensions (including zero) are allowed in the
    field and there can be any number of PCs.

    **Arguments:**

    *pcs*
        PCs contained in a `~iris.cube.Cube`.

    *field*
        Field Spatial-temporal field contained in a `~iris.cube.Cube`.

    **Keyword arguments:**

    *ddof*
        'Delta degrees of freedom'. The divisor used to normalize
        the covariance matrix is *N - ddof* where *N* is the
        number of samples. Defaults to *1*.

    **Returns:**

    *covariance_maps*
        A `~iris.cube.Cube` containing the covariance maps.

    **Examples:**

    Compute covariance maps for each PC::

        pcs = solver.pcs(pcscaling=1)
        covariance_maps = covariance_map(pcs, field)

    """
    # Compute the covariance map and retrieve appropriate Iris coordinate
    # dimensions for it.
    cov, dims = _map_and_dims(pcs, field, standard.covariance_map, ddof=ddof)
    if not dims:
        # There are no output dimensions, return a scalar.
        return cov
    # Otherwise return an Iris cube.
    cov = Cube(cov, dim_coords_and_dims=list(zip(dims, range(cov.ndim))))
    cov.long_name = 'pc_covariance'
    return cov
Ejemplo n.º 12
0
def covariance_map(pcs, field, ddof=1):
    """Covariance between PCs and a field.

    Computes maps of the covariance between each PC and the given
    field at each grid point.

    Given a set of PCs contained in a `~iris.cube.Cube` (e.g., as output
    from `eofs.iris.Eof.pcs`) and a field with a time dimension
    contained in a `iris.cube.Cube`, one covariance map per PC is
    computed.

    The field must have the same length time dimension as the PCs. Any
    number of spatial dimensions (including zero) are allowed in the
    field and there can be any number of PCs.

    **Arguments:**

    *pcs*
        PCs contained in a `~iris.cube.Cube`.

    *field*
        Field Spatial-temporal field contained in a `~iris.cube.Cube`.

    **Keyword arguments:**

    *ddof*
        'Delta degrees of freedom'. The divisor used to normalize
        the covariance matrix is *N - ddof* where *N* is the
        number of samples. Defaults to *1*.

    **Returns:**

    *covariance_maps*
        A `~iris.cube.Cube` containing the covariance maps.

    **Examples:**

    Compute covariance maps for each PC::

        pcs = solver.pcs(pcscaling=1)
        covariance_maps = covariance_map(pcs, field)

    """
    # Compute the covariance map and retrieve appropriate Iris coordinate
    # dimensions for it.
    cov, dims = _map_and_dims(pcs, field, standard.covariance_map, ddof=1)
    if not dims:
        # There are no output dimensions, return a scalar.
        return cov
    # Otherwise return an Iris cube.
    cov = Cube(cov, dim_coords_and_dims=zip(dims, range(cov.ndim)))
    cov.long_name = 'pc_covariance'
    return cov
Ejemplo n.º 13
0
def empty_model_level_cube(data, name=None, unit=None, stash=None, **kwargs):
    """
    Create a model_level cube from input data.
    """
    if data is None:
        data = np.empty([1, 3, 8, 6])
    assert data.shape == (3, 8, 6)
    # Make axis=0 for time dim_coord
    new_data = data[np.newaxis, :]
    cube = Cube(new_data)

    # time = AuxCoord([0], 'time', units='hours since epoch')
    time = DimCoord([0], 'time', units='hours since epoch')

    # model = DimCoord([1, 2, 3], 'model_level_number',
    #                  attributes={'positive': 'up'})
    model = DimCoord([1, 2, 3], 'air_pressure',
                     attributes={'positive': 'up'})
    latitude = DimCoord([6.26953125, 6.38671875, 6.50390625, 6.62109375,
                         6.73828125, 6.85546875, 6.97265625, 7.08984375],
                        standard_name='latitude', units='degrees')

    longitude = DimCoord([81.12304688, 81.29882812, 81.47460938,
                          81.65039062, 81.82617188, 82.00195312],
                         standard_name='longitude', units='degrees')

    level_heights = np.array([20., 53.336, 100.])
    level_height = DimCoord(level_heights, long_name='level_height', units='m')
    surface = AuxCoord(topo_aps3.data, 'surface_altitude', units='m')

    sigma = AuxCoord([0.99772321, 0.99393402, 0.98864199], long_name='sigma')

    cube.add_dim_coord(time, 0)
    cube.add_dim_coord(model, 1)
    cube.add_dim_coord(latitude, 2)
    cube.add_dim_coord(longitude, 3)

    cube.add_aux_coord(level_height, 1)
    cube.add_aux_coord(sigma, 1)
    cube.add_aux_coord(surface, (2, 3))

    # Now that we have all of the necessary information, construct a
    # HybridHeight derived "altitude" coordinate.
    cube.add_aux_factory(HybridHeightFactory(level_height, sigma, surface))

    if name:
        cube.long_name = name
    if unit:
        cube.units = unit
    if stash:
        cube.attributes['STASH'] = stash

    return cube
Ejemplo n.º 14
0
def correlation_map(pcs, field):
    """Correlation between PCs and a field.

    Computes maps of the correlation between each PC and the given
    field at each grid point.

    Given a set of PCs contained in a `~iris.cube.Cube` (e.g., as output
    from `eofs.iris.Eof.pcs`) and a field with a time dimension
    contained in a `iris.cube.Cube`, one correlation map per PC is
    computed.

    The field must have the same length time dimension as the PCs. Any
    number of spatial dimensions (including zero) are allowed in the
    field and there can be any number of PCs.

    **Arguments:**

    *pcs*
        PCs contained in a `~iris.cube.Cube`.

    *field*
        Field Spatial-temporal field contained in a `~iris.cube.Cube`.

    **Returns:**

    *correlation_maps*
        A `~iris.cube.Cube` containing the correlation maps.

    **Examples:**

    Assuming *solver* is an instance of `eofs.iris.Eof`, compute
    correlation maps for each PC::

        pcs = solver.pcs(pcscaling=1)
        correlation_maps = correlation_map(pcs, field)

    """
    # Compute the correlation map and retrieve appropriate Iris coordinate
    # dimensions for it.
    cor, dims = _map_and_dims(pcs, field, standard.correlation_map)
    if not dims:
        # There are no output dimensions, return a scalar.
        return cor
    # Otherwise return an Iris cube.
    cor = Cube(cor, dim_coords_and_dims=list(zip(dims, range(cor.ndim))))
    cor.long_name = 'pc_correlation'
    return cor
Ejemplo n.º 15
0
def correlation_map(pcs, field):
    """Correlation between PCs and a field.

    Computes maps of the correlation between each PC and the given
    field at each grid point.

    Given a set of PCs contained in a `~iris.cube.Cube` (e.g., as output
    from `eofs.iris.Eof.pcs`) and a field with a time dimension
    contained in a `iris.cube.Cube`, one correlation map per PC is
    computed.

    The field must have the same length time dimension as the PCs. Any
    number of spatial dimensions (including zero) are allowed in the
    field and there can be any number of PCs.

    **Arguments:**

    *pcs*
        PCs contained in a `~iris.cube.Cube`.

    *field*
        Field Spatial-temporal field contained in a `~iris.cube.Cube`.

    **Returns:**

    *correlation_maps*
        A `~iris.cube.Cube` containing the correlation maps.

    **Examples:**

    Assuming *solver* is an instance of `eofs.iris.Eof`, compute
    correlation maps for each PC::

        pcs = solver.pcs(pcscaling=1)
        correlation_maps = correlation_map(pcs, field)

    """
    # Compute the correlation map and retrieve appropriate Iris coordinate
    # dimensions for it.
    cor, dims = _map_and_dims(pcs, field, standard.correlation_map)
    if not dims:
        # There are no output dimensions, return a scalar.
        return cor
    # Otherwise return an Iris cube.
    cor = Cube(cor, dim_coords_and_dims=zip(dims, range(cor.ndim)))
    cor.long_name = 'pc_correlation'
    return cor
Ejemplo n.º 16
0
def simple_3d():
    cube = Cube(np.arange(24, dtype=np.int32).reshape((2, 3, 4)))
    cube.long_name = "thingness"
    cube.units = "1"
    wibble_coord = DimCoord(np.array([10.0, 30.0], dtype=np.float32),
                            long_name="wibble",
                            units="1")
    lon = DimCoord(
        [-180, -90, 0, 90],
        standard_name="longitude",
        units="degrees",
        circular=True,
    )
    lat = DimCoord([90, 0, -90], standard_name="latitude", units="degrees")
    cube.add_dim_coord(wibble_coord, [0])
    cube.add_dim_coord(lat, [1])
    cube.add_dim_coord(lon, [2])
    return cube
Ejemplo n.º 17
0
def simple_1d(with_bounds=True):
    """
    Returns an abstract, one-dimensional cube.

    >>> print(simple_1d())
    thingness                           (foo: 11)
         Dimension coordinates:
              foo                           x

    >>> print(repr(simple_1d().data))
    [ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10]

    """
    cube = Cube(np.arange(11, dtype=np.int32))
    cube.long_name = 'thingness'
    cube.units = '1'
    points = np.arange(11, dtype=np.int32) + 1
    bounds = np.column_stack([np.arange(11, dtype=np.int32), np.arange(11, dtype=np.int32) + 1])
    coord = DimCoord(points, long_name='foo', units='1', bounds=bounds)
    cube.add_dim_coord(coord, 0)
    return cube
Ejemplo n.º 18
0
def simple_3d():
    """
    Returns an abstract three dimensional cube.

    >>> print(simple_3d())
    thingness / (1)                     (wibble: 2; latitude: 3; longitude: 4)
     Dimension coordinates:
          wibble                           x            -             -
          latitude                         -            x             -
          longitude                        -            -             x

    >>> print(simple_3d().data)
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]

    """
    cube = Cube(np.arange(24, dtype=np.int32).reshape((2, 3, 4)))
    cube.long_name = "thingness"
    cube.units = "1"
    wibble_coord = DimCoord(np.array([10.0, 30.0], dtype=np.float32),
                            long_name="wibble",
                            units="1")
    lon = DimCoord(
        [-180, -90, 0, 90],
        standard_name="longitude",
        units="degrees",
        circular=True,
    )
    lat = DimCoord([90, 0, -90], standard_name="latitude", units="degrees")
    cube.add_dim_coord(wibble_coord, [0])
    cube.add_dim_coord(lat, [1])
    cube.add_dim_coord(lon, [2])
    return cube
Ejemplo n.º 19
0
def simple_3d():
    """
    Returns an abstract three dimensional cube.

    >>>print simple_3d()
    thingness / (1)                     (wibble: 2; latitude: 3; longitude: 4)
     Dimension coordinates:
          wibble                           x            -             -
          latitude                         -            x             -
          longitude                        -            -             x

    >>> print simple_3d().data
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]

    """
    cube = Cube(np.arange(24, dtype=np.int32).reshape((2, 3, 4)))
    cube.long_name = 'thingness'
    cube.units = '1'
    wibble_coord = iris.coords.DimCoord(np.array([10., 30.], dtype=np.float32),
                                        long_name='wibble',
                                        units='1')
    lon = iris.coords.DimCoord([-180, -90, 0, 90],
                               standard_name='longitude',
                               units='degrees',
                               circular=True)
    lat = iris.coords.DimCoord([90, 0, -90],
                               standard_name='latitude',
                               units='degrees')
    cube.add_dim_coord(wibble_coord, [0])
    cube.add_dim_coord(lat, [1])
    cube.add_dim_coord(lon, [2])
    return cube
Ejemplo n.º 20
0
def simple_1d(with_bounds=True):
    """
    Returns an abstract, one-dimensional cube.

    >>> print(simple_1d())
    thingness                           (foo: 11)
         Dimension coordinates:
              foo                           x

    >>> print(repr(simple_1d().data))
    [ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10]

    """
    cube = Cube(np.arange(11, dtype=np.int32))
    cube.long_name = "thingness"
    cube.units = "1"
    points = np.arange(11, dtype=np.int32) + 1
    bounds = np.column_stack(
        [np.arange(11, dtype=np.int32),
         np.arange(11, dtype=np.int32) + 1])
    coord = DimCoord(points, long_name="foo", units="1", bounds=bounds)
    cube.add_dim_coord(coord, 0)
    return cube
Ejemplo n.º 21
0
def simple_3d():
    """
    Returns an abstract three dimensional cube.

    >>> print(simple_3d())
    thingness / (1)                     (wibble: 2; latitude: 3; longitude: 4)
     Dimension coordinates:
          wibble                           x            -             -
          latitude                         -            x             -
          longitude                        -            -             x

    >>> print(simple_3d().data)
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]

    """
    cube = Cube(np.arange(24, dtype=np.int32).reshape((2, 3, 4)))
    cube.long_name = 'thingness'
    cube.units = '1'
    wibble_coord = DimCoord(np.array([10., 30.],
                                                 dtype=np.float32),
                                        long_name='wibble', units='1')
    lon = DimCoord([-180, -90, 0, 90],
                               standard_name='longitude',
                               units='degrees', circular=True)
    lat = DimCoord([90, 0, -90],
                               standard_name='latitude', units='degrees')
    cube.add_dim_coord(wibble_coord, [0])
    cube.add_dim_coord(lat, [1])
    cube.add_dim_coord(lon, [2])
    return cube
Ejemplo n.º 22
0
    def gradient(self, chi, truncation=None):
        """Computes the vector gradient of a scalar field on the sphere.

        **Argument:**

        *chi*
            A scalar field. It must be a `~iris.cube.Cube`
            with the same latitude and longitude dimensions as the
            vector wind components that initialized the `VectorWind`
            instance.

        **Optional argument:**

        *truncation*
            Truncation limit (triangular truncation) for the spherical
            harmonic computation.

        **Returns:**

        *uchi*, *vchi*
            The zonal and meridional components of the vector gradient
            respectively.

        **Examples:**

        Compute the vector gradient of absolute vorticity::

            avrt = w.absolutevorticity()
            avrt_zonal, avrt_meridional = w.gradient(avrt)

        Compute the vector gradient of absolute vorticity and apply
        spectral truncation at triangular T13::

            avrt = w.absolutevorticity()
            avrt_zonalT13, avrt_meridionalT13 = w.gradient(avrt, truncation=13)

        """
        if type(chi) is not Cube:
            raise TypeError('scalar field must be an iris cube')
        name = chi.name()
        lat, lat_dim = _dim_coord_and_dim(chi, 'latitude')
        lon, lon_dim = _dim_coord_and_dim(chi, 'longitude')
        if (lat.points[0] < lat.points[1]):
            # need to reverse latitude dimension
            chi = reverse(chi, lat_dim)
            lat, lat_dim = _dim_coord_and_dim(chi, 'latitude')
        apiorder, reorder = get_apiorder(chi.ndim, lat_dim, lon_dim)
        chi = chi.copy()
        chi.transpose(apiorder)
        ishape = chi.shape
        coords = chi.dim_coords
        chi = chi.data.reshape(chi.shape[:2] + (np.prod(chi.shape[2:]), ))
        uchi, vchi = self._api.gradient(chi, truncation=truncation)
        uchi = uchi.reshape(ishape)
        vchi = vchi.reshape(ishape)
        uchi = Cube(uchi,
                    dim_coords_and_dims=list(zip(coords, range(uchi.ndim))))
        vchi = Cube(vchi,
                    dim_coords_and_dims=list(zip(coords, range(vchi.ndim))))
        uchi.transpose(reorder)
        vchi.transpose(reorder)
        uchi.long_name = 'zonal_gradient_of_{!s}'.format(name)
        vchi.long_name = 'meridional_gradient_of_{!s}'.format(name)
        return uchi, vchi