source: trunk/UTIL/PYTHON/make_netcdf.py @ 394

Last change on this file since 394 was 379, checked in by acolaitis, 14 years ago

Fixed a rare but annoying conflict occuring when calling make_gcm_netcdf with a time dimension which length is equal to longitude/or/latitude/or/altitude

File size: 4.2 KB
Line 
1### A. Colaitis -- LMD -- 11/11/2011
2
3def make_gcm_netcdf (zfilename="filename.nc", \
4                     zdescription=None, \
5                     zlon=None, \
6                     zlat=None, \
7                     zalt=None, \
8                     ztime=None, \
9                     zvariables=None, \
10                     znames=None):
11
12   from os import system
13   from netCDF4 import Dataset
14   import numpy as np
15
16#####################
17## Run some checks ##
18#####################
19
20# Number of variables and number of variables' names
21
22   nvar = len(zvariables)
23   nnames = len(znames)
24
25   if nnames < nvar:
26      print "not enough variables name specified, using automatic labbeling"
27      i=0
28      zznames=[[]]*nvar
29      for zvar in zvariables:
30          zznames[i]="var"+np.string(i+1)
31          i=i+1
32   
33   elif nnames > nvar:
34      print "Warning, more variables than names are specified."
35      i=0
36      zznames=[[]]*nvar
37      for zvar in zvariables:
38          zznames[i]=znames[i]
39          i=i+1
40   else:
41      zznames=znames[:]
42   
43   # Dimensions
44   
45   nx,ny,nz,nt = 0,0,0,0
46   
47   if zlon is not None:
48      nx=len(zlon)
49   if zlat is not None:
50      ny=len(zlat)
51   if zalt is not None:
52      nz=len(zalt)
53   if ztime is not None:
54      nt=len(ztime)
55   
56   zdims={}
57   zdims['longitude']=nx
58   zdims['latitude']=ny
59   zdims['altitude']=nz
60   zdims['Time']=nt
61   print zdims
62   # Find which variable uses which dimensions
63   
64   i=0
65   zvarcarac={}
66   for zvar in zvariables:
67       zvardim=np.array(zvar).shape
68       ndim=len(zvardim)
69       zzvardim=[[]]*ndim
70       j=0
71       for dim in zvardim:
72           if dim not in zdims.values():
73              print "WARNING -----------------------------"
74              print "Dimensions given to subroutine do not match variables dimensions :"
75              print "Dimensions: ",zdims
76              print "Variable: ",zznames[i],", dimensions: ",zvardim
77              print " PROGRAM EXIT"
78              exit()
79           else:
80              a=get_key(zdims,dim)
81              if len(a) is not 1:
82                 if j is 0:                ##this should solve most conflicts with Time
83                    zzvardim[j]=a[1]
84                 else:
85                    zzvardim[j]=a[0]
86              else:
87                 zzvardim[j]=a[0]
88              j=j+1
89       zvarcarac[zznames[i]]=zzvardim
90       i=i+1
91   print zvarcarac 
92 
93   #########################
94   ## Clean previous file ##
95   #########################
96   
97   system("rm -f "+zfilename)
98   
99   ## Open file
100   file = Dataset(zfilename, 'w', format='NETCDF3_64BIT') #netcdf4 does not work with ncview and ncdump yet
101   if zdescription is not None:
102      file.description = zdescription
103   ## Dimensions
104   if ztime is not None:
105      file.createDimension('Time', None)
106   if zalt is not None:
107      file.createDimension('altitude',nz)
108   if zlat is not None:
109       file.createDimension('latitude',ny)
110   if zlon is not None:
111      file.createDimension('longitude',nx)
112   ## Variables for dimensions & Data assignment
113   if ztime is not None:
114      times = file.createVariable('Time', 'f', ('Time',))
115      times[:] = ztime[:]
116   if zalt is not None:
117      altitudes = file.createVariable('altitude', 'f', ('altitude',))
118      altitudes[:] = zalt[:]
119   if zlat is not None:
120      latitudes = file.createVariable('latitude', 'f', ('latitude',))
121      latitudes[:] = zlat[:]
122   if zlon is not None:
123      longitudes = file.createVariable('longitude', 'f', ('longitude',))
124      longitudes[:] = zlon[:]
125   ## Other Variables Creation & Data assignment
126   i=0
127   for name in zznames:
128       za = file.createVariable(name, 'f', tuple(zvarcarac[name]))
129       if len(zvarcarac[name]) is 1:
130          za[:] = zvariables[i][:]
131       elif len(zvarcarac[name]) is 2:
132          za[:,:] = zvariables[i][:,:]
133       elif len(zvarcarac[name]) is 3:
134          za[:,:,:] = zvariables[i][:,:,:]
135       elif len(zvarcarac[name]) is 4:
136          za[:,:,:,:] = zvariables[i][:,:,:,:]
137       i=i+1
138   ## close file
139   file.close()
140
141def find_key(dic, val):
142    """return the key of dictionary dic given the value"""
143    return [k for k, v in dic.iteritems() if v == val][0]
144
145def get_key(self, value):
146    """find the key(s) as a list given a value"""   
147    return [item[0] for item in self.items() if item[1] == value]
Note: See TracBrowser for help on using the repository browser.