예제 #1
0
 def test_non_cube_coordinate(self):
     cube = self.cube[0, :, :, 0]
     pts = -100 + np.arange(cube.shape[1]) * 13
     x = coords.DimCoord(
         pts,
         standard_name="model_level_number",
         attributes={"positive": "up"},
         units="1",
     )
     self.draw("contourf", cube, coords=["grid_latitude", x])
예제 #2
0
    def setup(self):
        repeat_number = 10
        repeat_range = range(int(ARTIFICIAL_DIM_SIZE / repeat_number))
        array_repeat = np.repeat(repeat_range, repeat_number)
        array_unique = np.arange(len(array_repeat))

        coord_repeat = coords.AuxCoord(points=array_repeat, long_name="repeat")
        coord_unique = coords.DimCoord(points=array_unique, long_name="unique")

        local_cube = general_cube.copy()
        local_cube.add_aux_coord(coord_repeat, 0)
        local_cube.add_dim_coord(coord_unique, 0)
        self.cube = local_cube
예제 #3
0
def realistic_3d():
    """
    Returns a realistic 3d cube.

    >>> print(repr(realistic_3d()))
    <iris 'Cube' of air_potential_temperature (time: 7; grid_latitude: 9;
    grid_longitude: 11)>

    """
    data = np.arange(7 * 9 * 11).reshape((7, 9, 11))
    lat_pts = np.linspace(-4, 4, 9)
    lon_pts = np.linspace(-5, 5, 11)
    time_pts = np.linspace(394200, 394236, 7)
    forecast_period_pts = np.linspace(0, 36, 7)
    ll_cs = RotatedGeogCS(37.5, 177.5, ellipsoid=GeogCS(6371229.0))

    lat = icoords.DimCoord(lat_pts,
                           standard_name='grid_latitude',
                           units='degrees',
                           coord_system=ll_cs)
    lon = icoords.DimCoord(lon_pts,
                           standard_name='grid_longitude',
                           units='degrees',
                           coord_system=ll_cs)
    time = icoords.DimCoord(time_pts,
                            standard_name='time',
                            units='hours since 1970-01-01 00:00:00')
    forecast_period = icoords.DimCoord(forecast_period_pts,
                                       standard_name='forecast_period',
                                       units='hours')
    height = icoords.DimCoord(1000.0, standard_name='air_pressure', units='Pa')
    cube = iris.cube.Cube(data,
                          standard_name='air_potential_temperature',
                          units='K',
                          dim_coords_and_dims=[(time, 0), (lat, 1), (lon, 2)],
                          aux_coords_and_dims=[(forecast_period, 0),
                                               (height, None)],
                          attributes={'source': 'Iris test case'})
    return cube
예제 #4
0
def make_time_coord(coord_dict):
    from datetime import datetime,timedelta
    from iris import coords
    timestr=str(int(coord_dict['iyear1'][0]))+str(int(coord_dict['imonth1'][0])).zfill(2)+str(int(coord_dict['idate1'][0])).zfill(2)+str(int(coord_dict['itime1'][0])).zfill(4)
    timeobj = datetime.strptime(timestr,"%Y%m%d%H%M")+timedelta(seconds=1)*coord_dict['time'][0]

    if timeobj<datetime(100,1,1):
        base_date=datetime(1,1,1)
    else:
        base_date=datetime(1970,1,1)
    time_units='days since '+ base_date.strftime('%Y-%m-%d')

    time_days=(timeobj - base_date).total_seconds() / timedelta(days=1).total_seconds()
    time_coord=coords.DimCoord(time_days, standard_name='time', long_name='time', var_name='time', units=time_units, bounds=None, attributes=None, coord_system=None, circular=False)
    return time_coord    
예제 #5
0
    def setup(self):
        # Manufacture data from which contours can be derived.
        # Should generate 10 distinct contours, regardless of dim size.
        dim_size = int(ARTIFICIAL_DIM_SIZE / 5)
        repeat_number = int(dim_size / 10)
        repeat_range = range(int((dim_size ** 2) / repeat_number))
        data = np.repeat(repeat_range, repeat_number)
        data = data.reshape((dim_size,) * 2)

        # These benchmarks are from a user perspective, so setting up a
        # user-level case that will prompt the calling of aux_coords.sort in plot.py.
        dim_coord = coords.DimCoord(np.arange(dim_size))
        local_cube = cube.Cube(data)
        local_cube.add_aux_coord(dim_coord, 0)
        self.cube = local_cube
