1
2
3
4
5
6
7
8
9 '''
10 FILENAME:
11 ncreader.py
12
13 DESCRIPTION:
14 Introduction to various python objects
15 Python Seminar 13.09.2012
16
17 Sample ncfile "../Nio/sresa1b_ncar_ccsm3_0_run1_200001.nc
18
19 '''
20
21
22
23
24
25
26 __author__ = "A. U. Thor"
27 __version__ = "0.0"
28 __date__ = "0000/00/00"
29
30
31 import sys
32 import os
33 from optparse import OptionParser
34 import Nio
35 import numpy as np
36 import matplotlib.pyplot as plt
37 import pdb
38 import cPickle as cP
39
40
41
42
43 class NcReader:
44
45 ''' As an example, this particular Class is basically
46 a set of convenience functions that are meant
47 to speed up some of your routine work with NetCDF files '''
48
49 def __init__(self, file_path):
50 ''' Initialize object '''
51 self.fpath = file_path
52 self.ncfile = Nio.open_file(self.fpath)
53 self.variables = self.ncfile.variables
54
55 def printVars(self):
56 ''' prints variables dictionary '''
57 for i in self.variables:
58 print i
59
60 def plotVar(self, var_name):
61 ''' plots single 1d variable '''
62 variable = self.ncfile.variables[var_name][:]
63 plt.plot(variable)
64 plt.show()
65
66 def plot2dVar(self, *args, **kwargs):
67 '''plots multiple 2d variables '''
68
69
70
71
72 for i in args:
73 try:
74 var = self.variables[i]
75 print var[:].shape
76 plt.imshow(self.variables[i][0,:])
77 except:
78 raise
79
80 if kwargs['colorbar'] == True:
81 plt.colorbar()
82 plt.show()
83
84
85
86
87
88
89 def parse_options():
90
91 ''' Parse command line options and arguments '''
92
93 usage = "usage: %prog [options] <input_files>";
94 version = "%prog 0.1"
95 parser = OptionParser(usage)
96
97 parser.add_option("-d", "--pdb_switch", dest = 'pdb_switch',
98 action = "store_true", default = "False")
99 parser.add_option("-i", "--input_file", dest = 'input_file')
100
101 (options, args) = parser.parse_args()
102
103 return (options, args)
104
105
106
107
108
109
110 def main():
111
112 options, arguments = parse_options()
113
114 input_file = options.input_file
115
116 variables = arguments[:]
117
118 a = NcReader(input_file)
119 a.printVars()
120
121
122
123 a.plotVar('plev')
124 a.plot2dVar(*variables, colorbar = True)
125
126
127 pdb_switch = options.pdb_switch
128
129
130
131
132
133 if __name__ == "__main__":
134 main()
LehreWiki: PythonCourse/PythonLES/SeminarLog5 (last edited 2012-09-13 00:22:20 by MikhailItkin)