Using Iris to access data from COAWST (curvilinear grid ROMS model output)


In [1]:
from IPython.core.display import HTML
HTML('<iframe src=http://scitools.org.uk/iris/ width=800 height=350></iframe>')


Out[1]:

In [2]:
import numpy
import matplotlib.pyplot as plt
import datetime as dt

import iris
import iris.quickplot as qplt
import cartopy.crs as ccrs

In [3]:
def time_near(cube,start):
    timevar=cube.coord('time')
    itime = timevar.nearest_neighbour_index(timevar.units.date2num(start))
    return timevar.points[itime]

In [15]:
# DAP URL: USGS COAWST model
# cubes = iris.load('http://geoport.whoi.edu/thredds/dodsC/fmrc/NCEP/ww3/cfsr/4m/best')
#cubes = iris.load('http://geoport.whoi.edu/thredds/dodsC/coawst_4/use/fmrc/coawst_4_use_best.ncd');
temp = iris.load('http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc', 'potential temperature')[0]

In [16]:
print temp


potential temperature / (Celsius)   (*ANONYMOUS*: 21538; S-coordinate at RHO-points: 30; *ANONYMOUS*: 191; *ANONYMOUS*: 671)
     Dimension coordinates:
          S-coordinate at RHO-points            -                                  x                -                 -
     Auxiliary coordinates:
          time since initialization             x                                  -                -                 -
          latitude                              -                                  -                x                 x
          longitude                             -                                  -                x                 x
     Attributes:
          Author: pyroms.gridgen
          CPP_options: TXLA, ANA_BSFLUX, ANA_BTFLUX, ASSUMED_SHAPE, BULK_FLUXES, CURVGRID, DIFF_GRID,...
          Conventions: CF-1.4
          Created: 2009-12-10T14:26:12.202390
          Description: ROMS grid
          NCO: 4.0.8
          ana_file: /scratch/zhangxq/projects/txla_nesting6/Functionals/ana_btflux.h, /scratch/zhangxq/projects/txla_nesting6/Functionals/ana_hmixcoef.h,...
          bry_file: txla_bry_2009_new.nc
          clm_file: txla_clm_2009_new.nc
          code_dir: /scratch/zhangxq/ROMS
          compiler_command: /g/software/openmpi/1.4.3/intel/bin/mpif90
          compiler_flags: -heap-arrays -fp-model precise -assume 2underscores -convert big_endian...
          compiler_system: ifort
          cpu: x86_64
          field: temperature, scalar, series
          file: ocean_his_0133.nc
          format: netCDF-3 classic file
          frc_file_01: txla_blk_narr_2009.nc
          frc_file_02: TXLA_river_4dyes_2011.nc
          frc_file_03: txla_flx_frc_9911.nc
          grd_file: txla_grd_v4_new.nc
          header_dir: /scratch/zhangxq/projects/txla_nesting6
          header_file: txla.h
          his_base: ocean_his
          history: ROMS/TOMS, Version 3.4, Wednesday - November 30, 2011 -  3:11:47 PM
          ini_file: ocean_rst.nc
          os: Linux
          rst_file: ocean_rst.nc
          script_file: External/ocean_txla.in
          svn_rev: exported
          svn_url: https://www.myroms.org/svn/src/trunk
          tiling: 016x032
          time: ocean_time
          title: Texas and Louisiana Shelf case (Nesting)
          type: ROMS/TOMS history file

In [7]:
# Let's do this above instead..  -rdh.
#temp=cubes[0]
#temp=cubes[32]

In [17]:
#print temp

In [10]:
# slice by indices
# use contraints to select geographic subset and nearest time
mytime=dt.datetime(2009,3,1,12)  #specified time...
#mytime=dt.datetime.utcnow()      # .... or now
slice=temp.extract(iris.Constraint(time=time_near(temp,mytime)))
slice=slice[-1,:,:]  # surface
print slice


---------------------------------------------------------------------------
CoordinateNotFoundError                   Traceback (most recent call last)
<ipython-input-10-c9c89c29abab> in <module>()
      3 mytime=dt.datetime(2009,3,1,12)  #specified time...
      4 #mytime=dt.datetime.utcnow()      # .... or now
----> 5 slice=temp.extract(iris.Constraint(time=time_near(temp,mytime)))
      6 slice=slice[-1,:,:]  # surface
      7 print slice

<ipython-input-3-50cebc19dabc> in time_near(cube, start)
      1 def time_near(cube,start):
----> 2     timevar=cube.coord('time')
      3     itime = timevar.nearest_neighbour_index(timevar.units.date2num(start))
      4     return timevar.points[itime]

/home/local/python27_epd/lib/python2.7/site-packages/Iris-1.5.0_dev-py2.7.egg/iris/cube.pyc in coord(self, name, standard_name, long_name, var_name, attributes, axis, contains_dimension, dimensions, coord, coord_system, dim_coords)
   1045             msg = 'Expected to find exactly 1 %s coordinate, but found ' \
   1046                   'none.' % bad_name