def realistic_3d():
    data = np.arange(7 * 9 * 11).reshape((7, 9, 11))
    lat_pts = np.linspace(-4, 4, 9)
    lon_pts = np.linspace(-5, 5, 11)
    time_pts = np.linspace(394200, 394236, 7)
    forecast_period_pts = np.linspace(0, 36, 7)
    ll_cs = RotatedGeogCS(37.5, 177.5, ellipsoid=GeogCS(6371229.0))

    lat = icoords.DimCoord(
        lat_pts,
        standard_name="grid_latitude",
        units="degrees",
        coord_system=ll_cs,
    )
    lon = icoords.DimCoord(
        lon_pts,
        standard_name="grid_longitude",
        units="degrees",
        coord_system=ll_cs,
    )
    time = icoords.DimCoord(time_pts,
                            standard_name="time",
                            units="hours since 1970-01-01 00:00:00")
    forecast_period = icoords.DimCoord(forecast_period_pts,
                                       standard_name="forecast_period",
                                       units="hours")
    height = icoords.DimCoord(1000.0, standard_name="air_pressure", units="Pa")
    cube = iris.cube.Cube(
        data,
        standard_name="air_potential_temperature",
        units="K",
        dim_coords_and_dims=[(time, 0), (lat, 1), (lon, 2)],
        aux_coords_and_dims=[(forecast_period, 0), (height, None)],
        attributes={"source": "Iris test case"},
    )
    return cube
예제 #7
0
파일: stock.py 프로젝트: mcmweb80/iris
def hybrid_height():
    """
    Returns a two-dimensional (Z, X), hybrid-height cube.

    >>> print hybrid_height()
    TODO: Update!
    air_temperature                     (level_height: 3; *ANONYMOUS*: 4)
         Dimension coordinates:
              level_height                           x               -
         Auxiliary coordinates:
              model_level_number                     x               -
              sigma                                  x               -
              surface_altitude                       -               x
         Derived coordinates:
              altitude                               x               x

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

    """
    data = np.arange(12, dtype='i8').reshape((3, 4))

    orography = icoords.AuxCoord([10, 25, 50, 5],
                                 standard_name='surface_altitude',
                                 units='m')
    model_level = icoords.AuxCoord([2, 1, 0],
                                   standard_name='model_level_number')
    level_height = icoords.DimCoord([100, 50, 10],
                                    long_name='level_height',
                                    units='m',
                                    attributes={'positive': 'up'},
                                    bounds=[[150, 75], [75, 20], [20, 0]])
    sigma = icoords.AuxCoord([0.8, 0.9, 0.95],
                             long_name='sigma',
                             bounds=[[0.7, 0.85], [0.85, 0.97], [0.97, 1.0]])
    hybrid_height = iris.aux_factory.HybridHeightFactory(
        level_height, sigma, orography)

    cube = iris.cube.Cube(data,
                          standard_name='air_temperature',
                          units='K',
                          dim_coords_and_dims=[(level_height, 0)],
                          aux_coords_and_dims=[(orography, 1),
                                               (model_level, 0), (sigma, 0)],
                          aux_factories=[hybrid_height])
    return cube
예제 #8
0
def add_dim_coordinates(filename, variable,variable_cube,variable_dict, coord_dict,domain,add_coordinates=None):        
    from iris import coords
    import numpy as np
   
        #    from iris import coord_systems

