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

Last change on this file since 1159 was 1158, checked in by aslmd, 11 years ago

planetoplot. added treatment for xmin xmax from main pp class.

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