In [1]:
from IPython.external import mathjax; mathjax.install_mathjax()


Downloading mathjax source from https://github.com/mathjax/MathJax/archive/2.4.0.tar.gz
Extracting to C:\Users\Stephan Kindermann\.ipython\nbextensions\mathjax
Out[1]:
0

In [1]:
%matplotlib inline

In [2]:
import math
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0 , 1.0+0.01 , 0.01)
s = np.cos(2*2*math.pi*t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets , folks ')
plt.grid(True)
plt.show()



In [3]:
from pylab import *
x = arange(0,10, 0.2)
y = sin(x)
plot(x, y)
show()



In [4]:
import math
import numpy as np
import matplotlib.pyplot as plt

t = np. arange (0.0 , 1.0+0.01 , 0.01)
s = np.cos (2*2*math .pi*t)
plt.plot (t, s)

plt.xlabel ('time (s)')
plt.ylabel ('voltage (mV)')
plt.title ('About as simple as it gets , folks ')
plt.grid (True)
plt.show()
#plt.savefig ('simple_plot')



In [5]:
figure (1, figsize =(2,2))
#ax = axes([0.1 , 0.1 , 0.8 , 0.8])

labels = 'Frogs ', 'Hogs ', 'Dogs ', 'Logs '
fracs = [15 , 30, 45, 10]

explode =(0 , 0.05 , 0, 0)

pie (fracs , explode = explode , labels = labels)


Out[5]:
([<matplotlib.patches.Wedge at 0x7ff7054f41d0>,
  <matplotlib.patches.Wedge at 0x7ff7054f4bd0>,
  <matplotlib.patches.Wedge at 0x7ff705484590>,
  <matplotlib.patches.Wedge at 0x7ff705484f10>],
 [<matplotlib.text.Text at 0x7ff7054f4790>,
  <matplotlib.text.Text at 0x7ff7054841d0>,
  <matplotlib.text.Text at 0x7ff705484b50>,
  <matplotlib.text.Text at 0x7ff70548e510>])

In [6]:
import numpy as np
import matplotlib.pyplot as plt

mu , sigma = 100 , 15
x = mu + sigma * np. random . randn (10000)

# the histogram of the data
n, bins , patches = plt.hist(x, 50, normed =1, facecolor ='g', alpha =0.75)

plt.xlabel ('Smarts ')
plt.ylabel ('Probability ')
plt.title ('Histogram of IQ ')
plt.text (60 , .025 , r'$\mu =100 ,\ \ sigma =15$')
plt.axis ([40 , 160 , 0, 0.03])
plt.grid ( True )



In [7]:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = Axes3D (fig)
X = np.arange (-5, 5, 0.25)
Y = np.arange (-5, 5, 0.25)
X, Y = np.meshgrid (X, Y)
R = np.sqrt (X**2 + Y **2)
Z = np.sin(R)
ax.plot_surface (X, Y, Z, rstride =1, cstride =1, cmap =cm.jet)
plt.show()


BASEMAP


In [9]:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
# set up orthographic map projection with
# perspective of satellite looking down at 50N, 100W.
# use low resolution coastlines.
map = Basemap(projection='ortho',lat_0=45,lon_0=-100,resolution='l')
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
map.fillcontinents(color='coral',lake_color='aqua')
# draw the edge of the map projection region (the projection limb)
map.drawmapboundary(fill_color='aqua')
# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(np.arange(0,360,30))
map.drawparallels(np.arange(-90,90,30))
# make up some data on a regular lat/lon grid.
nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1)
lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:])
lons = (delta*np.indices((nlats,nlons))[1,:,:])
wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons))
mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.)
# compute native map projection coordinates of lat/lon grid.
x, y = map(lons*180./np.pi, lats*180./np.pi)
# contour data over the map.
cs = map.contour(x,y,wave+mean,15,linewidths=1.5)
plt.title('contour lines over filled continent background')
plt.show()



In [11]:
import netCDF4

#cmip5_pr = netCDF4.Dataset('pr_day_MPI-ESM-LR_1pctCO2_r1i1p1_18500101-18591231.nc', mode='r')
#cmip5_psl = netCDF4.Dataset('psl_day_MPI-ESM-LR_1pctCO2_r1i1p1_19600101-19691231.nc', mode='r')
cmip5_psl = netCDF4.Dataset('../../Data/psl_day_MPI-ESM-LR_1pctCO2_r1i1p1_18600101-18691231.nc', mode='r')
#cordex_psl = netCDF4.Dataset('/home/stephan/psl_EUR-44_CCCma-CanESM2_historical_r1i1p1_SMHI-RCA4_v1_day_20010101-20051231.nc' , mode ='r')
#cordex_airtemp = netCDF4.Dataset('/home/stephan/ta200_EUR-44_CCCma-CanESM2_rcp45_r1i1p1_SMHI-RCA4_v1_day_20960101-21001231.nc', mode='r')

print cmip5_psl

lat = cmip5_psl.variables['lat'][:]
lon = cmip5_psl.variables['lon'][:]

psl = 0.01* cmip5_psl.variables['psl'][:]

cmip5_psl.close()
#cordex_airtemp.close()

nlat = lat.size - 1
nlon = lon.size - 1

myPSL = psl[0,:,:]


