In [7]:
%%bash
ncdump data/model-gfs.nc


netcdf model-gfs {
dimensions:
	profile = 24 ;
	station = 1 ;
	isobaric3 = 1 ;
	station_name_strlen = 10 ;
	station_description_strlen = 33 ;
variables:
	float Convective_available_potential_energy_surface(station, profile) ;
		Convective_available_potential_energy_surface:standard_name = "Convective_available_potential_energy_surface" ;
		Convective_available_potential_energy_surface:long_name = "Convective_available_potential_energy_surface" ;
		Convective_available_potential_energy_surface:units = "J/kg" ;
		Convective_available_potential_energy_surface:coordinates = "time longitude latitude" ;
	float Convective_inhibition_surface(station, profile) ;
		Convective_inhibition_surface:standard_name = "Convective_inhibition_surface" ;
		Convective_inhibition_surface:long_name = "Convective_inhibition_surface" ;
		Convective_inhibition_surface:units = "J/kg" ;
		Convective_inhibition_surface:coordinates = "time longitude latitude" ;
	float Temperature_surface(station, profile) ;
		Temperature_surface:standard_name = "Temperature_surface" ;
		Temperature_surface:long_name = "Temperature_surface" ;
		Temperature_surface:units = "K" ;
		Temperature_surface:coordinates = "time longitude latitude" ;
	float isobaric3(station, profile, isobaric3) ;
		isobaric3:standard_name = "isobaric3" ;
		isobaric3:long_name = "isobaric3" ;
		isobaric3:units = "Pa" ;
		isobaric3:positive = "down" ;
		isobaric3:axis = "Z" ;
	float u-component_of_wind_isobaric(station, profile, isobaric3) ;
		u-component_of_wind_isobaric:standard_name = "u-component_of_wind_isobaric" ;
		u-component_of_wind_isobaric:long_name = "u-component_of_wind_isobaric" ;
		u-component_of_wind_isobaric:units = "m/s" ;
		u-component_of_wind_isobaric:coordinates = "time longitude latitude isobaric3" ;
	float Temperature_isobaric(station, profile, isobaric3) ;
		Temperature_isobaric:standard_name = "Temperature_isobaric" ;
		Temperature_isobaric:long_name = "Temperature_isobaric" ;
		Temperature_isobaric:units = "K" ;
		Temperature_isobaric:coordinates = "time longitude latitude isobaric3" ;
	float Relative_humidity_isobaric(station, profile, isobaric3) ;
		Relative_humidity_isobaric:standard_name = "Relative_humidity_isobaric" ;
		Relative_humidity_isobaric:long_name = "Relative_humidity_isobaric" ;
		Relative_humidity_isobaric:units = "%" ;
		Relative_humidity_isobaric:coordinates = "time longitude latitude isobaric3" ;
	float v-component_of_wind_isobaric(station, profile, isobaric3) ;
		v-component_of_wind_isobaric:standard_name = "v-component_of_wind_isobaric" ;
		v-component_of_wind_isobaric:long_name = "v-component_of_wind_isobaric" ;
		v-component_of_wind_isobaric:units = "m/s" ;
		v-component_of_wind_isobaric:coordinates = "time longitude latitude isobaric3" ;
	char station_name(station, station_name_strlen) ;
		station_name:long_name = "station name" ;
		station_name:cf_role = "timeseries_id" ;
	char station_description(station, station_description_strlen) ;
		station_description:long_name = "station description" ;
		station_description:standard_name = "platform_name" ;
	double latitude(station) ;
		latitude:units = "degrees_north" ;
		latitude:long_name = "profile latitude" ;
	double longitude(station) ;
		longitude:units = "degrees_east" ;
		longitude:long_name = "profile longitude" ;
	double time(station, profile) ;
		time:units = "Hour since 2015-07-14T00:00:00Z" ;
		time:calendar = "proleptic_gregorian" ;
		time:standard_name = "time" ;
		time:long_name = "GRIB forecast or observation time" ;

// global attributes:
		:Conventions = "CDM-Extended-CF" ;
		:history = "Written by CFPointWriter" ;
		:title = "Extract Points data from Grid file /data/ldm/pub/native/grid/NCEP/GFS/Global_0p25deg/GFS-Global_0p25deg.ncx3" ;
		:featureType = "timeSeriesProfile" ;
		:time_coverage_start = "2015-07-17T21:00:00Z" ;
		:time_coverage_end = "2015-07-20T18:00:00Z" ;
		:geospatial_lat_min = 39.9995 ;
		:geospatial_lat_max = 40.0005 ;
		:geospatial_lon_min = -105.0005 ;
		:geospatial_lon_max = -104.9995 ;
data:

 Convective_available_potential_energy_surface =
  113, 69, 19, 0, 0, 0, 0, 42, 177, 143, 0, 0, 0, 32, 344, 292, 198, 79, 54, 
    0, 0, 0, 0, 0 ;

 Convective_inhibition_surface =
  -9, -16, -200, 0, 0, 0, 0, -71, -3, -5, 0, 0, 0, -266, -104, -20, 0, -166, 
    -111, 0, 0, 0, 0, 0 ;

 Temperature_surface =
  310.7, 308, 296.4, 289.5, 288.5, 287.1, 301.1, 308.3, 311.5, 305.1, 295.6, 
    292.4, 290.4, 289.1, 299.4, 307.9, 316.6, 293.9, 291.2, 289.8, 287.1, 
    285.8, 303.3, 310 ;

 isobaric3 =
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000,
  100000 ;

 u-component_of_wind_isobaric =
  4.06,
  6.2,
  5.69,
  -2.02,
  2.48,
  2.5,
  -2.03,
  -4.75,
  -2.39,
  -2.46,
  2,
  2.27,
  -0.76,
  0.8,
  -0.9,
  -2.92,
  -0.81,
  2.19,
  -0.43,
  0.3,
  2.63,
  2.78,
  0.49,
  -2.11 ;

 Temperature_isobaric =
  316,
  316.3,
  308.9,
  304,
  302,
  300.8,
  306.2,
  309.8,
  313.5,
  313.3,
  308.3,
  304.9,
  301,
  299.2,
  302.6,
  309,
  311.8,
  304.7,
  304.6,
  301.8,
  300.6,
  299.9,
  306.3,
  311.3 ;

 Relative_humidity_isobaric =
  10.5,
  10,
  22.2,
  33,
  37.5,
  36.8,
  27.3,
  25.3,
  17.5,
  18.2,
  27.5,
  34.4,
  61.3,
  78.5,
  65.8,
  35.2,
  26,
  53.4,
  52.1,
  64.5,
  56.6,
  43.5,
  29.1,
  18.3 ;

 v-component_of_wind_isobaric =
  1.96,
  0.26,
  -0.19,
  -3.08,
  1.98,
  1.58,
  -1.85,
  -0.27,
  3.08,
  4.54,
  3.5,
  -0.99,
  -3.78,
  -2.31,
  -1.5,
  -0.1,
  0.74,
  1.71,
  3.8,
  -2.58,
  0.09,
  0.5,
  0.28,
  1.86 ;

 station_name =
  "Grid Point" ;

 station_description =
  "Grid Point at lat/lon=40.0,-105.0" ;

 latitude = 40 ;

 longitude = -105 ;

 time =
  93, 96, 99, 102, 105, 108, 111, 114, 117, 120, 123, 126, 129, 132, 135, 
    138, 141, 144, 147, 150, 153, 156, 159, 162 ;
}

