source: trunk/UTIL/PYTHON/mcd/mcd.py @ 827

Last change on this file since 827 was 827, checked in by aslmd, 12 years ago

PYTHON UTIL mcd interface. few improvements: set bounds, set better resolution for figs, address Steve remarks.

  • Property svn:executable set to *
File size: 39.2 KB
Line 
1####################################################
2### A Python Class for the Mars Climate Database ###
3### ---------------------------------------------###
4### Aymeric SPIGA 17-21/04/2012                  ###
5### ---------------------------------------------###
6### (see mcdtest.py for examples of use)         ###
7####################################################
8
9import numpy as np
10import fmcd
11import matplotlib.pyplot as mpl
12import myplot
13
14
15class mcd():
16 
17    def __repr__(self):
18    # print out a help string when help is invoked on the object
19        whatprint = 'MCD object. \"help(mcd)\" for more information\n'
20        return whatprint
21
22########################
23### Default settings ###
24########################
25
26    def __init__(self):
27    # default settings
28        ## 0. general stuff
29        self.name      = "MCD v4.3"
30        self.ack       = "Mars Climate Database (c) LMD/OU/IAA/ESA/CNES"
31        #self.dset      = '/home/aymeric/Science/MCD_v4.3/data/'
32        self.dset      = '/home/marshttp/MCD_v4.3/data/'
33        ## 1. spatio-temporal coordinates
34        self.lat       = 0.
35        self.lats      = None
36        self.late      = None
37        self.lon       = 0.
38        self.lons      = None
39        self.lone      = None
40        self.loct      = 0.
41        self.locts     = None
42        self.locte     = None
43        self.xdate     = 0.  # see datekey
44        self.xdates    = None
45        self.xdatee    = None
46        self.xz        = 10. # see zkey
47        self.xzs       = None
48        self.xze       = None
49        ## 1bis. related settings
50        self.zkey      = 3  # specify that xz is the altitude above surface (m)
51                            # zkey  : <integer>   type of vertical coordinate xz
52                            # 1 = radius from centre of planet (m)
53                            # 2 = height above areoid (m) (MOLA zero datum)
54                            # 3 = height above surface (m)
55                            # 4 = pressure level (Pa)
56                            # 5 = altitude above mean Mars Radius(=3396000m) (m)
57        self.datekey   = 1  # 0 = "Earth time": xdate is given in Julian days (localtime must be set to zero)
58                            # 1 = "Mars date": xdate is the value of Ls
59        ## 2. climatological options
60        self.dust      = 2  #our best guess MY24 scenario, with solar average conditions
61        self.hrkey     = 1  #set high resolution mode on (hrkey=0 to set high resolution off)
62        ## 3. additional settings for advanced use
63        self.extvarkey = 1  #extra output variables (1: yes, 0: no)
64        self.perturkey = 0  #integer perturkey ! perturbation type (0: none)
65        self.seedin    = 1  #random number generator seed (unused if perturkey=0)
66        self.gwlength  = 0. #gravity Wave wavelength (unused if perturkey=0)
67        ## outputs. just to define attributes.
68        ## --> in update
69        self.pres = None ; self.dens = None ; self.temp = None ; self.zonwind = None ; self.merwind = None ; self.meanvar = None ; self.extvar = None
70        self.seedout = None ; self.ierr = None
71        ## --> in prepare
72        self.xcoord = None ; self.ycoord = None
73        self.prestab = None ; self.denstab = None ; self.temptab = None 
74        self.zonwindtab = None ; self.merwindtab = None ; self.meanvartab = None ; self.extvartab = None
75        ## plot stuff
76        self.xlabel = None ; self.ylabel = None ; self.title = ""
77        self.vertplot = False
78        self.fmt = "%.2e" 
79        self.colorm = "jet"
80        self.fixedlt = False
81        self.zonmean = False
82        self.min2d = None
83        self.max2d = None
84        self.dpi = 80.
85
86    def viking1(self): self.name = "Viking 1 site. MCD v4.3 output" ; self.lat = 22.48 ; self.lon = -49.97 ; self.xdate = 97.
87    def viking2(self): self.name = "Viking 2 site. MCD v4.3 output" ; self.lat = 47.97 ; self.lon = -225.74 ; self.xdate = 117.6
88
89    def getdustlabel(self):
90        if self.dust == 1: self.dustlabel = "MY24 minimum solar scenario"
91        elif self.dust == 2: self.dustlabel = "MY24 average solar scenario"
92        elif self.dust == 3: self.dustlabel = "MY24 maximum solar scenario"
93        elif self.dust == 4: self.dustlabel = "dust storm minimum solar scenario"
94        elif self.dust == 5: self.dustlabel = "dust storm average solar scenario"
95        elif self.dust == 6: self.dustlabel = "dust storm maximum solar scenario"
96        elif self.dust == 7: self.dustlabel = "warm scenario (dusty, maximum solar)"
97        elif self.dust == 8: self.dustlabel = "cold scenario (low dust, minimum solar)"
98
99    def gettitle(self,oneline=False):
100        self.getdustlabel()
101        self.title = self.name + " with " + self.dustlabel + "."
102        if self.datekey == 1:    self.title = self.title + " Ls " + str(self.xdate) + "deg."
103        elif self.datekey == 0:  self.title = self.title + " JD " + str(self.xdate) + "."
104        if not oneline: self.title = self.title + "\n"
105        if self.lats is None:  self.title = self.title + " Latitude " + str(self.lat) + "N"
106        if self.zonmean and self.lats is not None and self.xzs is not None: 
107            self.title = self.title + "Zonal mean over all longitudes."
108        elif self.lons is None: 
109            self.title = self.title + " Longitude " + str(self.lon) + "E"
110        if self.xzs is None:   
111            self.vertunits()
112            self.title = self.title + " Altitude " + str(self.xz) + " " + self.vunits
113        if self.locts is None:
114            self.title = self.title + " Local time " + str(self.loct) + "h"
115            if not self.fixedlt:  self.title = self.title + " (at longitude 0) "
116
117    def getextvarlab(self,num):
118        whichfield = { \
119        91: "Pressure (Pa)", \
120        92: "Density (kg/m3)", \
121        93: "Temperature (K)", \
122        94: "W-E wind component (m/s)", \
123        95: "S-N wind component (m/s)", \
124        1: "Radial distance from planet center (m)",\
125        2: "Altitude above areoid (Mars geoid) (m)",\
126        3: "Altitude above local surface (m)",\
127        4: "orographic height (m) (surf alt above areoid)",\
128        5: "Ls, solar longitude of Mars (deg)",\
129        6: "LST local true solar time (hrs)",\
130        7: "Universal solar time (LST at lon=0) (hrs)",\
131        8: "Air heat capacity Cp (J kg-1 K-1)",\
132        9: "gamma=Cp/Cv Ratio of specific heats",\
133        10: "density RMS day to day variations (kg/m^3)",\
134        11: "[not defined]",\
135        12: "[not defined]",\
136        13: "scale height H(p) (m)",\
137        14: "GCM orography (m)",\
138        15: "surface temperature (K)",\
139        16: "daily max mean surface temperature (K)",\
140        17: "daily min mean surface temperature (K)",\
141        18: "surf. temperature RMS day to day variations (K)",\
142        19: "surface pressure (high resolution if hireskey=1)",\
143        20: "GCM surface pressure (Pa)",\
144        21: "atmospheric pressure RMS day to day variations (Pa)",\
145        22: "surface pressure RMS day to day variations (Pa)",\
146        23: "temperature RMS day to day variations (K)",\
147        24: "zonal wind RMS day to day variations (m/s)",\
148        25: "meridional wind RMS day to day variations (m/s)",\
149        26: "vertical wind component (m/s) >0 when downwards!",\
150        27: "vertical wind RMS day to day variations (m/s)",\
151        28: "small scale perturbation (gravity wave) (kg/m^3)",\
152        29: "q2: turbulent kinetic energy (m2/s2)",\
153        30: "[not defined]",\
154        31: "thermal IR flux to surface (W/m2)",\
155        32: "solar flux to surface (W/m2)",\
156        33: "thermal IR flux to space (W/m2)",\
157        34: "solar flux reflected to space (W/m2)",\
158        35: "surface CO2 ice layer (kg/m2)",\
159        36: "DOD: Dust column visible optical depth",\
160        37: "Dust mass mixing ratio (kg/kg)",\
161        38: "DOD RMS day to day variations",\
162        39: "DOD total standard deviation over season",\
163        40: "Water vapor column (kg/m2)",\
164        41: "Water vapor vol. mixing ratio (mol/mol)",\
165        42: "Water ice column (kg/m2)",\
166        43: "Water ice mixing ratio (mol/mol)",\
167        44: "O3 ozone vol. mixing ratio (mol/mol)",\
168        45: "[CO2] vol. mixing ratio (mol/mol)",\
169        46: "[O] vol. mixing ratio (mol/mol)",\
170        47: "[N2] vol. mixing ratio (mol/mol)",\
171        48: "[CO] vol. mixing ratio (mol/mol)",\
172        49: "R: Molecular gas constant (J K-1 kg-1)",\
173        50: "Air viscosity estimation (N s m-2)"
174        }
175        if num not in whichfield: myplot.errormess("Incorrect subscript in extvar.")
176
177        dastuff = whichfield[num]
178 
179        if "(K)" in dastuff:      self.fmt="%.0f"
180        elif "(Pa)" in dastuff:   self.fmt="%.1f"
181        elif "(W/m2)" in dastuff: self.fmt="%.0f"
182        elif "(m/s)" in dastuff:  self.fmt="%.1f"
183        else:                     self.fmt="%.2e"
184
185        return dastuff
186
187    def convertlab(self,num):       
188        ## a conversion from text inquiries to extvar numbers. to be completed.
189        if num == "p": num = 91
190        elif num == "rho": num = 92
191        elif num == "t": num = 93
192        elif num == "u": num = 94
193        elif num == "v": num = 95
194        elif num == "tsurf": num = 15
195        elif num == "topo": num = 4
196        elif num == "h": num = 13
197        elif num == "ps": num = 19
198        elif num == "tau": num = 36
199        elif num == "mtot": num = 40
200        elif num == "icetot": num = 42
201        elif num == "ps_ddv": num = 22
202        elif num == "h2ovap": num = 41
203        elif num == "h2oice": num = 43
204        elif num == "cp": num = 8
205        elif num == "rho_ddv": num = 10
206        elif num == "tsurfmx": num = 16
207        elif num == "tsurfmn": num = 17
208        elif num == "lwdown": num = 31
209        elif num == "swdown": num = 32
210        elif num == "lwup": num = 33
211        elif num == "swup": num = 34
212        elif num == "o3": num = 44
213        elif num == "o": num = 46
214        elif num == "co": num = 48
215        elif num == "visc": num = 50
216        elif num == "co2ice": num = 35
217        elif not isinstance(num, np.int): myplot.errormess("field reference not found.")
218        return num
219
220###################
221### One request ###
222###################
223
224    def update(self):
225    # retrieve fields from MCD (call_mcd). more info in fmcd.call_mcd.__doc__
226        ## sanity first
227        self.loct = abs(self.loct)%24
228        if self.locts is not None and self.locte is not None: 
229            self.locts = abs(self.locts)%24
230            self.locte = abs(self.locte)%24
231            if self.locts == self.locte: self.locte = self.locts + 24
232        if self.lat > 90.: self.lat = 90.
233        if self.lat < -90.: self.lat = -90.
234        if self.lats is not None and self.late is not None:
235            if abs(self.lats) > 90.: self.lats = 90.
236            if abs(self.late) > 90.: self.late = 90.
237            if abs(self.lats) < -90.: self.lats = -90.
238            if abs(self.late) < -90.: self.late = -90.
239        ## now MCD request
240        (self.pres, self.dens, self.temp, self.zonwind, self.merwind, \
241         self.meanvar, self.extvar, self.seedout, self.ierr) \
242         = \
243         fmcd.call_mcd(self.zkey,self.xz,self.lon,self.lat,self.hrkey, \
244             self.datekey,self.xdate,self.loct,self.dset,self.dust, \
245             self.perturkey,self.seedin,self.gwlength,self.extvarkey )
246        ## we use the end of extvar (unused) to store meanvar. this is convenient for getextvar(lab)
247        self.extvar[90] = self.pres ; self.extvar[91] = self.dens
248        self.extvar[92] = self.temp ; self.extvar[93] = self.zonwind ; self.extvar[94] = self.merwind
249        ## treat missing values
250        if self.temp == -999: self.extvar[:] = np.NaN ; self.meanvar[:] = np.NaN
251
252    def printset(self):
253    # print main settings
254        print "zkey",self.zkey,"xz",self.xz,"lon",self.lon,"lat",self.lat,"hrkey",self.hrkey, \
255              "xdate",self.xdate,"loct",self.loct,"dust",self.dust
256
257    def getnameset(self):
258    # set a name referring to settings [convenient for databases]
259        strlat = str(self.lat)+str(self.lats)+str(self.late)
260        strlon = str(self.lon)+str(self.lons)+str(self.lone)
261        strxz = str(self.xz)+str(self.xzs)+str(self.xze)
262        strloct = str(self.loct)+str(self.locts)+str(self.locte)
263        name = str(self.zkey)+strxz+strlon+strlat+str(self.hrkey)+str(self.datekey)+str(self.xdate)+strloct+str(self.dust)
264        return name
265
266    def printcoord(self):
267    # print requested space-time coordinates
268        print "LAT",self.lat,"LON",self.lon,"LOCT",self.loct,"XDATE",self.xdate
269
270    def printmeanvar(self):
271    # print mean MCD variables
272        print "Pressure = %5.3f pascals. " % (self.pres)
273        print "Density = %5.3f kilograms per cubic meter. " % (self.dens)
274        print "Temperature = %3.0f kelvins (%4.0f degrees celsius)." % (self.temp,self.temp-273.15)
275        print "Zonal wind = %5.3f meters per second." % (self.zonwind)
276        print "Meridional wind = %5.3f meters per second." % (self.merwind)
277        print "Total horizontal wind = %5.3f meters per second." % ( np.sqrt(self.zonwind**2 + self.merwind**2) )
278
279    def printextvar(self,num):
280    # print extra MCD variables
281        num = self.convertlab(num)
282        dastr = str(self.extvar[num-1])
283        if dastr == "nan":   print "!!!! There is a problem, probably a value is requested below the surface !!!!"
284        else:                print self.getextvarlab(num) + " ..... " + dastr
285
286    def printallextvar(self):
287    # print all extra MCD variables   
288        for i in range(50): self.printextvar(i+1)
289
290    def htmlprinttabextvar(self,tabtodo):
291        self.fixedlt = True ## local time is real local time
292        self.gettitle()
293        print "<hr>"
294        print self.title
295        print "<hr>"
296        print "<ul>"
297        for i in range(len(tabtodo)): print "<li>" ; self.printextvar(tabtodo[i]) ; print "</li>"
298        print "</ul>"
299        print "<hr>"
300        print self.ack
301        print "<hr>"
302        #print "SETTINGS<br />"
303        #self.printcoord()
304        #self.printset()
305
306    def printmcd(self):
307    # 1. call MCD 2. print settings 3. print mean vars
308        self.update()
309        self.printcoord()
310        print "-------------------------------------------"
311        self.printmeanvar()
312
313########################
314### Several requests ###
315########################
316
317    def prepare(self,ndx=None,ndy=None):
318    ### prepare I/O arrays for 1d slices
319      if ndx is None:  print "No dimension in prepare. Exit. Set at least ndx." ; exit()
320      else:            self.xcoord = np.ones(ndx)
321      if ndy is None:  dashape = (ndx)     ; dashapemean = (ndx,6)     ; dashapeext = (ndx,101)     ; self.ycoord = None
322      else:            dashape = (ndx,ndy) ; dashapemean = (ndx,ndy,6) ; dashapeext = (ndx,ndy,101) ; self.ycoord = np.ones(ndy)
323      self.prestab = np.ones(dashape) ; self.denstab = np.ones(dashape) ; self.temptab = np.ones(dashape)
324      self.zonwindtab = np.ones(dashape) ; self.merwindtab = np.ones(dashape) 
325      self.meanvartab = np.ones(dashapemean) ; self.extvartab = np.ones(dashapeext)
326
327    def getextvar(self,num):
328    ### get a given var in extvartab
329      try: field=self.extvartab[:,:,num] 
330      except: field=self.extvartab[:,num]
331      return field
332
333    def definefield(self,choice):
334    ### for analysis or plot purposes, set field and field label from user-defined choice
335      choice = self.convertlab(choice)
336      field = self.getextvar(choice); fieldlab = self.getextvarlab(choice)
337      ## fix for possibly slightly negative tracers
338      if "(mol/mol)" in fieldlab or "(kg/kg)" in fieldlab or "(kg/m2)" in fieldlab or "(W/m2)" in fieldlab:
339         ind = np.where(field < 1.e-30)
340         if ind != -1: field[ind] = 1.e-30  ## 0 does not work everywhere.
341      return field,fieldlab
342
343    def ininterv(self,dstart,dend,nd,start=None,end=None,yaxis=False,vertcoord=False):
344    ### user-defined start and end are used to create xcoord (or ycoord) vector
345      if start is not None and end is not None:  first, second = self.correctbounds(start,end,vertcoord)
346      else:                                      first, second = self.correctbounds(dstart,dend,vertcoord) 
347      if self.zkey != 4 or not vertcoord:   tabtab = np.linspace(first,second,nd)
348      else:                                 tabtab = np.logspace(first,second,nd)
349      if not yaxis:      self.xcoord = tabtab
350      else:              self.ycoord = tabtab
351
352    def correctbounds(self,start,end,vertcoord):
353      if self.zkey != 4 or not vertcoord:
354        # regular altitudes
355        if start > end: first = end ; second = start
356        else:           first = start ; second = end
357      else:
358        # pressure: reversed avis
359        if start < end: first = np.log10(end) ; second = np.log10(start)
360        else:           first = np.log10(start) ; second = np.log10(end)
361      return first, second
362
363    def vertlabel(self):
364      if self.zkey == 1:   self.xlabel = "radius from centre of planet (m)"
365      elif self.zkey == 2: self.xlabel = "height above areoid (m) (MOLA zero datum)"
366      elif self.zkey == 3: self.xlabel = "height above surface (m)"
367      elif self.zkey == 4: self.xlabel = "pressure level (Pa)"
368      elif self.zkey == 5: self.xlabel = "altitude above mean Mars Radius(=3396000m) (m)"
369
370    def vertunits(self):
371      if self.zkey == 1:   self.vunits = "m CP"
372      elif self.zkey == 2: self.vunits = "m AMR"
373      elif self.zkey == 3: self.vunits = "m ALS"
374      elif self.zkey == 4: self.vunits = "Pa"
375      elif self.zkey == 5: self.vunits = "m AMMRad"
376
377    def vertaxis(self,number,yaxis=False):
378      if self.zkey == 2:   self.ininterv(-5000.,100000.,number,start=self.xzs,end=self.xze,yaxis=yaxis,vertcoord=True)
379      elif self.zkey == 3: self.ininterv(0.,120000.,number,start=self.xzs,end=self.xze,yaxis=yaxis,vertcoord=True)
380      elif self.zkey == 5: self.ininterv(-5000.,100000.,number,start=self.xzs,end=self.xze,yaxis=yaxis,vertcoord=True)
381      elif self.zkey == 4: self.ininterv(1000.,0.001,number,start=self.xzs,end=self.xze,yaxis=yaxis,vertcoord=True)
382      elif self.zkey == 1: self.ininterv(3396000,3596000,number,start=self.xzs,end=self.xze,yaxis=yaxis,vertcoord=True)
383
384###################
385### 1D analysis ###
386###################
387
388    def put1d(self,i):
389    ## fill in subscript i in output arrays
390    ## (arrays must have been correctly defined through prepare)
391      if self.prestab is None:  myplot.errormess("arrays must be prepared first through self.prepare")
392      self.prestab[i] = self.pres ; self.denstab[i] = self.dens ; self.temptab[i] = self.temp
393      self.zonwindtab[i] = self.zonwind ; self.merwindtab[i] = self.merwind
394      self.meanvartab[i,1:5] = self.meanvar[0:4]  ## note: var numbering according to MCD manual is kept
395      self.extvartab[i,1:100] = self.extvar[0:99] ## note: var numbering according to MCD manual is kept
396
397    def diurnal(self,nd=13):
398    ### retrieve a local time slice
399      self.fixedlt = True  ## local time is real local time
400      save = self.loct
401      self.xlabel = "Local time (Martian hour)"
402      self.prepare(ndx=nd) ; self.ininterv(0.,24.,nd,start=self.locts,end=self.locte) 
403      for i in range(nd): self.loct = self.xcoord[i] ; self.update() ; self.put1d(i)
404      self.loct = save
405
406    def zonal(self,nd=37):
407    ### retrieve a longitude slice
408      save = self.lon
409      self.xlabel = "East longitude (degrees)"
410      self.prepare(ndx=nd) ; self.ininterv(-180.,180.,nd,start=self.lons,end=self.lone)
411      if not self.fixedlt: umst = self.loct
412      for i in range(nd): 
413          self.lon = self.xcoord[i]
414          if not self.fixedlt: self.loct = (umst + self.lon/15.) % 24
415          self.update() ; self.put1d(i)
416      self.lon = save
417
418    def meridional(self,nd=19):
419    ### retrieve a latitude slice
420      self.fixedlt = True  ## local time is real local time
421      save = self.lat
422      self.xlabel = "North latitude (degrees)"
423      self.prepare(ndx=nd) ; self.ininterv(-90.,90.,nd,start=self.lats,end=self.late)
424      for i in range(nd): self.lat = self.xcoord[i] ; self.update() ; self.put1d(i)
425      self.lat = save
426
427    def profile(self,nd=20,tabperso=None):
428    ### retrieve an altitude slice (profile)
429      self.fixedlt = True  ## local time is real local time
430      save = self.xz
431      self.vertlabel()
432      self.vertplot = True
433      if tabperso is not None: nd = len(tabperso)
434      correct = False
435      self.prepare(ndx=nd) ; self.vertaxis(nd)
436      if tabperso is not None: self.xcoord = tabperso
437      for i in range(nd): self.xz = self.xcoord[i] ; self.update() ; self.put1d(i)
438      self.xz = save
439
440    def seasonal(self,nd=12):
441    ### retrieve a seasonal slice
442      save = self.xdate
443      self.xlabel = "Areocentric longitude (degrees)"
444      self.prepare(ndx=nd) ; self.ininterv(0.,360.,nd,start=self.xdates,end=self.xdatee)
445      for i in range(nd): self.xdate = self.xcoord[i] ; self.update() ; self.put1d(i)
446      self.xdate = save
447
448    def getascii(self,tabtodo,filename="output.txt"):
449    ### print out values in an ascii file
450      if isinstance(tabtodo,np.str): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
451      if isinstance(tabtodo,np.int): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
452      asciifile = open(filename, "w")
453      for i in range(len(tabtodo)): 
454          (field, fieldlab) = self.definefield(tabtodo[i])
455          self.gettitle(oneline=True)
456          asciifile.write("### " + self.title + "\n")
457          asciifile.write("### " + self.ack + "\n")
458          asciifile.write("### Column 1 is " + self.xlabel + "\n")
459          asciifile.write("### Column 2 is " + fieldlab + "\n")
460          for ix in range(len(self.xcoord)):
461              asciifile.write("%15.5e%15.5e\n" % ( self.xcoord[ix], field[ix] ) )
462      asciifile.close()
463      return 
464
465    def makeplot1d(self,choice):
466    ### one 1D plot is created for the user-defined variable in choice.
467      (field, fieldlab) = self.definefield(choice)
468      if not self.vertplot:  absc = self.xcoord ; ordo = field ; ordolab = fieldlab ; absclab = self.xlabel
469      else:                  ordo = self.xcoord ; absc = field ; absclab = fieldlab ; ordolab = self.xlabel
470      mpl.plot(absc,ordo,'-bo') ; mpl.ylabel(ordolab) ; mpl.xlabel(absclab) #; mpl.xticks(query.xcoord)
471      if self.zkey == 4: mpl.semilogy() ; ax = mpl.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
472      mpl.figtext(0.5, 0.01, self.ack, ha='center')
473
474    def plot1d(self,tabtodo):
475    ### complete 1D figure with possible multiplots
476      if isinstance(tabtodo,np.str): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
477      if isinstance(tabtodo,np.int): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
478      fig = mpl.figure() ; subv,subh = myplot.definesubplot( len(tabtodo) , fig ) 
479      for i in range(len(tabtodo)): mpl.subplot(subv,subh,i+1).grid(True, linestyle=':', color='grey') ; self.makeplot1d(tabtodo[i])
480
481    def htmlplot1d(self,tabtodo,figname="temp.png",title=""):
482    ### complete 1D figure with possible multiplots
483    ### added in 09/2012 for online MCD
484    ### see http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
485      from matplotlib.figure import Figure
486      from matplotlib.backends.backend_agg import FigureCanvasAgg
487      if isinstance(tabtodo,np.str): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
488      if isinstance(tabtodo,np.int): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
489
490      howmanyplots = len(tabtodo)
491      if howmanyplots == 1: fig = Figure(figsize=(16,8))
492      elif howmanyplots == 2: fig = Figure(figsize=(8,8))
493      elif howmanyplots == 3: fig = Figure(figsize=(8,16))
494      elif howmanyplots == 4: fig = Figure(figsize=(16,8))
495
496      subv,subh = myplot.definesubplot( len(tabtodo) , fig )
497      for i in range(len(tabtodo)):
498        yeah = fig.add_subplot(subv,subh,i+1) #.grid(True, linestyle=':', color='grey')
499        choice = tabtodo[i]
500        (field, fieldlab) = self.definefield(choice)
501        if not self.vertplot:  absc = self.xcoord ; ordo = field ; ordolab = fieldlab ; absclab = self.xlabel
502        else:                  ordo = self.xcoord ; absc = field ; absclab = fieldlab ; ordolab = self.xlabel
503        yeah.plot(absc,ordo,'-bo') #; mpl.xticks(query.xcoord)
504        ax = fig.gca() ; ax.set_ylabel(ordolab) ; ax.set_xlabel(absclab)
505
506        if self.xzs is not None and self.zkey == 4: ax.set_yscale('log') ; ax.set_ylim(ax.get_ylim()[::-1])
507
508        if self.lats is not None:      ax.set_xticks(np.arange(-90,91,15)) ; ax.set_xbound(lower=self.lats, upper=self.late)
509        elif self.lons is not None:    ax.set_xticks(np.arange(-360,361,30)) ; ax.set_xbound(lower=self.lons, upper=self.lone)
510        elif self.locts is not None:   ax.set_xticks(np.arange(0,26,2)) ; ax.set_xbound(lower=self.locts, upper=self.locte)
511
512        ax.grid(True, linestyle=':', color='grey')
513
514      self.gettitle()
515      fig.text(0.5, 0.95, self.title, ha='center')
516      fig.text(0.5, 0.01, self.ack, ha='center')
517      canvas = FigureCanvasAgg(fig)
518      # The size * the dpi gives the final image size
519      #   a4"x4" image * 80 dpi ==> 320x320 pixel image
520      canvas.print_figure(figname, dpi=self.dpi)
521
522###################
523### 2D analysis ###
524###################
525
526    def latlon(self,ndx=37,ndy=19):
527    ### retrieve a latitude/longitude slice
528    ### default is: local time is not fixed. user-defined local time is at longitude 0.
529      save1 = self.lon ; save2 = self.lat ; save3 = self.loct
530      self.xlabel = "East longitude (degrees)" ; self.ylabel = "North latitude (degrees)"
531      self.prepare(ndx=ndx,ndy=ndy)
532      self.ininterv(-180.,180.,ndx,start=self.lons,end=self.lone)
533      self.ininterv(-90.,  90.,ndy,start=self.lats,end=self.late,yaxis=True)
534      if not self.fixedlt: umst = self.loct
535      for i in range(ndx):
536       for j in range(ndy):
537         self.lon = self.xcoord[i] ; self.lat = self.ycoord[j]
538         if not self.fixedlt: self.loct = (umst + self.lon/15.) % 24
539         self.update() ; self.put2d(i,j)
540      if not self.fixedlt: self.loct = umst
541      self.lon = save1 ; self.lat = save2 ; self.loct = save3
542
543    def secalt(self,ndx=37,ndy=20,typex="lat"):
544    ### retrieve a coordinate/altitude slice
545      save1 = self.lon ; save2 = self.xz ; save3 = self.loct ; save4 = self.lat
546      self.prepare(ndx=ndx,ndy=ndy)
547      self.vertlabel() ; self.ylabel = self.xlabel
548      self.vertaxis(ndy,yaxis=True)
549      if "lat" in typex:
550          self.xlabel = "North latitude (degrees)"
551          self.ininterv(-90.,90.,ndx,start=self.lats,end=self.late)
552      elif typex == "lon":
553          self.xlabel = "East longitude (degrees)"
554          self.ininterv(-180.,180.,ndx,start=self.lons,end=self.lone)
555      if not self.fixedlt: umst = self.loct
556      for i in range(ndx):
557       for j in range(ndy):
558         if typex == "lat":   self.lat = self.xcoord[i]
559         elif typex == "lon": self.lon = self.xcoord[i]
560         self.xz = self.ycoord[j]
561         if not self.fixedlt: self.loct = (umst + self.lon/15.) % 24
562         self.update() ; self.put2d(i,j)
563      if not self.fixedlt: self.loct = umst
564      self.lon = save1 ; self.xz = save2 ; self.loct = save3 ; self.lat = save4
565
566    def zonalmean(self,ndx=37,ndy=20,ndmean=32):
567    ### retrieve a zonalmean lat/altitude slice
568      self.fixedlt = False
569      save1 = self.lon ; save2 = self.xz ; save3 = self.loct ; save4 = self.lat
570      self.prepare(ndx=ndx,ndy=ndy)
571      self.vertlabel() ; self.ylabel = self.xlabel
572      self.vertaxis(ndy,yaxis=True)
573      self.xlabel = "North latitude (degrees)"
574      self.ininterv(-180.,180.,ndmean)
575      coordmean = self.xcoord
576      self.ininterv(-90.,90.,ndx,start=self.lats,end=self.late)
577      umst = self.loct #fixedlt false for this case
578      for i in range(ndx):
579       self.lat = self.xcoord[i]
580       for j in range(ndy):
581        self.xz = self.ycoord[j]
582        meanpres = 0. ; meandens = 0. ; meantemp = 0. ; meanzonwind = 0. ; meanmerwind = 0. ; meanmeanvar = np.zeros(5) ; meanextvar = np.zeros(100)       
583        for m in range(ndmean):
584           self.lon = coordmean[m]
585           self.loct = (umst + self.lon/15.) % 24 #fixedlt false for this case
586           self.update() 
587           meanpres = meanpres + self.pres/float(ndmean) ; meandens = meandens + self.dens/float(ndmean) ; meantemp = meantemp + self.temp/float(ndmean)
588           meanzonwind = meanzonwind + self.zonwind/float(ndmean) ; meanmerwind = meanmerwind + self.merwind/float(ndmean)
589           meanmeanvar = meanmeanvar + self.meanvar/float(ndmean) ; meanextvar = meanextvar + self.extvar/float(ndmean)
590        self.pres=meanpres ; self.dens=meandens ; self.temp=meantemp ; self.zonwind=meanzonwind ; self.merwind=meanmerwind
591        self.meanvar=meanmeanvar ; self.extvar=meanextvar
592        self.put2d(i,j)
593      self.loct = umst #fixedlt false for this case
594      self.lon = save1 ; self.xz = save2 ; self.loct = save3 ; self.lat = save4
595
596    def hovmoller(self,ndtime=25,ndcoord=20,typex="lat"):
597    ### retrieve a time/other coordinate slice
598      save1 = self.lat ; save2 = self.xz ; save3 = self.loct ; save4 = self.lon
599      if typex == "lat": 
600          ndx = ndcoord ; self.xlabel = "North latitude (degrees)" 
601          ndy = ndtime ; self.ylabel = "Local time (Martian hour)"
602          self.prepare(ndx=ndx,ndy=ndy)
603          self.ininterv(-90.,90.,ndx,start=self.lats,end=self.late)
604          self.ininterv(0.,24.,ndy,start=self.locts,end=self.locte,yaxis=True)
605      elif typex == "lon":
606          ndx = ndcoord ; self.xlabel = "East longitude (degrees)"
607          ndy = ndtime ; self.ylabel = "Local time (Martian hour)"
608          self.prepare(ndx=ndx,ndy=ndy)
609          self.ininterv(-180.,180.,ndx,start=self.lons,end=self.lone)
610          self.ininterv(0.,24.,ndy,start=self.locts,end=self.locte,yaxis=True)
611      elif typex == "alt":
612          ndy = ndcoord ; self.vertlabel() ; self.ylabel = self.xlabel
613          ndx = ndtime ; self.xlabel = "Local time (Martian hour)"
614          self.prepare(ndx=ndx,ndy=ndy)
615          self.vertaxis(ndy,yaxis=True)
616          self.ininterv(0.,24.,ndx,start=self.locts,end=self.locte)
617      for i in range(ndx):
618       for j in range(ndy):
619         if typex == "lat":   self.lat = self.xcoord[i] ; self.loct = self.ycoord[j]
620         elif typex == "lon": self.lon = self.xcoord[i] ; self.loct = self.ycoord[j]
621         elif typex == "alt": self.xz = self.ycoord[j] ; self.loct = self.xcoord[i]
622         self.update() ; self.put2d(i,j)
623      self.lat = save1 ; self.xz = save2 ; self.loct = save3 ; self.lon = save4
624
625    def put2d(self,i,j):
626    ## fill in subscript i,j in output arrays
627    ## (arrays must have been correctly defined through prepare)
628      if self.prestab is None:  myplot.errormess("arrays must be prepared first through self.prepare")
629      self.prestab[i,j] = self.pres ; self.denstab[i,j] = self.dens ; self.temptab[i,j] = self.temp
630      self.zonwindtab[i,j] = self.zonwind ; self.merwindtab[i,j] = self.merwind
631      self.meanvartab[i,j,1:5] = self.meanvar[0:4]  ## note: var numbering according to MCD manual is kept
632      self.extvartab[i,j,1:100] = self.extvar[0:99] ## note: var numbering according to MCD manual is kept
633
634    def makemap2d(self,choice,incwind=False,proj="cyl"):
635    ### one 2D map is created for the user-defined variable in choice.
636      self.latlon() ## a map is implicitely a lat-lon plot. otherwise it is a plot (cf. makeplot2d)
637      if choice == "wind" or incwind:
638          (windx, fieldlabwx) = self.definefield("u")
639          (windy, fieldlabwy) = self.definefield("v")
640      if choice == "wind":
641          field = np.sqrt(windx*windx + windy*windy)
642          fieldlab = "Horizontal wind speed (m/s)"
643      else:   
644          (field, fieldlab) = self.definefield(choice)
645      if incwind:   myplot.maplatlon(self.xcoord,self.ycoord,field,title=fieldlab,proj=proj,vecx=windx,vecy=windy) #,stride=1)
646      else:         myplot.maplatlon(self.xcoord,self.ycoord,field,title=fieldlab,proj=proj)
647      mpl.figtext(0.5, 0.0, self.ack, ha='center')
648
649    def map2d(self,tabtodo,incwind=False,proj="cyl"):
650    ### complete 2D figure with possible multiplots
651      if isinstance(tabtodo,np.str): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
652      if isinstance(tabtodo,np.int): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
653      fig = mpl.figure()
654      subv,subh = myplot.definesubplot( len(tabtodo) , fig ) 
655      for i in range(len(tabtodo)): mpl.subplot(subv,subh,i+1) ; self.makemap2d(tabtodo[i],incwind=incwind,proj=proj)
656
657    def htmlmap2d(self,tabtodo,incwind=False,figname="temp.png",back="zMOL"):
658    ### complete 2D figure with possible multiplots
659    ### added in 09/2012 for online MCD
660    ### see http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
661      from matplotlib.figure import Figure
662      from matplotlib.backends.backend_agg import FigureCanvasAgg
663      from matplotlib.cm import get_cmap
664      from matplotlib import rcParams
665      #from mpl_toolkits.basemap import Basemap # does not work
666      from Scientific.IO import NetCDF
667
668      filename = "/home/marshttp/surface.nc"
669      zefile = NetCDF.NetCDFFile(filename, 'r') 
670      fieldc = zefile.variables[back]
671      yc = zefile.variables['latitude']
672      xc = zefile.variables['longitude']
673
674      if isinstance(tabtodo,np.str): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
675      if isinstance(tabtodo,np.int): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
676
677      howmanyplots = len(tabtodo)
678      if howmanyplots == 1: fig = Figure(figsize=(16,8)) 
679      elif howmanyplots == 2: fig = Figure(figsize=(8,8)) 
680      elif howmanyplots == 3: fig = Figure(figsize=(8,16)) 
681      elif howmanyplots == 4: fig = Figure(figsize=(16,8)) 
682
683      subv,subh = myplot.definesubplot( len(tabtodo) , fig )
684
685      for i in range(len(tabtodo)):
686        yeah = fig.add_subplot(subv,subh,i+1)
687        choice = tabtodo[i]
688        self.latlon(ndx=64,ndy=48) 
689        ## a map is implicitely a lat-lon plot. otherwise it is a plot (cf. makeplot2d)
690        (field, fieldlab) = self.definefield(choice)
691        if incwind: (windx, fieldlabwx) = self.definefield("u") ; (windy, fieldlabwy) = self.definefield("v")
692
693        proj="moll" ; colorb= self.colorm ; ndiv=20 ; zeback="molabw" ; trans=1.0 #0.6
694        vecx=None ; vecy=None ; stride=2
695        lon = self.xcoord
696        lat = self.ycoord
697       
698        #[lon2d,lat2d] = np.meshgrid(lon,lat)
699        ##### define projection and background. define x and y given the projection
700        ##[wlon,wlat] = myplot.latinterv()
701        ##yeahm = myplot.define_proj(proj,wlon,wlat,back=zeback,blat=None,blon=None)
702        ##x, y = yeahm(lon2d, lat2d)
703        #map = Basemap(projection='ortho',lat_0=45,lon_0=-100)
704        #x, y = map(lon2d, lat2d)
705
706        #### TEMP
707        x = lon ; y = lat
708
709        ## define field. bound field.
710        what_I_plot = np.transpose(field)
711        zevmin, zevmax = myplot.calculate_bounds(what_I_plot,vmin=self.min2d,vmax=self.max2d) 
712        what_I_plot = myplot.bounds(what_I_plot,zevmin,zevmax)
713        ## define contour field levels. define color palette
714        ticks = ndiv + 1
715        zelevels = np.linspace(zevmin,zevmax,ticks)
716        palette = get_cmap(name=colorb)
717
718        # You can set negative contours to be solid instead of dashed:
719        rcParams['contour.negative_linestyle'] = 'solid'
720        ## contours topo
721        zelevc = np.linspace(-9.,20.,11)
722        yeah.contour( xc, yc, fieldc, zelevc, colors='black',linewidths = 0.4)
723        yeah.contour( np.array(xc) + 360., yc, fieldc, zelevc, colors='black',linewidths = 0.4)
724        yeah.contour( np.array(xc) - 360., yc, fieldc, zelevc, colors='black',linewidths = 0.4)
725        # contour field
726        c = yeah.contourf( x, y, what_I_plot, zelevels, cmap = palette, alpha = trans )
727        clb = Figure.colorbar(fig,c,orientation='vertical',format=self.fmt,ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])))
728        clb.set_label(fieldlab)
729        if incwind:
730          [x2d,y2d] = np.meshgrid(x,y)
731          yeah.quiver(x2d,y2d,np.transpose(windx),np.transpose(windy))
732        ax = fig.gca() ; ax.set_ylabel("Latitude") ; ax.set_xlabel("Longitude")
733        ax.set_xticks(np.arange(-360,361,45)) ; ax.set_xbound(lower=self.lons, upper=self.lone)
734        ax.set_yticks(np.arange(-90,91,30)) ; ax.set_ybound(lower=self.lats, upper=self.late)
735      self.gettitle()
736      fig.text(0.5, 0.95, self.title, ha='center')
737      fig.text(0.5, 0.01, self.ack, ha='center')
738      canvas = FigureCanvasAgg(fig)
739      # The size * the dpi gives the final image size
740      #   a4"x4" image * 80 dpi ==> 320x320 pixel image
741      canvas.print_figure(figname, dpi=self.dpi)
742
743    def htmlplot2d(self,tabtodo,figname="temp.png"):
744    ### complete 2D figure with possible multiplots
745    ### added in 10/2012 for online MCD
746    ### see http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
747      from matplotlib.figure import Figure
748      from matplotlib.backends.backend_agg import FigureCanvasAgg
749      from matplotlib.cm import get_cmap
750      if isinstance(tabtodo,np.str): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
751      if isinstance(tabtodo,np.int): tabtodo=[tabtodo] ## so that asking one element without [] is possible.
752
753      howmanyplots = len(tabtodo)
754      if howmanyplots == 1: fig = Figure(figsize=(16,8))
755      elif howmanyplots == 2: fig = Figure(figsize=(8,8))
756      elif howmanyplots == 3: fig = Figure(figsize=(8,16))
757      elif howmanyplots == 4: fig = Figure(figsize=(16,8))
758
759      subv,subh = myplot.definesubplot( len(tabtodo) , fig )
760
761      for i in range(len(tabtodo)):
762        yeah = fig.add_subplot(subv,subh,i+1)
763        choice = tabtodo[i]
764
765        if self.lons is not None:   
766           if self.locts is None:  self.secalt(ndx=64,ndy=35,typex="lon")
767           else:                   self.hovmoller(ndcoord=64,typex="lon")
768        elif self.lats is not None: 
769           if self.locts is None: 
770               if self.zonmean:   self.zonalmean()
771               else:         self.secalt(ndx=48,ndy=35,typex="lat")
772           else:                   self.hovmoller(ndcoord=48,typex="lat")
773        else:
774           self.hovmoller(ndcoord=35,typex="alt")
775
776        (field, fieldlab) = self.definefield(choice)
777
778        colorb=self.colorm ; ndiv=20 
779
780        ## define field. bound field.
781        what_I_plot = np.transpose(field)
782        zevmin, zevmax = myplot.calculate_bounds(what_I_plot,vmin=self.min2d,vmax=self.max2d) 
783        what_I_plot = myplot.bounds(what_I_plot,zevmin,zevmax)
784        ## define contour field levels. define color palette
785        ticks = ndiv + 1
786        zelevels = np.linspace(zevmin,zevmax,ticks)
787        palette = get_cmap(name=colorb)
788        # contour field
789        c = yeah.contourf( self.xcoord, self.ycoord, what_I_plot, zelevels, cmap = palette )
790        clb = Figure.colorbar(fig,c,orientation='vertical',format=self.fmt,ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])))
791        clb.set_label(fieldlab)
792        ax = fig.gca() ; ax.set_ylabel(self.ylabel) ; ax.set_xlabel(self.xlabel)
793
794        if self.lons is not None:   ax.set_xticks(np.arange(-360,361,45)) ; ax.set_xbound(lower=self.lons, upper=self.lone)
795        elif self.lats is not None: ax.set_xticks(np.arange(-90,91,30)) ; ax.set_xbound(lower=self.lats, upper=self.late)
796
797        if self.locts is not None: 
798            if self.xzs is not None: ax.set_xticks(np.arange(0,26,2)) ; ax.set_xbound(lower=self.locts, upper=self.locte)
799            else:                    ax.set_yticks(np.arange(0,26,2)) ; ax.set_ybound(lower=self.locts, upper=self.locte)
800
801        if self.zkey == 4 and self.xzs is not None: 
802            ax.set_yscale('log') ; ax.set_ylim(ax.get_ylim()[::-1])
803        else:
804            #ax.set_yticks(np.arange(self.xzs,self.xze,10000.)) ;
805            ax.set_ybound(lower=self.xzs, upper=self.xze)
806
807      self.gettitle()
808      fig.text(0.5, 0.95, self.title, ha='center')
809      fig.text(0.5, 0.01, self.ack, ha='center')
810      canvas = FigureCanvasAgg(fig)
811      # The size * the dpi gives the final image size
812      #   a4"x4" image * 80 dpi ==> 320x320 pixel image
813      canvas.print_figure(figname, dpi=self.dpi)
814
815
816    ### TODO: makeplot2d, plot2d, passer plot settings
817
Note: See TracBrowser for help on using the repository browser.