Changeset 3329
- Timestamp:
- 08/02/08 20:03:02 (12 years ago)
- Location:
- nappy/trunk/nappy/nc_interface
- Files:
-
- 1 added
- 1 deleted
- 1 moved
Legend:
- Unmodified
- Added
- Removed
-
nappy/trunk/nappy/nc_interface/cdms_to_na.py
r3321 r3329 4 4 # Q Public License, version 1.0 or later. http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt 5 5 6 helpMessage="""7 8 cdms2na.py9 ==========10 11 Converts a CdmsFile object into one a NASA Ames file.12 13 Usage14 =====15 16 cdms2na.py [<options>] -i <infilename> -o <outfilename>17 18 Where19 -----20 21 infilename - name of input file (NetCDF).22 outfilename - name of output file (NASA Ames).23 options - list of options.24 25 6 """ 7 cdms_to_na.py 8 ============= 9 10 Holds the class CDMSToNA that converts a set of CDMS variables and global attributes. 11 12 """ 26 13 27 14 # Imports from python standard library 28 import sys, os, time, string, fileinput, re 29 if len(sys.argv)>0: 30 sys.path.append(os.path.join("..", "..")) 31 sys.path.append("..") 32 33 # Import cdat modules 34 if sys.platform.find("win")>-1: 35 pass 36 else: 37 import cdms, cdtime, Numeric 38 # Define cdms variables 39 cdms.setAutoBounds("off") 40 41 # Import nappy modules 42 import cdmsMap 43 import version 44 import general 45 import localRules 46 from naCore import * 47 from naError import * 48 49 50 # Set up functions 51 def compareAxes(ax1, ax2): 52 """ 53 Takes 2 cmds axis objects returning 1 if they are essentially 54 the same and 0 if not. 55 """ 56 for axtype in ("time", "level", "latitude", "longitude"): 57 if cdms.axisMatches(ax1, axtype) and not cdms.axisMatches(ax2, axtype): 58 return 0 59 60 # Check ids 61 if ax1.id!=ax2.id: return 0 62 # Check lengths 63 if len(ax1)!=len(ax2): return 0 64 # Check values 65 if ax1._data_!=ax2._data_: return 0 66 # Check units 67 if ax1.units!=ax2.units: return 0 68 # OK, I think they are the same axis! 69 return 1 70 71 72 def compareVariables(var1, var2): 73 """ 74 Compares two cdms variables to see if they are defined on identical 75 axes. Returns 1 if true, 0 if not. 76 """ 77 try: 78 for i in range(len(var1.getAxisList())): 79 ax1=var1.getAxis(i) 80 ax2=var2.getAxis(i) 81 if compareAxes(ax1, ax2)==0: 82 return 0 83 except: 84 return 0 85 return 1 15 import sys 16 import os 17 import time 18 import string 19 import re 20 21 # Import from nappy package 22 from nappy.na_error import na_error 23 import nappy.utils 24 import nappy.utils.common_utils 25 import nappy.na_file.na_core 26 27 28 nc_to_na_map = utils.getConfigDict()["nc_to_na_map"] 29 30 # Import external packages (if available) 31 if sys.platform.find("win") > -1: 32 raise na_error.NAPlatformError("Windows does not support CDMS. CDMS is required to convert to CDMS objects and NetCDF.") 33 try: 34 import cdms, Numeric 35 except: 36 raise Exception("Could not import third-party software. Nappy requires the CDMS and Numeric packages to be installed to convert to CDMS and NetCDF.") 37 38 cdms.setAutoBounds("off") 39 40 compareAxes = nappy.cdms_utils.axis_utils.compareAxes 41 compareVariables = nappy.cdms_utils.var_utils.compareVariables 42 arrayToList = nappy.utils.list_manipulator.arrayToList 43 listOfListsCreator = nappy.utils.list_manipulator.listOfListsCreator 86 44 87 45 … … 98 56 99 57 100 def arrayToList(array, inlist): 101 """ 102 Takes an n-dimensional Numeric array and converts it to an 103 n-dimensional list object. 104 """ 105 dimlist=array.shape 106 if len(dimlist[1:])>0: 107 for i in range(dimlist[0]): 108 arrayToList(inlist[i], array[i]) 109 else: 110 for i in range(dimlist[0]): 111 inlist.append(array[i]) 112 return inlist 113 114 115 def listOfListsCreator(inlist, dimlist): 116 """ 117 Creates a list of lists with dimensions defined in dimlist (a list of integers). 118 """ 119 if len(dimlist[1:])>0: 120 for i in range(dimlist[0]): 121 inlist.append([]) 122 listOfListsCreator(inlist[i], array, dimlist[1:]) 123 return inlist 124 125 126 def getBestName(var): 127 """ 128 Returns the most appropriate variable name for a NASA Ames header 129 """ 130 name=None 131 if hasattr(var, "id"): name=var.id 132 if hasattr(var, "shortname"): name=var.short_name 133 if hasattr(var, "name"): name=var.name 134 if hasattr(var, "title"): name=var.title 135 if hasattr(var, "standard_name"): name=var.standard_name 136 if hasattr(var, "long_name"): name=var.long_name 137 #if hasattr(var, "standard_name"): name=var.standard_name 138 139 if hasattr(var, "has_key"): 140 if var.has_key("id"): name=var["id"] 141 if var.has_key("short_name"): name=var["short_name"] 142 if var.has_key("name"): name=var["name"] 143 if var.has_key("title"): name=var["title"] 144 if var.has_key("standard_name"): name=var["standard_name"] 145 if var.has_key("long_name"): name=var["long_name"] 146 #if var.has_key("standard_name"): name=var["standard_name"] 147 148 if hasattr(var, "units") and not re.match("^\s+$", var.units): 149 units=var.units.strip() 150 name="%s (%s)" % (name, units) 151 # Do a check to see units are not duplicated 152 # [The regex below failed because it interpreted 'm**2' as 153 # regex characters] 154 #match=re.match("(.*\(%s\)\s*)\(%s\)(.*)$" % (var.units, var.units), name) 155 #if match: 156 # name=match.groups()[0]+match.groups()[1] 157 if name.count("(%s)" % units)>1: 158 name=name.replace("(%s)" % units, "") 159 name="%s (%s)" % (name, units) 160 161 if name[-2:]=="()": name=name[:-2] 162 return name 163 164 165 def getMissingValue(var): 166 """ 167 Returns the missing value or defaults to 1.E20. 168 """ 169 miss=None 170 if hasattr(var, "missing_value"): miss=var.missing_value 171 if hasattr(var, "_fill_value"): miss=var._fill_value 172 # if hasattr(var, "fill_value"): miss=var.fill_value # returns an array???? 173 if hasattr(var, "_FillValue"): miss=var._FillValue 174 if miss==None: 175 try: 176 miss=var.getMissing() 177 except: 178 miss=1.E20 179 return miss 180 181 182 def fixHeaderLengthNowDefunct(file): 183 """ 184 Fixes length of header. 185 """ 186 lines=open(file).readlines()[:200] 187 count=0 188 for line in lines: 189 count=count+1 190 if line=="###Data Section begins on the next line###\n": 191 break 192 # Now replace 1st line NLHEAD with count 193 firstline=lines[0] 194 newline="%s %s" % (count, firstline.split()[-1]) 195 for line in fileinput.input(file, inplace=1): 196 if line==firstline: 197 # write the changed line 198 sys.stdout.write(newline+"\n") 199 else: 200 # write the line unchanged 201 sys.stdout.write(line) 202 203 def flatten2DTimeData(var, timevar): 204 """ 205 Returns a flattened 2D array variable with a recalculated time axies. 206 """ 207 import MV, cdtime 208 data=MV.ravel(var) 209 missing=var.getMissing() 210 211 timevalues=timevar._data 212 timeunit=timevar.units 213 samprate=var.getAxis(1) 214 rate=int(samprate.id[3:]) 215 newTimeValues=[] 216 217 for t in timevalues: 218 for i in range(rate): 219 tvalue=t+((1./rate)*i) 220 newTimeValues.append(tvalue) 221 222 newTimeAx=cdms.createAxis(newTimeValues) 223 newTimeAx.units=timeunit 224 newTimeAx.designateTime() 225 newTimeAx.id=newTimeAx.long_name=newTimeAx.standard_name="time" 226 227 atts=var.attributes 228 newAtts={} 229 for att,value in atts.items(): 230 if type(value) in (type((1,1)), type([1,2]), type(Numeric.array([1.]))) and len(value)==1: 231 value=value[0] 232 if type(value) in (type(1), type(1.), type(long(1))): 233 newAtts[att]=value 234 elif type(value)==type(""): 235 newAtts[att]=value.strip() 236 237 # Now create the variable 238 newvar=cdms.createVariable(data, id=var.id, fill_value=missing, axes=[newTimeAx], attributes=newAtts) 239 return newvar 240 241 242 def modifyNADictCopy(indict, v_new, start, end, ivol, nvol): 243 """ 244 Returns a copy of a dictionary with some modifications. 245 """ 246 newDict={} 247 for key,value in indict.items(): 248 if key=="X": 249 newlist=indict["X"][start:end] 250 newDict["X"]=newlist 251 elif key=="V": 252 newDict["V"]=v_new 253 elif key=="IVOL": 254 newDict["IVOL"]=ivol 255 elif key=="NVOL": 256 newDict["NVOL"]=nvol 257 else: 258 newDict[key]=value 259 return newDict 260 261 262 def cdms2na(infilename, outfilenames, naVars={}, variables=None, nFilesOnly="no", 58 getBestName = nappy.cdms_utils.var_utils.getBestName 59 getMissingValue = nappy.cdms_utils.var_utils.getMissingValue 60 flatten2DTimeAxis = nappy.contrib.aircraft.aircraft_utils.flatten2DTimeAxis 61 modifyNADictCopy = nappy.utils.common_utils.modifyNADictCopy 62 63 64 65 GOT HERE GOT HERE GOT HERE GOT HERE 66 67 68 def cdms2na(ncfile, na_file_names, naVars={}, variables=None, nFilesOnly="no", 263 69 rule=None, ffi="automatic", spacer=" ", floatFormat="%g", 264 70 rules=None, sizeLimit=None): … … 268 74 """ 269 75 #print infilename, outfilenames, nFilesOnly, naVars, variables 270 if type(outfilenames)==type(""): outfilenames=[outfilenames] 76 if type(na_file_names) == type("string"): 77 na_file_names = [na_file_names] 271 78 272 allowedOverwriteMetadata=["DATE", "RDATE", "ANAME", "MNAME", 273 "ONAME", "ORG", "SNAME", "VNAME"] 79 # Get which NASA Ames internal variables are allowed to be overwritten in the output files (i.e. by user inputs) 80 allowedOverwriteMetadata = ("DATE", "RDATE", "ANAME", "MNAME", 81 "ONAME", "ORG", "SNAME", "VNAME") 274 82 arrayArgs=["DATE", "RDATE", "ANAME", "VNAME"] 275 83 # ANAME[a] - array of 'a' x ANAME strings - aux var names
Note: See TracChangeset
for help on using the changeset viewer.