#    coord_system=coord_systems.LambertConformal(central_lat=MOAD_CEN_LAT, central_lon=CEN_LON, false_easting=0.0, false_northing=0.0, secant_latitudes=(TRUELAT1, TRUELAT2))
    coord_system=None
    if (variable_dict[variable]==3):
        time_coord=make_time_coord(coord_dict)
        variable_cube.add_aux_coord(time_coord)
        z_coord=coords.DimCoord(coord_dict['ztn01'], standard_name='geopotential_height', long_name='z', var_name='z', units='m', bounds=None, attributes=None, coord_system=coord_system)
        variable_cube.add_dim_coord(z_coord,0)
        model_level_number_coord=make_model_level_number_coordinate(len(z_coord.points))
        variable_cube.add_aux_coord(model_level_number_coord,0)
        x_coord=coords.DimCoord(np.arange(len(coord_dict['xtn0'+domain])), long_name='x', units='1', bounds=None, attributes=None, coord_system=coord_system)
        variable_cube.add_dim_coord(x_coord,2)
        y_coord=coords.DimCoord(np.arange(len(coord_dict['ytn0'+domain])), long_name='y', units='1', bounds=None, attributes=None, coord_system=coord_system)
        variable_cube.add_dim_coord(y_coord,1)
        projection_x_coord=coords.DimCoord(coord_dict['xtn0'+domain], standard_name='projection_x_coordinate', long_name='x', var_name='x', units='m', bounds=None, attributes=None, coord_system=coord_system)
        variable_cube.add_aux_coord(projection_x_coord,(2))
        projection_y_coord=coords.DimCoord(coord_dict['ytn0'+domain], standard_name='projection_y_coordinate', long_name='y', var_name='y', units='m', bounds=None, attributes=None, coord_system=coord_system)
        variable_cube.add_aux_coord(projection_y_coord,(1))



    elif (variable_dict[variable]==2):
        x_coord=coords.DimCoord(np.arange(len(coord_dict['xtn0'+domain])), long_name='x', units='1', bounds=None, attributes=None, coord_system=coord_system)
        variable_cube.add_dim_coord(x_coord,1)
        y_coord=coords.DimCoord(np.arange(len(coord_dict['ytn0'+domain])), long_name='y', units='1', bounds=None, attributes=None, coord_system=coord_system)
        variable_cube.add_dim_coord(y_coord,0)
        projection_x_coord=coords.DimCoord(coord_dict['xtn0'+domain], standard_name='projection_x_coordinate', long_name='x', var_name='x', units='m', bounds=None, attributes=None, coord_system=coord_system)
        variable_cube.add_aux_coord(projection_x_coord,(1))
        projection_y_coord=coords.DimCoord(coord_dict['ytn0'+domain], standard_name='projection_y_coordinate', long_name='y', var_name='y', units='m', bounds=None, attributes=None, coord_system=coord_system)
        variable_cube.add_aux_coord(projection_y_coord,(0))
        time_coord=make_time_coord(coord_dict)
        variable_cube.add_aux_coord(time_coord)
    return variable_cube
def NAME_to_cube(filenames, callback):
    """Returns a generator of cubes given a list of filenames and a callback."""

    for filename in filenames:
        header, column_headings, data_arrays = load_NAME_III(filename)

        for i, data_array in enumerate(data_arrays):
            # turn the dictionary of column headers with a list of header information for each field into a dictionary of
            # headers for just this field. Ignore the first 4 columns of grid position (data was located with the data array).
            field_headings = dict([(k, v[i + 4])
                                   for k, v in column_headings.iteritems()])

            # make an cube
            cube = iris.cube.Cube(data_array)

            # define the name and unit
            name = ('%s %s' % (field_headings['species'],
                               field_headings['quantity'])).upper().replace(
                                   ' ', '_')
            cube.rename(name)
            # Some units are badly encoded in the file, fix this by putting a space in between. (if gs is not found, then the
            # string will be returned unchanged)
            cube.units = field_headings['unit'].replace('gs', 'g s')

            # define and add the singular coordinates of the field (flight level, time etc.)
            cube.add_aux_coord(
                icoords.AuxCoord(field_headings['z_level'],
                                 long_name='flight_level',
                                 units='1'))

            # define the time unit and use it to serialise the datetime for the time coordinate
            time_unit = iris.unit.Unit('hours since epoch',
                                       calendar=iris.unit.CALENDAR_GREGORIAN)
            time_coord = icoords.AuxCoord(time_unit.date2num(
                field_headings['time']),
                                          standard_name='time',
                                          units=time_unit)
            cube.add_aux_coord(time_coord)

            # build a coordinate system which can be referenced by latitude and longitude coordinates
            lat_lon_coord_system = icoord_systems.LatLonCS(
                icoord_systems.SpheroidDatum("spherical",
                                             6371229.0,
                                             flattening=0.0,
                                             units='m'),
                icoord_systems.PrimeMeridian(label="Greenwich", value=0.0),
                n_pole=icoord_systems.GeoPosition(90, 0),
                reference_longitude=0.0)

            # build regular latitude and longitude coordinates which have bounds
            start = header['X grid origin'] + header['X grid resolution']
            step = header['X grid resolution']
            count = header['X grid size']
            pts = start + numpy.arange(count, dtype=numpy.float32) * step
            lon_coord = icoords.DimCoord(pts,
                                         standard_name='longitude',
                                         units='degrees',
                                         coord_system=lat_lon_coord_system)
            lon_coord.guess_bounds()

            start = header['Y grid origin'] + header['Y grid resolution']
            step = header['Y grid resolution']
            count = header['Y grid size']
            pts = start + numpy.arange(count, dtype=numpy.float32) * step
            lat_coord = icoords.DimCoord(pts,
                                         standard_name='latitude',
                                         units='degrees',
                                         coord_system=lat_lon_coord_system)
            lat_coord.guess_bounds()

            # add the latitude and longitude coordinates to the cube, with mappings to data dimensions
            cube.add_dim_coord(lat_coord, 0)
            cube.add_dim_coord(lon_coord, 1)

            # implement standard iris callback capability. Although callbacks are not used in this example, the standard
            # mechanism for a custom loader to implement a callback is shown:
            cube = iris.io.run_callback(callback, cube,
                                        [header, field_headings, data_array],
                                        filename)

            # yield the cube created (the loop will continue when the next() element is requested)
            yield cube
