In [1]:
from notebook.services.config import ConfigManager
cm = ConfigManager()
cm.update('livereveal',
          {'theme': 'serif',
           'transition': 'slide',
           'start_slideshow_at': 'selected',
           'width': 1024,
           'height': 768});

In [2]:
import warnings
from IPython.display import HTML


warnings.filterwarnings("ignore")

with open('./custom.css') as f:
    css = f.read()

ids = """<li>
          <a href="https://github.com/ocefpaf">
            <span class="icon github">
              <svg version="1.1" class="github-icon-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
                 viewBox="0 0 16 16" enable-background="new 0 0 16 16" xml:space="preserve">
                <path fill-rule="evenodd" clip-rule="evenodd" fill="#C2C2C2" d="M7.999,0.431c-4.285,0-7.76,3.474-7.76,7.761
                c0,3.428,2.223,6.337,5.307,7.363c0.388,0.071,0.53-0.168,0.53-0.374c0-0.184-0.007-0.672-0.01-1.32
                c-2.159,0.469-2.614-1.04-2.614-1.04c-0.353-0.896-0.862-1.135-0.862-1.135c-0.705-0.481,0.053-0.472,0.053-0.472
                c0.779,0.055,1.189,0.8,1.189,0.8c0.692,1.186,1.816,0.843,2.258,0.645c0.071-0.502,0.271-0.843,0.493-1.037
                C4.86,11.425,3.049,10.76,3.049,7.786c0-0.847,0.302-1.54,0.799-2.082C3.768,5.507,3.501,4.718,3.924,3.65
                c0,0,0.652-0.209,2.134,0.796C6.677,4.273,7.34,4.187,8,4.184c0.659,0.003,1.323,0.089,1.943,0.261
                c1.482-1.004,2.132-0.796,2.132-0.796c0.423,1.068,0.157,1.857,0.077,2.054c0.497,0.542,0.798,1.235,0.798,2.082
                c0,2.981-1.814,3.637-3.543,3.829c0.279,0.24,0.527,0.713,0.527,1.437c0,1.037-0.01,1.874-0.01,2.129
                c0,0.208,0.14,0.449,0.534,0.373c3.081-1.028,5.302-3.935,5.302-7.362C15.76,3.906,12.285,0.431,7.999,0.431z"/>
              </svg>
            </span>
            <span class="username">ocefpaf</span>
          </a>
        </li>
        
        <li>
          <a href="https://twitter.com/ocefpaf">
            <span class="icon twitter">
              <svg version="1.1" class="twitter-icon-svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
                 viewBox="0 0 16 16" enable-background="new 0 0 16 16" xml:space="preserve">
                <path fill="#C2C2C2" d="M15.969,3.058c-0.586,0.26-1.217,0.436-1.878,0.515c0.675-0.405,1.194-1.045,1.438-1.809
                c-0.632,0.375-1.332,0.647-2.076,0.793c-0.596-0.636-1.446-1.033-2.387-1.033c-1.806,0-3.27,1.464-3.27,3.27
                c0,0.256,0.029,0.506,0.085,0.745C5.163,5.404,2.753,4.102,1.14,2.124C0.859,2.607,0.698,3.168,0.698,3.767
                c0,1.134,0.577,2.135,1.455,2.722C1.616,6.472,1.112,6.325,0.671,6.08c0,0.014,0,0.027,0,0.041c0,1.584,1.127,2.906,2.623,3.206
                C3.02,9.402,2.731,9.442,2.433,9.442c-0.211,0-0.416-0.021-0.615-0.059c0.416,1.299,1.624,2.245,3.055,2.271
                c-1.119,0.877-2.529,1.4-4.061,1.4c-0.264,0-0.524-0.015-0.78-0.046c1.447,0.928,3.166,1.469,5.013,1.469
                c6.015,0,9.304-4.983,9.304-9.304c0-0.142-0.003-0.283-0.009-0.423C14.976,4.29,15.531,3.714,15.969,3.058z"/>
              </svg>
            </span>
            <span class="username">ocefpaf</span>
          </a>
        </li>
       <li>
       <a href="mailto:ocefpaf@gmail.com">ocefpaf@gmail.com</a>
       </li>
"""

A tour of the Scientific Oceanographic Python stack


In [3]:
HTML(ids)




Before we begin some FAQ

  • How to install Python?
  • Should I use a distribution?
  • Python 2 or 3?
  • Why we cannot have a single installer like MatlabTM!?

One answer to all questions is to use the Anaconda Python distribution:

url=http://bit.ly/miniconda

wget $url -O miniconda.sh
bash miniconda.sh -b
export PATH=$HOME/miniconda/bin:$PATH
conda update --yes --all
url=http://bit.ly/conda-env

wget $url -O environment.yml
conda env create environment.yml

Reading some data


In [4]:
!head -n 5 ./data/dados_pirata.csv


,datahora,t_1,t_10,t_100,t_120,t_13,t_140,t_180,t_20,t_300,t_40,t_5,t_500,t_60,t_80
0,2005-08-24 12:00:00+00:00,25.19,-99999.0,25.2,24.89,-99999.0,23.79,20.6,25.17,12.46,25.17,-99999.0,6.82,25.19,25.19
1,2005-08-25 12:00:00+00:00,25.19,-99999.0,25.17,24.72,-99999.0,23.61,20.31,25.18,12.27,25.18,-99999.0,6.85,25.21,25.18
2,2005-08-26 12:00:00+00:00,25.26,-99999.0,25.13,24.74,-99999.0,23.63,20.43,25.24,12.36,25.22,-99999.0,6.87,25.2,25.16
3,2005-08-27 12:00:00+00:00,25.23,-99999.0,25.04,24.77,-99999.0,23.74,20.1,25.19,12.23,25.19,-99999.0,6.86,25.14,25.08

We need to skip the header and the date-time columns


In [5]:
import numpy as np

data = np.loadtxt("./data/dados_pirata.csv",
                  skiprows=1,
                  usecols=range(2, 16),
                  delimiter=',')

data[data == -99999.] = np.NaN

data.shape, data.dtype


Out[5]:
((3653, 14), dtype('float64'))

But the depth information was in header!

We need to type that in...


In [6]:
%matplotlib inline
import matplotlib.pyplot as plt

z = [1, 10, 100, 120, 13, 140, 180, 20,
     300, 40,5, 500, 60, 80]

fig, ax = plt.subplots()
# Points because z was not ordered.
ax.plot(data[42, :], z, 'ko')
ax.invert_yaxis()


Pandas: can we do better than NumPy arrays?

http://pandas.pydata.org/

Note that almost everything we did before, and some more, is now done at the loading time


In [7]:
import pandas as pd

df = pd.read_csv('./data/dados_pirata.csv',
                 index_col='datahora',
                 parse_dates=True,
                 na_values=-99999)