In [8]:
from netCDF4 import Dataset, num2date

In [96]:
data = Dataset('data/model-gfs.nc', 'r')

ImportError on netCDF4? From the command line:

with anaconda:

  • conda install netCDF4

with canopy:

  • pip install netCDF
  • pip install --upgrade netCDF

In [23]:
# get the time variable, and convert to datetimes
time_var = data.variables['time']
print time_var


<type 'netCDF4._netCDF4.Variable'>
float64 time(station, profile)
    units: Hour since 2015-07-14T00:00:00Z
    calendar: proleptic_gregorian
    standard_name: time
    long_name: GRIB forecast or observation time
unlimited dimensions: 
current shape = (1, 24)
filling on, default _FillValue of 9.96920996839e+36 used


In [13]:
num2date?

In [18]:
print time_var.units
print time_var[:]


Hour since 2015-07-14T00:00:00Z
[[  93.   96.   99.  102.  105.  108.  111.  114.  117.  120.  123.  126.
   129.  132.  135.  138.  141.  144.  147.  150.  153.  156.  159.  162.]]

In [25]:
time = num2date(time_var[:], time_var.units ).squeeze()
print time.shape


(24,)
(1, 24)

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

In [30]:
fig, ax = plt.subplots(1,1, figsize=(12,6))
T_iso = data.variables['Temperature_isobaric']
ax.plot(time, T_iso[:].squeeze(), 'r-')