예제 #10
0
파일: stock.py 프로젝트: mcmweb80/iris
def realistic_4d():
    """
    Returns a realistic 4d cube.

    >>> print repr(realistic_4d())
    <iris 'Cube' of air_potential_temperature (time: 6; model_level_number: 70; grid_latitude: 100; grid_longitude: 100)>

    """
    # the stock arrays were created in Iris 0.8 with:
    #    >>> fname = iris.sample_data_path('PP', 'COLPEX', 'theta_and_orog_subset.pp')
    #    >>> theta = iris.load_cube(fname, 'air_potential_temperature')
    #    >>> for coord in theta.coords():
    #    ...  print coord.name, coord.has_points(), coord.has_bounds(), coord.units
    #    ...
    #    grid_latitude True True degrees
    #    grid_longitude True True degrees
    #    level_height True True m
    #    model_level True False 1
    #    sigma True True 1
    #    time True False hours since 1970-01-01 00:00:00
    #    source True False no_unit
    #    forecast_period True False hours
    #    >>> arrays = []
    #    >>> for coord in theta.coords():
    #    ...  if coord.has_points(): arrays.append(coord.points)
    #    ...  if coord.has_bounds(): arrays.append(coord.bounds)
    #    >>> arrays.append(theta.data)
    #    >>> arrays.append(theta.coord('sigma').coord_system.orography.data)
    #    >>> np.savez('stock_arrays.npz', *arrays)

    data_path = os.path.join(os.path.dirname(__file__), 'stock_arrays.npz')
    r = np.load(data_path)
    # sort the arrays based on the order they were originally given. The names given are of the form 'arr_1' or 'arr_10'
    _, arrays = zip(*sorted(r.iteritems(), key=lambda item: int(item[0][4:])))

    lat_pts, lat_bnds, lon_pts, lon_bnds, level_height_pts, \
    level_height_bnds, model_level_pts, sigma_pts, sigma_bnds, time_pts, \
    _source_pts, forecast_period_pts, data, orography = arrays

    ll_cs = RotatedGeogCS(37.5, 177.5, ellipsoid=GeogCS(6371229.0))

    lat = icoords.DimCoord(lat_pts,
                           standard_name='grid_latitude',
                           units='degrees',
                           bounds=lat_bnds,
                           coord_system=ll_cs)
    lon = icoords.DimCoord(lon_pts,
                           standard_name='grid_longitude',
                           units='degrees',
                           bounds=lon_bnds,
                           coord_system=ll_cs)
    level_height = icoords.DimCoord(level_height_pts,
                                    long_name='level_height',
                                    units='m',
                                    bounds=level_height_bnds,
                                    attributes={'positive': 'up'})
    model_level = icoords.DimCoord(model_level_pts,
                                   standard_name='model_level_number',
                                   units='1',
                                   attributes={'positive': 'up'})
    sigma = icoords.AuxCoord(sigma_pts,
                             long_name='sigma',
                             units='1',
                             bounds=sigma_bnds)
    orography = icoords.AuxCoord(orography,
                                 standard_name='surface_altitude',
                                 units='m')
    time = icoords.DimCoord(time_pts,
                            standard_name='time',
                            units='hours since 1970-01-01 00:00:00')
    forecast_period = icoords.DimCoord(forecast_period_pts,
                                       standard_name='forecast_period',
                                       units='hours')

    hybrid_height = iris.aux_factory.HybridHeightFactory(
        level_height, sigma, orography)

    cube = iris.cube.Cube(data,
                          standard_name='air_potential_temperature',
                          units='K',
                          dim_coords_and_dims=[(time, 0), (model_level, 1),
                                               (lat, 2), (lon, 3)],
                          aux_coords_and_dims=[(orography, (2, 3)),
                                               (level_height, 1), (sigma, 1),
                                               (forecast_period, None)],
                          attributes={'source': 'Iris test case'},
                          aux_factories=[hybrid_height])
    return cube
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jul  7 13:16:46 2017

