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

Last change on this file since 1336 was 1317, checked in by tnavarro, 11 years ago

bug in verbose mode

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