Friday, February 7, 2014

[Pygrads] Basic functions

Python-grads interface is exactly what I want.
Hopefully, I will discuss time module operations in next blog. Here we go!

First things first: install pygrads version: 1.1.8
First step: import libraries
#Libraries
import grads
import matplotlib.pyplot as plt
import numpy as np

# start grads
ga = grads.GrADS()
# or
#ga = grads.GrADS(Bin='grads',Window=False,Echo=False)

Second step: open files in GrADS thru python
# open control file
ctl_file = 'home/computer/usr/filename.nc'
ga('sdfopen' + ctl_file)

# display data
ga.imshow('variable.1(t=400)', interpolation = 'nearest')
plt.show()

Third step: import data into python
# import data
data = ga.exp('variable.1(t=1)')
# extract grid information
ga('set t 1 last')
info = ga.coords()
nt = len(info.time)
nlat = len(info.lat)
nlon = len(info.lon)
print info
print nt, nlat, nlon


Basic operations:
asum = np.sum(data)
amean = np.mean(data)
astd = np.std(data)
print(asum,amean,astd)

# extract data for a single point in the domain
ga('set x 100')
ga('set y 100')
ga('set t 1 last')
data = ga.eval('dataname.1')

# calculate areal mean over multiple time series
ga('set t 1')
mean_vals = []
for t in xrange(0,nt):
     data = ga.exp('dataname.1(t=' + str(t+1) + ')') # python和grads里面的index初始值不一样
     mean_vals.append(np.mean(data))

# plot the data
plt.plot(data)
plt.show()





No comments:

Post a Comment