<type 'netCDF4._netCDF4.Dataset'>
root group (NETCDF3_CLASSIC data model, file format UNDEFINED):
    institution: Max Planck Institute for Meteorology
    institute_id: MPI-M
    experiment_id: 1pctCO2
    source: MPI-ESM-LR 2011; URL: http://svn.zmaw.de/svn/cosmos/branches/releases/mpi-esm-cmip5/src/mod; atmosphere: ECHAM6 (REV: 4571), T63L47; land: JSBACH (REV: 4571); ocean: MPIOM (REV: 4571), GR15L40; sea ice: 4571; marine bgc: HAMOCC (REV: 4571);
    model_id: MPI-ESM-LR
    forcing: N/A
    parent_experiment_id: piControl
    parent_experiment_rip: r1i1p1
    branch_time: 10957.0
    contact: cmip5-mpi-esm@dkrz.de
    history: Model raw output postprocessing with modelling environment (IMDI) at DKRZ: URL: http://svn-mad.zmaw.de/svn/mad/Model/IMDI/trunk, REV: 3208 2011-05-31T14:50:49Z CMOR rewrote data to comply with CF standards and CMIP5 requirements.
    references: ECHAM6: n/a; JSBACH: Raddatz et al., 2007. Will the tropical land biosphere dominate the climate-carbon cycle feedback during the twenty first century? Climate Dynamics, 29, 565-574, doi 10.1007/s00382-007-0247-8;  MPIOM: Marsland et al., 2003. The Max-Planck-Institute global ocean/sea ice model with orthogonal curvilinear coordinates. Ocean Modelling, 5, 91-127;  HAMOCC: http://www.mpimet.mpg.de/fileadmin/models/MPIOM/HAMOCC5.1_TECHNICAL_REPORT.pdf;
    initialization_method: 1
    physics_version: 1
    tracking_id: 4b58693e-f03d-4daf-894a-9099844657a9
    product: output
    experiment: 1 percent per year CO2
    frequency: day
    creation_date: 2011-05-31T14:50:58Z
    Conventions: CF-1.4
    project_id: CMIP5
    table_id: Table day (27 April 2011) 86d1558d99b6ed1e7a886ab3fd717b58
    title: MPI-ESM-LR model output prepared for CMIP5 1 percent per year CO2
    parent_experiment: pre-industrial control
    modeling_realm: atmos
    realization: 1
    cmor_version: 2.5.9
    dimensions(sizes): time(3653), lat(96), lon(192), bnds(2)
    variables(dimensions): float64 time(time), float64 time_bnds(time,bnds), float64 lat(lat), float64 lat_bnds(lat,bnds), float64 lon(lon), float64 lon_bnds(lon,bnds), float32 psl(time,lat,lon)
    groups: 


In [12]:
myPSL = psl[1,:,:]

In [14]:
fig = plt.figure (1, figsize =(10 ,30) , dpi =75)
ax = fig.add_axes ([0.05 ,0.05 ,0.9 ,0.85])


m = Basemap(projection ='mill',llcrnrlat =lat[0] , urcrnrlat = lat[nlat],
    llcrnrlon = lon[0] , urcrnrlon =lon[nlon] )
m.drawcoastlines(linewidth =1.25)
m.fillcontinents(color ='0.8 ')
m.drawparallels(np.arange(-80 ,81 ,20) , labels =[1 ,1 ,0 ,0])
m.drawmeridians(np.arange(-180 ,180 ,60) , labels =[0 ,0 ,0 ,1])
im = m.imshow(myPSL ,interpolation ='nearest',
    extent =[ lon[0] , lon[nlon], lat[0] , lat[nlat]],
    cmap = plt.cm.jet )
plt.colorbar(orientation ='horizontal',shrink =.8)
plt.title('Sea Level Pressure')
plt.savefig('fig_slp.png')
plt.show()



In [16]:
def bmContourPlot (var , lats , lons , figName , figTitle):
    plt.figure()
    latLow = lats[0]; latHigh = lats[-1]
    lonLow = lons[0]; lonHigh = lons[-1]
    m = Basemap(projection ='mill ', llcrnrlat = latLow, urcrnrlat = latHigh,
            llcrnrlon =lonLow , urcrnrlon = lonHigh ,resolution ='c')
    m.drawcoastlines()
    m.drawparallels(np.arange(latLow , latHigh +1 ,30.))
    m.drawmeridians(np.arange(lonLow , lonHigh +1 ,60.))
    longrid , latgrid = np.meshgrid(lons , lats )
    x, y = m(longrid ,latgrid)
    m.contour(x,y,var ); m.contourf(x,y,var)
    plt.title(figTitle)
    plt.colorbar(shrink =.8)
    plt.savefig(figName + '.png')
    plt.show()

In [17]:
time = ncFid.variables ['time '][:]
lev = ncFid.variables ['lev '][:]
lat = ncFid.variables ['lat '][:]
lon = ncFid.variables ['lon '][:]
T = ncFid.variables ['T'][:]
level500 = 29 # level of interest
T500 = T[:, level500 ,: ,:] # time , lat , lon
T500mean = np.mean(T500 ,0)
T500var = np.var(T500 ,0)

bmContourPlot(T500mean , lat , lon , 'fig_TempMean','Spatial Temperature Mean')
bmContourPlot(T500var , lat , lon , 'fig_TempVariance', 'Spatial Temperature Variance')


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-17-3e878ec4fc26> in <module>()
----> 1 time = ncFid.variables ['time '][:]
      2 lev = ncFid.variables ['lev '][:]
      3 lat = ncFid.variables ['lat '][:]
      4 lon = ncFid.variables ['lon '][:]
      5 T = ncFid.variables ['T'][:]

NameError: name 'ncFid' is not defined

In [ ]:
import numpy as np

def sliceLatLon (lat , lon , (minLat ,maxLat), (minLon ,maxLon)):
    indexLat = np.nonzero(( lat [:]>= minLat ) & (lat [:]<= maxLat ))[0]
    indexLon = np.nonzero(( lon [:]>= minLon ) & (lon [:]<= maxLon ))[0]
    return indexLat , indexLon