df.drop('Unnamed: 0', axis=1, inplace=True)
df.columns = ['{0:0>3}'.format(col.split('_')[1]) for
              col in df.columns]
df.sort(axis=1, inplace=True)

df.head(3)


Out[7]:
001 005 010 013 020 040 060 080 100 120 140 180 300 500
datahora
2005-08-24 12:00:00 25.19 NaN NaN NaN 25.17 25.17 25.19 25.19 25.20 24.89 23.79 20.60 12.46 6.82
2005-08-25 12:00:00 25.19 NaN NaN NaN 25.18 25.18 25.21 25.18 25.17 24.72 23.61 20.31 12.27 6.85
2005-08-26 12:00:00 25.26 NaN NaN NaN 25.24 25.22 25.20 25.16 25.13 24.74 23.63 20.43 12.36 6.87

Pandas behave like masked-arrays, but with some extra convenience functions beyond nan{min,max,mean,etc}


In [8]:
df.dropna(how='all', axis=1, inplace=True)

df.head(3)


Out[8]:
001 020 040 060 080 100 120 140 180 300 500
datahora
2005-08-24 12:00:00 25.19 25.17 25.17 25.19 25.19 25.20 24.89 23.79 20.60 12.46 6.82
2005-08-25 12:00:00 25.19 25.18 25.18 25.21 25.18 25.17 24.72 23.61 20.31 12.27 6.85
2005-08-26 12:00:00 25.26 25.24 25.22 25.20 25.16 25.13 24.74 23.63 20.43 12.36 6.87

Quick way to explore the data


In [9]:
desc = df.describe()
desc


Out[9]:
001 020 040 060 080 100 120 140 180 300 500
count 3206.000000 2949.000000 3408.000000 3408.000000 3161.000000 3407.000000 3405.000000 3405.000000 3405.000000 3405.000000 3405.000000
mean 26.903054 26.856673 26.746086 26.283706 25.486109 24.681382 23.947416 23.076496 20.080417 12.359806 6.675656
std 1.030174 0.999788 0.992836 0.840345 0.523529 0.500878 0.607452 0.755077 1.081181 0.461918 0.266193
min 24.710000 24.820000 24.630000 24.550000 23.950000 22.850000 21.450000 20.110000 17.210000 10.930000 5.620000
25% 26.020000 25.970000 25.880000 25.590000 25.120000 24.350000 23.550000 22.590000 19.260000 12.050000 6.500000
50% 26.940000 26.900000 26.820000 26.210000 25.430000 24.660000 23.920000 23.090000 20.100000 12.370000 6.700000
75% 27.750000 27.720000 27.580000 26.960000 25.800000 24.990000 24.350000 23.620000 20.880000 12.670000 6.840000
max 29.090000 28.840000 28.790000 28.580000 27.080000 26.450000 25.580000 25.180000 23.210000 13.630000 7.790000

High level code! No need for comments to describe what is being computed below:


In [10]:
desc.ix['std'] ** 2


Out[10]:
001    1.061258
020    0.999577
040    0.985722
060    0.706179
080    0.274083
100    0.250879
120    0.368998
140    0.570141
180    1.168953
300    0.213368
500    0.070859
Name: std, dtype: float64

What levels are we plotting?


In [11]:
ax = df[['001', '500']].plot(figsize=(11, 3))


More convenience functions:

  • interpolate

In [12]:
df['001'].interpolate().plot(figsize=(11, 3))
ax = df['001'].plot()


Full control of the interpolation


In [13]:
kw = dict(method='time', limit=20)
df['001'].interpolate(**kw).plot(figsize=(11, 3))
ax = df['001'].plot()


Pandas loves time-series


In [14]:
key = lambda x: x.month

grouped = df.groupby(key)

monthly = grouped.mean()

fig, ax = plt.subplots(figsize=(9, 5))

ax = monthly.plot(ax=ax)


Pandas has a few siblings:

  • geopandas
  • ctd
  • xray

GeoPandas read GeoJSONs, Shapefiles, etc as pandas DataFrames

http://geopandas.org/


In [15]:
import rasterio
import geopandas as gpd

fname = "./data/2013-04-29-Running.geojson"

df = gpd.read_file(fname)
ax = df.plot()


The geometries are essentially shapely objects


In [16]:
shape = df['geometry'][0]

msg = """
Length is {} km.

The center is locate at {!r}.

The track bounds are {}.
""".format
print(msg(shape.length * 111, shape.centroid.xy,
          shape.bounds))


Length is 7.2781139639 km.

The center is locate at (array('d', [-46.724456529983655]), array('d', [-23.55928803359001])).

The track bounds are (-46.73799172975123, -23.564499272033572, -46.71305129304528, -23.551835222169757).

ptyhon-ctd loads ctd, xbt, and many more ocean profilers directly into pandas

https://pypi.python.org/pypi/ctd


In [17]:
from ctd import DataFrame

cast = DataFrame.from_cnv('./data/CTD_001.cnv.gz', compression='gzip')

cast.head()


Out[17]:
scan timeS t090C t190C c0S/m c1S/m sbeox0V par spar ph ... longitude pumps pla sbeox0PS sbeox0Mm/Kg dz/dtM accM flSP xmiss flag
Pressure [dbar]
2.810 1 0.000 24.2158 24.2132 5.527058 5.526362 2.8107 1.000000e-12 11.761 -2.332 ... -47.452167 True 24.221 71.49588 147.595 0.000 0.00 0.11111 96.8657 False
2.846 2 0.042 24.2158 24.2132 5.527065 5.526352 2.8120 1.000000e-12 13.721 -2.336 ... -47.452167 True 24.221 71.53789 147.682 0.878 21.08 0.10867 96.8657 False
2.810 3 0.083 24.2156 24.2131 5.527060 5.526333 2.8120 1.000000e-12 11.761 -2.336 ... -47.452167 True 24.221 71.53759 147.682 -0.878 -42.16 0.10623 96.8657 False
2.744 4 0.125 24.2156 24.2132 5.527091 5.526339 2.8120 1.000000e-12 13.721 -2.336 ... -47.452167 True 24.221 71.53702 147.680 -1.581 -16.87 0.10745 96.8657 False
2.707 5 0.167 24.2158 24.2134 5.527052 5.526343 2.8132 1.000000e-12 13.721 -2.332 ... -47.452167 True 24.221 71.57837 147.766 -0.878 16.87 0.11111 96.9189 False

5 rows × 30 columns

The augmented DataFrame has some extra methods to process CTD data


In [18]:
downcast, upcast = cast['t090C'].split()
fig, ax = downcast.plot(figsize=(3, 7))


xray: netCDF4 + pandas for >2D tables

http://xray.readthedocs.org/en/stable/


In [19]:
import xray

url = ('http://geoport.whoi.edu/thredds/dodsC/clay/usgs/'
       'users/jcwarner/Projects/Sandy/triple_nest/'
       '00_dir_NYB05.ncml')

