Using Iris to access data from US-IOOS models


In [2]:
import datetime as dt
import time

import iris

In [3]:
def time_near(cube,start):
    #    coord_names = [coord.name() for coord in cube.coords()]
    #    timevar = cube.coord(coord_names[0]))
    timevar=cube.coord('time')
    try:
        itime = timevar.nearest_neighbour_index(timevar.units.date2num(start))
    except:
        itime = -1
    return timevar.points[itime]

In [4]:
def var_lev_date(url=None,var=None,mytime=None,lev=0,subsample=1):
    time0= time.time()
    cube = iris.load(url,iris.Constraint(name=var.strip()))[0]
    # flip z if necessary
    z=cube.coord(axis='Z').points
    if abs(z[0])>abs(z[1]):
        lev = -lev-1
    try:
        cube.coord(axis='T').rename('time')
    except:
        pass
    slice = cube.extract(iris.Constraint(time=time_near(cube,mytime)))
    slice = slice[lev,::subsample,::subsample]  
    print 'slice retrieved in %f seconds' % (time.time()-time0)
    return slice

In [5]:
def myplot(slice):
    # make the plot
    figure(figsize=(12,8))
    lat=slice.coord(axis='Y').points
    lon=slice.coord(axis='X').points
    time=slice.coord('time')[0]
    subplot(111,aspect=(1.0/cos(mean(lat)*pi/180.0)))
    pcolormesh(lon,lat,ma.masked_invalid(slice.data));
    colorbar()
    grid()
    try:
        titl=slice.attributes['title']
    except:
        titl=slice.attributes['location']
    date=time.units.num2date(time.points)
    date_str=date[0].strftime('%Y-%m-%d %H:%M:%S %Z')
    plt.title('%s: %s: %s' % (titl,slice.long_name,date_str));

Specify Time


In [6]:
#mytime=dt.datetime(2008,7,28,12)  #specified time...
mytime=dt.datetime.utcnow()      # .... or now

Specify Vertical Level to Plot


In [7]:
# level 0=surface, -1=bottom
lev = 0

Specify some specific DAP URLS


In [8]:
#Rutgers ROMS Espresso latest forecast
url='http://tds.marine.rutgers.edu/thredds/dodsC/roms/espresso/2013_da/his_Best/ESPRESSO_Real-Time_v2_History_Best_Available_best.ncd'
var = 'sea_water_potential_temperature'
slice=var_lev_date(url=url,var=var, mytime=mytime, lev=lev)
myplot(slice)


slice retrieved in 2.818627 seconds
/home/local/python27_epd/lib/python2.7/site-packages/iris/fileformats/_pyke_rules/compiled_krb/fc_rules_cf_fc.py:1216: UserWarning: Gracefully filling 'time' dimension coordinate masked points
  warnings.warn(msg.format(str(cf_coord_var.cf_name)))

In [9]:
# HIOOS
url='http://oos.soest.hawaii.edu/thredds/dodsC/hioos/roms_assim/hiig/ROMS_Hawaii_Regional_Ocean_Model_Assimilation_best.ncd'
var='sea_water_potential_temperature'
slice=var_lev_date(url=url,var=var, mytime=mytime, lev=lev)
myplot(slice)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-c7ce4b3434d7> in <module>()
      2 url='http://oos.soest.hawaii.edu/thredds/dodsC/hioos/roms_assim/hiig/ROMS_Hawaii_Regional_Ocean_Model_Assimilation_best.ncd'
      3 var='sea_water_potential_temperature'
----> 4 slice=var_lev_date(url=url,var=var, mytime=mytime, lev=lev)
      5 myplot(slice)

<ipython-input-4-5b51f58ca9c1> in var_lev_date(url, var, mytime, lev, subsample)
      1 def var_lev_date(url=None,var=None,mytime=None,lev=0,subsample=1):
      2     time0= time.time()
----> 3     cube = iris.load(url,iris.Constraint(name=var.strip()))[0]
      4     # flip z if necessary
      5     z=cube.coord(axis='Z').points

/home/local/python27_epd/lib/python2.7/site-packages/iris/__init__.pyc in load(uris, constraints, callback)
    279 
    280     """
--> 281     return _load_collection(uris, constraints, callback).merged().cubes()
    282 
    283 

/home/local/python27_epd/lib/python2.7/site-packages/iris/cube.pyc in merged(self, unique)
    174         """
    175         return _CubeFilterCollection([pair.merged(unique) for pair in
--> 176                                       self.pairs])
    177 
    178 

/home/local/python27_epd/lib/python2.7/site-packages/iris/cube.pyc in merged(self, unique)
    116 
    117         """
--> 118         return _CubeFilter(self.constraint, self.cubes.merge(unique))
    119 
    120 

/home/local/python27_epd/lib/python2.7/site-packages/iris/cube.pyc in merge(self, unique)
    419         for name in sorted(proto_cubes_by_name):
    420             for proto_cube in proto_cubes_by_name[name]:
--> 421                 merged_cubes.extend(proto_cube.merge(unique=unique))
    422 
    423         return merged_cubes

/home/local/python27_epd/lib/python2.7/site-packages/iris/_merge.pyc in merge(self, unique)
   1183                 stack[nd_index] = data
   1184 
-> 1185             merged_data = biggus.ArrayStack(stack)
   1186             if all_have_data:
   1187                 merged_data = merged_data.masked_array()

/home/local/python27_epd/lib/python2.7/site-packages/biggus/__init__.pyc in __init__(self, stack)
    394             if (array.shape != item_shape or array.dtype != dtype or
    395                     array.fill_value != fill_value):
--> 396                 raise ValueError('invalid sub-array')
    397         self._stack = stack
    398         self._item_shape = item_shape

ValueError: invalid sub-array

In [ ]:
print slice

In [10]:
iris.__version__


Out[10]:
'1.7.0-dev'

In [ ]: