source: trunk/UTIL/PYTHON/planetoplot_v2/ppclass.py @ 1191

Last change on this file since 1191 was 1178, checked in by tnavarro, 11 years ago

bug with method comp for t and z-axis : last point was always discarded

File size: 100.0 KB
Line 
1###############################################
2## PLANETOPLOT                               ##
3## --> PPCLASS                               ##
4## A generic and versatile Python module     ##
5## ... to read netCDF files and plot         ##
6###############################################
7## Author: Aymeric Spiga. 02-03/2013         ##
8###############################################
9# python built-in librairies
10import os
11import time as timelib
12import pickle
13# added librairies
14import numpy as np
15import netCDF4
16import matplotlib.pyplot as mpl
17# personal librairies
18import ppplot
19import ppcompute
20###############################################
21
22###################################
23#### HEADER                      ##
24#### ... executed when imported  ##
25###################################
26# where settings files are located...
27# ... this can be hardcoded here
28whereset = None
29whereset = ppcompute.findset(whereset)
30# ... we load user-defined automatic settings from set_ppclass.txt
31zefile = "set_ppclass.txt"
32glob_listx = [] ; glob_listy = [] ; glob_listz = [] ; glob_listt = []
33glob_listarea = []
34try: 
35    f = open(whereset+zefile, 'r') ; lines = f.readlines()
36    for stuff in lines[5].strip().split(';'): glob_listx.append(stuff)
37    for stuff in lines[8].strip().split(';'): glob_listy.append(stuff)
38    for stuff in lines[11].strip().split(';'): glob_listz.append(stuff)
39    for stuff in lines[14].strip().split(';'): glob_listt.append(stuff)
40    for stuff in lines[17].strip().split(';'): glob_listarea.append(stuff)
41except IOError: 
42    print "PPCLASS warning: "+zefile+" not in "+whereset+" ; no presets."
43
44##################################
45#### USEFUL GENERIC FUNCTIONS ####
46##################################
47
48# inspect variables and dimensions in a netCDF file
49def inspect(filename):
50    print "---------------------------------------------------------------"
51    print "**** INSPECT FILE",filename
52    test = netCDF4.Dataset(filename)
53    print "---------------------------------------------------------------"
54    print "**** DIMENSIONS:"
55    for obj in test.dimensions.values(): print obj
56    print "---------------------------------------------------------------"
57    print "**** VARIABLES: ",test.variables.keys()
58    print "---------------------------------------------------------------"
59    findinlist(test,glob_listx,"**** FOUND X-AXIS ---> ")
60    findinlist(test,glob_listy,"**** FOUND Y-AXIS ---> ")
61    findinlist(test,glob_listz,"**** FOUND Z-AXIS ---> ")
62    findinlist(test,glob_listt,"**** FOUND T-AXIS ---> ")
63    print "**** ( according to settings in "+whereset+zefile+" )"
64    print "---------------------------------------------------------------"
65# -- function defined for the above function inspect
66def findinlist(netcdfobj,extlist,message):
67    found = False
68    for c in extlist:
69      if c in netcdfobj.variables.keys():
70        found = True
71        output = message+str(c)
72        if c in netcdfobj.dimensions.keys():
73          output = output+" ---- has "+str(len(netcdfobj.dimensions[c]))+" values"
74          try: output = output + " ---- from "+str(netcdfobj.variables[c][0])+" to "+str(netcdfobj.variables[c][-1])
75          except: pass
76        print output ; output = "" 
77    if not found:
78      print message+"not found. will simply use index (check out dimensions)."
79
80# request a given attribute (and test if it is here)
81def ncattr(filename,char):
82    nc = netCDF4.Dataset(filename)
83    if hasattr(nc,char): ncattr=getattr(nc,char)
84    return ncattr
85
86# check a tab and exit if wrong. if just one string make it a list.
87# (if allownumber, convert this into a string).
88def checktab(tab,mess="",allownone=False,allownumber=False):
89    if tab is None: 
90      if not allownone:  print "pp.define: no "+mess ; exit()
91      else: pass
92    else:
93      if not isinstance(tab, list):
94        if isinstance(tab, str): 
95            tab = [tab]
96        elif (isinstance(tab, int) or isinstance(tab, float)) and allownumber: 
97            tab = [str(tab)] 
98        else: 
99            print "pp.define: "+mess+" should be either a string or a list of strings!" ; exit()
100      elif isinstance(tab, list):
101        if isinstance(tab[0],str): 
102            pass
103        elif (isinstance(tab[0], int) or isinstance(tab[0], float)) and allownumber:
104            for iii in range(len(tab)): tab[iii] = str(tab[iii])
105        else: 
106            print "pp.define: "+mess+" should be either a string or a list of strings!" ; exit()
107    return tab
108
109# determine which method is to be applied to a given dimension
110def findmethod(tab):
111    if tab is None:              output = "free"
112    elif tab[0,0] != tab[0,1]:   output = "comp"
113    else:                        output = "fixed"
114    return output
115
116# read what is given by the user (version of T. Navarro)
117def readslices(saxis):
118    if saxis == None:
119        zesaxis = None
120    else:
121        zesaxis = np.empty((len(saxis),2))
122        for i in range(len(saxis)):
123            a = separatenames(saxis[i])
124            if len(a) == 1:
125                zesaxis[i,:] = float(a[0])
126            else:
127                zesaxis[i,0] = float(a[0])
128                zesaxis[i,1] = float(a[1])         
129    return zesaxis
130
131# look for comas in the input name to separate different names (files, variables,etc ..)
132# (needed by readslices)
133def separatenames (name):
134    if name is None: names = None
135    else:
136      names = [] ; stop = 0 ; currentname = name
137      while stop == 0:
138        indexvir = currentname.find(',')
139        if indexvir == -1: stop = 1 ; name1 = currentname
140        else: name1 = currentname[0:indexvir]
141        names = np.concatenate((names,[name1]))
142        currentname = currentname[indexvir+1:len(currentname)]
143    return names
144
145#######################
146### THE MAIN OBJECT ###
147#######################
148class pp():
149
150    # print out a help string when help is invoked on the object
151    def __repr__(self):
152        whatprint = 'pp object. \"help(pp)\" for more information\n'
153        return whatprint
154
155    # default settings
156    # -- user can define settings by two methods.
157    # -- 1. yeah = pp(file="file.nc")
158    # -- 2. yeah = pp() ; yeah.file = "file.nc"
159    def __init__(self,file=None,var="notset",\
160                      filegoal=None,vargoal=None,\
161                      x=None,y=None,z=None,t=None,\
162                      sx=1,sy=1,\
163                      sz=1,st=1,\
164                      svx=1,\
165                      svy=1,\
166                      compute="mean",\
167                      kind3d="tyx",\
168                      verbose=False,\
169                      quiet=False,\
170                      noproj=False,\
171                      superpose=False,\
172                      plotin=None,\
173                      forcedimplot=-1,\
174                      out="gui",\
175                      filename="myplot",\
176                      folder="./",\
177                      includedate=True,\
178                      res=150.,\
179                      xlabel=None,ylabel=None,\
180                      xcoeff=None,ycoeff=None,\
181                      xmin=None,ymin=None,\
182                      xmax=None,ymax=None,\
183                      nxticks=10,nyticks=10,\
184                      proj=None,\
185                      vmin=None,vmax=None,\
186                      div=None,\
187                      colorbar=None,\
188                      linestyle=None,\
189                      marker=None,\
190                      color=None,\
191                      legend=None,\
192                      changetime=None,\
193                      units=None,\
194                      savtxt=False,\
195                      modx=None,\
196                      fmt=None,\
197                      xp=16,yp=8,\
198                      missing=1.e25,\
199                      trans=None,back=None,\
200                      showcb=None,\
201                      logy=None,\
202                      title=None):
203        self.request = None
204        self.nrequest = 0
205        self.nfin = 0 ; self.nvin = 0
206        self.nplotx = None ; self.nploty = None
207        self.nplotz = None ; self.nplott = None
208        self.status = "init"
209        self.fig = None ; self.subv = None ; self.subh = None 
210        self.n = 0 ; self.howmanyplots = 0
211        self.nplot = 0
212        self.p = None
213        self.customplot = False
214        self.f = None
215        self.l = None
216        ## what could be defined by the user
217        self.file = file
218        self.var = var
219        self.filegoal = filegoal
220        self.vargoal = vargoal
221        self.x = x ; self.y = y   ## if None, free dimension
222        self.z = z ; self.t = t   ## if None, free dimension
223        self.sx = sx ; self.sy = sy
224        self.sz = sz ; self.st = st
225        self.svx = svx
226        self.svy = svy
227        self.compute = compute
228        self.kind3d = kind3d
229        self.verbose = verbose
230        self.quiet = quiet
231        self.noproj = noproj
232        self.plotin = plotin
233        self.superpose = superpose
234        self.forcedimplot = forcedimplot
235        self.out = out
236        self.filename = filename
237        self.res = res
238        self.folder = folder
239        self.includedate = includedate
240        self.changetime = changetime
241        self.savtxt = savtxt
242        self.modx = modx
243        self.missing = missing
244        ## here are user-defined plot settings
245        ## -- if not None, valid on all plots in the pp() objects
246        self.xlabel = xlabel ; self.xcoeff = xcoeff
247        self.ylabel = ylabel ; self.ycoeff = ycoeff
248        self.xmin = xmin ; self.xmax = xmax
249        self.ymin = ymin ; self.ymax = ymax
250        self.proj = proj
251        self.vmin = vmin ; self.vmax = vmax
252        self.div = div
253        self.colorbar = colorbar
254        self.linestyle = linestyle
255        self.marker = marker
256        self.color = color
257        self.legend = legend
258        self.units = units
259        self.title = title
260        self.xp = xp ; self.yp = yp
261        self.nxticks = nxticks ; self.nyticks = nyticks
262        self.fmt = fmt
263        self.trans = trans ; self.back = back
264        self.showcb = showcb
265        self.logy = logy
266
267    # print status
268    def printstatus(self):
269      if not self.quiet:
270        if self.filename == "THIS_IS_A_CLONE":
271            pass
272        else:
273            print "**** PPCLASS. Done step: " + self.status
274
275    # print attributes
276    def printme(self):
277        for k, v in vars(self).items():
278            print k,v
279
280    #####################################################
281    # EMULATE OPERATORS + - * / ** << FOR PP() OBJECTS  #
282    #####################################################
283
284    # define the operation <<
285    # ... e.g. obj2 << obj1
286    # ... means: get init for pp object obj2 from another pp object obj1
287    # ... (this should solve the affectation trap obj2 = obj1)
288    def __lshift__(self,other):
289        if other.__class__.__name__ == "pp":
290            self.file = other.file
291            self.var = other.var
292            self.filegoal = other.filegoal
293            self.vargoal = other.vargoal
294            self.x = other.x ; self.y = other.y   ## if None, free dimension
295            self.z = other.z ; self.t = other.t   ## if None, free dimension
296            self.sx = other.sx ; self.sy = other.sy
297            self.sz = other.sz ; self.st = other.st
298            self.compute = other.compute
299            self.kind3d = other.kind3d
300            self.verbose = other.verbose
301            self.noproj = other.noproj
302            self.plotin = other.plotin
303            self.superpose = other.superpose
304            self.forcedimplot = other.forcedimplot
305            self.out = other.out
306            self.filename = other.filename
307            self.folder = other.folder
308            self.xlabel = other.xlabel ; self.xcoeff = other.xcoeff
309            self.ylabel = other.ylabel ; self.ycoeff = other.ycoeff
310            self.proj = other.proj
311            self.vmin = other.vmin ; self.vmax = other.vmax
312            self.xmin = other.xmin ; self.xmax = other.xmax
313            self.ymin = other.ymin ; self.ymax = other.ymax
314            self.div = other.div
315            self.colorbar = other.colorbar
316            self.linestyle = other.linestyle
317            self.marker = other.marker
318            self.color = other.color
319            self.legend = other.legend
320            self.units = other.units
321            self.title = other.title
322            self.includedate = other.includedate
323            self.changetime = other.changetime
324            self.savtxt = other.savtxt
325            self.modx = other.modx
326            self.xp = other.xp ; self.yp = other.yp
327            self.missing = other.missing
328            self.nxticks = other.nxticks ; self.nyticks = other.nyticks
329            self.fmt = other.fmt
330            self.trans = other.trans ; self.back = other.back
331            self.showcb = other.showcb
332            self.logy = other.logy
333        else:
334            print "!! ERROR !! argument must be a pp object." ; exit()
335
336    # check the compatibility of two objects for operations
337    # --> if other is a pp class, test sizes and return isnum = False
338    # --> if other is an int or a float, return isnum = True
339    # --> otherwise, just print an error and exit
340    def checktwo(self,other):
341        if other.__class__.__name__ == "pp":
342          isnum = False
343          if self.status in ["init","defined"] or other.status in ["init","define"]: 
344             print "!! ERROR !! Please use .retrieve to get fields for plots with one of your pp operands." ; exit()
345          if self.nfin   != other.nfin   or \
346             self.nvin   != other.nvin   or \
347             self.nplott != other.nplott or \
348             self.nplotz != other.nploty or \
349             self.nploty != other.nploty or \
350             self.nplotx != other.nplotx :
351               print "!! ERROR !! The two operands do not have the same number of files, variables, t z y x requests."
352               exit()
353        elif isinstance(other,int) or isinstance(other,float):
354          isnum = True
355        else:
356          print "!! ERROR !! The operand is neither a pp class nor an integer or a float." ; exit()
357        return isnum
358
359    # define a selective copy of a pp() object for operations
360    # ... copy.copy() is not conservative (still acts like a pointer)
361    # ... copy.deepcopy() does not work with netCDF objects
362    # so what is done here is a copy of everything except
363    # (to avoid sharing with self and therefore modifying self through operations)
364    # - request attribute of pp() object
365    # - field attribute of the onerequest() objects
366    def selective_copy(self):
367        if self.status in ["init","defined"]:
368            print "!! ERROR !! Please use .retrieve to get fields for the object you want to copy from." ; exit()
369        the_clone = pp()
370        for k, v in vars(self).items():
371           if k != "request":
372               setattr(the_clone,k,v)
373        the_clone.verbose = False
374        the_clone.filename = "THIS_IS_A_CLONE" # trick to avoid additional outputs
375        the_clone.define()
376        for i in range(self.nfin):
377         for j in range(self.nvin):
378          for t in range(self.nplott):
379           for z in range(self.nplotz):
380            for y in range(self.nploty):
381             for x in range(self.nplotx):
382              obj_ref = self.request[i][j][t][z][y][x]
383              obj = the_clone.request[i][j][t][z][y][x]
384              for k, v in vars(obj_ref).items():
385               if k != "field":
386                setattr(obj,k,v)
387        the_clone.status = "retrieved"
388        the_clone.filename = self.filename
389        return the_clone
390
391    # define the operation + on two objects. or with an int/float.
392    # ... with selective_copy the self object is not modified.
393    def __add__(self,other):
394        isnum = self.checktwo(other)
395        the_clone = self.selective_copy()
396        for i in range(self.nfin):
397         for j in range(self.nvin):
398          for t in range(self.nplott):
399           for z in range(self.nplotz):
400            for y in range(self.nploty):
401             for x in range(self.nplotx):
402              obj = the_clone.request[i][j][t][z][y][x]
403              obj_ref = self.request[i][j][t][z][y][x]
404              if not isnum:   
405                  ope = other.request[i][j][t][z][y][x].field
406                  if ope.ndim == 0: 
407                    ope = float(ope) # if no dimension then this means that ope is a single value (not to be kept as an array)
408                  elif obj_ref.field.shape != ope.shape:
409                    print "!! ERROR !! The two fields for operation do not have the same shape.",obj_ref.field.shape,ope.shape
410                    exit()
411              else:           
412                  ope = other
413              goal = self.vargoal[j] + self.filegoal[i]
414              if ("vector" in goal) or ("contour" in goal):
415                  if self.verbose: print "!! WARNING !! No operation was made on contours and vectors. This can be debatted actually."
416                  obj.field = obj_ref.field
417              else:
418                  obj.field = obj_ref.field + ope
419        return the_clone
420
421    # define the operation - on two objects. or with an int/float.
422    # ... with selective_copy the self object is not modified.
423    def __sub__(self,other):
424        isnum = self.checktwo(other)
425        the_clone = self.selective_copy()
426        for i in range(self.nfin):
427         for j in range(self.nvin):
428          for t in range(self.nplott):
429           for z in range(self.nplotz):
430            for y in range(self.nploty):
431             for x in range(self.nplotx):
432              obj = the_clone.request[i][j][t][z][y][x]
433              obj_ref = self.request[i][j][t][z][y][x]
434              if not isnum:
435                  ope = other.request[i][j][t][z][y][x].field
436                  if ope.ndim == 0: 
437                    ope = float(ope) # if no dimension then this means that ope is a single value (not to be kept as an array)
438                  elif obj_ref.field.shape != ope.shape:
439                    print "!! ERROR !! The two fields for operation do not have the same shape.",obj_ref.field.shape,ope.shape
440                    exit()
441              else:
442                  ope = other
443              goal = self.vargoal[j] + self.filegoal[i]
444              if ("vector" in goal) or ("contour" in goal):
445                  if self.verbose: print "!! WARNING !! No operation was made on contours and vectors. This can be debatted actually."
446                  obj.field = obj_ref.field
447              else:
448                  obj.field = obj_ref.field - ope
449        return the_clone
450
451    # define the operation * on two objects. or with an int/float.
452    # ... with selective_copy the self object is not modified.
453    def __mul__(self,other):
454        isnum = self.checktwo(other)
455        the_clone = self.selective_copy()
456        for i in range(self.nfin):
457         for j in range(self.nvin):
458          for t in range(self.nplott):
459           for z in range(self.nplotz):
460            for y in range(self.nploty):
461             for x in range(self.nplotx):
462              obj = the_clone.request[i][j][t][z][y][x]
463              obj_ref = self.request[i][j][t][z][y][x]
464              if not isnum:
465                  ope = other.request[i][j][t][z][y][x].field
466                  if ope.ndim == 0: 
467                    ope = float(ope) # if no dimension then this means that ope is a single value (not to be kept as an array)
468                  elif obj_ref.field.shape != ope.shape:
469                    print "!! ERROR !! The two fields for operation do not have the same shape.",obj_ref.field.shape,ope.shape
470                    exit()
471              else:
472                  ope = other
473              goal = self.vargoal[j] + self.filegoal[i]
474              if ("vector" in goal) or ("contour" in goal):
475                  if self.verbose: print "!! WARNING !! No operation was made on contours and vectors. This can be debatted actually."
476                  obj.field = obj_ref.field
477              else:
478                  obj.field = obj_ref.field * ope
479        return the_clone
480
481    # define the operation / on two objects. or with an int/float.
482    # ... with selective_copy the self object is not modified.
483    def __div__(self,other):
484        isnum = self.checktwo(other)
485        the_clone = self.selective_copy()
486        for i in range(self.nfin):
487         for j in range(self.nvin):
488          for t in range(self.nplott):
489           for z in range(self.nplotz):
490            for y in range(self.nploty):
491             for x in range(self.nplotx):
492              obj = the_clone.request[i][j][t][z][y][x]
493              obj_ref = self.request[i][j][t][z][y][x]
494              if not isnum:
495                  ope = other.request[i][j][t][z][y][x].field
496                  if ope.ndim == 0: 
497                    ope = float(ope) # if no dimension then this means that ope is a single value (not to be kept as an array)
498                  elif obj_ref.field.shape != ope.shape:
499                    print "!! ERROR !! The two fields for operation do not have the same shape.",obj_ref.field.shape,ope.shape
500                    exit()
501              else:
502                  ope = other
503              goal = self.vargoal[j] + self.filegoal[i]
504              if ("vector" in goal) or ("contour" in goal):
505                  if self.verbose: print "!! WARNING !! No operation was made on contours and vectors. This can be debatted actually."
506                  obj.field = obj_ref.field
507              else:
508                  obj.field = obj_ref.field / ope
509        return the_clone
510
511    # define the reverse operation float/int + object
512    def __radd__(self,other):
513        isnum = self.checktwo(other)
514        if not isnum: print "!! ERROR !! Operand should be a number" ; exit()
515        return self.__add__(other)
516
517    # define the reverse operation float/int - object
518    def __rsub__(self,other):
519        isnum = self.checktwo(other)
520        if not isnum: print "!! ERROR !! Operand should be a number" ; exit()
521        return self.__sub__(other)
522
523    # define the reverse operation float/int * object
524    def __rmul__(self,other):
525        isnum = self.checktwo(other)
526        if not isnum: print "!! ERROR !! Operand should be a number" ; exit()
527        return self.__mul__(other)
528
529    # define the reverse operation float/int / object
530    def __rdiv__(self,other):
531        isnum = self.checktwo(other)
532        if not isnum: print "!! ERROR !! Operand should be a number" ; exit()
533        return self.__div__(other)
534
535    # define the operation ** on one object.
536    # ... with selective_copy the self object is not modified.
537    def __pow__(self,num):
538        the_clone = self.selective_copy()
539        if isinstance(num,int) or isinstance(num,float):
540            for i in range(self.nfin):
541             for j in range(self.nvin):
542              for t in range(self.nplott):
543               for z in range(self.nplotz):
544                for y in range(self.nploty):
545                 for x in range(self.nplotx):
546                  obj  = the_clone.request[i][j][t][z][y][x]
547                  obj_ref = self.request[i][j][t][z][y][x]
548                  goal = self.vargoal[j] + self.filegoal[i]
549                  if ("vector" in goal) or ("contour" in goal):
550                      if self.verbose: print "!! WARNING !! No operation was made on contours and vectors. This can be debatted actually."
551                      obj.field = obj_ref.field
552                  else:
553                      obj.field = obj_ref.field ** num
554        else:
555            print "!! ERROR !! To define a power, either an int or a float is needed." ; exit()
556        return the_clone
557
558    ### TBD: reverse power? for exponentials?
559
560    ##############################################################################################
561    # define method
562    # ---------
563    # ... (file and var are either one string or a vector of strings)
564    # ... the goal of define is to define a 2D array of onerequest() objects (see class below)
565    #     given the number of file, var, x, y, z, t asked by the user
566    # ... objectives for file or var are given through filegoal and vargoal
567    #     --> possible values: main contour vector
568    # ---------
569    # ... then onerequest() objects are being defined more precisely
570    #     by getting index_x index_y index_z index_t
571    #     and setting method_x method_y method_z method_t to either
572    #      - "free" for free dimensions (plot dimensions)
573    #      - "comp" for averages, max, min
574    #      - "fixed" for fixed dimensions (possibly several i.e. multislice)
575    ##############################################################################################
576    def define(self):
577        self.printstatus()
578        # initial check and get dimensions
579        self.file = checktab(self.file,mess="file")
580        self.nfin = len(self.file)
581        if self.verbose:
582            for i in range(self.nfin): inspect(self.file[i])
583        self.var = checktab(self.var,mess="var")
584        self.nvin = len(self.var)
585        # check goal tabs for files and variables
586        # ... default is to plot everything
587        if self.filegoal is None: self.filegoal = ["main"]*self.nfin
588        if self.vargoal is None:  self.vargoal  = ["main"]*self.nvin
589        self.filegoal = checktab(self.filegoal, mess="filegoal")
590        self.vargoal  = checktab(self.vargoal,  mess="vargoal")
591        if len(self.filegoal) != self.nfin:  print "!! ERROR !! filegoal must be the same size as file." ; exit()
592        if len(self.vargoal)  != self.nvin:  print "!! ERROR !! vargoal must be the same size as var." ; exit()
593        # variables: initial check
594        self.x = checktab(self.x,mess="x",allownone=True,allownumber=True)
595        self.y = checktab(self.y,mess="y",allownone=True,allownumber=True)
596        self.z = checktab(self.z,mess="z",allownone=True,allownumber=True)
597        self.t = checktab(self.t,mess="t",allownone=True,allownumber=True)
598        # for the moment not var- nor file- dependent.
599        # but this could be the case.
600        sx = readslices(self.x) ; sy = readslices(self.y)
601        sz = readslices(self.z) ; st = readslices(self.t)
602        # get methods
603        mx = findmethod(sx) ; my = findmethod(sy)
604        mz = findmethod(sz) ; mt = findmethod(st)
605        # get number of plots to be done
606        if mx in ["fixed","comp"]: self.nplotx = sx.size/2
607        else:                      self.nplotx = 1
608        if my in ["fixed","comp"]: self.nploty = sy.size/2
609        else:                      self.nploty = 1
610        if mz in ["fixed","comp"]: self.nplotz = sz.size/2
611        else:                      self.nplotz = 1
612        if mt in ["fixed","comp"]: self.nplott = st.size/2
613        else:                      self.nplott = 1
614        if self.verbose:  print "**** OK. Plots over x,y,z,t -->",self.nplotx,self.nploty,self.nplotz,self.nplott
615        # create the list of onerequest() objects
616        self.request = [[[[[[ \
617                       onerequest() \
618                       for x in range(self.nplotx)] for y in range(self.nploty)] \
619                       for z in range(self.nplotz)] for t in range(self.nplott)] \
620                       for j in range(self.nvin)]   for i in range(self.nfin)] 
621        # store how many onerequest() objects are in self.request
622        self.nrequest = self.nfin*self.nvin*self.nplotx*self.nploty*self.nplotz*self.nplott
623        # loop on onerequest() objects
624        for i in range(self.nfin):
625         for j in range(self.nvin):
626          for t in range(self.nplott):
627           for z in range(self.nplotz):
628            for y in range(self.nploty):
629             for x in range(self.nplotx):
630              obj = self.request[i][j][t][z][y][x]
631              # fill in names for files and variables
632              obj.verbose = self.verbose
633              obj.file = self.file[i]
634              obj.var = self.var[j]
635              # get methods
636              obj.method_x = mx ; obj.method_y = my
637              obj.method_z = mz ; obj.method_t = mt
638              # indicate the computation method
639              obj.compute = self.compute
640              # indicate the kind of 3D fields
641              obj.kind3d = self.kind3d
642              # open the files (the same file might be opened several times but this is cheap)
643              obj.openfile()
644              ### get x,y,z,t dimensions from file
645              obj.getdim()
646              ### possible time axis change
647              obj.changetime = self.changetime
648              obj.performtimechange()
649              # get strides
650              obj.sx = self.sx ; obj.sy = self.sy
651              obj.sz = self.sz ; obj.st = self.st
652              ### get index
653              obj.getindextime(dalist=st,ind=t)
654              obj.getindexvert(dalist=sz,ind=z)
655              obj.getindexhori(dalistx=sx,dalisty=sy,indx=x,indy=y)
656              # missing value
657              obj.missing = self.missing
658        # change status
659        self.status = "defined"
660        return self
661
662    ##############################################################################################
663    # retrieve method
664    # --> for each element onerequest() in the array, get field .var from .f file
665    # --> see below the onerequest() class:
666    #        - only get what is needed for computing and plotting
667    #        - averages etc... are computed here
668    # --> RESULT: each onerequest() object has now its attribute .field filled
669    # --> if one wants to perform operations on fields, this should be done after retrieve()
670    ##############################################################################################
671    def retrieve(self):
672        self.printstatus()
673        # check if things were done OK before
674        if self.status != "defined": print "!! ERROR !! Please use .define() to define your pp object." ; exit()
675        ## create the list of f() and l() objects
676        ## --> so that the user can easily access values (and labels for easy exploration)
677        ## --> see example easy_get_field
678        self.f = [ [] for iii in range(self.nrequest) ]
679        self.l = [ [] for iii in range(self.nrequest) ]
680        count = 0
681        ## first get fields
682        ## ... only what is needed is extracted from the files
683        ## ... and computations are performed
684        for i in range(self.nfin):
685         for j in range(self.nvin):
686          for t in range(self.nplott):
687           for z in range(self.nplotz):
688            for y in range(self.nploty):
689             for x in range(self.nplotx):
690              obj = self.request[i][j][t][z][y][x]
691              obj.getfield()
692              if self.compute != "nothing":
693                  obj.computations()
694              # save fields in self.f for the user
695              self.f[count] = obj.field
696              # save a legend in self.l for the user
697              self.l[count] = "_"
698              if self.nfin > 1:   self.l[count] = self.l[count] + "f=#"+str(int(i+1))+'_'
699              if self.nvin > 1:   self.l[count] = self.l[count] + "v="+obj.var+'_'
700              if self.nplotx > 1: self.l[count] = self.l[count] + "x="+str(self.x[x])+'_'
701              if self.nploty > 1: self.l[count] = self.l[count] + "y="+str(self.y[y])+'_'
702              if self.nplotz > 1: self.l[count] = self.l[count] + "z="+str(self.z[z])+'_'
703              if self.nplott > 1: self.l[count] = self.l[count] + "t="+str(self.t[t])+'_'
704              # close the file
705              obj.closefile()
706              count = count + 1
707        ## make it simple: self.f is simply the data array if self.nrequest=1
708        if self.nrequest == 1: self.f = self.f[0]
709        # change status
710        self.status = "retrieved"
711        return self
712
713    ##########################################################
714    # get: a shortcut method for the define + retrieve chain #
715    ##########################################################
716    def get(self):
717        self.define()
718        self.retrieve()
719        return self 
720
721    ###########################################################
722    # getf: a shortcut method for the define + retrieve chain #
723    #       ... in which the output is self.f                 #
724    #       ... and the ppclass is kept quiet                 #
725    ###########################################################
726    def getf(self):
727        self.quiet = True
728        self.get()
729        return self.f
730
731    ############################################################
732    # getfl: a shortcut method for the define + retrieve chain #
733    #       ... in which the output is self.f, self.l          #
734    #       ... and the ppclass is kept quiet                 #
735    ############################################################
736    def getfl(self):
737        self.quiet = True
738        self.get()
739        return self.f,self.l
740
741    ########################################
742    # smooth: smooth the field in 1D or 2D #
743    ########################################
744    ## TBD: smooth not OK with masked array in the end of retrieve()
745    def smooth(self,window):
746        if self.verbose: 
747            print "!! WARNING !! Performing a smoothing with a window size",window
748            print "!! WARNING !! To come back to unsmoothed file, use .get() again"
749        for i in range(self.nfin):
750         for j in range(self.nvin):
751          for t in range(self.nplott):
752           for z in range(self.nplotz):
753            for y in range(self.nploty):
754             for x in range(self.nplotx):
755              obj = self.request[i][j][t][z][y][x]
756              if obj.field.ndim == 1:
757                  print "!! ERROR !! 1D smoothing not supported yet because reduces array sizes."
758                  exit()
759                  # TBD TBD TBD
760                  #obj.field = ppcompute.smooth1d(obj.field,window=window)
761              elif obj.field.ndim == 2:
762                  obj.field = ppcompute.smooth2d(obj.field,window=window)
763                  #obj.field = ppcompute.smooth2diter(obj.field,n=window)
764
765    ############################################################################################## 
766    # defineplot method
767    # --> defineplot first defines arrays of plot objects and set each of them
768    #     ... simple looping except cases where goal is not main (e.g. contour or vector)
769    # --> principle: each onerequest() object gives birth to a subplot
770    # --> defineplot vs. makeplot: defining plot and actually plotting it are clearly separated
771    # --> THE KEY OUPUT OF defineplot IS AN ARRAY self.p OF PLOT OBJECTS
772    # optional arguments
773    # --> extraplot: to indicate a number of plots to be added afterwards (use self.plotin)
774    # --> loadfile: to use self.p from a previously saved file
775    ##############################################################################################
776    def defineplot(self,extraplot=0,loadfile=None):
777        # -----------------------------------------------------
778        # LOAD MODE: load a self.p object. count plots from it.
779        # -----------------------------------------------------
780        if loadfile is not None:
781            try: filehandler = open(loadfile, 'r') ; self.p = pickle.load(filehandler) 
782            except IOError: print "!! ERROR !! Cannot find object file to load." ; exit()
783            self.status = "definedplot" ; self.plotin = None
784            self.nplot = len(self.p) ; self.howmanyplots = self.nplot
785            ## [BUG FIX: apparently info about missing values is not saved correctly]
786            for count in range(self.nplot):
787              pl = self.p[count]
788              masked = np.ma.masked_where(np.abs(pl.f) > self.missing,pl.f)
789              pl.f = masked ; pl.f[pl.f.mask] = np.NaN
790            return #self?
791        # -----------------------------------------------------
792        # REGULAR MODE
793        # -----------------------------------------------------
794        self.printstatus()
795        # check if things were done OK before
796        if self.status in ["init","defined"]: 
797            print "!! ERROR !! Please use .retrieve() to get fields for plots with your pp object." ; exit()
798        # check self.plotin (an existing fig on which to add plots afterwards)
799        if self.plotin.__class__.__name__ == "pp":
800            if self.plotin.fig is None:
801                self.plotin = None # this is an additional security in case
802                                   #   a pp object is given without figure opened yet.
803        elif self.plotin is not None:
804            print "!! ERROR !! plotin argument must be a pp object." ; exit()
805        # initialize the array of subplot objects
806        # either something new or attributes coming from plotin object
807        if self.plotin is None:  self.p = [ ]
808        else:                    self.p = self.plotin.p
809        # create an array of subplot objects
810        # ... in theory the order of looping can be changed without any harm
811        # ... the only important thing is to keep i,j,t,z,y,x resp. for file,var,t,z,y,x
812        count = 0
813        for i in range(self.nfin):
814         if self.filegoal[i] == "main": 
815          for j in range(self.nvin):
816           if self.vargoal[j] == "main":
817            for t in range(self.nplott):
818             for z in range(self.nplotz):
819              for y in range(self.nploty):
820               for x in range(self.nplotx):
821                # look at dimension and append the right plot object
822                obj = self.request[i][j][t][z][y][x]
823                dp = obj.dimplot
824                if dp == 1 or self.forcedimplot == 1:    plobj = ppplot.plot1d()
825                elif dp == 2 or self.forcedimplot == 2:  plobj = ppplot.plot2d()
826                elif dp == 0: print "**** OK. VALUES VALUES VALUES",obj.field
827                else:         print "!! ERROR !! 3D or 4D plots not supported" ; exit()
828                # load abscissa and ordinate in obj
829                obj.definecoord()
830                # we start to define things here before appending
831                # (convenient: could be overridden by the user before makeplot)
832                # ... the if loop is necessary so that we can loop above on the dp=0 case
833                if dp in [1,2]:
834                    # and define what to do in plobj
835                    plobj.invert = obj.invert_axes
836                    plobj.swap = obj.swap_axes
837                    # axis labels
838                    plobj.xlabel = obj.absclab ; plobj.ylabel = obj.ordilab
839                    # superpose or not (this is mostly for saving purpose)
840                    plobj.superpose = self.superpose
841                    # get title, colormaps, labels, etc.. from var
842                    plobj.var = obj.var
843                    plobj.define_from_var()
844                    # generic 1D/2D: load field and coord in plot object
845                    plobj.f = obj.field    # field to be plotted
846                    plobj.x = obj.absc      # abscissa (or longitude)
847                    plobj.y = obj.ordi      # ordinate (or latitude)
848                                               # -- useless in 1D but not used anyway
849                    # specific 1D plot stuff
850                    if dp == 1:
851                        # -- a default legend
852                        plobj.legend = ""
853                        if self.nfin > 1: plobj.legend = plobj.legend + " file #"+str(i+1)
854                        if self.nvin > 1: plobj.legend = plobj.legend + " var "+plobj.var
855                        if self.nplott > 1: plobj.legend = plobj.legend + " t="+str(self.t[t])
856                        if self.nplotz > 1: plobj.legend = plobj.legend + " z="+str(self.z[z])
857                        if self.nploty > 1: plobj.legend = plobj.legend + " y="+str(self.y[y])
858                        if self.nplotx > 1: plobj.legend = plobj.legend + " x="+str(self.x[x])
859                    # specific 2d plot stuff
860                    if dp == 2:
861                        # -- light grey background for missing values
862                        if type(plobj.f).__name__ in 'MaskedArray': plobj.axisbg = '0.75'
863                        # -- define if it is a map or a plot
864                        plobj.mapmode = ( obj.method_x+obj.method_y == "freefree" \
865                                       and "grid points" not in obj.name_x \
866                                       and not self.noproj )
867                    # possible user-defined plot settings shared by all plots
868                    if self.div is not None: plobj.div = self.div
869                    if self.xlabel is not None: plobj.xlabel = self.xlabel
870                    if self.xcoeff is not None: plobj.xcoeff = self.xcoeff
871                    if self.ylabel is not None: plobj.ylabel = self.ylabel
872                    if self.ycoeff is not None: plobj.ycoeff = self.ycoeff
873                    if self.title is not None: plobj.title = self.title
874                    if self.units is not None: plobj.units = self.units
875                    if self.colorbar is not None: plobj.colorbar = self.colorbar
876                    if self.modx is not None: plobj.modx = self.modx
877                    if self.nxticks is not None: plobj.nxticks = self.nxticks
878                    if self.nyticks is not None: plobj.nyticks = self.nyticks
879                    if self.fmt is not None: plobj.fmt = self.fmt
880                    if self.showcb is not None: plobj.showcb = self.showcb
881                    if self.logy is not None: plobj.logy = self.logy
882                    if self.xmin is not None: plobj.xmin = self.xmin
883                    if self.xmax is not None: plobj.xmax = self.xmax
884                    if self.ymin is not None: plobj.ymin = self.ymin
885                    if self.ymax is not None: plobj.ymax = self.ymax
886                    # -- 1D specific
887                    if dp == 1:
888                        if self.linestyle is not None: plobj.linestyle = self.linestyle
889                        if self.marker is not None: plobj.marker = self.marker
890                        if self.color is not None: plobj.color = self.color
891                        if self.legend is not None: plobj.legend = self.legend
892                    # -- 2D specific
893                    elif dp == 2:
894                        if self.proj is not None and not self.noproj: plobj.proj = self.proj
895                        if self.vmin is not None: plobj.vmin = self.vmin
896                        if self.vmax is not None: plobj.vmax = self.vmax
897                        if self.trans is not None: plobj.trans = self.trans
898                        if self.back is not None: plobj.back = self.back
899                        plobj.svx = self.svx
900                        plobj.svy = self.svy
901                    # finally append plot object
902                    self.p.append(plobj)
903                    count = count + 1
904        # self.nplot is number of plot to be defined in this call to defineplot()
905        # (because of self.plotin this might less than length of self.p)
906        self.nplot = count
907        # --- superimposed contours and vectors ---
908        # we have to start another loop because we need forward information
909        # TBD: there is probably a more flexible way to do that
910        count = 0
911        for i in range(self.nfin):
912         for j in range(self.nvin):
913          for t in range(self.nplott):
914           for z in range(self.nplotz):
915            for y in range(self.nploty):
916             for x in range(self.nplotx):
917              goal = self.vargoal[j] + self.filegoal[i]
918              obj = self.request[i][j][t][z][y][x]
919              if "mainmain" in goal and obj.dimplot == 2:
920                  # the plot object we consider in the loop
921                  plobj = self.p[count]
922                  # -- see if there is a contour requested...
923                  # (we use try because we might be at the end of the list)
924                  found = 0
925                  try:    condvar = self.vargoal[j+1]
926                  except: condvar = "itisok"
927                  try:    condfile = self.filegoal[i+1]
928                  except: condfile = "itisok"
929                  # ... get contour
930                  ##########################################
931                  # NB: contour is expected to be right after main otherwise it is not displayed
932                  ##########################################
933                  if condvar == "contour":
934                      plobj.c = self.request[i][j+1][t][z][y][x].field ; found += 1
935                  if condfile == "contour":
936                      plobj.c = self.request[i+1][j][t][z][y][x].field ; found += 1
937                  # see if there is a vector requested...
938                  # (we use try because we might be at the end of the list)
939                  try:    condvar = self.vargoal[j+found+1]+self.vargoal[j+found+2]
940                  except: condvar = "itisok"
941                  try:    condfile = self.filegoal[i+found+1]+self.filegoal[i+found+2]
942                  except: condfile = "itisok"
943                  # ... get vector and go directly to the next iteration
944                  # (in some cases we would do this twice but this is cheap)
945                  if "vector" in condvar:
946                      plobj.vx = self.request[i][j+found+1][t][z][y][x].field
947                      plobj.vy = self.request[i][j+found+2][t][z][y][x].field
948                  if "vector" in condfile:
949                      plobj.vx = self.request[i+found+1][j][t][z][y][x].field
950                      plobj.vy = self.request[i+found+2][j][t][z][y][x].field
951                  count = count + 1
952        # COUNT PLOTS. if 0 just exit.
953        # self.howmanyplots is self.nplot + possible extraplots
954        self.howmanyplots = self.nplot + extraplot
955        if self.howmanyplots > 0:
956            if self.verbose: print "**** OK. expect %i plots" % (self.howmanyplots)
957        else:
958            pass # because this means that we only had 0D values !
959        # final status
960        self.status = "definedplot"
961        return self
962
963    ##############################################################################################
964    # makeplot method
965    # --> after defineplot and before makeplot, user-defined plot settings can be easily given
966    #     simply by modifying the attributes of each elements of self.p
967    # --> to change only one plot setting, no need to call defineplot again before makeplot
968    # --> in the end, the array self.p of plot objects is saved for easy and convenient replotting
969    # --> see practical examples in the folder 'examples'
970    ##############################################################################################
971    def makeplot(self):
972      if self.howmanyplots > 0:
973        self.printstatus()
974        # a few initial operations
975        # ------------------------
976        if "definedplot" not in self.status: 
977            print "!! ERROR !! Please use .defineplot() before .makeplot() can be used with your pp object." ; exit()
978        # open a figure and define subplots         
979        # ---------------------------------
980        if self.plotin is None: 
981            # start from scratch
982            self.fig = ppplot.figuref(x=self.xp,y=self.yp)
983            self.subv,self.subh = ppplot.definesubplot(self.howmanyplots,self.fig) 
984            self.n = 0
985            ## adapted space for labels etc
986            ## ... except for ortho because there is no label anyway
987            self.customplot = self.p[0].f.ndim == 2 \
988                        and self.p[0].mapmode == True \
989                        and self.p[0].proj not in ["ortho"]
990            if self.customplot:
991                margin = 0.07
992                self.fig.subplots_adjust(left=margin,right=1-margin,bottom=margin,top=1-margin)
993        else:
994            # start from an existing figure.
995            # extraplot must have been set in the call to the previous figure.
996            self.fig = self.plotin.fig
997            self.subv,self.subh = self.plotin.subv,self.plotin.subh
998            self.n = self.plotin.n
999            self.howmanyplots = self.plotin.howmanyplots
1000            self.customplot = self.plotin.customplot
1001        # LOOP on all subplots
1002        # NB: cannot use 'for pl in self.p' if self.plotin not None
1003        # --------------------
1004        for count in range(self.nplot):
1005            # the plot object we consider in the loop
1006            pl = self.p[self.n]
1007            # before making the plot, create a subplot. the first one is numbered 1 not 0.
1008            # ... if pl.superpose, we use only one and only figure
1009            # ... (and we have to be careful with not doing things several times)
1010            if pl.superpose:
1011                if self.n == 0: 
1012                    self.fig.add_subplot(1,1,1,axisbg=pl.axisbg) # define one subplot (still needed for user-defined font sizes)
1013                    sav = pl.xlabel,pl.ylabel,\
1014                          pl.xcoeff,pl.ycoeff,\
1015                          pl.nxticks,pl.nyticks,\
1016                          pl.xmin,pl.xmax,\
1017                          pl.ymin,pl.ymax,\
1018                          pl.title,pl.swaplab # save titles and labels
1019                    # possibility to color lines according to a color map
1020                    # ... made so that all plots span the whole color map automatically.
1021                    if self.colorbar is not None: 
1022                        if self.verbose: print "**** OK. We make a rainbow spaghetti plot with color map ",self.colorbar
1023                        ppplot.rainbow(cb=self.colorbar,num=self.howmanyplots)
1024                else: 
1025                    pl.invert = False ; pl.linestyle = None # don't invert again axis
1026                    # set saved titles and labels
1027                    if self.plotin is None:
1028                        pl.xlabel,pl.ylabel,\
1029                        pl.xcoeff,pl.ycoeff,\
1030                        pl.nxticks,pl.nyticks,\
1031                        pl.xmin,pl.xmax,\
1032                        pl.ymin,pl.ymax,\
1033                        pl.title,pl.swaplab = sav
1034                    else:
1035                        prev_plot = self.plotin.p[self.n-1]
1036                        pl.xlabel = prev_plot.xlabel ; pl.ylabel = prev_plot.ylabel
1037                        pl.xcoeff = prev_plot.xcoeff ; pl.ycoeff = prev_plot.ycoeff
1038                        pl.nxticks = prev_plot.nxticks ; pl.nyticks = prev_plot.nyticks
1039                        pl.xmin = prev_plot.xmin ; pl.xmax = prev_plot.xmax
1040                        pl.ymin = prev_plot.ymin ; pl.ymax = prev_plot.ymax
1041                        pl.title = prev_plot.title ; pl.swaplab = prev_plot.swaplab
1042            else:
1043                self.fig.add_subplot(self.subv,self.subh,self.n+1,axisbg=pl.axisbg)
1044            if self.verbose: print "**** Done subplot %i / %i " %( self.n+1,self.howmanyplots ) 
1045            # finally make the plot
1046            pl.make()
1047            # possibly print results in a text file
1048            if self.savtxt:
1049                if self.verbose: print "**** Printing results in a text file"
1050                name = pl.var + "%04d" % self.n
1051                ppplot.writeascii(field=pl.f,absc=pl.x,name=name) 
1052            # increment plot count (and propagate this in plotin)
1053            self.n = self.n+1
1054            if self.plotin is not None: self.plotin.n = self.n
1055        # once completed show the plot (cannot show intermediate plotin)
1056        # ... added a fix (customplot=True) for the label problem in basemap
1057        if not self.quiet: print "**** PPCLASS. Done step: makeplot"
1058        if (self.n == self.howmanyplots):
1059            ppplot.save(mode=self.out,filename=self.filename,folder=self.folder,custom=self.customplot,includedate=self.includedate,res=self.res)
1060            mpl.close()
1061        # SAVE A PICKLE FILE WITH THE self.p ARRAY OF OBJECTS
1062        if self.verbose: print "**** Saving session in "+self.filename + ".ppobj"
1063        savfile = self.folder + "/" + self.filename + ".ppobj"
1064        try: 
1065            filehandler = open(savfile, 'w')
1066            pickle.dump(self.p, filehandler)
1067        except IOError: 
1068            if self.verbose: print "!! WARNING !! Saved object file not written. Probably do not have permission to write here."
1069        return self
1070
1071    ###########################################################
1072    # plot: a shortcut method for the defineplot + plot chain #
1073    ###########################################################
1074    def plot(self,extraplot=0):
1075        self.defineplot(extraplot=extraplot)
1076        self.makeplot()
1077        return self
1078
1079    #######################################################
1080    # getplot: a shortcut method for the get + plot chain #
1081    #######################################################
1082    def getplot(self,extraplot=0):
1083        self.get()
1084        self.plot(extraplot=extraplot)
1085        return self
1086
1087    ###################################################################
1088    # getdefineplot: a shortcut method for the get + defineplot chain #
1089    ###################################################################
1090    def getdefineplot(self,extraplot=0):
1091        self.get()
1092        self.defineplot(extraplot=extraplot)
1093        return self
1094
1095    #################################################################
1096    # func: operation on two pp objects being on status 'definedplot'
1097    # this allows for one field being function of another one
1098    # e.g. u.func(v) means u will be displayed as a function of v
1099    # ... no need to do defineplot after u.func(v), makeplot directly
1100    #################################################################
1101    def func(self,other):
1102        # preamble: for this operation to work, defineplot() must have been done
1103        if self.status != "definedplot":
1104            if self.verbose: print "!! WARNING !! performing defineplot on operand"
1105            self.defineplot()
1106        if other.status != "definedplot":
1107            if self.verbose: print "!! WARNING !! performing defineplot on operand"
1108            other.defineplot()
1109        # check total number of plots
1110        if self.howmanyplots != other.howmanyplots:
1111               print "!! ERROR !! The two operands do not have the same number of subplots."
1112               exit()
1113        # and now operation.
1114        count = 0
1115        while count < self.howmanyplots:
1116           sobj = self.p[count] ; oobj = other.p[count]
1117           if sobj.f.ndim !=1 or oobj.f.ndim !=1:
1118               if self.verbose: print "!! WARNING !! Flattening arrays because more than one-dimensional."
1119               sobj.f = np.ravel(sobj.f)
1120               oobj.f = np.ravel(oobj.f)
1121           sobj.x = oobj.f
1122           sobj.xlabel = oobj.ylabel
1123           if sobj.x.size > sobj.f.size:
1124               if self.verbose:
1125                   print "!! WARNING !! Trying to define y=f(x) with x and y not at the same size.",sobj.x.size,sobj.f.size
1126                   print "!! WARNING !! Modifying x to fit y size but please check." 
1127               sobj.x = sobj.x[0:sobj.f.size]
1128           count = count + 1
1129        return self
1130
1131    ###########################################################
1132    # copyopt: get options from e.g. a parser
1133    # ... allow for simple scripting and user-defined settings
1134    # ... must be called between defineplot and makeplot
1135    # REQUIRED: attributes of opt must be the same as in the pp object
1136    ###########################################################
1137    def getopt(self,opt):
1138        # -- if only one, or less than the number of plots --> we take the first one
1139        # -- if as many as number of plots --> OK, each plot has its own setting
1140        # (except a few cases such as trans)
1141        for iii in range(self.howmanyplots):
1142            ## solve the bug about reversed labels with swaplab
1143            if opt.xlabel is None and opt.ylabel is None:
1144                self.p[iii].swaplab = True
1145            else:
1146                self.p[iii].swaplab = False
1147            ##
1148            if opt.void:
1149                self.p[iii].showcb = False
1150            else:
1151                self.p[iii].showcb = True
1152            ###
1153            try: self.p[iii].trans = opt.trans
1154            except: pass
1155            ###
1156            try: self.p[iii].div = opt.div
1157            except: pass
1158            ###
1159            try: self.p[iii].logy = opt.logy
1160            except: pass
1161            ###
1162            try: self.p[iii].colorbar = opt.colorbar[iii]
1163            except: 
1164                try: self.p[iii].colorbar = opt.colorbar[0] ; self.colorbar = opt.colorbar[0]
1165                except: pass
1166            ###
1167            if opt.void:
1168                self.p[iii].title = ""
1169            else:
1170              try: self.p[iii].title = opt.title[iii]
1171              except: 
1172                try: self.p[iii].title = opt.title[0]
1173                except: pass
1174            ###
1175            if opt.void:
1176                self.p[iii].xlabel = ""
1177            else:
1178              try: self.p[iii].xlabel = opt.xlabel[iii]
1179              except: 
1180                try: self.p[iii].xlabel = opt.xlabel[0]
1181                except: pass
1182            ###
1183            if opt.void:
1184                self.p[iii].ylabel = ""
1185            else:
1186              try: self.p[iii].ylabel = opt.ylabel[iii]
1187              except: 
1188                try: self.p[iii].ylabel = opt.ylabel[0]
1189                except: pass
1190            ###
1191            try: self.p[iii].linestyle = opt.linestyle[iii]
1192            except: 
1193                try: self.p[iii].linestyle = opt.linestyle[0]
1194                except: pass
1195            ###
1196            try: self.p[iii].color = opt.color[iii]
1197            except: 
1198                try: self.p[iii].color = opt.color[0]
1199                except: pass
1200            ###
1201            try: self.p[iii].marker = opt.marker[iii]
1202            except: 
1203                try: self.p[iii].marker = opt.marker[0]
1204                except: pass
1205            ###
1206            try: self.p[iii].legend = opt.legend[iii]
1207            except:
1208                try: self.p[iii].legend = opt.legend[0]
1209                except: pass
1210            ###
1211            try: self.p[iii].proj = opt.proj[iii]
1212            except: 
1213                try: self.p[iii].proj = opt.proj[0]
1214                except: pass
1215            ###
1216            try: self.p[iii].back = opt.back[iii]
1217            except: 
1218                try: self.p[iii].back = opt.back[0]
1219                except: pass
1220            ###
1221            try: self.p[iii].area = opt.area[iii]
1222            except: 
1223                try: self.p[iii].area = opt.area[0]
1224                except: pass
1225            ###
1226            try: self.p[iii].blon = opt.blon[iii]
1227            except: 
1228                try: self.p[iii].blon = opt.blon[0]
1229                except: pass
1230            ###
1231            try: self.p[iii].blat = opt.blat[iii]
1232            except: 
1233                try: self.p[iii].blat = opt.blat[0]
1234                except: pass
1235            ###
1236            try: self.p[iii].vmin = opt.vmin[iii]
1237            except: 
1238                try: self.p[iii].vmin = opt.vmin[0]
1239                except: pass
1240            ###
1241            try: self.p[iii].vmax = opt.vmax[iii]
1242            except: 
1243                try: self.p[iii].vmax = opt.vmax[0]
1244                except: pass
1245            ###
1246            try: self.p[iii].xcoeff = opt.xcoeff[iii]
1247            except:
1248                try: self.p[iii].xcoeff = opt.xcoeff[0]
1249                except: pass
1250            ###
1251            try: self.p[iii].ycoeff = opt.ycoeff[iii]
1252            except:
1253                try: self.p[iii].ycoeff = opt.ycoeff[0]
1254                except: pass
1255            ###
1256            try: self.p[iii].units = opt.units[iii]
1257            except:
1258                try: self.p[iii].units = opt.units[0]
1259                except: pass
1260            ###
1261            try: self.p[iii].wscale = opt.wscale[iii]
1262            except:
1263                try: self.p[iii].wscale = opt.wscale[0]
1264                except: pass
1265            ###
1266            try: self.p[iii].xmin = opt.xmin[iii]
1267            except:
1268                try: self.p[iii].xmin = opt.xmin[0]
1269                except: pass
1270            ###
1271            try: self.p[iii].ymin = opt.ymin[iii]
1272            except:
1273                try: self.p[iii].ymin = opt.ymin[0]
1274                except: pass
1275            ###
1276            try: self.p[iii].xmax = opt.xmax[iii]
1277            except:
1278                try: self.p[iii].xmax = opt.xmax[0]
1279                except: pass
1280            ###
1281            try: self.p[iii].ymax = opt.ymax[iii]
1282            except:
1283                try: self.p[iii].ymax = opt.ymax[0]
1284                except: pass
1285            ###
1286            try: self.p[iii].nxticks = opt.nxticks[iii]
1287            except:
1288                try: self.p[iii].nxticks = opt.nxticks[0]
1289                except: pass
1290            ###
1291            try: self.p[iii].nyticks = opt.nyticks[iii]
1292            except:
1293                try: self.p[iii].nyticks = opt.nyticks[0]
1294                except: pass
1295            ###
1296            try: self.p[iii].cbticks = opt.cbticks[iii]
1297            except:
1298                try: self.p[iii].cbticks = opt.cbticks[0]
1299                except: pass
1300            ###
1301            try: self.p[iii].modx = opt.modx[iii]
1302            except:
1303                try: self.p[iii].modx = opt.modx[0]
1304                except: pass
1305            ###
1306            try: self.p[iii].fmt = opt.fmt[iii]
1307            except:
1308                try: self.p[iii].fmt = opt.fmt[0]
1309                except: pass
1310
1311
1312##########################################################
1313### THE ONEREQUEST SUBOBJECT TO PP (ON WHICH IT LOOPS) ###
1314##########################################################
1315class onerequest():
1316
1317    # default settings. mostly initialized to diagnose problem, except dimplot, nplot, verbose, swap_axes, invert_axes
1318    # -------------------------------
1319    def __init__(self):
1320        self.file  = '!! file: I am not set, damned !!'
1321        self.f     = None
1322        self.dim   = None
1323        self.var   = '!! var: I am not set, damned !!'
1324        self.index_x = [] ; self.index_y = [] ; self.index_z = [] ; self.index_t = []
1325        self.index_x2d = [] ; self.index_y2d = []
1326        self.method_x = '!! method_x: I am not set, damned !!'
1327        self.method_y = '!! method_y: I am not set, damned !!'
1328        self.method_z = '!! method_z: I am not set, damned !!'
1329        self.method_t = '!! method_t: I am not set, damned !!'
1330        self.field = None
1331        self.name_x = None ; self.name_y = None ; self.name_z = None ; self.name_t = None
1332        self.dim_x = None ; self.dim_y = None ; self.dim_z = None ; self.dim_t = None
1333        self.field_x = None ; self.field_y = None ; self.field_z = None ; self.field_t = None
1334        self.tabtime = None
1335        self.dimplot = 0
1336        self.nplot = 1
1337        self.absc = None ; self.ordi = None ; self.absclab = None ; self.ordilab = None
1338        self.verbose = True
1339        self.swap_axes = False ; self.invert_axes = False
1340        self.compute = None
1341        self.changetime = None
1342        self.sx = 1 ; self.sy = 1 ; self.sz = 1 ; self.st = 1
1343        self.missing = '!! missing value: I am not set, damned !!'
1344        self.kind3d = '!! kind3d: I am not set, damned !!'
1345
1346    # open a file. for now it is netcdf. TBD for other formats.
1347    # check that self.var is inside.
1348    # -------------------------------
1349    def openfile(self):
1350        if not os.path.exists(self.file): print '!! ERROR !! I could not find the following file: '+self.file ; exit()
1351        if not os.path.isfile(self.file): print '!! ERROR !! This does not appear to be a file: '+self.file ; exit()
1352        self.f = netCDF4.Dataset(self.file)
1353        if self.verbose: print "**** OK. Opened file "+self.file
1354        if self.var not in self.f.variables.keys(): 
1355            print '!! ERROR !! File '+self.file+' does not contain variable: '+self.var
1356            print '..... try instead with ',self.f.variables.keys() ; exit()
1357
1358    # close a file
1359    # ------------
1360    def closefile(self):
1361        self.f.close()
1362
1363    # copy attributes from another existing object
1364    # --------------------------------------------
1365    def copy(self,source):
1366        for k, v in vars(source).items():
1367            setattr(self,k,v)
1368
1369    # get x,y,z,t dimensions from NETCDF file
1370    # TBD: user could request for a specific altitude dimension
1371    # TBD: staggered variables could request specific dimensions
1372    # -------------------------------
1373    def getdim(self):
1374          # GET SIZES OF EACH DIMENSION
1375          if self.verbose: print "**** OK. Found variable "+self.var
1376          shape = self.f.variables[self.var].shape
1377          self.dim = len(shape)
1378          if self.dim == 1:
1379              if self.verbose: print "**** OK. 1D field. I assume this varies with time."
1380              self.dim_x = 1 ; self.dim_y = 1 ; self.dim_z = 1 ; self.dim_t = shape[0]
1381          elif self.dim == 2:
1382              if self.verbose: print "**** OK. 2D field. I assume this is not-time-varying lat-lon map."
1383              self.dim_x = shape[1] ; self.dim_y = shape[0] ; self.dim_z = 1 ; self.dim_t = 1
1384          elif self.dim == 3:
1385              if self.verbose: print "**** OK. 3D field. I assume this is time-varying lat-lon map."
1386              ## see below for comment
1387              if self.kind3d == "tyx":
1388                self.dim_x = shape[2] ; self.dim_y = shape[1] ; self.dim_z = 1 ; self.dim_t = shape[0]
1389              elif self.kind3d == "tzy":
1390                self.dim_x = 1 ; self.dim_y = shape[2] ; self.dim_z = shape[1] ; self.dim_t = shape[0]
1391              else:
1392                print "!! ERROR !! This kind of 3D field is not supported. Please send feedback."
1393                print self.kind3d
1394                exit() 
1395          elif self.dim == 4:
1396              if self.verbose: print "**** OK. 4D field."
1397              self.dim_x = shape[3] ; self.dim_y = shape[2] ; self.dim_z = shape[1] ; self.dim_t = shape[0]
1398          # LONGITUDE. Try preset fields. If not present set grid points axis.
1399          self.name_x = "nothing"
1400          for c in glob_listx:
1401            if c in self.f.variables.keys():
1402             self.name_x = c
1403          if self.name_x == "nothing":
1404            self.field_x = np.array(range(self.dim_x))
1405            self.name_x = "x grid points"
1406          else:
1407            self.field_x = self.f.variables[self.name_x]
1408          # LATITUDE. Try preset fields. If not present set grid points axis.
1409          self.name_y = "nothing"
1410          for c in glob_listy:
1411            if c in self.f.variables.keys():
1412             self.name_y = c
1413          if self.name_y == "nothing":
1414            self.field_y = np.array(range(self.dim_y))
1415            self.name_y = "y grid points"
1416          else:
1417            self.field_y = self.f.variables[self.name_y]
1418          # ensure that lon and lat are 2D fields
1419          # 1. simple 1D case (not time-varying)
1420          if len(self.field_x.shape)*len(self.field_y.shape) == 1:
1421               if self.verbose: print "**** OK. recasting lon and lat as 2D fields." 
1422               [self.field_x,self.field_y] = np.meshgrid(self.field_x,self.field_y)
1423          # 2. complex 3D case (time-varying, actually just copied over time axis)
1424          elif len(self.field_x.shape)*len(self.field_y.shape) == 9:
1425               if self.verbose: print "**** OK. reducing lon and lat as 2D fields. get rid of time."
1426               self.field_x = self.field_x[0,:,:]
1427               self.field_y = self.field_y[0,:,:]
1428          # if xy axis are apparently undefined, set 2D grid points axis.
1429          if "grid points" not in self.name_x:
1430            if np.all(self.field_x == self.field_x[0,0]) \
1431             or self.field_x.min() == self.field_x.max() \
1432             or self.field_y.min() == self.field_y.max():
1433               if self.verbose: print "!! WARNING !! xy axis look undefined. creating non-dummy ones."
1434               self.field_x = np.array(range(self.dim_x)) ; self.name_x = "x grid points"
1435               self.field_y = np.array(range(self.dim_y)) ; self.name_y = "y grid points"
1436               [self.field_x,self.field_y] = np.meshgrid(self.field_x,self.field_y)
1437          if self.dim_x > 1: 
1438               if self.verbose: print "**** OK. x axis %4.0f values [%5.1f,%5.1f]" % (self.dim_x,self.field_x.min(),self.field_x.max())
1439          if self.dim_y > 1: 
1440               if self.verbose: print "**** OK. y axis %4.0f values [%5.1f,%5.1f]" % (self.dim_y,self.field_y.min(),self.field_y.max())
1441          # ALTITUDE. Try preset fields. If not present set grid points axis.
1442          # WARNING: how do we do if several are available? the last one is chosen.
1443          self.name_z = "nothing"
1444          for c in glob_listz:
1445            if c in self.f.variables.keys():
1446             self.name_z = c
1447          if self.name_z == "nothing":
1448            self.field_z = np.array(range(self.dim_z))
1449            self.name_z = "z grid points"
1450          else:
1451            tabalt = self.f.variables[self.name_z]
1452            # (consider the case where tabtime is not dim 1) TBD: 2D and 3D cases
1453            if tabalt.ndim == 4: 
1454                try:
1455                    self.field_z = tabalt[1,:,0,0] # 4D case. alt is usually third dimension.
1456                                                   # 1 for time to avoid initial 0s
1457                except:
1458                    self.field_z = tabalt[0,:,0,0]
1459                if self.verbose: print "!! WARNING !! "+self.name_z+" is 4D var. We made it 1D."
1460            else: 
1461                self.field_z = self.f.variables[self.name_z][:] # specify dimension
1462            # TBD: problems when self.dim_z != self.field_z.size
1463            if self.field_z.size != self.dim_z:
1464                if self.verbose: print "!! WARNING !! Cannot use this z coordinate. Not enough points. Use simple z axis."
1465                self.field_z = np.array(range(self.dim_z))
1466                self.name_z = "z grid points"
1467          if self.dim_z > 1: 
1468               if self.verbose: print "**** OK. z axis %4.0f values [%5.1f,%5.1f]" % (self.dim_z,self.field_z.min(),self.field_z.max())
1469
1470          # TIME. Try preset fields.
1471          self.name_t = "nothing"
1472          for c in glob_listt:
1473            if c in self.f.variables.keys():
1474             self.name_t = c
1475             if self.verbose: print "**** OK. Found time variable: ",c
1476          try:
1477            # speed up: only get first value, last one.
1478            self.tabtime = self.f.variables[self.name_t]
1479            # (consider the case where tabtime is not dim 1)
1480            # (time is most often the first dimension)
1481            if self.tabtime.ndim == 2: self.tabtime = self.tabtime[:,0]
1482            elif self.tabtime.ndim == 3: self.tabtime = self.tabtime[:,0,0]
1483            elif self.tabtime.ndim == 4: self.tabtime = self.tabtime[:,0,0,0]
1484            # (now proceed) (the +0. just ensures this is a number)
1485            dafirst = self.tabtime[0] + 0.
1486            if self.dim_t == 1:
1487                self.field_t = np.array([dafirst])
1488            else:
1489                daint = self.tabtime[1] - dafirst
1490                dalast = dafirst + (self.dim_t-1)*daint
1491                self.field_t = np.linspace(dafirst,dalast,num=self.dim_t)
1492                if self.verbose:
1493                    print "!! WARNING !! WARNING !! Time axis is supposed to be equally spaced !!"
1494                    if dalast != self.tabtime[self.dim_t-1]:
1495                        print "!! WARNING !! Time axis has been recast to be monotonic",dalast,self.tabtime[self.dim_t-1]
1496          except:
1497            # ... or if a problem encountered, define a simple time axis
1498            if self.verbose: print "**** OK. There is something weird. Let us go for a simple time axis."
1499            self.field_t = np.array(range(self.dim_t))
1500            self.name_t = "t grid points"
1501          if self.dim_t > 1: 
1502               if self.verbose: print "**** OK. t axis %4.0f values [%5.1f,%5.1f]" % (self.dim_t,self.field_t.min(),self.field_t.max())     
1503
1504    # change time axis
1505    # ... add your options here!
1506    # --------------------------
1507    def performtimechange(self):
1508        if self.changetime is not None:
1509            if self.verbose: print "**** OK. Converting time axis:",self.changetime
1510            ### options added by T. Navarro
1511            if self.changetime == "mars_sol2ls":
1512                if "controle" in self.f.variables: 
1513                   self.field_t =  self.field_t \
1514                                 + self.f.variables['controle'][3]%669 \
1515                                 + self.f.variables['controle'][26]
1516                self.field_t = ppcompute.mars_sol2ls(self.field_t)
1517            elif self.changetime == "mars_dayini" and "controle" in self.f.variables:
1518                self.field_t =  self.field_t \
1519                              + self.f.variables['controle'][3]%669 \
1520                              + self.f.variables['controle'][26]
1521            ### options added by A. Spiga
1522            elif self.changetime == "correctls":
1523             if self.tabtime is None:
1524              print "!! WARNING !! Encountered a problem with correctls. Check your time dimension. Skipping this part."
1525             else: 
1526              dafirst = self.tabtime[0] + 0.
1527              if self.dim_t == 1:
1528                self.field_t = np.array([dafirst])
1529              else:
1530                daint = self.tabtime[1] - dafirst
1531                dalast = dafirst + (self.dim_t-1)*daint
1532                year = 0.
1533                add = np.linspace(dafirst,dalast,num=self.dim_t) ; add[0] = 0.
1534                for iii in range(1,self.dim_t):
1535                  if self.tabtime[iii] - self.tabtime[iii-1] < 0: year = year+1.
1536                  add[iii] = year*360.
1537                self.field_t = add + self.tabtime
1538            elif "mars_meso" in self.changetime:
1539                if 'Times' not in self.f.variables.keys():
1540                    if self.verbose: print "!! WARNING !! Variable Times not in file. Cannot proceed to change of time axis."
1541                else:
1542                    # get the array of strings describing dates
1543                    dates = self.f.variables['Times']
1544                    dates.set_auto_maskandscale(False) # necessary to solve the api Times bug!
1545                    # get ls sol utc from those strings
1546                    ls, sol, utc = ppcompute.mars_date(dates[:])
1547                    # populate self.field_t with the right output from mars_date
1548                    if self.changetime == "mars_meso_ls": 
1549                        self.field_t = ls
1550                        self.name_t = "Ls"
1551                    elif self.changetime == "mars_meso_sol": 
1552                        self.field_t = sol
1553                        self.name_t = "sol"
1554                    elif self.changetime == "mars_meso_utc" \
1555                        and ( self.changetime == "mars_meso_lt" \
1556                              and not hasattr(self.f,'CEN_LON') ): 
1557                        self.field_t = ppcompute.timecorrect(utc)
1558                        self.name_t = "utc"
1559                        if self.method_t == "fixed": 
1560                            self.field_t = self.field_t % 24 # so that the user is not mistaken!
1561                    elif self.changetime == "mars_meso_lt":
1562                        self.field_t = ppcompute.timecorrect(utc) + getattr(self.f,'CEN_LON') / 15.
1563                        self.field_t = ppcompute.timecorrect(self.field_t)
1564                        self.name_t = "local time (center of domain)"
1565                        if self.method_t == "fixed": 
1566                            self.field_t = self.field_t % 24 # so that the user is not mistaken!
1567            else:
1568                if self.verbose: print "!! WARNING !! This time change is not implemented. Nothing is done."
1569            if self.verbose: print "**** OK. new t axis values [%5.1f,%5.1f]" % (self.field_t.min(),self.field_t.max())
1570
1571    # get list of index to be retrieved for time axis
1572    ### TBD: il faudrait ne prendre que les indices qui correspondent a l interieur d un plot (dans all)
1573    # -------------------------------
1574    def getindextime(self,dalist=None,ind=None):
1575        if self.method_t == "free": 
1576            self.index_t = np.arange(0,self.dim_t,self.st)
1577            if self.dim_t > 1: 
1578                self.dimplot = self.dimplot + 1 
1579                if self.verbose: print "**** OK. t values. all."
1580            else:               
1581                self.method_t = "fixed"
1582                if self.verbose: print "**** OK. no t dimension."
1583        elif self.method_t == "comp":
1584            start = np.argmin( np.abs( self.field_t - dalist[ind][0] ) )
1585            stop = np.argmin( np.abs( self.field_t - dalist[ind][1] ) )
1586            self.index_t = np.arange(start,stop+1,self.st)
1587            if self.verbose: print "**** OK. t values. comp over interval ",self.field_t[start],self.field_t[stop]," nvalues=",self.index_t.size
1588        elif self.method_t == "fixed":
1589            self.index_t.append( np.argmin( np.abs( self.field_t - dalist[ind][0] ) ))
1590            if self.verbose: print "**** OK. t values",self.field_t[self.index_t]
1591        else:
1592            print "!! ERROR !! method "+self.method_t+" not supported"
1593        self.index_t = np.array(self.index_t)
1594             
1595    # get list of index to be retrieved for vertical axis
1596    ### TBD: il faudrait ne prendre que les indices qui correspondent a l interieur d un plot (dans all)
1597    # -------------------------------
1598    def getindexvert(self,dalist=None,ind=None):
1599        if self.method_z == "free": 
1600            self.index_z = np.arange(0,self.dim_z,self.sz)
1601            if self.dim_z > 1: 
1602                self.dimplot = self.dimplot + 1
1603                if self.verbose: print "**** OK. z values. all."
1604            else:               
1605                self.method_z = "fixed"
1606                if self.verbose: print "**** OK. no z dimension."
1607        elif self.method_z == "comp":
1608            start = np.argmin( np.abs( self.field_z - dalist[ind][0] ) )
1609            stop = np.argmin( np.abs( self.field_z - dalist[ind][1] ) )
1610            self.index_z = np.arange(start,stop+1,self.sz)
1611            if self.verbose: print "**** OK. z values. comp over interval",self.field_z[start],self.field_z[stop]," nvalues=",self.index_z.size
1612        elif self.method_z == "fixed":
1613            self.index_z.append( np.argmin( np.abs( self.field_z - dalist[ind][0] ) ))
1614            if self.verbose: print "**** OK. z values",self.field_z[self.index_z]
1615        else:
1616            if self.verbose: print "!! ERROR !! method "+self.method_z+" not supported"
1617        self.index_z = np.array(self.index_z)
1618
1619    # get list of index to be retrieved for horizontal grid
1620    # --> index_x and index_y are slices to be retrieved from NETCDF files
1621    # --> index_x2d and index_y2d are the actual (x,y) coordinates corresponding to each relevant point
1622    # [this is slightly more complicated because 2D arrays for lat-lon projection possibly irregular]
1623    # NB: to append index we use lists (the most convenient) then we convert into a numpy.array
1624    ### TBD: il faudrait ne prendre que les indices qui correspondent a l interieur d un plot (dans all)
1625    # -------------------------------
1626    def getindexhori(self,dalistx=None,dalisty=None,indx=None,indy=None):
1627        ## get what is the method over x and y axis
1628        test = self.method_x+self.method_y
1629        ## CASE 0, EASY CASES:
1630        ## - LAT IS FREE (we do here what must be done whatever LON case is)
1631        ## - LON IS FREE (we do here what must be done whatever LAT case is)
1632        ## - LAT IS COMP AND LON IS FREE
1633        ## - LON IS COMP AND LAT IS FREE
1634        if self.method_x == "free" or test in ["compfree","compcomp"]:
1635            self.index_x = range(0,self.dim_x,self.sx)
1636            if self.dim_x > 1: 
1637                if self.method_x == "free": self.dimplot = self.dimplot + 1
1638                if self.verbose: print "**** OK. x values. all."
1639            else:               
1640                self.method_x = "fixed"
1641                if self.verbose: print "**** OK. no x dimension."
1642        if self.method_y == "free" or test in ["freecomp","compcomp"]:
1643            self.index_y = range(0,self.dim_y,self.sy)
1644            if self.dim_y > 1: 
1645                if self.method_y == "free": self.dimplot = self.dimplot + 1
1646                if self.verbose: print "**** OK. y values. all."
1647            else:               
1648                self.method_y = "fixed"
1649                if self.verbose: print "**** OK. no y dimension."
1650        ## CASE 0 above, this is just for continuity for free.
1651        ## ... for comp we have to select bounds.
1652        ## ... TBD: take the bool array strategy for what follows!
1653        if self.method_x in ["free","comp"] and self.method_y in ["free","comp"]:
1654            ### ref1_dirty_hack
1655            ### ... for the moment this is a hack. but actually this is more powerful.
1656            if self.method_x == "comp":
1657                yeah = (self.field_x >= dalistx[indx][0])*(self.field_x <= dalistx[indx][1])
1658                self.index_x = yeah[0,:]
1659            if self.method_y == "comp":
1660                yeah = (self.field_y >= dalisty[indy][0]) * (self.field_y <= dalisty[indy][1])
1661                self.index_y = yeah[:,0]
1662            self.index_x2d = self.index_x
1663            self.index_y2d = self.index_y
1664        ## AND NOW THE LITTLE BIT MORE COMPLICATED CASES
1665        ## CASE 1 LAT AND LON ARE FIXED
1666        elif test == "fixedfixed":
1667            idy,idx = np.unravel_index( np.argmin( ( self.field_x - dalistx[indx][0])**2 + (self.field_y - dalisty[indy][0])**2 ), self.field_x.shape ) 
1668                          #TBD: pb with staggered coord
1669            if idx not in self.index_x:  self.index_x.append(idx)
1670            if idy not in self.index_y:  self.index_y.append(idy)
1671            self.index_x2d.append(idx)
1672            self.index_y2d.append(idy)
1673        ## CASE 2 LON IS FIXED BUT NOT LAT
1674        elif test in ["fixedfree","fixedcomp"]:
1675            # find where are requested x values for each y on the free dimension
1676            # NB: this does not work for non-bijective cases e.g. polar stereographic
1677            for iy in range(self.dim_y):
1678              idx = np.argmin( np.abs( self.field_x[iy,:] - dalistx[indx][0] ) )
1679              # if comp is requested we select only indexes which yield values between requested min and max
1680              storeval = (self.method_y == "comp") and (self.field_y[iy,idx] > dalisty[indy][0]) and (self.field_y[iy,idx] < dalisty[indy][1])
1681              storeval = storeval or (self.method_y == "free")
1682              if storeval:
1683                  if idx not in self.index_x:  self.index_x.append(idx)
1684                  if iy not in self.index_y and self.method_y == "comp": self.index_y.append(iy)
1685                  if idx not in self.index_x2d or iy not in self.index_y2d:
1686                    self.index_x2d.append(idx)
1687                    self.index_y2d.append(iy)
1688        ## CASE 3 LAT IS FIXED BUT NOT LON
1689        elif test in ["freefixed","compfixed"]:
1690            # find where are requested y values for each x on the free dimension
1691            # NB: this does not work for non-bijective cases e.g. polar stereographic
1692            for ix in range(self.dim_x):
1693              idy = np.argmin( np.abs( self.field_y[:,ix] - dalisty[indy][0] ) )
1694              # if comp is requested we select only indexes which yield values between requested min and max
1695              storeval = (self.method_x == "comp") and (self.field_x[idy,ix] > dalistx[indx][0]) and (self.field_x[idy,ix] < dalistx[indx][1])
1696              storeval = storeval or (self.method_x == "free")
1697              if storeval:
1698                  if idy not in self.index_y:  self.index_y.append(idy)
1699                  if ix not in self.index_x and self.method_x == "comp": self.index_x.append(ix)
1700                  if ix not in self.index_x2d or idy not in self.index_y2d:
1701                    self.index_x2d.append(ix)
1702                    self.index_y2d.append(idy)
1703        ## check index tab
1704        if len(self.index_x) == 0 or len(self.index_y) == 0:
1705            print "!! ERROR !! no indices found. check prescribed latitudes or longitudes" ; exit()
1706        ## ensure the array is a numpy array for getfield to work
1707        self.index_x = np.array(self.index_x)
1708        self.index_y = np.array(self.index_y)
1709        self.index_x2d = np.array(self.index_x2d)
1710        self.index_y2d = np.array(self.index_y2d)
1711        ### print extrema
1712        printx = self.field_x[np.ix_(self.index_y2d, self.index_x2d)]
1713        printy = self.field_y[np.ix_(self.index_y2d, self.index_x2d)]
1714        if self.verbose: 
1715            print "**** OK. x values (min,max).", printx.min(),printx.max()
1716            print "**** OK. y values (min,max).", printy.min(),printy.max()
1717
1718    # get the field from the NETCDF file and perform averages
1719    # -------------------------------
1720    def getfield(self):
1721        ## first tell what is to be done
1722        if self.verbose:
1723          if self.dimplot > 2:                       print "**** !! WARNING !! "+str(self.dimplot)+"D plots will not be supported!"
1724          elif self.dimplot == 0 and self.verbose:   print "**** OK. 0D value requested."
1725          elif self.dimplot == 1 and self.verbose:   print "**** OK. 1D plot requested."
1726          elif self.verbose:                         print "**** OK. 2D section requested."
1727        # well, now get field from netcdf file
1728        # part below is necessary otherwise there is an index error below
1729        if self.index_x.size == 1: self.index_x = self.index_x[0]
1730        if self.index_y.size == 1: self.index_y = self.index_y[0]
1731        if self.index_z.size == 1: self.index_z = self.index_z[0]
1732        if self.index_t.size == 1: self.index_t = self.index_t[0]
1733        # then retrieve what is requested by user
1734        # each self.dim case corresponds to tests in the beginning of getdim.
1735        time0 = timelib.time()
1736        if self.verbose: print "**** OK. I am getting values from files. Please wait."
1737        if self.dim == 1: 
1738            nt = self.index_t.size ; nz = 1 ; ny = 1 ; nx = 1
1739            self.field = self.f.variables[self.var][self.index_t]
1740        elif self.dim == 2:
1741            nt = 1 ; nz = 1 ; ny = self.index_y.size ; nx = self.index_x.size
1742            self.field = self.f.variables[self.var][self.index_y,self.index_x]
1743        elif self.dim == 3:
1744            ## DEFAULT tyx (time-varying 2D field)
1745            if self.kind3d == "tyx":
1746               nt = self.index_t.size ; nz = 1 ; ny = self.index_y.size ; nx = self.index_x.size
1747               self.field = self.f.variables[self.var][self.index_t,self.index_y,self.index_x]
1748            ## CASE tzy (e.g. time-varying zonal mean y-z field)
1749            elif self.kind3d == "tzy":
1750               nt = self.index_t.size ; nz = self.index_z.size ; ny = self.index_y.size ; nx = 1
1751               self.field = self.f.variables[self.var][self.index_t,self.index_z,self.index_y]
1752            else:
1753               print "!! ERROR !! This kind of 3D field is not supported. Please send feedback." ; exit()
1754            # this is far faster than retrieving each term with a loop
1755        elif self.dim == 4:
1756            nt = self.index_t.size ; nz = self.index_z.size ; ny = self.index_y.size ; nx = self.index_x.size
1757            self.field = self.f.variables[self.var][self.index_t,self.index_z,self.index_y,self.index_x]
1758        else:
1759            print "!! ERROR !! field would have more than four dimensions ?" ; exit()
1760        # dirty hack (AS) ref1_dirty_hack
1761        # waiting for more fundamental modifications. case when self.index_y is a bool array.
1762        # ... be careful if no point...
1763        try:
1764            if type(self.index_x[0]) == np.bool_: nx = np.sum(self.index_x) ## gives the size of the True part!
1765            if type(self.index_y[0]) == np.bool_: ny = np.sum(self.index_y) ## gives the size of the True part!
1766        except:
1767            pass
1768        # NB: ... always 4D array but possibly with "size 1" dimensions
1769        #     ... if one dimension is missing because 1D 2D or 3D requests, make it appear again
1770        self.field = np.reshape(self.field,(nt,nz,ny,nx))
1771        if self.verbose: print "**** OK. I got %7.1e values. This took me %6.4f seconds" % (nx*ny*nz*nt,timelib.time() - time0)
1772        if self.verbose: print "**** OK. I got var "+self.var+" with shape",self.field.shape
1773        # reduce coordinates to useful points
1774        # ... TBD: this should be ordered in the case of non-regular projections
1775        if self.method_x in ["free","comp"] and self.method_y in ["free","comp"]:
1776          # we need 2D coordinates (free) or we get broadcast problem (comp) so we use np.ix
1777          self.field_x = self.field_x[np.ix_(self.index_y2d, self.index_x2d)]
1778          self.field_y = self.field_y[np.ix_(self.index_y2d, self.index_x2d)]
1779        else:
1780          # we are OK with 1D coordinates
1781          self.field_x = self.field_x[self.index_y2d, self.index_x2d]
1782          self.field_y = self.field_y[self.index_y2d, self.index_x2d]
1783          # ... there are special cases with strides
1784          # ... some other fixes will be needed probably TBD
1785          if self.method_x == "free" and self.sx != 1:
1786              self.field_x = self.field_x[self.index_x]
1787          if self.method_y == "free" and self.sy != 1: 
1788              self.field_y = self.field_y[self.index_y]
1789        self.field_z = self.field_z[self.index_z]
1790        self.field_t = self.field_t[self.index_t]
1791        # extract relevant horizontal points
1792        # TBD: is compfree OK with computing on irregular grid?
1793        test = self.method_x + self.method_y
1794        if test in ["fixedfixed","freefree"]:
1795          pass
1796        elif test in ["fixedfree","fixedcomp"] or test in ["freefixed","compfixed"]: 
1797         if self.sx == 1 and self.sy == 1:
1798          time0 = timelib.time()
1799          # now have to obtain the new indexes which correspond to the extracted self.field
1800          # for it to work with unique index, ensure that any index_* is a numpy array
1801          if not isinstance(self.index_x, np.ndarray): self.index_x = np.array([self.index_x])
1802          if not isinstance(self.index_y, np.ndarray): self.index_y = np.array([self.index_y])
1803          if not isinstance(self.index_z, np.ndarray): self.index_z = np.array([self.index_z])
1804          if not isinstance(self.index_t, np.ndarray): self.index_t = np.array([self.index_t])
1805          for val in self.index_x: self.index_x2d[np.where(self.index_x2d == val)] = np.where(self.index_x == val)[0]
1806          for val in self.index_y: self.index_y2d[np.where(self.index_y2d == val)] = np.where(self.index_y == val)[0]
1807               ##### VERY EXPENSIVE
1808               ## recast self.field with 2D horizontal arrays because we might have extracted
1809               ## more than what is to be actually plot or computed, in particular for comps on 2D lat,lon coordinates
1810               #self.field = self.field[np.ix_(self.index_t,self.index_z,self.index_y2d,self.index_x2d)]
1811               #(nt,nz,ny,nx) = self.field.shape       
1812          # prepare the loop on all relevant horizontal points
1813          if self.method_x in ["comp","free"]:   
1814              nnn = self.index_x2d.shape[0] ; what_I_am_supposed_to_do = "keepx"
1815          elif self.method_y in ["comp","free"]: 
1816              nnn = self.index_y2d.shape[0] ; what_I_am_supposed_to_do = "keepy" 
1817          # LOOP to extract only useful values over horizontal dimensions
1818          # only take diagonal terms, do not loop on all self.index_x2d*self.index_y2d
1819          # ... this method is fast enough, perhaps there is a faster way though
1820          # ... (for sure the method with np.diag is much slower)
1821          for iii in range(nnn):
1822           ix = self.index_x2d[iii] ; iy = self.index_y2d[iii]
1823           for iz in range(self.index_z.size):
1824            for it in range(self.index_t.size):
1825              if what_I_am_supposed_to_do == "keepx":    self.field[it,iz,0,ix] = self.field[it,iz,iy,ix]
1826              elif what_I_am_supposed_to_do == "keepy":  self.field[it,iz,iy,0] = self.field[it,iz,iy,ix]
1827          if self.verbose: print "**** OK. I got to pick the right values for your request. This took me %6.4f seconds" % (timelib.time() - time0)
1828          # we only keep the one value that was modified on the dimension which is not free
1829          if what_I_am_supposed_to_do == "keepx":     self.field = self.field[:,:,0,:] ; ny = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1830          elif what_I_am_supposed_to_do == "keepy":   self.field = self.field[:,:,:,0] ; nx = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1831         else:
1832          # there is a problem above if stride != 1. a fix must be found. rewrite might be necessary. TBD
1833          pass
1834        # check if 'not finite' values are present
1835        # (happens with some netCDF files where -- appears in arrays)
1836        # (but isn't it that netcdf4 returns masked arrays?)
1837        # -- we do not perform this correction for computations for which -- are handled correctly
1838        if "comp" not in self.method_t+self.method_z+self.method_y+self.method_x:
1839          w = np.where(np.isfinite(self.field) != True)
1840          self.field[w] = np.NaN
1841        ## catch netCDF missing values (TBD: add a test try)
1842        #miss = self.f.variables[self.var].missing_value
1843        #if miss is not None: self.missing = miss
1844        # make a mask in case there are non-NaN missing values.
1845        # ... this is important for computations below (see ppcompute)
1846        masked = np.ma.masked_where(np.abs(self.field) >= self.missing,self.field)
1847        if masked.mask.any() == True:
1848             if self.verbose: print "!! WARNING !! Values over %5.3e are considered missing values." % self.missing
1849             self.field = masked
1850             self.field.set_fill_value([np.NaN])
1851
1852    # perform computations
1853    # -------------------------------
1854    # available: mean, max, min, meanarea
1855    # TB: integrals? for derivatives, define a function self.dx()
1856    def computations(self): 
1857        nt,nz,ny,nx = self.field.shape
1858        # treat the case of mean on fields normalized with grid mesh area
1859        # ... this is done in the .area() method.
1860        # after that self.field contains field*area/totarea
1861        if "area" in self.compute: 
1862            if "comp" in self.method_x+self.method_y: 
1863                self.area()
1864            else:
1865                if self.verbose: print "!! WARNING !! No area accounted for (computing on t and/or z axis)."
1866        # prepare quadratic mean
1867        if "qmean" in self.compute: self.field = self.field*self.field
1868        # now ready to compute [TBD: we would like to have e.g. mean over x,y and min over t ??]
1869        if self.method_t == "comp":
1870            if self.verbose: print "**** OK. Computing over t axis."
1871            if "mean" in self.compute: self.field = ppcompute.mean(self.field,axis=0)
1872            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=0)
1873            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=0)
1874            else: print "!! ERROR !! operation not supported." ; exit()
1875            nt = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1876        if self.method_z == "comp": 
1877            if self.verbose: print "**** OK. Computing over z axis."
1878            if "mean" in self.compute: self.field = ppcompute.mean(self.field,axis=1)
1879            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=1)
1880            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=1)
1881            else: print "!! ERROR !! operation not supported." ; exit()
1882            nz = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1883        if self.method_y == "comp": 
1884            if self.verbose: print "**** OK. Computing over y axis."
1885            if self.compute == "meanarea": self.field = ppcompute.sum(self.field,axis=2)
1886            elif "mean" in self.compute: self.field = ppcompute.mean(self.field,axis=2)
1887            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=2)
1888            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=2)
1889            else: print "!! ERROR !! operation not supported." ; exit()
1890            ny = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1891            if self.field_x.ndim == 2: self.field_x = self.field_x[0,:] # TBD: this is OK for regular grid but not for irregular
1892        if self.method_x == "comp":
1893            if self.verbose: print "**** OK. Computing over x axis."
1894            if self.compute == "meanarea": self.field = ppcompute.sum(self.field,axis=3)
1895            elif "mean" in self.compute: self.field = ppcompute.mean(self.field,axis=3)
1896            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=3)
1897            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=3)
1898            else: print "!! ERROR !! operation not supported." ; exit()
1899            nx = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1900            if self.field_y.ndim == 2: self.field_y = self.field_y[:,0] # TBD: this is OK for regular grid but not for irregular
1901        # remove all dimensions with size 1 to prepare plot (and check the resulting dimension with dimplot)
1902        self.field = np.squeeze(self.field)
1903        # take root mean square for quadratic mean
1904        if self.compute == "qmean": self.field = np.sqrt(self.field)
1905        # error handling and verbose
1906        if self.field.ndim != self.dimplot: 
1907            print "!! ERROR !! Problem: self.field is different than plot dimensions", self.field.ndim, self.dimplot ; exit()
1908        if self.verbose: 
1909            print "**** OK. Final shape for "+self.var+" after averaging and squeezing",self.field.shape
1910   
1911    # get areas for computations and ponderate self.field by area/totarea
1912    # -------------------------------------------------------------------
1913    def area(self):
1914        if self.verbose: print "**** OK. Get area array for computations."
1915        # create a request object for area
1916        # ... and copy known attributes from self
1917        aire = onerequest()
1918        aire.copy(self)
1919        # get area field name
1920        aire.var = "nothing"
1921        for c in glob_listarea:
1922         if c in aire.f.variables.keys():
1923            aire.var = c
1924        # do not try to calculate areas automatically
1925        if aire.var == "nothing":
1926            print "!! ERROR !! area variable not found... needs to be added in set_ppclass.txt?"
1927            exit()
1928        # define area request dimensions
1929        aire.getdim()
1930        # ensure this is a 2D horizontal request and define indexes
1931        #    ... areas are not supposed to vary with time and height
1932        aire.method_x = "free" ; aire.method_y = "free"
1933        aire.getindexhori() ; aire.dimplot = 2
1934        aire.method_z = "fixed" ; aire.field_z = np.array([0]) ; aire.index_z = np.array([0])
1935        aire.method_t = "fixed" ; aire.field_t = np.array([0]) ; aire.index_t = np.array([0])
1936        # read the 2D area array in netCDF file
1937        aire.getfield()
1938        aire.field = np.squeeze(aire.field)
1939        # reduce with self horizontal indexes
1940        if "fixed" in self.method_x+self.method_y:
1941            aire.field = aire.field[self.index_y,self.index_x]
1942        # calculate total area
1943        # ... 2D comp is easy. 1D comp is a bit less easy but simple array manipulation.
1944        if "free" in self.method_x+self.method_y:
1945            if self.method_x == "free":
1946                totarea = ppcompute.sum(aire.field,axis=0)
1947                totarea = np.reshape(totarea,(1,totarea.size))
1948                totarea = np.tile(totarea,(1,self.index_x))
1949            elif self.method_y == "free":
1950                totarea = ppcompute.sum(aire.field,axis=1)
1951                totarea = np.reshape(totarea,(totarea.size,1))
1952                totarea = np.tile(totarea,(1,self.index_x.size))
1953        elif self.method_x == "comp" and self.method_y == "comp":
1954            aire.field = aire.field[np.ix_(self.index_y, self.index_x)] # reduce to requested indexes only
1955            totarea = ppcompute.sum(ppcompute.sum(aire.field,axis=1),axis=0)
1956        else:
1957            if self.verbose: print "!! WARNING !! Not account for areas. Only averaging over z and/or t axis."
1958        # normalize by total area
1959        print "**** OK. I can now normalize field by areas."
1960        aire.field = aire.field / totarea
1961        # tile area array over self t and z axis so that area field could be multiplied with self.field
1962        aire.field = np.tile(aire.field,(self.index_t.size,self.index_z.size,1,1))
1963        if self.field.shape != aire.field.shape:
1964            print "!! ERROR !! Problem in area(). Check array shapes."
1965            print "Field vs. aire:",self.field.shape,aire.field.shape ; exit()
1966        else:
1967            self.field = self.field*aire.field
1968
1969    # define coordinates for plot
1970    # -------------------------------
1971    def definecoord(self):
1972        I_got_abs = False ; I_got_ord = False
1973        # here is the thing. time is usually taken as an abscissa so we start with time.
1974        if self.method_t ==  "free": 
1975            self.absc = self.field_t ; self.absclab = self.name_t
1976            I_got_abs = True
1977        # then we usually have x as an abscissa.
1978        if self.method_x == "free":
1979            if I_got_abs: 
1980                self.ordi = self.field_x ; self.ordilab = self.name_x
1981                I_got_ord = True
1982            else:         
1983                self.absc = self.field_x ; self.absclab = self.name_x
1984                I_got_abs = True
1985        # ... or we have y
1986        if self.method_y == "free":
1987            if I_got_abs:   
1988                self.ordi = self.field_y ; self.ordilab = self.name_y
1989                I_got_ord = True
1990            else:         
1991                self.absc = self.field_y ; self.absclab = self.name_y
1992                I_got_abs = True
1993        # ... and we end with z because it is usually not an abscissa (profiles).
1994        if self.method_z == "free":
1995            if self.field_z[0] > self.field_z[1]:
1996                self.invert_axes = True # the axis will be turned upside-down
1997            if I_got_abs: 
1998                self.ordi = self.field_z ; self.ordilab = self.name_z
1999                I_got_ord = True
2000            else:
2001                self.absc = self.field_z ; self.absclab = self.name_z
2002                I_got_abs = True
2003                self.swap_axes = True # says that altitude is not supposed to remain as an abscissa
2004        if I_got_abs and self.verbose: print "**** OK. abscissa:",self.absclab, self.absc.shape
2005        if I_got_ord and self.verbose: print "**** OK. ordinate:",self.ordilab, self.ordi.shape
Note: See TracBrowser for help on using the repository browser.