Out[30]:
[<matplotlib.lines.Line2D at 0x1098c74d0>]

In [31]:
from datetime import datetime
print datetime.now()


2015-08-20 10:30:58.915760

In [75]:
def set_defaults(ax, label_font):

    ax.set_xlabel('Forecast time (UTC)', fontdict=label_font)

    from matplotlib.dates import DateFormatter, DayLocator, HourLocator
    ax.xaxis.set_major_locator(DayLocator())
    ax.xaxis.set_minor_locator(HourLocator(range(6,24,6)))

    ax.xaxis.set_major_formatter(DateFormatter('%b %d'))
    ax.xaxis.set_minor_formatter(DateFormatter('%HZ'))

    # format code documentation is at (among other places): http://strftime.org

In [52]:
fig, ax = plt.subplots(1, 1, figsize=(12, 6))
ax.plot(time, data.variables['Temperature_isobaric'][:].squeeze(), 'r-', linewidth=2)

set_defaults(ax)



In [53]:
vals = [1,2,3,4]
names = ['one', 'two','three','four']
pairs = zip(names,vals)


[('one', 1), ('two', 2), ('three', 3), ('four', 4)]

In [54]:
print zip(*pairs)


[('one', 'two', 'three', 'four'), (1, 2, 3, 4)]

In [64]:
a,b,c,d,e = 'ericb'
print c


i

In [65]:
import math
def polar_to_cartesian(r,th):
    x = r*math.cos(th)
    y = r*math.sin(th)
    return x, y

X, Y = polar_to_cartesian(2, math.pi/3)
print(X,Y)


(1.0000000000000002, 1.7320508075688772)

In [69]:
format_template = "{0} == {1}, which is the {0}th number"

for nv in zip(names, vals):
    print(format_template.format(*nv))


one == 1, which is the oneth number
two == 2, which is the twoth number
three == 3, which is the threeth number
four == 4, which is the fourth number

In [77]:
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
label_font = dict(size=16, weight='bold')

for ax, varname in zip(axes, ['Temperature_isobaric', 'Relative_humidity_isobaric']):
    ax.plot(time, data.variables[varname][:].squeeze(), 'r-', linewidth=2)
    set_defaults(ax, label_font) 
    ax.set_ylabel(varname, fontdict=label_font)



In [78]:
num_map = dict(zip(vals, names))
print num_map


{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

In [80]:
print num_map[1]


one

In [83]:
states = dict(Colorado={'abbreviation': 'CO', 'capitol': 'Denver', 'notes': 'Home!', 'flat':False},
              Oklahoma={'abbreviation': 'OK', 'capitol': 'Oklahoma City', 'flat': True},
              Kansas={'abbreviation': 'KS', 'capitol': 'Topeka', 'flat': True})

In [84]:
states['Colorado']['capitol']


Out[84]:
'Denver'

In [92]:
def K2F(K):
    return 1.8 * (K-273.15) + 32

print K2F(300)
print K2F


80.33
<function K2F at 0x10c424938>

In [100]:
variable_styles = {'Temperature_isobaric':{'line':dict(color='r', marker='s', linestyle='-'),
                                           'label':u'Temperature (°F)', 'converter':K2F},
                   'Relative_humidity_isobaric': {'line':dict(color='g', marker='o'),
                                           'label':'RH (%)', 'converter':None}}

In [101]:
print variable_styles['Temperature_isobaric']['line']
print variable_styles['Relative_humidity_isobaric']['label']


{'marker': 's', 'color': 'r', 'linestyle': '-'}
RH (%)

In [102]:
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
label_font = dict(size=16, weight='bold')
vars_to_plot = ['Temperature_isobaric', 'Relative_humidity_isobaric']

for ax, varname in zip(axes, vars_to_plot):
    data_vals = data.variables[varname][:].squeeze()
    
    # get the converter from the dictionary
    converter = variable_styles[varname]['converter']
    if converter is not None:
        # do something to the data if there is a converter
        data_vals = converter(data_vals)
        
    linespec = variable_styles[varname]['line']
    ax.plot(time, data_vals, **linespec)
    set_defaults(ax, label_font) 
    ax.set_ylabel(variable_styles[varname]['label'], fontdict=label_font)


What are good resources for further learning? Learning Python Python Essential Reference