Skip to content

Instantly share code, notes, and snippets.

@cpelley
Created August 29, 2012 13:41
Show Gist options
  • Save cpelley/3512677 to your computer and use it in GitHub Desktop.
Save cpelley/3512677 to your computer and use it in GitHub Desktop.
Regridding a masked cube. The regridding method of a cube from iris
import numpy as np
import iris
def lat_lon_cube(x, mval, latgrid, longrid):
"""
Returns a masked cube with a latitude and longitude suitable for testing.
Args:
* x
Input numpy array for resulting cube data
* mval
masked value in the cubes masked data array
* latgrid
numpy array for latitude grid
* longrid
numpy array for longitude grid
Returns:
Cube with masked data
"""
cube = iris.cube.Cube(np.ma.masked_values(x, mval))
cs =iris.coord_systems.LatLonCS(None, 'pm', iris.coord_systems.GeoPosition(90, 0), 0)
cube.add_dim_coord(iris.coords.DimCoord(points=np.array(latgrid, dtype=np.float32), standard_name='latitude', units='degrees', coord_system=cs), 0)
cube.add_dim_coord(iris.coords.DimCoord(points=np.array(longrid, dtype=np.float32), standard_name='longitude', units='degrees', coord_system=cs), 1)
return cube
#create cube1
x = np.arange(9, dtype=np.float32).reshape((3, 3))
mval = 4
longrid = latgrid = [-1, 0, 1]
cube = lat_lon_cube(x, mval, latgrid, longrid)
#create cube2 on slightly different grid
x = np.zeros(9, dtype=np.float32).reshape((3, 3))
mval = 4
longrid = [-0.5, 0, 0.5]
latgrid = [-0.5, 0, 0.5]
cube2 = lat_lon_cube(x, mval, latgrid, longrid)
#regrid cube1 onto cube2 grid
rcube = cube.regridded(cube2, mode='bilinear')
#print the resulting cube
print rcube.data, type(rcube.data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment