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

Last change on this file since 1242 was 1077, checked in by aslmd, 11 years ago

UTIL PYTHON MCD ONLINE. various improvements and bug fixes: notably altitude 0, wind modulus.

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