-> 1047             raise iris.exceptions.CoordinateNotFoundError(msg)
   1048 
   1049         return coords[0]

CoordinateNotFoundError: 'Expected to find exactly 1 time coordinate, but found none.'

In [9]:
def slice_bbox_extract(slice,bbox):
    ''' 
    Extract a subsetted slice inside a lon,lat bounding box
    bbox=[lon_min lon_max lat_min lat_max]
    '''
    data = slice.data
    lons = slice.coord('longitude').points
    lats = slice.coord('latitude').points

    def minmax(v):
        return np.min(v), np.max(v)

    inregion = np.logical_and(np.logical_and(lons > bbox[0], lons < bbox[1]),
                          np.logical_and(lats > bbox[2], lats < bbox[3]))
    # extract the rectangular subarray containing the whole valid region ...
    region_inds = np.where(inregion)
    imin, imax = minmax(region_inds[0])
    jmin, jmax = minmax(region_inds[1])
    subslice = slice[imin:imax+1, jmin:jmax+1]
    return subslice

In [10]:
# bbox to extract
bbox=[ -71.5, -65.0, 39.5, 46.0]
subslice=slice_bbox_extract(slice,bbox)

In [11]:
print subslice


potential temperature / Celsius     (*ANONYMOUS*: 112; *ANONYMOUS*: 171)
     Auxiliary coordinates:
          latitude                              x                 x
          longitude                             x                 x
     Scalar coordinates:
          S-coordinate at RHO-points: -0.03125
          forecast_reference_time: 2013-04-02 13:00:00
          time: 2013-04-03 00:00:00
     Attributes:
          CPP_options: ISABEL, ATM_PRESS, ANA_BPFLUX, ANA_BSFLUX, ANA_BTFLUX, ANA_FSOBC, ANA_M2OBC,...
          Conventions: CF-1.4, _Coordinates
          _ChunkSize: [  1   4 112 299]
          _CoordSysBuilder: ucar.nc2.dataset.conv.CF1Convention
          _DODS_Unlimited_Dimension: ocean_time
          ana_file: ROMS/Functionals/ana_btflux.h, ROMS/Functionals/ana_fsobc.h, ROMS/Functionals/ana_m2obc.h,...
          bry_file: ./forcings3/USE_coawst_bdy.nc
          cdm_data_type: GRID
          clm_file: ./forcings3/USE_coawst_clm.nc
          code_dir: /raid1/barmstrong/Projects/COAWST_4
          compiler_command: /usr/local/mpi/bin/mpif90
          compiler_flags:  -fastsse -Mipa=fast -tp k8-64 -Mfree
          compiler_system: pgi
          cpu: x86_64
          featureType: GRID
          field: temperature, scalar, series
          file: ./Output/coawst_use_his_0001.nc
          format: netCDF-3 classic file
          frc_file_01: ./forcings/cloud_coawst.nc
          frc_file_02: ./forcings/Pair_coawst.nc
          frc_file_03: ./forcings/Qair_coawst.nc
          frc_file_04: ./forcings/rain_coawst.nc
          frc_file_05: ./forcings/swrad_coawst.nc
          frc_file_06: ./forcings/Tair_coawst.nc
          frc_file_07: ./forcings/lwrad_coawst.nc
          frc_file_08: ./forcings/Big_grd2_coawstwind.nc
          frc_file_09: ./grids/tide_forc_USeast_grd16_osu_rev1.nc
          grd_file: ./grids/USeast_grd19.nc
          header_dir: /raid1/barmstrong/Projects/COAWST_4/Projects/coawst
          header_file: coawst.h
          his_base: ./Output/coawst_use_his
          history: ROMS/TOMS, Version 3.4, Friday - March 29, 2013 -  3:36:45 AM ;
FMRC Best...
          ini_file: ./restart/ocean_use_rst.nc
          location: Proto fmrc:coawst_4_use
          os: Linux
          rst_file: ./Output/ocean_use_rst.nc
          script_file: Projects/coawst/ocean_coawst.in
          svn_rev: exported
          svn_url: https://www.myroms.org/svn/omlab/branches/jcwarner
          tiling: 010x004
          time: ocean_time
          title: COAWST
          type: ROMS/TOMS history file

In [12]:
# make the plot
figure(figsize=(12,8))
Z=subslice.data
Zm = ma.masked_where(np.isnan(Z),Z)
ax1 = plt.axes(projection=ccrs.PlateCarree())
ax2=pcolormesh(subslice.coord('longitude').points,subslice.coord('latitude').points,Zm,vmin=0,vmax=20);
dat=slice.coord('time')[0].units.num2date(slice.coord('time')[0].points)
plt.colorbar()
ax1.gridlines(draw_labels=True);
plt.title('Temperature in the Gulf of Maine: %s' % dat)


Out[12]:
<matplotlib.text.Text at 0x49f5710>