@author: gy11s2s
"""
import iris
import iris.coords as icoords
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

level_number_coord = icoords.DimCoord(range(1, 86),
                                      standard_name='model_level_number')
model_height = np.loadtxt(
    '/nfs/see-fs-01_users/gy11s2s/Python/Layers_over_time_analysis/Model/model_height_levels.txt',
    delimiter=',')
#hybrid_ht = np.array([20, 53.33334, 100, 160, 233.3333, 320, 420, 533.3334, 659.9999, 799.9999, 953.3337, 1120, 1300, 1493.333, 1700, 1920, 2153.333, 2400, 2659.999, 2933.333, 3220, 3520, 3833.333, 4160, 4500, 4853.333, 5220, 5600, 5993.333, 6400, 6820, 7253.333, 7700, 8160.001, 8633.34, 9120.007, 9620.02, 10133.37, 10660.08, 11200.16, 11753.64, 12320.55, 12900.93, 13494.88, 14102.48, 14723.88, 15359.24, 16008.82, 16672.9, 17351.9, 18046.29, 18756.7, 19483.89, 20228.78, 20992.53, 21776.51, 22582.39, 23412.16, 24268.18, 25153.22, 26070.59, 27024.11, 28018.26, 29058.23, 30150.02, 31300.54, 32517.71, 33810.59, 35189.52, 36666.24, 38254.03, 39967.93, 41824.85, 43843.83, 46046.21, 48455.83, 51099.35, 54006.43,57210.02,60746.7,64656.96,68985.52,73781.77,79100.02,85000])

MLO_data = iris.load_cube(
    '/nfs/see-fs-01_users/gy11s2s/Python/Layers_over_time_analysis/model_extinction_sites/Extinction_550nm_site_10.nc'
)

x = np.array(range(0, 3600))  #TIME FOR WHOLE RANGE OF MODEL DATA

# Setting time to 3600(240(10 days x 3 x 8 points/day) x 15 (number of months Dec1990-Feb1992))/120 = 30
# 1-30 = Dec1990, 31-60 = Jan1991 etc...
time = (x / 240)  # Each month has an index e.g. 0 = Dec1990
months = [
    'Dec 1990', 'Jan 1991', 'Feb 1991', 'Mar 1991', 'Apr 1991', 'May 1991',
예제 #12
0
파일: __init__.py 프로젝트: wilbertcs/iris
def realistic_4d():
    """
    Returns a realistic 4d cube.

    >>> print(repr(realistic_4d()))
    <iris 'Cube' of air_potential_temperature (time: 6; model_level_number: 70;
    grid_latitude: 100; grid_longitude: 100)>

    """
    data_path = tests.get_data_path(("stock", "stock_arrays.npz"))
    if not os.path.isfile(data_path):
        raise IOError("Test data is not available at {}.".format(data_path))
    r = np.load(data_path)
    # sort the arrays based on the order they were originally given.
    # The names given are of the form 'arr_1' or 'arr_10'
    _, arrays = zip(*sorted(r.items(), key=lambda item: int(item[0][4:])))

    (
        lat_pts,
        lat_bnds,
        lon_pts,
        lon_bnds,
        level_height_pts,
        level_height_bnds,
        model_level_pts,
        sigma_pts,
        sigma_bnds,
        time_pts,
        _source_pts,
        forecast_period_pts,
        data,
        orography,
    ) = arrays

    ll_cs = RotatedGeogCS(37.5, 177.5, ellipsoid=GeogCS(6371229.0))

    lat = icoords.DimCoord(
        lat_pts,
        standard_name="grid_latitude",
        units="degrees",
        bounds=lat_bnds,
        coord_system=ll_cs,
    )
    lon = icoords.DimCoord(
        lon_pts,
        standard_name="grid_longitude",
        units="degrees",
        bounds=lon_bnds,
        coord_system=ll_cs,
    )
    level_height = icoords.DimCoord(
        level_height_pts,
        long_name="level_height",
        units="m",
        bounds=level_height_bnds,
        attributes={"positive": "up"},
    )
    model_level = icoords.DimCoord(
        model_level_pts,
        standard_name="model_level_number",
        units="1",
        attributes={"positive": "up"},
    )
    sigma = icoords.AuxCoord(sigma_pts,
                             long_name="sigma",
                             units="1",
                             bounds=sigma_bnds)
    orography = icoords.AuxCoord(orography,
                                 standard_name="surface_altitude",
                                 units="m")
    time = icoords.DimCoord(time_pts,
                            standard_name="time",
                            units="hours since 1970-01-01 00:00:00")
    forecast_period = icoords.DimCoord(forecast_period_pts,
                                       standard_name="forecast_period",
                                       units="hours")

    hybrid_height = iris.aux_factory.HybridHeightFactory(
        level_height, sigma, orography)

    cube = iris.cube.Cube(
        data,
        standard_name="air_potential_temperature",
        units="K",
        dim_coords_and_dims=[(time, 0), (model_level, 1), (lat, 2), (lon, 3)],
        aux_coords_and_dims=[
            (orography, (2, 3)),
            (level_height, 1),
            (sigma, 1),
            (forecast_period, None),
        ],
        attributes={"source": "Iris test case"},
        aux_factories=[hybrid_height],
    )
    return cube
예제 #13
0
def NAME_to_cube(filenames, callback):
    """
    Returns a generator of cubes given a list of filenames and a callback.
    """

    for filename in filenames:
        header, column_headings, data_arrays = load_NAME_III(filename)

        for i, data_array in enumerate(data_arrays):
            # turn the dictionary of column headers with a list of header
            # information for each field into a dictionary of headers for just
            # this field. Ignore the first 4 columns of grid position (data was
            # located with the data array).
            field_headings = dict(
                (k, v[i + 4]) for k, v in column_headings.items())

            # make an cube
            cube = iris.cube.Cube(data_array)

            # define the name and unit
            name = "%s %s" % (
                field_headings["species"],
                field_headings["quantity"],
            )
            name = name.upper().replace(" ", "_")
            cube.rename(name)
            # Some units are badly encoded in the file, fix this by putting a
            # space in between. (if gs is not found, then the string will be
            # returned unchanged)
            cube.units = field_headings["unit"].replace("gs", "g s")

            # define and add the singular coordinates of the field (flight
            # level, time etc.)
            cube.add_aux_coord(
                icoords.AuxCoord(
                    field_headings["z_level"],
                    long_name="flight_level",
                    units="1",
                ))

            # define the time unit and use it to serialise the datetime for the
            # time coordinate
            time_unit = Unit("hours since epoch", calendar=CALENDAR_GREGORIAN)
            time_coord = icoords.AuxCoord(
                time_unit.date2num(field_headings["time"]),
                standard_name="time",
                units=time_unit,
            )
            cube.add_aux_coord(time_coord)

            # build a coordinate system which can be referenced by latitude and
            # longitude coordinates
            lat_lon_coord_system = icoord_systems.GeogCS(6371229)

            # build regular latitude and longitude coordinates which have
            # bounds
            start = header["X grid origin"] + header["X grid resolution"]
            step = header["X grid resolution"]
            count = header["X grid size"]
            pts = start + np.arange(count, dtype=np.float32) * step
            lon_coord = icoords.DimCoord(
                pts,
                standard_name="longitude",
                units="degrees",
                coord_system=lat_lon_coord_system,
            )
            lon_coord.guess_bounds()

            start = header["Y grid origin"] + header["Y grid resolution"]
            step = header["Y grid resolution"]
            count = header["Y grid size"]
            pts = start + np.arange(count, dtype=np.float32) * step
            lat_coord = icoords.DimCoord(
                pts,
                standard_name="latitude",
                units="degrees",
                coord_system=lat_lon_coord_system,
            )
            lat_coord.guess_bounds()

            # add the latitude and longitude coordinates to the cube, with
            # mappings to data dimensions
            cube.add_dim_coord(lat_coord, 0)
            cube.add_dim_coord(lon_coord, 1)

            # implement standard iris callback capability. Although callbacks
            # are not used in this example, the standard mechanism for a custom
            # loader to implement a callback is shown:
            cube = iris.io.run_callback(callback, cube,
                                        [header, field_headings, data_array],
                                        filename)

            # yield the cube created (the loop will continue when the next()
            # element is requested)
            yield cube
예제 #14
0
def realistic_4d():
    """
    Returns a realistic 4d cube.

    >>> print(repr(realistic_4d()))
    <iris 'Cube' of air_potential_temperature (time: 6; model_level_number: 70;
    grid_latitude: 100; grid_longitude: 100)>

    """
    data_path = tests.get_data_path(('stock', 'stock_arrays.npz'))
    if not os.path.isfile(data_path):
        raise IOError('Test data is not available at {}.'.format(data_path))
    r = np.load(data_path)
    # sort the arrays based on the order they were originally given.
    # The names given are of the form 'arr_1' or 'arr_10'
    _, arrays = zip(*sorted(r.items(), key=lambda item: int(item[0][4:])))

    lat_pts, lat_bnds, lon_pts, lon_bnds, level_height_pts, \
        level_height_bnds, model_level_pts, sigma_pts, sigma_bnds, time_pts, \
        _source_pts, forecast_period_pts, data, orography = arrays

    ll_cs = RotatedGeogCS(37.5, 177.5, ellipsoid=GeogCS(6371229.0))

    lat = icoords.DimCoord(lat_pts,
                           standard_name='grid_latitude',
                           units='degrees',
                           bounds=lat_bnds,
                           coord_system=ll_cs)
    lon = icoords.DimCoord(lon_pts,
                           standard_name='grid_longitude',
                           units='degrees',
                           bounds=lon_bnds,
                           coord_system=ll_cs)
    level_height = icoords.DimCoord(level_height_pts,
                                    long_name='level_height',
                                    units='m',
                                    bounds=level_height_bnds,
                                    attributes={'positive': 'up'})
    model_level = icoords.DimCoord(model_level_pts,
                                   standard_name='model_level_number',
                                   units='1',
                                   attributes={'positive': 'up'})
    sigma = icoords.AuxCoord(sigma_pts,
                             long_name='sigma',
                             units='1',
                             bounds=sigma_bnds)
    orography = icoords.AuxCoord(orography,
                                 standard_name='surface_altitude',
                                 units='m')
    time = icoords.DimCoord(time_pts,
                            standard_name='time',
                            units='hours since 1970-01-01 00:00:00')
    forecast_period = icoords.DimCoord(forecast_period_pts,
                                       standard_name='forecast_period',
                                       units='hours')

    hybrid_height = iris.aux_factory.HybridHeightFactory(
        level_height, sigma, orography)

    cube = iris.cube.Cube(data,
                          standard_name='air_potential_temperature',
                          units='K',
                          dim_coords_and_dims=[(time, 0), (model_level, 1),
                                               (lat, 2), (lon, 3)],
                          aux_coords_and_dims=[(orography, (2, 3)),
                                               (level_height, 1), (sigma, 1),
                                               (forecast_period, None)],
                          attributes={'source': 'Iris test case'},
                          aux_factories=[hybrid_height])
    return cube
예제 #15
0
 def test_non_cube_coordinate(self):
     cube = self.cube[0, :, :, 0]
     pts = -100 + np.arange(cube.shape[1]) * 13
     x = coords.DimCoord(pts, standard_name='model_level_number',
                         attributes={'positive': 'up'})
     self.draw('contourf', cube, coords=['grid_latitude', x])
예제 #16
0
 def create(self):
     return coords.DimCoord(**self.create_kwargs)