NCCOOS Trac Projects: Top | Web | Platforms | Processing | Viz | Sprints | Sandbox | (Wind)

root/raw2proc/trunk/raw2proc/ncutil.py

Revision 213 (checked in by haines, 16 years ago)

ncutil--added functions; proc2latest--moved to procutil; configs--added the computed mean_water_depth where measured and mean_water_depth_time_period

Line 
1 #!/usr/bin/env python
2 # Last modified:  Time-stamp: <2008-10-23 11:31:24 haines>
3 """
4 Create, update and load utilities for netcdf files
5 """
6
7 from pycdf import *
8 import os
9 import numpy
10
11 def nc_create(ncFile, (global_atts, var_atts, dim_inits, var_inits, var_data)):
12     """
13     Create new netcdf file
14
15     :Parameters:
16         ncFile : string
17            Path and name of file to create
18         (global_atts, var_atts, dim_inits, var_inits, var_data) : tuple
19            Global Attributes, Variable Attributes, Dimensions, Variable Dimensions, and Data
20            Everything you need to create a netCDF file.
21     """
22     try:
23         # Open new netCDF file, overwrite if it exists, create if does not
24         nc = CDF(ncFile, NC.WRITE|NC.CREATE|NC.TRUNC)
25         # Automatically set define and data modes.
26         nc.automode()
27         #
28         # GLOBALS
29         for attrName in global_atts.keys():
30             setattr(nc, attrName, global_atts[attrName])
31        
32         # DIMENSIONS
33         for dim in dim_inits:
34             dimName, dimValue = dim
35             # print '%s = %d' % (dimName, dimValue)
36             ncdim = nc.def_dim(dimName, dimValue)
37        
38         # VARIABLES
39         for var in var_inits:
40             varName, varType, varDim = var
41             ncvar = nc.def_var(varName, varType, varDim)
42             # add attributes
43             for attrName in var_atts[varName].keys():
44                 setattr(ncvar, attrName, var_atts[varName][attrName])
45             # setattr(ncvar, '_FillValue', numpy.nan)
46            
47         # add data
48         nrecs = nc.inq_unlimlen()
49         for var in var_data:
50             varName, varData = var
51             # print varName
52             ncvar = nc.var(varName)
53             # e.g. lat = array(var_data['lat'])
54             # if an array
55             if type(varData) == numpy.ndarray:
56                 if ncvar.isrecord():
57                     # time, ens, u, v
58                     ncvar[nrecs:nrecs+len(varData)] = varData.tolist()
59                 else:
60                     ncvar[:] = varData.tolist() # z
61             else:
62                 # if tuple, sequence or scalar
63                 ncvar[:] = varData
64        
65         nc.close()
66     except CDFError, msg:
67         print "CDFError:", msg
68         # if nc:
69         #     nc.close()
70         #     del(nc)
71
72 def nc_update(ncFile, (global_atts, var_atts, var_data)):
73     """
74     Create new netcdf file
75
76     :Parameters:
77         ncFile : string
78           Path and name of file to create
79         (global_atts, var_atts, var_data) : tuple
80           Global Attributes, Variable Attributes and Data
81           Everything you need to update a netCDF file.
82     """
83     try:
84         # Open netCDF in write mode
85         nc = CDF(ncFile, NC.WRITE)
86         # Automatically set define and data modes.
87         nc.automode()
88         #
89         # GLOBALS
90         for attrName in global_atts.keys():
91             setattr(nc, attrName, global_atts[attrName])
92        
93         # VARIABLES
94         # update attributes
95         for var in var_atts:
96             varName, atts = var
97             ncvar = nc.var(varName)
98             for attrName in atts.keys():
99                 setattr(ncvar, attrName, atts[attrName])
100            
101         # update data
102         nrecs = nc.inq_unlimlen()
103         for var in var_data:
104             varName, varData = var
105             ncvar = nc.var(varName)
106             # e.g. lat = array(var_data['lat'])
107             # if an array
108             if type(varData) == numpy.ndarray:
109                 if ncvar.isrecord():
110                     # time, ens, u, v (with unlimited dimension)
111                     ncvar[nrecs:nrecs+len(varData)] = varData.tolist()
112                 else:
113                     ncvar[:] = varData.tolist() # z (limited dimension)
114             else:
115                 # if tuple, sequence or scalar
116                 ncvar[:] = varData
117
118         nc.close()
119     except CDFError, msg:
120         print "CDFError:", msg
121         # if nc:
122         #     nc.close()
123         #     del(nc)
124
125 def nc_get_time(ncFile):
126     """Get time array from file """
127     try:
128         nc = CDF(ncFile)
129         ncvars = nc.variables()
130         if 'time' in ncvars.keys():
131             es = nc.var('time')[:]
132             units = nc.var('time').units
133         else:
134             print "time variable not found in ", ncFile
135         nc.close()
136         return (es, units)
137     except CDFError, msg:
138         print "CDFError:", msg
139
140                    
141 def nc_find_record_vars(ncFile):
142     """Find which variable are record variables"""
143     try:
144         nc = CDF(ncFile)
145         ncvars = nc.variables()
146         # list which variables is a record variable
147         var_list = [varName for varName in ncvars.keys() if nc.var(varName).isrecord()]
148         nc.close()
149         return var_list
150     except CDFError, msg:
151         print "CDFError:", msg
152                    
153
154 def nc_replace_fillvalue(ncFile, newfillvalue=-99999.0):
155     """
156     Replaces any occurrence of old _FillValue with new one
157
158     This function is useful for replacing the _FillValue global
159     attribute and then searching the data for the old value and
160     replacing it with the new one.
161
162     :Parameters:
163         ncFile : string
164           Path and name of file to create
165
166     :Other Parameters:
167         newfillvalue : type match to data (generally float)
168           By default is -99999.0
169    
170     """
171     try:
172         nc = CDF(ncFile, NC.WRITE)
173         nc.automode()
174         oldfillvalue = nc._FillValue
175         nc._FillValue = newfillvalue
176         for v in nc.variables().keys():
177             vd = nc.var(v)[:]
178             if numpy.isnan(oldfillvalue):
179                 idx = numpy.isnan(vd)
180             else:
181                 idx = vd == oldfillvalue
182             if idx.any():
183                 vd[idx] =  nc._FillValue
184                 nc.var(v)[:] = vd       
185         nc.close()
186     except CDFError, msg:
187         print "CDFError:", msg
188
189 def nc_rename_dimension(ncFile, oldname, newname):
190     """ Rename dimension name """
191     try:
192         nc = CDF(ncFile, NC.WRITE)
193         nc.definemode()
194         for d in nc.dimensions().keys():
195             if d==oldname: nc.dim(d).rename(newname)
196         nc.close()
197     except CDFError, msg:
198         print "CDFError:", msg
199                                
200
201 def nc_load(ncFile, varsLoad='all', nameType='variable_name',
202             ga_flag=True, va_flag=True):
203     """
204     Load netcdf file
205
206     :Parameters:
207         ncFile : string
208             Path and name of file to load
209
210     :Other Parameters:
211         nameType : string 'variable_name' (default) or 'standard_name'
212             Defines naming convention to use for variable names as data
213             are loaded.  Variable name is the name used to store data
214             in file.  'standard_name' means use variable name based on
215             variable attribute called 'standard_name' of netcdf variable.
216         varLoad : string or tuple of strings
217             specific variable names to be loaded into a sequence or scalar
218             in python following specification set in nameType
219             By default, all variables will be loaded.
220         ga_flag : boolean flag
221             By default, load the global file attributes
222         va_flag : boolean flag
223             By default, load the variable file attributes
224            
225     :Returns:
226         (global_atts, var_atts, dim_inits, var_inits, var_data) : tuple
227           Global Attributes, Variable Attributes, Dimensions, Variable Dimensions, and Variable Data
228           Everything you need to create a netCDF file.
229
230     """
231     try:
232         nc = CDF(ncFile, NC.NOWRITE)
233
234         ncdims = nc.dimensions(full=1)
235         ncvars = nc.variables()
236
237         # GLOBAL ATTRIBUTES (global_atts)
238         if ga_flag:
239             global_atts = nc.attributes()
240         else:
241             global_atts = {}
242
243         # DIMENSIONS (dim_inits)
244         dim_inits = [None for j in range(len(ncdims))]
245         if len(ncdims)>0:
246             for dimName,dimValue in ncdims.items():
247                 val,idx,isUN = dimValue
248                 if isUN:
249                     dim_inits[idx] = (dimName, NC.UNLIMITED)
250                 else:
251                     dim_inits[idx] = (dimName, val)
252
253         if varsLoad == 'all':
254             varNames = ncvars.keys()
255         else:
256             varNames = varsLoad
257
258         # VARIABLE DIMENSIONS (var_inits)
259         # gets init info for requested variables and original order
260
261         # initialize with same number of original variables
262         # so order can be preserved by idx
263         var_inits = [None for j in range(len(ncvars))]
264         if len(ncvars)>0:
265             for varName in varNames:
266                     val,shape,typ,idx = ncvars[varName]
267                     var_inits[idx] = (varName, typ, val)
268
269         # remove the None values from the list to preserve original order
270         var_inits = [v for v in var_inits if v != None]
271        
272         # VARIABLE ATTRIBUTES (var_atts)
273         # gets attributes of requested variables
274         var_atts = {}
275         if len(ncvars)>0 and va_flag:
276             for var in varNames:
277                 varAttrs = nc.var(var).attributes()
278                 var_atts[var] = varAttrs
279
280         # VARIABLE DATA (var_data)
281         # loads requested variables, original order preserved as with var_inits
282         var_data = [None for j in range(len(ncvars))]
283         if len(ncvars)>0:
284             for varName in varNames:
285                 val,shape,typ,idx = ncvars[varName]
286                 var_data[idx] = (varName, nc.var(varName)[:])
287
288         var_data = [v for v in var_data if v != None]
289
290         # type cast lists into tuples
291         dim_inits = tuple(dim_inits)
292         var_inits = tuple(var_inits)
293         var_data = tuple(var_data)
294
295         nc.close()
296         return (global_atts, var_atts, dim_inits, var_inits, var_data)
297        
298     except CDFError, msg:
299         print "CDFError:", msg
300
301        
Note: See TracBrowser for help on using the browser.