ds = xray.open_dataset(url)
ds


Out[19]:
<xray.Dataset>
Dimensions:                 (NST: 6, Nbed: 1, eta_psi: 106, eta_rho: 107, eta_u: 107, eta_v: 106, ocean_time: 201, s_rho: 16, s_w: 17, tracer: 8, xi_psi: 344, xi_rho: 345, xi_u: 344, xi_v: 345)
Coordinates:
  * s_rho                   (s_rho) float64 -0.9688 -0.9062 -0.8438 -0.7812 ...
  * s_w                     (s_w) float64 -1.0 -0.9375 -0.875 -0.8125 -0.75 ...
    lon_rho                 (eta_rho, xi_rho) float64 ...
    lat_rho                 (eta_rho, xi_rho) float64 ...
    lon_u                   (eta_u, xi_u) float64 ...
    lat_u                   (eta_u, xi_u) float64 ...
    lon_v                   (eta_v, xi_v) float64 ...
    lat_v                   (eta_v, xi_v) float64 ...
    lon_psi                 (eta_psi, xi_psi) float64 ...
    lat_psi                 (eta_psi, xi_psi) float64 ...
  * ocean_time              (ocean_time) datetime64[ns] 2012-10-25 ...
  * NST                     (NST) int64 0 1 2 3 4 5
  * Nbed                    (Nbed) int64 0
  * eta_psi                 (eta_psi) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ...
  * eta_rho                 (eta_rho) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ...
  * eta_u                   (eta_u) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
  * eta_v                   (eta_v) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
  * tracer                  (tracer) int64 0 1 2 3 4 5 6 7
  * xi_psi                  (xi_psi) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ...
  * xi_rho                  (xi_rho) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ...
  * xi_u                    (xi_u) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
  * xi_v                    (xi_v) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
