Scientific Python

_images/python-logo.gif _images/scipy-logo.gif _images/matplotlib-logo.png

Why Python & SciPy?

  • Free and open source, no commercial license constraints
  • Large and stable community
  • Fully featured programming language, truly object oriented
  • Very powerful & flexible
  • Favor readable code
  • Publication quality figure ploting
  • Easily read/write netcdf and grib data
  • Easily work with Fortran/C/C++
  • Wide library support for both numerical & non-numerical work

[from Ivan Lima’s presentation]


[from matplotlib/BaseMap example]

Read NetCDF file with doesn’s support writes at present and can only read NetCDF 3 files. To read a NetCDF file:

from import netcdf

f = netcdf.netcdf_file('', 'r')
print f.history
time = f.variables['time']
print time.units
print time.shape
print time[:]

Read/Write NetCDF file with Scientific.IO.NetCDF

To create a NetCDF file:

from Scientific.IO.NetCDF import NetCDFFile
import numpy as np

f = NetCDFFile('', 'w')

# dimension
f.createDimension('time', 12)

# variable
time = f.createVariable('time', 'd', ('time',))

# data
time[:] = np.random.uniform(size=12)


To read the file:

from Scientific.IO.NetCDF import NetCDFFile
import matplotlib.pyplot as plt

f = NetCDFFile('')
fig = plt.figure()
ax = fig.add_subplot(111)

Read/Write NetCDF file with netcdf4-python

To create a NetCDF file:

from netCDF4 import Dataset
import numpy as np

root_grp = Dataset('', 'w', format='NETCDF4')
root_grp.description = 'Example temperature data'

# dimensions
root_grp.createDimension('time', None)
root_grp.createDimension('lat', 72)
root_grp.createDimension('lon', 144)

# variables
times = root_grp.createVariable('time', 'f8', ('time',))
latitudes = root_grp.createVariable('latitude', 'f4', ('lat',))
longitudes = root_grp.createVariable('longitude', 'f4', ('lon',))
temp = root_grp.createVariable('temp', 'f4', ('time', 'lat', 'lon',))

# data
lats =  np.arange(-90, 90, 2.5)
lons =  np.arange(-180, 180, 2.5)
latitudes[:] = lats
longitudes[:] = lons
for i in range(5):
    temp[i,:,:] = np.random.uniform(size=(len(lats), len(lons)))

# group
# my_grp = root_grp.createGroup('my_group')


To read the file:

from netCDF4 import Dataset
import pylab as pl

root_grp = Dataset('')

temp = root_grp.variables['temp']

for i in range(len(temp)):
    raw_input('Press enter.')

Read/Write Grib files with pygrib

To read a Grib file:

import pygrib

grbs ='sampledata/flux.grb')
grb =[0]
print grb
grb ='Maximum temperature')[0]

To write a Grib file:

import pygrib

grbout = open('test.grb','wb')

Read/Write Matlab .mat file

To read a .mat file:

import as sio

mat_contents = sio.loadmat('data.mat')
print mat_contents

To write a .mat file:

import numpy as np
import as sio

vect = np.arange(10)
print vect.shape
sio.savemat('data.mat', {'vect':vect})