Data variables:
    ntimes                  int32 ...
    ndtfast                 int32 ...
    dt                      float64 ...
    dtfast                  float64 ...
    dstart                  datetime64[ns] ...
    nHIS                    int32 ...
    ndefHIS                 int32 ...
    nRST                    int32 ...
    Falpha                  float64 ...
    Fbeta                   float64 ...
    Fgamma                  float64 ...
    nl_tnu2                 (tracer) float64 ...
    nl_visc2                float64 ...
    LuvSponge               int32 ...
    LtracerSponge           (tracer) int32 ...
    Akt_bak                 (tracer) float64 ...
    Akv_bak                 float64 ...
    Akk_bak                 float64 ...
    Akp_bak                 float64 ...
    rdrg                    float64 ...
    rdrg2                   float64 ...
    Zob                     float64 ...
    Zos                     float64 ...
    gls_p                   float64 ...
    gls_m                   float64 ...
    gls_n                   float64 ...
    gls_cmu0                float64 ...
    gls_c1                  float64 ...
    gls_c2                  float64 ...
    gls_c3m                 float64 ...
    gls_c3p                 float64 ...
    gls_sigk                float64 ...
    gls_sigp                float64 ...
    gls_Kmin                float64 ...
    gls_Pmin                float64 ...
    Charnok_alpha           float64 ...
    Zos_hsig_alpha          float64 ...
    sz_alpha                float64 ...
    CrgBan_cw               float64 ...
    wec_alpha               float64 ...
    Znudg                   float64 ...
    M2nudg                  float64 ...
    M3nudg                  float64 ...
    Tnudg                   (tracer) float64 ...
    rho0                    float64 ...
    gamma2                  float64 ...
    LuvSrc                  int32 ...
    LwSrc                   int32 ...
    LtracerSrc              (tracer) int32 ...
    LsshCLM                 int32 ...
    Lm2CLM                  int32 ...
    Lm3CLM                  int32 ...
    LtracerCLM              (tracer) int32 ...
    LnudgeM2CLM             int32 ...
    LnudgeM3CLM             int32 ...
    LnudgeTCLM              (tracer) int32 ...
    minlayer_thick          float64 ...
    newlayer_thick          float64 ...
    bedload_coeff           float64 ...
    Sd50                    (NST) float64 ...
    Srho                    (NST) float64 ...
    Csed                    (NST) float64 ...
    Wsed                    (NST) float64 ...
    Erate                   (NST) float64 ...
    tau_ce                  (NST) float64 ...
    tau_cd                  (NST) float64 ...
    poros                   (NST) float64 ...
    spherical               int32 ...
    xl                      float64 ...
    el                      float64 ...
    Vtransform              int32 ...
    Vstretching             int32 ...
    theta_s                 float64 ...
    theta_b                 float64 ...
    Tcline                  float64 ...
    hc                      float64 ...
    Cs_r                    (s_rho) float64 ...
    Cs_w                    (s_w) float64 ...
    h                       (eta_rho, xi_rho) float64 ...
    f                       (eta_rho, xi_rho) float64 ...
    pm                      (eta_rho, xi_rho) float64 ...
    pn                      (eta_rho, xi_rho) float64 ...
    angle                   (eta_rho, xi_rho) float64 ...
    mask_rho                (eta_rho, xi_rho) float64 ...
    mask_u                  (eta_u, xi_u) float64 ...
    mask_v                  (eta_v, xi_v) float64 ...
    mask_psi                (eta_psi, xi_psi) float64 ...
    wetdry_mask_psi         (ocean_time, eta_psi, xi_psi) float32 ...
    wetdry_mask_rho         (ocean_time, eta_rho, xi_rho) float32 ...
    wetdry_mask_u           (ocean_time, eta_u, xi_u) float32 ...
    wetdry_mask_v           (ocean_time, eta_v, xi_v) float32 ...
    zeta                    (ocean_time, eta_rho, xi_rho) float32 ...
    ubar                    (ocean_time, eta_u, xi_u) float64 ...
    vbar                    (ocean_time, eta_v, xi_v) float64 ...
    u                       (ocean_time, s_rho, eta_u, xi_u) float64 ...
    v                       (ocean_time, s_rho, eta_v, xi_v) float64 ...
    w                       (ocean_time, s_w, eta_rho, xi_rho) float64 ...
    temp                    (ocean_time, s_rho, eta_rho, xi_rho) float64 ...
    salt                    (ocean_time, s_rho, eta_rho, xi_rho) float64 ...
    sand_01                 (ocean_time, s_rho, eta_rho, xi_rho) float64 ...
    sand_02                 (ocean_time, s_rho, eta_rho, xi_rho) float64 ...
    sand_03                 (ocean_time, s_rho, eta_rho, xi_rho) float64 ...
    sand_04                 (ocean_time, s_rho, eta_rho, xi_rho) float64 ...
    sand_05                 (ocean_time, s_rho, eta_rho, xi_rho) float64 ...
    sand_06                 (ocean_time, s_rho, eta_rho, xi_rho) float64 ...
    uWave                   (ocean_time, eta_rho, xi_rho) float64 ...
    vWave                   (ocean_time, eta_rho, xi_rho) float64 ...
    bustrc                  (ocean_time, eta_rho, xi_rho) float64 ...
    bvstrc                  (ocean_time, eta_rho, xi_rho) float64 ...
    bustrw                  (ocean_time, eta_rho, xi_rho) float64 ...
    bvstrw                  (ocean_time, eta_rho, xi_rho) float64 ...
    bustrcwmax              (ocean_time, eta_rho, xi_rho) float64 ...
    bvstrcwmax              (ocean_time, eta_rho, xi_rho) float64 ...
    bstrcwmax               (ocean_time, eta_rho, xi_rho) float64 ...
    bedload_Usand_01        (ocean_time, eta_u, xi_u) float64 ...
    bedload_Vsand_01        (ocean_time, eta_v, xi_v) float64 ...
    bedload_Usand_02        (ocean_time, eta_u, xi_u) float64 ...
    bedload_Vsand_02        (ocean_time, eta_v, xi_v) float64 ...
    bedload_Usand_03        (ocean_time, eta_u, xi_u) float64 ...
    bedload_Vsand_03        (ocean_time, eta_v, xi_v) float64 ...
    bedload_Usand_04        (ocean_time, eta_u, xi_u) float64 ...
    bedload_Vsand_04        (ocean_time, eta_v, xi_v) float64 ...
    bedload_Usand_05        (ocean_time, eta_u, xi_u) float64 ...
    bedload_Vsand_05        (ocean_time, eta_v, xi_v) float64 ...
    bedload_Usand_06        (ocean_time, eta_u, xi_u) float64 ...
    bedload_Vsand_06        (ocean_time, eta_v, xi_v) float64 ...
    sandfrac_01             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandfrac_02             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandfrac_03             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandfrac_04             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandfrac_05             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandfrac_06             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandmass_01             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandmass_02             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandmass_03             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandmass_04             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandmass_05             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    sandmass_06             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    bed_thickness           (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    bed_age                 (ocean_time, Nbed, eta_rho, xi_rho) timedelta64[ns] ...
    bed_porosity            (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    bed_biodiff             (ocean_time, Nbed, eta_rho, xi_rho) float64 ...
    grain_diameter          (ocean_time, eta_rho, xi_rho) float64 ...
    grain_density           (ocean_time, eta_rho, xi_rho) float64 ...
    settling_vel            (ocean_time, eta_rho, xi_rho) float64 ...
    erosion_stress          (ocean_time, eta_rho, xi_rho) float64 ...
    ripple_length           (ocean_time, eta_rho, xi_rho) float64 ...
    ripple_height           (ocean_time, eta_rho, xi_rho) float64 ...
    bed_wave_amp            (ocean_time, eta_rho, xi_rho) float64 ...
    Zo_def                  (ocean_time, eta_rho, xi_rho) float64 ...
    Zo_app                  (ocean_time, eta_rho, xi_rho) float64 ...
    active_layer_thickness  (ocean_time, eta_rho, xi_rho) float64 ...
    bed_inund_depth         (ocean_time, eta_rho, xi_rho) float64 ...
    dep_net                 (ocean_time, eta_rho, xi_rho) float64 ...
    u_stokes                (ocean_time, s_rho, eta_u, xi_u) float64 ...
    v_stokes                (ocean_time, s_rho, eta_v, xi_v) float64 ...
    Hwave                   (ocean_time, eta_rho, xi_rho) float64 ...
    Lwave                   (ocean_time, eta_rho, xi_rho) float64 ...
    Lwavep                  (ocean_time, eta_rho, xi_rho) float64 ...
    Dwave                   (ocean_time, eta_rho, xi_rho) float64 ...
    Pwave_top               (ocean_time, eta_rho, xi_rho) float64 ...
    Pwave_bot               (ocean_time, eta_rho, xi_rho) float64 ...
    Uwave_rms               (ocean_time, eta_rho, xi_rho) float64 ...
    grid                    int32 ...
Attributes:
    file: Output/ocean_NYB05_his_0016.nc
    format: netCDF-3 64bit offset file
    Conventions: CF-1.6, SGRID-0.1, ACDD-1.3
    type: ROMS/TOMS history file
    title: USGS-CMG-COAWST Model: Hurricane Sandy, NYB05 700m Nest
    rst_file: Output/ocean_NYB05_rst.nc
    his_base: Output/ocean_NYB05_his
    grd_file: ../grids/NYB_700m_05.nc
    ini_file: Output/ocean_NYB05_his_0009.nc
    frc_file_01: ../forcings/roms_namnarr_2030Oct2012.nc, ../forcings/roms_namnarr_30Oct10Nov2012.nc
    clm_file_01: ../forcings/merged_coawst_clm_10Sep_29Dec2012.nc
    script_file: 
    NLM_LBC: 
EDGE:         WEST   SOUTH  EAST   NORTH  
zeta:         Nes    Nes    Nes    Nes    
ubar:         Nes    Nes    Nes    Nes    
vbar:         Nes    Nes    Nes    Nes    
u:            Nes    Nes    Nes    Nes    
v:            Nes    Nes    Nes    Nes    
temp:         Nes    Nes    Nes    Nes    
salt:         Nes    Nes    Nes    Nes    
sand_01:      Nes    Nes    Nes    Nes    
sand_02:      Nes    Nes    Nes    Nes    
sand_03:      Nes    Nes    Nes    Nes    
sand_04:      Nes    Ne...
    svn_url: https:://myroms.org/svn/src
    svn_rev: exported
    code_dir: /raid3/jcwarner/Projects/Sandy/sim6
    header_dir: /raid3/jcwarner/Projects/Sandy/sim6/Projects/FireIsland
    header_file: fireisland.h
    os: Linux
    cpu: x86_64
    compiler_system: pgi
    compiler_command: /usr/local/mpi/bin/mpif90
    compiler_flags:  -fastsse -Mipa=fast -tp k8-64 -Mfree
    tiling: 008x005
    history: ROMS/TOMS, Version 3.7, Tuesday - June 2, 2015 - 10:15:23 PM
    ana_file: ROMS/Functionals/ana_btflux.h, ROMS/Functionals/ana_fsobc.h, ROMS/Functionals/ana_m2obc.h, ROMS/Functionals/ana_nudgcoef.h, ROMS/Functionals/ana_srflux.h, ROMS/Functionals/ana_stflux.h
    CPP_options: FIREISLAND, ANA_BPFLUX, ANA_BSFLUX, ANA_BTFLUX, ANA_FSOBC, ANA_M2OBC, ANA_NUDGCOEF, ANA_SPFLUX, ANA_SRFLUX, ASSUMED_SHAPE, ATM_PRESS, BEDLOAD_SOULSBY, BULK_FLUXES, CHARNOK, CRAIG_BANNER, COARE_TAYLOR_YELLAND, CURVGRID, DJ_GRADPS, DOUBLE_PRECISION, EMINUSP, GLS_MIXING, KANTHA_CLAYSON, MASKING, MCT_LIB, MIX_GEO_TS, MIX_S_UV, MPI, WEC_VF, WDISS_WAVEMOD, NESTING, NONLINEAR, NONLIN_EOS, NO_LBC_ATT, N2S2_HORAVG, !ONE_WAY, POWER_LAW, PROFILE, K_GSCHEME, !RST_SINGLE, SALINITY, SEDIMENT, SUSPLOAD, NON...
    cdm_data_type: Grid
    publisher_email: jcwarner@usgs.gov
    publisher_url: http://woodshole.er.usgs.gov/staffpages/jwarner/
    publisher_name: John Warner
    license: The data may be used and redistributed for free but is not intended for legal use, since it may contain inaccuracies. Neither the data Contributor, nor the United States Government, nor any of their employees or contractors, makes any warranty, express or implied, including warranties of merchantability and fitness for a particular purpose, or assumes any legal liability for the accuracy, completeness, or usefulness, of this information.
    creator_email: jcwarner@usgs.gov
    creator_url: http://woodshole.er.usgs.gov/staffpages/jwarner/
    creator_name: John Warner
    summary: Simulation of hydrodynamics, waves, bottom stress and sediment transport during Hurricane Sandy. These results are from the 700m finest resolutionnest of a three-level nested simulation.
    project: CMG_Portal,Sandy_Portal
    references: http://woodshole.er.usgs.gov/operations/modeling/COAWST/,doi:10.1016/j.cageo.2008.02.012
    id: USGS_COAWST_Sandy_NYB05_sim6
    naming_authority: gov.usgs.cmg

Slice the variables using the var name (like netCDF4)


In [20]:
temp = ds['temp']
temp


Out[20]:
<xray.DataArray 'temp' (ocean_time: 201, s_rho: 16, eta_rho: 107, xi_rho: 345)>
[118718640 values with dtype=float64]
Coordinates:
    lon_rho     (eta_rho, xi_rho) float64 ...
    lat_rho     (eta_rho, xi_rho) float64 ...
  * ocean_time  (ocean_time) datetime64[ns] 2012-10-25 2012-10-25T01:00:00 ...
  * xi_rho      (xi_rho) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
  * s_rho       (s_rho) float64 -0.9688 -0.9062 -0.8438 -0.7812 -0.7188 ...
  * eta_rho     (eta_rho) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
Attributes:
    long_name: potential temperature
    units: Celsius
    time: ocean_time
    field: temperature, scalar, series
    standard_name: sea_water_potential_temperature
    grid: grid
    content_coverage_type: modelResult
    location: face

Use high-level dates slice (like pandas)


In [21]:
temp.sel(ocean_time='2012-10-25')


Out[21]:
<xray.DataArray 'temp' (ocean_time: 24, s_rho: 16, eta_rho: 107, xi_rho: 345)>
[14175360 values with dtype=float64]
Coordinates:
    lon_rho     (eta_rho, xi_rho) float64 ...
    lat_rho     (eta_rho, xi_rho) float64 ...
  * ocean_time  (ocean_time) datetime64[ns] 2012-10-25 2012-10-25T01:00:00 ...
  * xi_rho      (xi_rho) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
  * s_rho       (s_rho) float64 -0.9688 -0.9062 -0.8438 -0.7812 -0.7188 ...
  * eta_rho     (eta_rho) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
Attributes:
    long_name: potential temperature
    units: Celsius
    time: ocean_time
    field: temperature, scalar, series
    standard_name: sea_water_potential_temperature
    grid: grid
    content_coverage_type: modelResult
    location: face

All pandas time-series goodies are present

temp.resample('1M', 'ocean_time')

You can even slice using integers and named the axis


In [22]:
t = temp.isel(s_rho=-1, ocean_time=0)

cs = t.plot()



In [23]:
import dask
from dask.async import get_sync
dask.set_options(get=get_sync)


Out[23]:
<dask.context.set_options at 0x7f53c6160410>

The following lines do not download the data


In [24]:
from netCDF4 import Dataset

nc = Dataset(url)

t = nc['temp']
s = nc['salt']

t.shape, s.shape


Out[24]:
((201, 16, 107, 345), (201, 16, 107, 345))

By making the netCDF4 variable a dask variable we can start computing stuff without loading the data! Note


In [25]:
import dask.array as da

chunks = (1, 16, 107, 345)

t = da.from_array(t, chunks=chunks)
s = da.from_array(s, chunks=chunks)

t


Out[25]:
dask.array<from-ar..., shape=(201, 16, 107, 345), dtype=float32, chunksize=(1, 16, 107, 345)>

Note that the result is a dask element wise object


In [26]:
(s + t) * 2


Out[26]:
dask.array<elemwis..., shape=(201, 16, 107, 345), dtype=float32, chunksize=(1, 16, 107, 345)>

You need to manually trigger the computations to load the data. Note that some operations, like plotting, will load the data automatically:


In [27]:
import gsw
import seawater as sw
import numpy.ma as ma

sigma0 = gsw.sigma0(s[-1, :, :, :], t[-1, :, :, :])
cs = plt.pcolormesh(ma.masked_equal(sigma0, -1000))


The first python library to actually solve the dateline problem


In [28]:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
projection = ccrs.PlateCarree()
ax = plt.axes(projection=projection)
ax.coastlines(); ax.set_global()

kw = dict(lw=4, color='g', transform=ccrs.Geodetic())
l0 = plt.plot([-100, 50], [25, 25], label='GD1', **kw)
l1 = plt.plot([-38, 147], [-13, -42], label='GD2', **kw)

kw = dict(linewidth=4, color='b', transform=projection)
l2 = plt.plot([-100, 50], [25, 25], label='PC1', **kw)
l3 = plt.plot([-38, 147], [-13, -42], label='PC2', **kw)

leg = ax.legend(loc=(1.05, 0.5))


When creating a lot of maps it is convenient to wrap them in a plotting function


In [29]:
from oceans import cm
import matplotlib.pyplot as plt

import cartopy.crs as ccrs
from cartopy.mpl.gridliner import (LONGITUDE_FORMATTER,
                                   LATITUDE_FORMATTER)

def make_map(projection=ccrs.PlateCarree()):
    subplot_kw = dict(projection=projection)
    fig, ax = plt.subplots(figsize=(9, 13),
                           subplot_kw=subplot_kw)
    gl = ax.gridlines(draw_labels=True)
    gl.xlabels_top = gl.ylabels_right = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    return fig, ax

In [30]:
lon = nc['lon_rho'][:]
lat = nc['lat_rho'][:]

fig, ax = make_map()
ax.set_extent([lon.min(), lon.max(), lat.min(), lat.max()])
ax.coastlines('10m')
s0 = ma.masked_equal(sigma0, -1000)
cs = ax.pcolormesh(lon, lat, s0, cmap=cm.avhrr)
cbar = fig.colorbar(cs, shrink=0.45, extend='both')


Iris is an interpretation of the CF-Conventions. The main object is the cube:


In [31]:
import iris

cubes = iris.load_raw(url)
print(cubes)


0: sediment concentration used in uniform initial conditions / (kilogram meter-3) (-- : 6)
1: sediment surface layer erosing rate / (kilogram meter-2 second-1) (-- : 6)
2: maximum wind and current, bottom v-wave stress / (newton meter-2) (time: 201; -- : 107; -- : 345)
3: erosion or deposition / (meter)     (time: 201; -- : 107; -- : 345)
4: sediment critical shear for deposition / (Newton meter-2) (-- : 6)
5: sediment critical shear for erosion / (Newton meter-2) (-- : 6)
6: v-Stokes drift velocity / (meter second-1) (time: 201; ocean_s_coordinate_g1: 16; -- : 106; -- : 345)
7: sediment median grain density / (kilogram meter3) (time: 201; -- : 107; -- : 345)
8: current-induced, bottom v-momentum stress / (newton meter-2) (time: 201; -- : 107; -- : 345)
9: wind-induced, bottom v-momentum stress / (newton meter-2) (time: 201; -- : 107; -- : 345)
10: sea_surface_wave_significant_height / (meter) (time: 201; -- : 107; -- : 345)
11: bed load flux of sand in V-direction, size class 03 / (kilogram meter-1 s-1) (time: 201; -- : 106; -- : 345)
12: bed load flux of sand in V-direction, size class 02 / (kilogram meter-1 s-1) (time: 201; -- : 106; -- : 345)
13: bed load flux of sand in V-direction, size class 01 / (kilogram meter-1 s-1) (time: 201; -- : 106; -- : 345)
14: biodiffusivity at bottom of each layer / (meter2 second-1) (time: 201; -- : 1; -- : 107; -- : 345)
15: bed load flux of sand in V-direction, size class 06 / (kilogram meter-1 s-1) (time: 201; -- : 106; -- : 345)
16: bed load flux of sand in V-direction, size class 05 / (kilogram meter-1 s-1) (time: 201; -- : 106; -- : 345)
17: bed load flux of sand in V-direction, size class 04 / (kilogram meter-1 s-1) (time: 201; -- : 106; -- : 345)
18: active layer thickness / (meter)    (time: 201; -- : 107; -- : 345)
19: Tracers nudging/relaxation inverse time scale / (day-1) (-- : 8)
20: tracer climatology processing switch / (1) (-- : 8)
21: sediment porosity / (1)             (-- : 6)
22: median sediment grain diameter used in uniform initial conditions / (millimeter) (-- : 6)
23: vertically integrated v-momentum component / (meter second-1) (time: 201; -- : 106; -- : 345)
24: wind-induced bottom wave Period / (second) (time: 201; -- : 107; -- : 345)
25: background vertical mixing coefficient for tracers / (meter2 second-1) (-- : 8)
26: max wave and current bottom stress magnitude / (newton meter-2) (time: 201; -- : 107; -- : 345)
27: wet/dry mask on PSI-points / (1)    (time: 201; -- : 106; -- : 344)
28: u-Stokes drift velocity / (meter second-1) (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 344)
29: maximum wind and current, bottom u-wave stress / (newton meter-2) (time: 201; -- : 107; -- : 345)
30: noncohesive sediment fraction, size class 02 / (1) (time: 201; -- : 1; -- : 107; -- : 345)
31: noncohesive sediment fraction, size class 03 / (1) (time: 201; -- : 1; -- : 107; -- : 345)
32: noncohesive sediment fraction, size class 01 / (1) (time: 201; -- : 1; -- : 107; -- : 345)
33: noncohesive sediment fraction, size class 06 / (1) (time: 201; -- : 1; -- : 107; -- : 345)
34: noncohesive sediment fraction, size class 04 / (1) (time: 201; -- : 1; -- : 107; -- : 345)
35: noncohesive sediment fraction, size class 05 / (1) (time: 201; -- : 1; -- : 107; -- : 345)
36: current-induced, bottom u-momentum stress / (newton meter-2) (time: 201; -- : 107; -- : 345)
37: tracer climatology nudging activation switch / (1) (-- : 8)
38: wind-induced, bottom u-momentum stress / (newton meter-2) (time: 201; -- : 107; -- : 345)
39: bed load flux of sand in U-direction, size class 02 / (kilogram meter-1 s-1) (time: 201; -- : 107; -- : 344)
40: bed load flux of sand in U-direction, size class 03 / (kilogram meter-1 s-1) (time: 201; -- : 107; -- : 344)
41: bed load flux of sand in U-direction, size class 01 / (kilogram meter-1 s-1) (time: 201; -- : 107; -- : 344)
42: bed load flux of sand in U-direction, size class 06 / (kilogram meter-1 s-1) (time: 201; -- : 107; -- : 344)
43: bed load flux of sand in U-direction, size class 04 / (kilogram meter-1 s-1) (time: 201; -- : 107; -- : 344)
44: bed load flux of sand in U-direction, size class 05 / (kilogram meter-1 s-1) (time: 201; -- : 107; -- : 344)
45: noncohesive sediment mass, size class 06 / (kilogram meter-2) (time: 201; -- : 1; -- : 107; -- : 345)
46: noncohesive sediment mass, size class 04 / (kilogram meter-2) (time: 201; -- : 1; -- : 107; -- : 345)
47: noncohesive sediment mass, size class 05 / (kilogram meter-2) (time: 201; -- : 1; -- : 107; -- : 345)
48: noncohesive sediment mass, size class 02 / (kilogram meter-2) (time: 201; -- : 1; -- : 107; -- : 345)
49: noncohesive sediment mass, size class 03 / (kilogram meter-2) (time: 201; -- : 1; -- : 107; -- : 345)
50: noncohesive sediment mass, size class 01 / (kilogram meter-2) (time: 201; -- : 1; -- : 107; -- : 345)
51: sediment grain density used in uniform initial conditions / (kilogram meter-3) (-- : 6)
52: sediment particle settling velocity / (meter second-1) (-- : 6)
53: vertical momentum component / (meter second-1) (time: 201; ocean_s_coordinate_g1: 17; -- : 107; -- : 345)
54: coupling vertically integrated u-momentum component / (meter second-1) (time: 201; -- : 107; -- : 345)
55: mask on V-points / (1)              (-- : 106; -- : 345)
56: mask on U-points / (1)              (-- : 107; -- : 344)
57: mask on RHO-points / (1)            (-- : 107; -- : 345)
58: sediment median critical erosion stress / (newton meter-2) (time: 201; -- : 107; -- : 345)
59: wet/dry mask on V-points / (1)      (time: 201; -- : 106; -- : 345)
60: wet/dry mask on U-points / (1)      (time: 201; -- : 107; -- : 344)
61: curvilinear coordinate metric in ETA / (meter-1) (-- : 107; -- : 345)
62: curvilinear coordinate metric in XI / (meter-1) (-- : 107; -- : 345)
63: bottom ripple length / (meter)      (time: 201; -- : 107; -- : 345)
64: wind-induced mean wavelength / (meter) (time: 201; -- : 107; -- : 345)
65: sediment median grain settling velocity / (meter second-1) (time: 201; -- : 107; -- : 345)
66: wind-induced peak surface wave Period / (second) (time: 201; -- : 107; -- : 345)
67: Coriolis parameter at RHO-points / (second-1) (-- : 107; -- : 345)
68: vertically integrated u-momentum component / (meter second-1) (time: 201; -- : 107; -- : 344)
69: y_sea_water_velocity / (meter second-1) (time: 201; ocean_s_coordinate_g1: 16; -- : 106; -- : 345)
70: sediment layer porosity / (1)       (time: 201; -- : 1; -- : 107; -- : 345)
71: horizontal diffusivity sponge activation switch / (1) (-- : 8)
72: coupling vertically integrated v-momentum component / (meter second-1) (time: 201; -- : 107; -- : 345)
73: nonlinear model Laplacian mixing coefficient for tracers / (meter2 second-1) (-- : 8)
74: inundation depth / (meter)          (time: 201; -- : 107; -- : 345)
75: wet/dry mask on RHO-points / (1)    (time: 201; -- : 107; -- : 345)
76: default bottom roughness length / (meter) (time: 201; -- : 107; -- : 345)
77: suspended noncohesive sediment, size class 02 / (kilogram meter-3) (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 345)
78: suspended noncohesive sediment, size class 03 / (kilogram meter-3) (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 345)
79: suspended noncohesive sediment, size class 01 / (kilogram meter-3) (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 345)
80: suspended noncohesive sediment, size class 06 / (kilogram meter-3) (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 345)
81: suspended noncohesive sediment, size class 04 / (kilogram meter-3) (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 345)
82: suspended noncohesive sediment, size class 05 / (kilogram meter-3) (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 345)
83: wind-induced peak wavelength / (meter) (time: 201; -- : 107; -- : 345)
84: wind-induced wave direction / (degrees) (time: 201; -- : 107; -- : 345)
85: sediment layer age / (seconds)      (time: 201; -- : 1; -- : 107; -- : 345)
86: sediment median grain diameter size / (meter) (time: 201; -- : 107; -- : 345)
87: tracer point sources and sink activation switch / (1) (-- : 8)
88: mask on psi-points / (1)            (-- : 106; -- : 344)
89: angle between XI-axis and EAST / (radians) (-- : 107; -- : 345)
90: apparent bottom roughness length / (meter) (time: 201; -- : 107; -- : 345)
91: sediment bed layer thickness / (meter) (time: 201; -- : 1; -- : 107; -- : 345)
92: bed wave excursion amplitude / (meter) (time: 201; -- : 107; -- : 345)
93: x_sea_water_velocity / (meter second-1) (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 344)
94: sea_water_potential_temperature / (Celsius) (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 345)
95: wind-induced bottom orbital velocity / (meter second-1) (time: 201; -- : 107; -- : 345)
96: sea_water_salinity / (1)            (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 345)
97: bottom ripple height / (meter)      (time: 201; -- : 107; -- : 345)

We can take advantage of the CF conventions to access variables by its standard_name


In [32]:
temp = cubes.extract_strict('sea_water_potential_temperature')
print(temp)


sea_water_potential_temperature               (time: 201; ocean_s_coordinate_g1: 16; -- : 107; -- : 345)
     Dimension coordinates:
          time                                             x                           -        -         -
          ocean_s_coordinate_g1                            -                           x        -         -
     Auxiliary coordinates:
          free-surface                                     x                           -        x         x
          S-coordinate stretching curves at RHO-points     -                           x        -         -
          bathymetry at RHO-points                         -                           -        x         x
          latitude                                         -                           -        x         x
          longitude                                        -                           -        x         x
     Derived coordinates:
          sea_surface_height_above_reference_ellipsoid     x                           x        x         x
     Scalar coordinates:
          S-coordinate parameter, critical depth: 2.0 meter
     Attributes:
          CPP_options: FIREISLAND, ANA_BPFLUX, ANA_BSFLUX, ANA_BTFLUX, ANA_FSOBC, ANA_M2OBC, ANA_NUDGCOEF,...
          Conventions: CF-1.6, SGRID-0.1, ACDD-1.3
          NLM_LBC: 
EDGE:         WEST   SOUTH  EAST   NORTH  
zeta:         Nes    Nes  ...
          ana_file: ROMS/Functionals/ana_btflux.h, ROMS/Functionals/ana_fsobc.h, ROMS/Functionals/ana_m2obc.h,...
          cdm_data_type: Grid
          clm_file_01: ../forcings/merged_coawst_clm_10Sep_29Dec2012.nc
          code_dir: /raid3/jcwarner/Projects/Sandy/sim6
          compiler_command: /usr/local/mpi/bin/mpif90
          compiler_flags:  -fastsse -Mipa=fast -tp k8-64 -Mfree
          compiler_system: pgi
          content_coverage_type: modelResult
          cpu: x86_64
          creator_email: jcwarner@usgs.gov
          creator_name: John Warner
          creator_url: http://woodshole.er.usgs.gov/staffpages/jwarner/
          field: temperature, scalar, series
          file: Output/ocean_NYB05_his_0016.nc
          format: netCDF-3 64bit offset file
          frc_file_01: ../forcings/roms_namnarr_2030Oct2012.nc, ../forcings/roms_namnarr_30Oc...
          grd_file: ../grids/NYB_700m_05.nc
          grid: grid
          header_dir: /raid3/jcwarner/Projects/Sandy/sim6/Projects/FireIsland
          header_file: fireisland.h
          his_base: Output/ocean_NYB05_his
          history: ROMS/TOMS, Version 3.7, Tuesday - June 2, 2015 - 10:15:23 PM
          id: USGS_COAWST_Sandy_NYB05_sim6
          ini_file: Output/ocean_NYB05_his_0009.nc
          license: The data may be used and redistributed for free but is not intended for...
          location: face
          naming_authority: gov.usgs.cmg
          os: Linux
          project: CMG_Portal,Sandy_Portal
          publisher_email: jcwarner@usgs.gov
          publisher_name: John Warner
          publisher_url: http://woodshole.er.usgs.gov/staffpages/jwarner/
          references: http://woodshole.er.usgs.gov/operations/modeling/COAWST/,doi:10.1016/j...
          rst_file: Output/ocean_NYB05_rst.nc
          script_file: 
          summary: Simulation of hydrodynamics, waves, bottom stress and sediment transport...
          svn_rev: exported
          svn_url: https:://myroms.org/svn/src
          tiling: 008x005
          time: ocean_time
          title: USGS-CMG-COAWST Model: Hurricane Sandy, NYB05 700m Nest
          type: ROMS/TOMS history file

Like xray we have both high and low level slicing (Although the high level slicing in iris is too sophisticated for my taste ;-)


In [33]:
t = temp[-1, -1, ...]

print(t)  # The metadata is always propagated.


sea_water_potential_temperature             (-- : 107; -- : 345)
     Auxiliary coordinates:
          bathymetry at RHO-points                         x         x
          free-surface                                     x         x
          latitude                                         x         x
          longitude                                        x         x
     Derived coordinates:
          sea_surface_height_above_reference_ellipsoid     x         x
     Scalar coordinates:
          S-coordinate parameter, critical depth: 2.0 meter
          S-coordinate stretching curves at RHO-points: -0.00225488671278
          ocean_s_coordinate_g1: -0.03125
          time: 2012-11-02 08:00:00.000006
     Attributes:
          CPP_options: FIREISLAND, ANA_BPFLUX, ANA_BSFLUX, ANA_BTFLUX, ANA_FSOBC, ANA_M2OBC, ANA_NUDGCOEF,...
          Conventions: CF-1.6, SGRID-0.1, ACDD-1.3
          NLM_LBC: 
EDGE:         WEST   SOUTH  EAST   NORTH  
zeta:         Nes    Nes  ...
          ana_file: ROMS/Functionals/ana_btflux.h, ROMS/Functionals/ana_fsobc.h, ROMS/Functionals/ana_m2obc.h,...
          cdm_data_type: Grid
          clm_file_01: ../forcings/merged_coawst_clm_10Sep_29Dec2012.nc
          code_dir: /raid3/jcwarner/Projects/Sandy/sim6
          compiler_command: /usr/local/mpi/bin/mpif90
          compiler_flags:  -fastsse -Mipa=fast -tp k8-64 -Mfree
          compiler_system: pgi
          content_coverage_type: modelResult
          cpu: x86_64
          creator_email: jcwarner@usgs.gov
          creator_name: John Warner
          creator_url: http://woodshole.er.usgs.gov/staffpages/jwarner/
          field: temperature, scalar, series
          file: Output/ocean_NYB05_his_0016.nc
          format: netCDF-3 64bit offset file
          frc_file_01: ../forcings/roms_namnarr_2030Oct2012.nc, ../forcings/roms_namnarr_30Oc...
          grd_file: ../grids/NYB_700m_05.nc
          grid: grid
          header_dir: /raid3/jcwarner/Projects/Sandy/sim6/Projects/FireIsland
          header_file: fireisland.h
          his_base: Output/ocean_NYB05_his
          history: ROMS/TOMS, Version 3.7, Tuesday - June 2, 2015 - 10:15:23 PM
          id: USGS_COAWST_Sandy_NYB05_sim6
          ini_file: Output/ocean_NYB05_his_0009.nc
          license: The data may be used and redistributed for free but is not intended for...
          location: face
          naming_authority: gov.usgs.cmg
          os: Linux
          project: CMG_Portal,Sandy_Portal
          publisher_email: jcwarner@usgs.gov
          publisher_name: John Warner
          publisher_url: http://woodshole.er.usgs.gov/staffpages/jwarner/
          references: http://woodshole.er.usgs.gov/operations/modeling/COAWST/,doi:10.1016/j...
          rst_file: Output/ocean_NYB05_rst.nc
          script_file: 
          summary: Simulation of hydrodynamics, waves, bottom stress and sediment transport...
          svn_rev: exported
          svn_url: https:://myroms.org/svn/src
          tiling: 008x005
          time: ocean_time
          title: USGS-CMG-COAWST Model: Hurricane Sandy, NYB05 700m Nest
          type: ROMS/TOMS history file

There are even some quick plotting routines to explore the data. Note the free colorbar, units label, and title:


In [34]:
import iris.quickplot as qplt

cs = qplt.pcolormesh(t)


Some very "oceanographic" libraries

Some not so "oceanographic" but very useful

Extra slides

Using python as a glue language

Calling matlab

(See matlab_kernel for full matlab)


In [35]:
try:
    %load_ext oct2py.ipython
    octave = True
except AttributeError as e:
    octave = False
    print(e)
    print("You cannot run the next 2 cells with the octave example :-(")

In [36]:
%%file fahr_to_kelvin.m

function ktemp = fahr_to_kelvin(ftemp)
    ktemp = ((ftemp - 32) * (5/9)) + 273.15;
end


Overwriting fahr_to_kelvin.m

In [37]:
if octave:
    %octave fahr_to_kelvin(32)


ans =  273.15

Calling Fortran


In [38]:
%load_ext fortranmagic



In [39]:
%%fortran

subroutine calc_sin(x, y)
    real, intent(in) :: x
    real, intent(out) :: y

    y = sin(x)

end subroutine calc_sin

In [40]:
calc_sin(np.pi/2)


Out[40]:
1.0

Calling R

  • chooseCRANmirror(graphics=FALSE)
  • install.packages('oce')

In [41]:
%load_ext rpy2.ipython

In [42]:
%%R
X=c(1,4,5,7)
Y = c(2,4,3,9)
print(summary(lm(Y~X)))


Call:
lm(formula = Y ~ X)

Residuals:
    1     2     3     4 
 0.88 -0.24 -2.28  1.64 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   0.0800     2.3000   0.035    0.975
X             1.0400     0.4822   2.157    0.164

Residual standard error: 2.088 on 2 degrees of freedom
Multiple R-squared:  0.6993,	Adjusted R-squared:  0.549 
F-statistic: 4.651 on 1 and 2 DF,  p-value: 0.1638


In [43]:
%%R
library(oce)
Sa <- 30; Ta <- 10; Sb <- 40; 
rho0 <- swRho(Sa, Ta, 0)
Tb <- uniroot(function(T) rho0-swRho(Sb,T,0), lower=0, upper=100)$root
Sc <- (Sa + Sb) /2; Tc <- (Ta + Tb) /2
drho <- swRho(Sc, Tc, 0) - rho0
dT <- drho / rho0 / swAlpha(Sc, Tc, 0)
plotTS(as.ctd(c(Sa, Sb, Sc), c(Ta, Tb, Tc), 0), pch=20, cex=2)
drawIsopycnals(levels=rho0, col="red", cex=0)
segments(Sa, Ta, Sb, Tb, col="blue")
text(Sb, Tb, "b", pos=4); text(Sa, Ta, "a", pos=4); text(Sc, Tc, "c", pos=4)
legend("topleft",legend=sprintf("Sa=%.1f, Ta=%.1f, Sb=%.1f  ->  Tb=%.1f, drho=%.2f, dT=%.2f",Sa, Ta, Sb, Tb, drho, dT),bg="white")



In [44]:
HTML(css)


Out[44]: