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

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

UTIL PYTHON planetoplot_v2. Solved a problem with operations: operands were modified, now operations are conservative for operands. Implemented reversed operations for int/float.

File size: 68.4 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###################################
26print "************************************"
27print "**** WELCOME TO PLANETOPLOT 2.0 ****"
28print "************************************"
29# where settings files are located...
30whereset = None
31whereset = ppcompute.findset(whereset)
32# ... we load user-defined automatic settings from set_ppclass.txt
33zefile = "set_ppclass.txt"
34glob_listx = [] ; glob_listy = [] ; glob_listz = [] ; glob_listt = []
35try: 
36    f = open(whereset+zefile, 'r') ; lines = f.readlines()
37    for stuff in lines[5].strip().split(';'): glob_listx.append(stuff)
38    for stuff in lines[8].strip().split(';'): glob_listy.append(stuff)
39    for stuff in lines[11].strip().split(';'): glob_listz.append(stuff)
40    for stuff in lines[14].strip().split(';'): glob_listt.append(stuff)
41except IOError: 
42    print "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 "**** INSPECT FILE",filename
51    test = netCDF4.Dataset(filename)
52    print "**** VARIABLES: ",test.variables.keys()
53    for dim in test.dimensions.keys():
54        output = "**** DIMENSION: "+str(dim)+" "+str(len(test.dimensions[dim]))
55        try: output = output + " ----> "+str(test.variables[dim][0])+"  "+str(test.variables[dim][-1])
56        except: pass
57        print output ; output = ""
58
59# check a tab and exit if wrong. if just one string make it a list.
60# (if allownumber, convert this into a string).
61def checktab(tab,mess="",allownone=False,allownumber=False):
62    if tab is None: 
63      if not allownone:  print "pp.define: no "+mess ; exit()
64      else: pass
65    else:
66      if not isinstance(tab, list):
67        if isinstance(tab, str): 
68            tab = [tab]
69        elif (isinstance(tab, int) or isinstance(tab, float)) and allownumber: 
70            tab = [str(tab)] 
71        else: 
72            print "pp.define: "+mess+" should be either a string or a list of strings!" ; exit()
73      elif isinstance(tab, list):
74        if isinstance(tab[0],str): 
75            pass
76        elif (isinstance(tab[0], int) or isinstance(tab[0], float)) and allownumber:
77            for iii in range(len(tab)): tab[iii] = str(tab[iii])
78        else: 
79            print "pp.define: "+mess+" should be either a string or a list of strings!" ; exit()
80    return tab
81
82# determine which method is to be applied to a given dimension
83def findmethod(tab):
84    if tab is None:              output = "free"
85    elif tab[0,0] != tab[0,1]:   output = "comp"
86    else:                        output = "fixed"
87    return output
88
89# read what is given by the user (version of T. Navarro)
90def readslices(saxis):
91    if saxis == None:
92        zesaxis = None
93    else:
94        zesaxis = np.empty((len(saxis),2))
95        for i in range(len(saxis)):
96            a = separatenames(saxis[i])
97            if len(a) == 1:
98                zesaxis[i,:] = float(a[0])
99            else:
100                zesaxis[i,0] = float(a[0])
101                zesaxis[i,1] = float(a[1])         
102    return zesaxis
103# (needed by readslices)
104# look for comas in the input name to separate different names (files, variables,etc ..)
105def separatenames (name):
106    if name is None: names = None
107    else:
108      names = [] ; stop = 0 ; currentname = name
109      while stop == 0:
110        indexvir = currentname.find(',')
111        if indexvir == -1: stop = 1 ; name1 = currentname
112        else: name1 = currentname[0:indexvir]
113        names = np.concatenate((names,[name1]))
114        currentname = currentname[indexvir+1:len(currentname)]
115    return names
116
117#######################
118### THE MAIN OBJECT ###
119#######################
120class pp():
121
122    # print out a help string when help is invoked on the object
123    def __repr__(self):
124        whatprint = 'pp object. \"help(pp)\" for more information\n'
125        return whatprint
126
127    # default settings
128    # -- user can define settings by two methods.
129    # -- 1. yeah = pp(file="file.nc")
130    # -- 2. yeah = pp() ; yeah.file = "file.nc"
131    def __init__(self,file=None,var="notset",\
132                      filegoal=None,vargoal=None,\
133                      x=None,y=None,z=None,t=None,\
134                      stridex=1,stridey=1,\
135                      stridez=1,stridet=1,\
136                      compute="mean",\
137                      verbose=False,noproj=False,\
138                      superpose=False,\
139                      plotin=None,\
140                      forcedimplot=-1,\
141                      out="gui",\
142                      filename="myplot",\
143                      folder="./"):
144        self.request = None
145        self.nfin = 0 ; self.nvin = 0
146        self.nplotx = None ; self.nploty = None
147        self.nplotz = None ; self.nplott = None
148        self.status = "init"
149        self.fig = None ; self.subv = None ; self.subh = None 
150        self.n = 0 ; self.howmanyplots = 0
151        self.nplot = 0
152        self.p = None
153        ## what could be defined by the user
154        self.file = file
155        self.var = var
156        self.filegoal = filegoal
157        self.vargoal = vargoal
158        self.x = x ; self.y = y   ## if None, free dimension
159        self.z = z ; self.t = t   ## if None, free dimension
160        self.stridex = stridex ; self.stridey = stridey
161        self.stridez = stridez ; self.stridet = stridet
162        self.compute = compute
163        self.verbose = verbose
164        self.noproj = noproj
165        self.plotin = plotin
166        self.superpose = superpose
167        self.forcedimplot = forcedimplot
168        self.out = out
169        self.filename = filename
170        self.folder = folder
171
172    # print status
173    def printstatus(self):
174        print "**** Done step: " + self.status
175
176    #####################################################
177    # EMULATE OPERATORS + - * / ** << FOR PP() OBJECTS  #
178    #####################################################
179
180    # check the compatibility of two objects for operations
181    # --> if other is a pp class, test sizes and return isnum = False
182    # --> if other is an int or a float, return isnum = True
183    # --> otherwise, just print an error and exit
184    def checktwo(self,other):
185        if other.__class__.__name__ == "pp":
186          isnum = False
187          if self.status in ["init","defined"] or other.status in ["init","define"]: 
188             print "!! ERROR !! Please use .retrieve to get fields for plots with one of your pp operands." ; exit()
189          if self.nfin   != other.nfin   or \
190             self.nvin   != other.nvin   or \
191             self.nplott != other.nplott or \
192             self.nplotz != other.nploty or \
193             self.nploty != other.nploty or \
194             self.nplotx != other.nplotx :
195               print "!! ERROR !! The two operands do not have the same number of files, variables, t z y x requests."
196               exit()
197        elif isinstance(other,int) or isinstance(other,float):
198          isnum = True
199        else:
200          print "!! ERROR !! The operand is neither a pp class nor an integer or a float." ; exit()
201        return isnum
202
203    # define a selective copy of a pp() object for operations
204    # ... copy.copy() is not conservative (still acts like a pointer)
205    # ... copy.deepcopy() does not work with netCDF objects
206    # so what is done here is a copy of everything except
207    # (to avoid sharing with self and therefore modifying self through operations)
208    # - request attribute of pp() object
209    # - field attribute of the onerequest() objects
210    def selective_copy(self):
211        if self.status in ["init","defined"]:
212            print "!! ERROR !! Please use .retrieve to get fields for the object you want to copy from." ; exit()
213        the_clone = pp()
214        for k, v in vars(self).items():
215           if k != "request":
216               setattr(the_clone,k,v)
217        the_clone.verbose = False
218        the_clone.define()
219        for i in range(self.nfin):
220         for j in range(self.nvin):
221          for t in range(self.nplott):
222           for z in range(self.nplotz):
223            for y in range(self.nploty):
224             for x in range(self.nplotx):
225              obj = self.request[i][j][t][z][y][x]
226              for k, v in vars(obj).items():
227               if k != "field":
228                setattr(the_clone,k,v)
229        the_clone.status = "retrieved"
230        return the_clone
231
232    # define the operation + on two objects. or with an int/float.
233    # ... with selective_copy the self object is not modified.
234    def __add__(self,other):
235        isnum = self.checktwo(other)
236        the_clone = self.selective_copy()
237        for i in range(self.nfin):
238         for j in range(self.nvin):
239          for t in range(self.nplott):
240           for z in range(self.nplotz):
241            for y in range(self.nploty):
242             for x in range(self.nplotx):
243              obj = the_clone.request[i][j][t][z][y][x]
244              obj_ref = self.request[i][j][t][z][y][x]
245              if not isnum:   
246                  ope = other.request[i][j][t][z][y][x].field
247                  if obj_ref.field.shape != ope.shape:
248                    print "!! ERROR !! The two fields for operation do not have the same shape.",self.field.shape,other.field.shape
249                    exit()
250              else:           
251                  ope = other
252              if "vector" in self.vargoal[j] + self.filegoal[i]:
253                  print "!! ERROR !! we do not operate on vectors yet."
254                  exit()
255              else:
256                  obj.field = obj_ref.field + ope
257        return the_clone
258
259    # define the operation - on two objects. or with an int/float.
260    # ... with selective_copy the self object is not modified.
261    def __sub__(self,other):
262        isnum = self.checktwo(other)
263        the_clone = self.selective_copy()
264        for i in range(self.nfin):
265         for j in range(self.nvin):
266          for t in range(self.nplott):
267           for z in range(self.nplotz):
268            for y in range(self.nploty):
269             for x in range(self.nplotx):
270              obj = the_clone.request[i][j][t][z][y][x]
271              obj_ref = self.request[i][j][t][z][y][x]
272              if not isnum:
273                  ope = other.request[i][j][t][z][y][x].field
274                  if obj_ref.field.shape != ope.shape:
275                    print "!! ERROR !! The two fields for operation do not have the same shape.",self.field.shape,other.field.shape
276                    exit()
277              else:
278                  ope = other
279              if "vector" in self.vargoal[j] + self.filegoal[i]:
280                  print "!! ERROR !! we do not operate on vectors yet."
281                  exit()
282              else:
283                  obj.field = obj_ref.field - ope
284        return the_clone
285
286    # define the operation * on two objects. or with an int/float.
287    # ... with selective_copy the self object is not modified.
288    def __mul__(self,other):
289        isnum = self.checktwo(other)
290        the_clone = self.selective_copy()
291        for i in range(self.nfin):
292         for j in range(self.nvin):
293          for t in range(self.nplott):
294           for z in range(self.nplotz):
295            for y in range(self.nploty):
296             for x in range(self.nplotx):
297              obj = the_clone.request[i][j][t][z][y][x]
298              obj_ref = self.request[i][j][t][z][y][x]
299              if not isnum:
300                  ope = other.request[i][j][t][z][y][x].field
301                  if obj_ref.field.shape != ope.shape:
302                    print "!! ERROR !! The two fields for operation do not have the same shape.",self.field.shape,other.field.shape
303                    exit()
304              else:
305                  ope = other
306              if "vector" in self.vargoal[j] + self.filegoal[i]:
307                  print "!! ERROR !! we do not operate on vectors yet."
308                  exit()
309              else:
310                  obj.field = obj_ref.field * ope
311        return the_clone
312
313    # define the operation / on two objects. or with an int/float.
314    # ... with selective_copy the self object is not modified.
315    def __div__(self,other):
316        isnum = self.checktwo(other)
317        the_clone = self.selective_copy()
318        for i in range(self.nfin):
319         for j in range(self.nvin):
320          for t in range(self.nplott):
321           for z in range(self.nplotz):
322            for y in range(self.nploty):
323             for x in range(self.nplotx):
324              obj = the_clone.request[i][j][t][z][y][x]
325              obj_ref = self.request[i][j][t][z][y][x]
326              if not isnum:
327                  ope = other.request[i][j][t][z][y][x].field
328                  if obj_ref.field.shape != ope.shape:
329                    print "!! ERROR !! The two fields for operation do not have the same shape.",self.field.shape,other.field.shape
330                    exit()
331              else:
332                  ope = other
333              if "vector" in self.vargoal[j] + self.filegoal[i]:
334                  print "!! ERROR !! we do not operate on vectors yet."
335                  exit()
336              else:
337                  obj.field = obj_ref.field / ope
338        return the_clone
339
340    # define the reverse operation float/int + object
341    def __radd__(self,other):
342        isnum = self.checktwo(other)
343        if not isnum: print "!! ERROR !! Operand should be a number" ; exit()
344        return self.__add__(other)
345
346    # define the reverse operation float/int - object
347    def __rsub__(self,other):
348        isnum = self.checktwo(other)
349        if not isnum: print "!! ERROR !! Operand should be a number" ; exit()
350        return self.__sub__(other)
351
352    # define the reverse operation float/int * object
353    def __rmul__(self,other):
354        isnum = self.checktwo(other)
355        if not isnum: print "!! ERROR !! Operand should be a number" ; exit()
356        return self.__mul__(other)
357
358    # define the reverse operation float/int / object
359    def __rdiv__(self,other):
360        isnum = self.checktwo(other)
361        if not isnum: print "!! ERROR !! Operand should be a number" ; exit()
362        return self.__div__(other)
363
364    # define the operation ** on one object.
365    # ... with selective_copy the self object is not modified.
366    def __pow__(self,num):
367        the_clone = self.selective_copy()
368        if isinstance(num,int) or isinstance(num,float):
369            for i in range(self.nfin):
370             for j in range(self.nvin):
371              for t in range(self.nplott):
372               for z in range(self.nplotz):
373                for y in range(self.nploty):
374                 for x in range(self.nplotx):
375                  obj  = the_clone.request[i][j][t][z][y][x]
376                  obj_ref = self.request[i][j][t][z][y][x]
377                  if "vector" in self.vargoal[j] + self.filegoal[i]:
378                      print "!! ERROR !! we do not operate on vectors yet."
379                      exit()
380                  else:
381                      obj.field = obj_ref.field ** num
382        else:
383            print "!! ERROR !! To define a power, either an int or a float is needed." ; exit()
384        return the_clone
385
386    # define the operation <<
387    # ... e.g. obj2 << obj1
388    # ... means: get init for pp object obj2 from another pp object obj1
389    # ... (this should solve the affectation trap obj2 = obj1)
390    def __lshift__(self,other):
391        if other.__class__.__name__ == "pp":
392            self.file = other.file
393            self.var = other.var
394            self.filegoal = other.filegoal
395            self.vargoal = other.vargoal
396            self.x = other.x ; self.y = other.y   ## if None, free dimension
397            self.z = other.z ; self.t = other.t   ## if None, free dimension
398            self.stridex = other.stridex ; self.stridey = other.stridey
399            self.stridez = other.stridez ; self.stridet = other.stridet
400            self.verbose = other.verbose
401            self.noproj = other.noproj
402            self.plotin = other.plotin
403            self.superpose = other.superpose
404            self.forcedimplot = other.forcedimplot
405            self.out = other.out
406            self.filename = other.filename
407            self.folder = other.folder
408        else:
409            print "!! ERROR !! argument must be a pp object." ; exit()
410
411    ##############################################################################################
412    # define method
413    # ---------
414    # ... (file and var are either one string or a vector of strings)
415    # ... the goal of define is to define a 2D array of onerequest() objects (see class below)
416    #     given the number of file, var, x, y, z, t asked by the user
417    # ... objectives for file or var are given through filegoal and vargoal
418    #     --> possible values: main contour vector
419    # ---------
420    # ... then onerequest() objects are being defined more precisely
421    #     by getting index_x index_y index_z index_t
422    #     and setting method_x method_y method_z method_t to either
423    #      - "free" for free dimensions (plot dimensions)
424    #      - "comp" for averages, max, min
425    #      - "fixed" for fixed dimensions (possibly several i.e. multislice)
426    ##############################################################################################
427    def define(self):
428        self.printstatus()
429        # initial check and get dimensions
430        self.file = checktab(self.file,mess="file")
431        self.nfin = len(self.file)
432        if self.verbose:
433            for i in range(self.nfin): inspect(self.file[i])
434        self.var = checktab(self.var,mess="var")
435        self.nvin = len(self.var)
436        # check goal tabs for files and variables
437        # ... default is to plot everything
438        if self.filegoal is None: self.filegoal = ["main"]*self.nfin
439        if self.vargoal is None:  self.vargoal  = ["main"]*self.nvin
440        self.filegoal = checktab(self.filegoal, mess="filegoal")
441        self.vargoal  = checktab(self.vargoal,  mess="vargoal")
442        if len(self.filegoal) != self.nfin:  print "!! ERROR !! filegoal must be the same size as file." ; exit()
443        if len(self.vargoal)  != self.nvin:  print "!! ERROR !! vargoal must be the same size as var." ; exit()
444        # variables: initial check
445        self.x = checktab(self.x,mess="x",allownone=True,allownumber=True)
446        self.y = checktab(self.y,mess="y",allownone=True,allownumber=True)
447        self.z = checktab(self.z,mess="z",allownone=True,allownumber=True)
448        self.t = checktab(self.t,mess="t",allownone=True,allownumber=True)
449        # for the moment not var- nor file- dependent.
450        # but this could be the case.
451        sx = readslices(self.x) ; sy = readslices(self.y)
452        sz = readslices(self.z) ; st = readslices(self.t)
453        # get methods
454        mx = findmethod(sx) ; my = findmethod(sy)
455        mz = findmethod(sz) ; mt = findmethod(st)
456        # get number of plots to be done
457        if mx == "fixed": self.nplotx = sx.size/2
458        else:             self.nplotx = 1
459        if my == "fixed": self.nploty = sy.size/2
460        else:             self.nploty = 1
461        if mz == "fixed": self.nplotz = sz.size/2
462        else:             self.nplotz = 1
463        if mt == "fixed": self.nplott = st.size/2
464        else:             self.nplott = 1
465        if self.verbose:  print "**** OK. Plots over x,y,z,t -->",self.nplotx,self.nploty,self.nplotz,self.nplott
466        # create the list of onerequest() objects
467        self.request = [[[[[[ \
468                       onerequest() \
469                       for x in range(self.nplotx)] for y in range(self.nploty)] \
470                       for z in range(self.nplotz)] for t in range(self.nplott)] \
471                       for j in range(self.nvin)]   for i in range(self.nfin)] 
472        # loop on onerequest() objects
473        for i in range(self.nfin):
474         for j in range(self.nvin):
475          for t in range(self.nplott):
476           for z in range(self.nplotz):
477            for y in range(self.nploty):
478             for x in range(self.nplotx):
479              obj = self.request[i][j][t][z][y][x]
480              # fill in names for files and variables
481              obj.verbose = self.verbose
482              obj.file = self.file[i]
483              obj.var = self.var[j]
484              # indicate the computation method
485              obj.compute = self.compute
486              # open the files (the same file might be opened several times but this is cheap)
487              obj.openfile()
488              ### get x,y,z,t dimensions from file
489              obj.getdim()
490              ### get methods
491              obj.method_x = mx ; obj.method_y = my
492              obj.method_z = mz ; obj.method_t = mt           
493              ### get index
494              obj.getindextime(st,t,self.stridet)
495              obj.getindexvert(sz,z,self.stridez)
496              obj.getindexhori(sx,sy,x,y,self.stridex,self.stridey)
497        # change status
498        self.status = "defined"
499
500    ##############################################################################################
501    # retrieve method
502    # --> for each element onerequest() in the array, get field .var from .f file
503    # --> see below the onerequest() class:
504    #        - only get what is needed for computing and plotting
505    #        - averages etc... are computed here
506    # --> RESULT: each onerequest() object has now its attribute .field filled
507    # --> if one wants to perform operations on fields, this should be done after retrieve()
508    ##############################################################################################
509    def retrieve(self):
510        self.printstatus()
511        # check if things were done OK before
512        if self.status != "defined": print "!! ERROR !! Please use .define() to define your pp object."
513        ## first get fields
514        ## ... only what is needed is extracted from the files
515        ## ... and averages are computed
516        for i in range(self.nfin):
517         for j in range(self.nvin):
518          for t in range(self.nplott):
519           for z in range(self.nplotz):
520            for y in range(self.nploty):
521             for x in range(self.nplotx):
522              obj = self.request[i][j][t][z][y][x]
523              obj.getfield()
524        # change status
525        self.status = "retrieved"
526
527    ##########################################################
528    # get: a shortcut method for the define + retrieve chain #
529    ##########################################################
530    def get(self):
531        self.define()
532        self.retrieve()
533
534    ########################################
535    # smooth: smooth the field in 1D or 2D #
536    ########################################
537    ## TBD: smooth not OK with masked array in the end of retrieve()
538    def smooth(self,window):
539        if self.verbose: 
540            print "!! WARNING !! Performing a smoothing with a window size",window
541            print "!! WARNING !! To come back to unsmoothed file, use .get() again"
542        for i in range(self.nfin):
543         for j in range(self.nvin):
544          for t in range(self.nplott):
545           for z in range(self.nplotz):
546            for y in range(self.nploty):
547             for x in range(self.nplotx):
548              obj = self.request[i][j][t][z][y][x]
549              if obj.field.ndim == 1:
550                  print "!! ERROR !! 1D smoothing not supported yet because reduces array sizes."
551                  exit()
552                  # TBD TBD TBD
553                  #obj.field = ppcompute.smooth1d(obj.field,window=window)
554              elif obj.field.ndim == 2:
555                  obj.field = ppcompute.smooth2d(obj.field,window=window)
556
557    ############################################################################################## 
558    # defineplot method
559    # --> defineplot first defines arrays of plot objects and set each of them
560    #     ... simple looping except cases where goal is not main (e.g. contour or vector)
561    # --> principle: each onerequest() object gives birth to a subplot
562    # --> defineplot vs. makeplot: defining plot and actually plotting it are clearly separated
563    # --> THE KEY OUPUT OF defineplot IS AN ARRAY self.p OF PLOT OBJECTS
564    # optional arguments
565    # --> extraplot: to indicate a number of plots to be added afterwards (use self.plotin)
566    # --> loadfile: to use self.p from a previously saved file
567    ##############################################################################################
568    def defineplot(self,extraplot=0,loadfile=None):
569        # -----------------------------------------------------
570        # LOAD MODE: load a self.p object. count plots from it.
571        # -----------------------------------------------------
572        if loadfile is not None:
573            try: filehandler = open(loadfile, 'r') ; self.p = pickle.load(filehandler) 
574            except IOError: print "!! ERROR !! Cannot find object file to load." ; exit()
575            self.status = "definedplot" ; self.plotin = None
576            self.nplot = len(self.p) ; self.howmanyplots = self.nplot
577            return
578        # -----------------------------------------------------
579        # REGULAR MODE
580        # -----------------------------------------------------
581        self.printstatus()
582        # check if things were done OK before
583        if self.status in ["init","defined"]: 
584            print "!! ERROR !! Please use .retrieve() to get fields for plots with your pp object." ; exit()
585        # check self.plotin (an existing fig on which to add plots afterwards)
586        if self.plotin.__class__.__name__ == "pp":
587            if self.plotin.fig is None:
588                self.plotin = None # this is an additional security in case
589                                   #   a pp object is given without figure opened yet.
590        elif self.plotin is not None:
591            print "!! ERROR !! plotin argument must be a pp object." ; exit()
592        # initialize the array of subplot objects
593        # either something new or attributes coming from plotin object
594        if self.plotin is None:  self.p = [ ]
595        else:                    self.p = self.plotin.p
596        # create an array of subplot objects
597        # ... in theory the order of looping can be changed without any harm
598        # ... the only important thing is to keep i,j,t,z,y,x resp. for file,var,t,z,y,x
599        count = 0
600        for i in range(self.nfin):
601         if self.filegoal[i] == "main": 
602          for j in range(self.nvin):
603           if self.vargoal[j] == "main":
604            for t in range(self.nplott):
605             for z in range(self.nplotz):
606              for y in range(self.nploty):
607               for x in range(self.nplotx):
608                # look at dimension and append the right plot object
609                obj = self.request[i][j][t][z][y][x]
610                dp = obj.dimplot
611                if dp == 1 or self.forcedimplot == 1:    plobj = ppplot.plot1d()
612                elif dp == 2 or self.forcedimplot == 2:  plobj = ppplot.plot2d()
613                elif dp == 0: print "**** OK. VALUES VALUES VALUES",obj.field
614                else:         print "!! ERROR !! 3D or 4D plots not supported" ; exit()
615                # load abscissa and ordinate in obj
616                obj.definecoord()
617                # we start to define things here before appending
618                # (convenient: could be overridden by the user before makeplot)
619                # ... the if loop is necessary so that we can loop above on the dp=0 case
620                if dp in [1,2]:
621                    # and define what to do in plobj
622                    plobj.invert = obj.invert_axes
623                    plobj.swap = obj.swap_axes
624                    # axis labels
625                    plobj.xlabel = obj.absclab ; plobj.ylabel = obj.ordilab
626                    # superpose or not (this is mostly for saving purpose)
627                    plobj.superpose = self.superpose
628                    # get title, colormaps, labels, etc.. from var
629                    plobj.var = obj.var
630                    plobj.define_from_var()
631                    # generic 1D/2D: load field and coord in plot object
632                    plobj.field = obj.field    # field to be plotted
633                    plobj.absc = obj.absc      # abscissa (or longitude)
634                    plobj.ordi = obj.ordi      # ordinate (or latitude)
635                                               # -- useless in 1D but not used anyway
636                    if dp == 2:
637                    # specific 2d plot stuff
638                        # -- light grey background for missing values
639                        if type(plobj.field).__name__ in 'MaskedArray': plobj.axisbg = '0.75'
640                        # -- define if it is a map or a plot
641                        plobj.mapmode = ( obj.method_x+obj.method_y == "freefree" \
642                                       and "grid points" not in obj.name_x \
643                                       and not self.noproj )
644                    # finally append
645                    self.p.append(plobj)
646                    count = count + 1
647        # self.nplot is number of plot to be defined in this call to defineplot()
648        # (because of self.plotin this might less than length of self.p)
649        self.nplot = count
650        # --- superimposed contours and vectors ---
651        # we have to start another loop because we need forward information
652        # TBD: there is probably a more flexible way to do that
653        count = 0
654        for i in range(self.nfin):
655         for j in range(self.nvin):
656          for t in range(self.nplott):
657           for z in range(self.nplotz):
658            for y in range(self.nploty):
659             for x in range(self.nplotx):
660              goal = self.vargoal[j] + self.filegoal[i]
661              obj = self.request[i][j][t][z][y][x]
662              if "mainmain" in goal and obj.dimplot == 2:
663                  # the plot object we consider in the loop
664                  pl = self.p[count]
665                  # -- see if there is a contour requested...
666                  # (we use try because we might be at the end of the list)
667                  found = 0
668                  try:    condvar = self.vargoal[j+1]
669                  except: condvar = "itisok"
670                  try:    condfile = self.filegoal[i+1]
671                  except: condfile = "itisok"
672                  # ... get contour
673                  ##########################################
674                  # NB: contour is expected to be right after main otherwise it is not displayed
675                  ##########################################
676                  if condvar == "contour":
677                      plobj.addcontour = self.request[i][j+1][t][z][y][x].field ; found += 1
678                  if condfile == "contour":
679                      plobj.addcontour = self.request[i+1][j][t][z][y][x].field ; found += 1
680                  # see if there is a vector requested...
681                  # (we use try because we might be at the end of the list)
682                  try:    condvar = self.vargoal[j+found+1]+self.vargoal[j+found+2]
683                  except: condvar = "itisok"
684                  try:    condfile = self.filegoal[i+found+1]+self.filegoal[i+found+2]
685                  except: condfile = "itisok"
686                  # ... get vector and go directly to the next iteration
687                  # (in some cases we would do this twice but this is cheap)
688                  if "vector" in condvar:
689                      plobj.addvecx = self.request[i][j+found+1][t][z][y][x].field
690                      plobj.addvecy = self.request[i][j+found+2][t][z][y][x].field
691                  if "vector" in condfile:
692                      plobj.addvecx = self.request[i+found+1][j][t][z][y][x].field
693                      plobj.addvecy = self.request[i+found+2][j][t][z][y][x].field
694                  count = count + 1
695        # COUNT PLOTS. if 0 just exit.
696        # self.howmanyplots is self.nplot + possible extraplots
697        self.howmanyplots = self.nplot + extraplot
698        if self.howmanyplots > 0:
699            if self.verbose: print "**** OK. expect %i plots" % (self.howmanyplots)
700        else:
701            exit() # because this means that we only had 0D values !
702        # final status
703        self.status = "definedplot"
704
705    ##############################################################################################
706    # makeplot method
707    # --> after defineplot and before makeplot, user-defined plot settings can be easily given
708    #     simply by modifying the attributes of each elements of self.p
709    # --> to change only one plot setting, no need to call defineplot again before makeplot
710    # --> in the end, the array self.p of plot objects is saved for easy and convenient replotting
711    # --> see practical examples in the folder 'examples'
712    ##############################################################################################
713    def makeplot(self):
714        self.printstatus()
715        # a few initial operations
716        # ------------------------
717        if "definedplot" not in self.status: 
718            print "!! ERROR !! Please use .defineplot() before .makeplot() can be used with your pp object." ; exit()
719        # open a figure and define subplots         
720        # ---------------------------------
721        if self.plotin is None: 
722            # start from scratch
723            self.fig = mpl.figure(figsize=(16,8))
724            self.subv,self.subh = ppplot.definesubplot(self.howmanyplots,self.fig) 
725            self.n = 0
726        else:
727            # start from an existing figure.
728            # extraplot must have been set in the call to the previous figure.
729            self.fig = self.plotin.fig
730            self.subv,self.subh = self.plotin.subv,self.plotin.subh
731            self.n = self.plotin.n
732            self.howmanyplots = self.plotin.howmanyplots
733        # LOOP on all subplots
734        # NB: cannot use 'for pl in self.p' if self.plotin not None
735        # --------------------
736        for count in range(self.nplot):
737            # the plot object we consider in the loop
738            pl = self.p[self.n]
739            # before making the plot, create a subplot. the first one is numbered 1 not 0.
740            # ... if pl.superpose, we use only one and only figure
741            # ... (and we have to be careful with not doing things several times)
742            if pl.superpose:
743                if self.n == 0: 
744                    self.fig.add_subplot(1,1,1,axisbg=pl.axisbg) # define one subplot (still needed for user-defined font sizes)
745                    sav = pl.xlabel,pl.ylabel,pl.xcoeff,pl.ycoeff,pl.title,pl.swaplab # save titles and labels
746                else: 
747                    pl.invert = False ; pl.lstyle = None # don't invert again axis
748                    # set saved titles and labels
749                    if self.plotin is None:
750                        pl.xlabel,pl.ylabel,pl.xcoeff,pl.ycoeff,pl.title,pl.swaplab = sav
751                    else:
752                        prev_plot = self.plotin.p[self.n-1]
753                        pl.xlabel = prev_plot.xlabel
754                        pl.ylabel = prev_plot.ylabel
755                        pl.xcoeff = prev_plot.xcoeff
756                        pl.ycoeff = prev_plot.ycoeff
757                        pl.title = prev_plot.title
758                        pl.swaplab = prev_plot.swaplab
759            else:
760                self.fig.add_subplot(self.subv,self.subh,self.n+1,axisbg=pl.axisbg)
761            if self.verbose: print "**** Done subplot %i / %i " %( self.n+1,self.howmanyplots ) 
762            # finally make the plot
763            pl.make()
764            self.n = self.n+1 
765        # once completed show the plot (cannot show intermediate plotin)
766        print "**** Done step: makeplot"
767        if (self.n == self.howmanyplots): ppplot.save(mode=self.out,filename=self.filename,folder=self.folder)
768        # SAVE A PICKLE FILE WITH THE self.p ARRAY OF OBJECTS
769        if self.verbose: print "**** Saving session in "+self.filename + ".ppobj"
770        savfile = self.folder + "/" + self.filename + ".ppobj"
771        filehandler = open(savfile, 'w')
772        pickle.dump(self.p, filehandler)
773
774    ###########################################################
775    # plot: a shortcut method for the defineplot + plot chain #
776    ###########################################################
777    def plot(self,extraplot=0):
778        self.defineplot(extraplot=extraplot)
779        self.makeplot()
780
781    #######################################################
782    # getplot: a shortcut method for the get + plot chain #
783    #######################################################
784    def getplot(self,extraplot=0):
785        self.get()
786        self.plot(extraplot=extraplot)
787
788    ###################################################################
789    # getdefineplot: a shortcut method for the get + defineplot chain #
790    ###################################################################
791    def getdefineplot(self,extraplot=0):
792        self.get()
793        self.defineplot(extraplot=extraplot)
794
795    ##############################################################
796    # f: operation on two pp objects being on status 'definedplot'
797    # this allows for one field being function of another one
798    # e.g. u.f(v) means u will be displayed as a function of v
799    # ... no need to do defineplot after u.f(v), makeplot directly
800    ##############################################################
801    def f(self,other):
802        # preamble: for this operation to work, defineplot() must have been done
803        if self.status != "definedplot":
804            if self.verbose: print "!! WARNING !! performing defineplot on operand"
805            self.defineplot()
806        if other.status != "definedplot":
807            if self.verbose: print "!! WARNING !! performing defineplot on operand"
808            other.defineplot()
809        # check total number of plots
810        if self.howmanyplots != other.howmanyplots:
811               print "!! ERROR !! The two operands do not have the same number of subplots."
812               exit()
813        # and now operation.
814        count = 0
815        while count < self.howmanyplots:
816           sobj = self.p[count] ; oobj = other.p[count]
817           if sobj.field.ndim !=1 or oobj.field.ndim !=1:
818               if self.verbose: print "!! WARNING !! Flattening arrays because more than one-dimensional."
819               sobj.field = np.ravel(sobj.field)
820               oobj.field = np.ravel(oobj.field)
821           sobj.absc = oobj.field
822           sobj.xlabel = oobj.ylabel
823           if sobj.absc.size > sobj.field.size:
824               if self.verbose:
825                   print "!! WARNING !! Trying to define y=f(x) with x and y not at the same size.",sobj.absc.size,sobj.field.size
826                   print "!! WARNING !! Modifying x to fit y size but please check." 
827               sobj.absc = sobj.absc[0:sobj.field.size]
828           count = count + 1
829        return self
830
831    ###########################################################
832    # copyopt: get options from e.g. a parser
833    # ... allow for simple scripting and user-defined settings
834    # ... must be called between defineplot and makeplot
835    # REQUIRED: attributes of opt must be the same as in the pp object
836    ###########################################################
837    def getopt(self,opt):
838        # -- if only one, or less than the number of plots --> we take the first one
839        # -- if as many as number of plots --> OK, each plot has its own setting
840        # (except a few cases such as trans)
841        for iii in range(self.howmanyplots):
842            ###
843            try: self.p[iii].trans = opt.trans
844            except: pass
845            ###
846            try: self.p[iii].div = opt.div
847            except: pass
848            ###
849            try: self.p[iii].logy = opt.logy
850            except: pass
851            ###
852            try: self.p[iii].colorb = opt.colorb[iii]
853            except: 
854                try: self.p[iii].colorb = opt.colorb[0]
855                except: pass
856            ###
857            try: self.p[iii].title = opt.title[iii]
858            except: 
859                try: self.p[iii].title = opt.title[0]
860                except: pass
861            ###
862            try: self.p[iii].xlabel = opt.xlabel[iii]
863            except: 
864                try: self.p[iii].xlabel = opt.xlabel[0]
865                except: pass
866            ###
867            try: self.p[iii].ylabel = opt.ylabel[iii]
868            except: 
869                try: self.p[iii].ylabel = opt.ylabel[0]
870                except: pass
871            ###
872            try: self.p[iii].lstyle = opt.lstyle[iii]
873            except: 
874                try: self.p[iii].lstyle = opt.lstyle[0]
875                except: pass
876            ###
877            try: self.p[iii].proj = opt.proj[iii]
878            except: 
879                try: self.p[iii].proj = opt.proj[0]
880                except: pass
881            ###
882            try: self.p[iii].back = opt.back[iii]
883            except: 
884                try: self.p[iii].back = opt.back[0]
885                except: pass
886            ###
887            try: self.p[iii].area = opt.area[iii]
888            except: 
889                try: self.p[iii].area = opt.area[0]
890                except: pass
891            ###
892            try: self.p[iii].blon = opt.blon[iii]
893            except: 
894                try: self.p[iii].blon = opt.blon[0]
895                except: pass
896            ###
897            try: self.p[iii].blat = opt.blat[iii]
898            except: 
899                try: self.p[iii].blat = opt.blat[0]
900                except: pass
901            ###
902            try: self.p[iii].vmin = opt.vmin[iii]
903            except: 
904                try: self.p[iii].vmin = opt.vmin[0]
905                except: pass
906            ###
907            try: self.p[iii].vmax = opt.vmax[iii]
908            except: 
909                try: self.p[iii].vmax = opt.vmax[0]
910                except: pass
911
912##########################################################
913### THE ONEREQUEST SUBOBJECT TO PP (ON WHICH IT LOOPS) ###
914##########################################################
915class onerequest():
916
917    # default settings. mostly initialized to diagnose problem, except dimplot, nplot, verbose, swap_axes, invert_axes
918    # -------------------------------
919    def __init__(self):
920        self.file  = '!! file: I am not set, damned !!'
921        self.f     = None
922        self.dim   = None
923        self.var   = '!! var: I am not set, damned !!'
924        self.index_x = [] ; self.index_y = [] ; self.index_z = [] ; self.index_t = []
925        self.index_x2d = [] ; self.index_y2d = []
926        self.method_x = '!! method_x: I am not set, damned !!'
927        self.method_y = '!! method_y: I am not set, damned !!'
928        self.method_z = '!! method_z: I am not set, damned !!'
929        self.method_t = '!! method_t: I am not set, damned !!'
930        self.field = None
931        self.name_x = None ; self.name_y = None ; self.name_z = None ; self.name_t = None
932        self.dim_x = None ; self.dim_y = None ; self.dim_z = None ; self.dim_t = None
933        self.field_x = None ; self.field_y = None ; self.field_z = None ; self.field_t = None
934        self.dimplot = 0
935        self.nplot = 1
936        self.absc = None ; self.ordi = None ; self.absclab = None ; self.ordilab = None
937        self.verbose = True
938        self.swap_axes = False ; self.invert_axes = False
939        self.compute = None
940
941    # open a file. for now it is netcdf. TBD for other formats.
942    # check that self.var is inside.
943    # -------------------------------
944    def openfile(self):
945        if not os.path.exists(self.file): print '!! ERROR !! I could not find the following file: '+self.file ; exit()
946        if not os.path.isfile(self.file): print '!! ERROR !! This does not appear to be a file: '+self.file ; exit()
947        self.f = netCDF4.Dataset(self.file)
948        if self.verbose: print "**** OK. Opened file "+self.file
949        if self.var not in self.f.variables.keys(): 
950            print '!! ERROR !! File '+self.file+' does not contain variable: '+self.var
951            print '..... try instead with ',self.f.variables.keys() ; exit()
952
953    # get x,y,z,t dimensions from NETCDF file
954    # TBD: user could request for a specific altitude dimension
955    # TBD: staggered variables could request specific dimensions
956    # -------------------------------
957    def getdim(self):
958          # GET SIZES OF EACH DIMENSION
959          if self.verbose: print "**** OK. Found variable "+self.var
960          shape = self.f.variables[self.var].shape
961          self.dim = len(shape)
962          if self.dim == 1:
963              if self.verbose: print "**** OK. 1D field. I assume this varies with time."
964              self.dim_x = 1 ; self.dim_y = 1 ; self.dim_z = 1 ; self.dim_t = shape[0]
965          elif self.dim == 2:
966              if self.verbose: print "**** OK. 2D field. I assume this is not-time-varying lat-lon map."
967              self.dim_x = shape[1] ; self.dim_y = shape[0] ; self.dim_z = 1 ; self.dim_t = 1
968          elif self.dim == 3:
969              if self.verbose: print "**** OK. 3D field. I assume this is time-varying lat-lon map."
970              self.dim_x = shape[2] ; self.dim_y = shape[1] ; self.dim_z = 1 ; self.dim_t = shape[0]
971          elif self.dim == 4:
972              if self.verbose: print "**** OK. 4D field."
973              self.dim_x = shape[3] ; self.dim_y = shape[2] ; self.dim_z = shape[1] ; self.dim_t = shape[0]
974          # LONGITUDE. Try preset fields. If not present set grid points axis.
975          self.name_x = "nothing"
976          for c in glob_listx:
977            if c in self.f.variables.keys():
978             self.name_x = c
979          if self.name_x == "nothing":
980            self.field_x = np.array(range(self.dim_x))
981            self.name_x = "x grid points"
982          else:
983            self.field_x = self.f.variables[self.name_x]
984          # LATITUDE. Try preset fields. If not present set grid points axis.
985          self.name_y = "nothing"
986          for c in glob_listy:
987            if c in self.f.variables.keys():
988             self.name_y = c
989          if self.name_y == "nothing":
990            self.field_y = np.array(range(self.dim_y))
991            self.name_y = "y grid points"
992          else:
993            self.field_y = self.f.variables[self.name_y]
994          # ensure that lon and lat are 2D fields
995          # 1. simple 1D case (not time-varying)
996          if len(self.field_x.shape)*len(self.field_y.shape) == 1:
997               if self.verbose: print "**** OK. recasting lon and lat as 2D fields." 
998               [self.field_x,self.field_y] = np.meshgrid(self.field_x,self.field_y)
999          # 2. complex 3D case (time-varying, actually just copied over time axis)
1000          elif len(self.field_x.shape)*len(self.field_y.shape) == 9:
1001               if self.verbose: print "**** OK. reducing lon and lat as 2D fields. get rid of time."
1002               self.field_x = self.field_x[0,:,:]
1003               self.field_y = self.field_y[0,:,:]
1004          # if xy axis are apparently undefined, set 2D grid points axis.
1005          if "grid points" not in self.name_x:
1006            if self.field_x.all() == self.field_x[0,0]:
1007               print "!! WARNING !! xy axis look undefined. creating a non-dummy ones."
1008               self.field_x = np.array(range(self.dim_x)) ; self.name_x = "x grid points"
1009               self.field_y = np.array(range(self.dim_y)) ; self.name_y = "y grid points"
1010               [self.field_x,self.field_y] = np.meshgrid(self.field_x,self.field_y)
1011          if self.dim_x > 1: 
1012               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())
1013          if self.dim_y > 1: 
1014               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())
1015          # ALTITUDE. Try preset fields. If not present set grid points axis.
1016          # WARNING: how do we do if several are available?
1017          self.name_z = "nothing"
1018          for c in glob_listz:
1019            if c in self.f.variables.keys():
1020             self.name_z = c
1021          if self.name_z == "nothing":
1022            self.field_z = np.array(range(self.dim_z))
1023            self.name_z = "z grid points"
1024          else:
1025            self.field_z = self.f.variables[self.name_z][:] # specify dimension
1026                                                            # TBD: have to check that this is not a 3D field
1027          if self.dim_z > 1: 
1028               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())
1029          # TIME. Try preset fields.
1030          self.name_t = "nothing"
1031          for c in glob_listt:
1032            if c in self.f.dimensions.keys():
1033             self.name_t = c
1034          try:
1035            # speed up: only get first value, last one.
1036            dafirst = self.f.variables[self.name_t][0]
1037            dalast = self.f.variables[self.name_t][self.dim_t-1]
1038            self.field_t = np.linspace(dafirst,dalast,num=self.dim_t)
1039            if dafirst == dalast: self.field_t = np.array([dafirst])
1040          except:
1041            # ... or if a problem encountered, define a simple time axis
1042            self.field_t = np.array(range(self.dim_t))
1043            self.name_t = "t grid points"
1044          if self.dim_t > 1: 
1045               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())     
1046
1047    # get list of index to be retrieved for time axis
1048    ### TBD: il faudrait ne prendre que les indices qui correspondent a l interieur d un plot (dans all)
1049    # -------------------------------
1050    def getindextime(self,dalist,ind,stride):
1051        if self.method_t == "free": 
1052            self.index_t = np.arange(0,self.dim_t,stride)
1053            if self.dim_t > 1: 
1054                self.dimplot = self.dimplot + 1 
1055                if self.verbose: print "**** OK. t values. all."
1056            else:               
1057                self.method_t = "fixed"
1058                if self.verbose: print "**** OK. no t dimension."
1059        elif self.method_t == "comp":
1060            start = np.argmin( np.abs( self.field_t - dalist[ind][0] ) )
1061            stop = np.argmin( np.abs( self.field_t - dalist[ind][1] ) )
1062            self.index_t = np.arange(start,stop,stride)
1063            if self.verbose: print "**** OK. t values. comp over interval ",self.field_t[start],self.field_t[stop]," nvalues=",self.index_t.size
1064        elif self.method_t == "fixed":
1065            self.index_t.append( np.argmin( np.abs( self.field_t - dalist[ind][0] ) ))
1066            if self.verbose: print "**** OK. t values",self.field_t[self.index_t]
1067        else:
1068            print "!! ERROR !! method "+self.method_t+" not supported"
1069        self.index_t = np.array(self.index_t)
1070             
1071    # get list of index to be retrieved for vertical axis
1072    ### TBD: il faudrait ne prendre que les indices qui correspondent a l interieur d un plot (dans all)
1073    # -------------------------------
1074    def getindexvert(self,dalist,ind,stride):
1075        if self.method_z == "free": 
1076            self.index_z = np.arange(0,self.dim_z,stride)
1077            if self.dim_z > 1: 
1078                self.dimplot = self.dimplot + 1
1079                if self.verbose: print "**** OK. z values. all."
1080            else:               
1081                self.method_z = "fixed"
1082                if self.verbose: print "**** OK. no z dimension."
1083        elif self.method_z == "comp":
1084            start = np.argmin( np.abs( self.field_z - dalist[ind][0] ) )
1085            stop = np.argmin( np.abs( self.field_z - dalist[ind][1] ) )
1086            self.index_z = np.arange(start,stop,stride)
1087            if self.verbose: print "**** OK. z values. comp over interval",self.field_z[start],self.field_z[stop]," nvalues=",self.index_z.size
1088        elif self.method_z == "fixed":
1089            self.index_z.append( np.argmin( np.abs( self.field_z - dalist[ind][0] ) ))
1090            if self.verbose: print "**** OK. z values",self.field_z[self.index_z]
1091        else:
1092            if self.verbose: print "!! ERROR !! method "+self.method_z+" not supported"
1093        self.index_z = np.array(self.index_z)
1094
1095    # get list of index to be retrieved for horizontal grid
1096    # --> index_x and index_y are slices to be retrieved from NETCDF files
1097    # --> index_x2d and index_y2d are the actual (x,y) coordinates corresponding to each relevant point
1098    # [this is slightly more complicated because 2D arrays for lat-lon projection possibly irregular]
1099    # NB: to append index we use lists (the most convenient) then we convert into a numpy.array
1100    ### TBD: il faudrait ne prendre que les indices qui correspondent a l interieur d un plot (dans all)
1101    # -------------------------------
1102    def getindexhori(self,dalistx,dalisty,indx,indy,stridex,stridey):
1103        ## get what is the method over x and y axis
1104        test = self.method_x+self.method_y
1105        ## CASE 0, EASY CASES:
1106        ## - LAT IS FREE (we do here what must be done whatever LON case is)
1107        ## - LON IS FREE (we do here what must be done whatever LAT case is)
1108        ## - LAT IS COMP AND LON IS FREE
1109        ## - LON IS COMP AND LAT IS FREE
1110        if self.method_x == "free" or test in ["compfree","compcomp"]:
1111            self.index_x = range(0,self.dim_x,stridex)
1112            if self.dim_x > 1: 
1113                if self.method_x == "free": self.dimplot = self.dimplot + 1
1114                if self.verbose: print "**** OK. x values. all."
1115            else:               
1116                self.method_x = "fixed"
1117                if self.verbose: print "**** OK. no x dimension."
1118        if self.method_y == "free" or test in ["compfree","compcomp"]:
1119            self.index_y = range(0,self.dim_y,stridey)
1120            if self.dim_y > 1: 
1121                if self.method_y == "free": self.dimplot = self.dimplot + 1
1122                if self.verbose: print "**** OK. y values. all."
1123            else:               
1124                self.method_y = "fixed"
1125                if self.verbose: print "**** OK. no y dimension."
1126        ## CASE 0 above, this is just for continuity.
1127        if self.method_x in ["free","comp"] and self.method_y in ["free","comp"]:
1128            self.index_x2d = self.index_x
1129            self.index_y2d = self.index_y
1130        ## AND NOW THE LITTLE BIT MORE COMPLICATED CASES
1131        ## CASE 1 LAT AND LON ARE FIXED
1132        elif test == "fixedfixed":
1133            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 ) 
1134                          #TBD: pb with staggered coord
1135            if idx not in self.index_x:  self.index_x.append(idx)
1136            if idy not in self.index_y:  self.index_y.append(idy)
1137            self.index_x2d.append(idx)
1138            self.index_y2d.append(idy)
1139        ## CASE 2 LON IS FIXED BUT NOT LAT
1140        elif test in ["fixedfree","fixedcomp"]:
1141            # find where are requested x values for each y on the free dimension
1142            # NB: this does not work for non-bijective cases e.g. polar stereographic
1143            for iy in range(self.dim_y):
1144              idx = np.argmin( np.abs( self.field_x[iy,:] - dalistx[indx][0] ) )
1145              # if comp is requested we select only indexes which yield values between requested min and max
1146              storeval = (self.method_y == "comp") and (self.field_y[iy,idx] > dalisty[indy][0]) and (self.field_y[iy,idx] < dalisty[indy][1])
1147              storeval = storeval or (self.method_y == "free")
1148              if storeval:
1149                  if idx not in self.index_x:  self.index_x.append(idx)
1150                  if iy not in self.index_y and self.method_y == "comp": self.index_y.append(iy)
1151                  if idx not in self.index_x2d or iy not in self.index_y2d:
1152                    self.index_x2d.append(idx)
1153                    self.index_y2d.append(iy)
1154        ## CASE 3 LAT IS FIXED BUT NOT LON
1155        elif test in ["freefixed","compfixed"]:
1156            # find where are requested y values for each x on the free dimension
1157            # NB: this does not work for non-bijective cases e.g. polar stereographic
1158            for ix in range(self.dim_x):
1159              idy = np.argmin( np.abs( self.field_y[:,ix] - dalisty[indy][0] ) )
1160              # if comp is requested we select only indexes which yield values between requested min and max
1161              storeval = (self.method_x == "comp") and (self.field_x[idy,ix] > dalistx[indx][0]) and (self.field_x[idy,ix] < dalistx[indx][1])
1162              storeval = storeval or (self.method_x == "free")
1163              if storeval:
1164                  if idy not in self.index_y:  self.index_y.append(idy)
1165                  if ix not in self.index_x and self.method_x == "comp": self.index_x.append(ix)
1166                  if ix not in self.index_x2d or idy not in self.index_y2d:
1167                    self.index_x2d.append(ix)
1168                    self.index_y2d.append(idy)
1169        ## check index tab
1170        if len(self.index_x) == 0 or len(self.index_y) == 0:
1171            print "!! ERROR !! no indices found. check prescribed latitudes or longitudes" ; exit()
1172        ## ensure the array is a numpy array for getfield to work
1173        self.index_x = np.array(self.index_x)
1174        self.index_y = np.array(self.index_y)
1175        self.index_x2d = np.array(self.index_x2d)
1176        self.index_y2d = np.array(self.index_y2d)
1177        ### print extrema
1178        printx = self.field_x[np.ix_(self.index_y2d, self.index_x2d)]
1179        printy = self.field_y[np.ix_(self.index_y2d, self.index_x2d)]
1180        if self.verbose: 
1181            print "**** OK. x values (min,max).", printx.min(),printx.max()
1182            print "**** OK. y values (min,max).", printy.min(),printy.max()
1183
1184    # get the field from the NETCDF file and perform averages
1185    # -------------------------------
1186    def getfield(self):
1187        ## first tell what is to be done
1188        if self.dimplot > 2:                       print "**** !! ERROR !! "+str(self.dimplot)+"D plots not supported!" ; exit()
1189        elif self.dimplot == 0 and self.verbose:   print "**** OK. 0D value requested."
1190        elif self.dimplot == 1 and self.verbose:   print "**** OK. 1D plot requested."
1191        elif self.verbose:                         print "**** OK. 2D section requested."
1192        # well, now get field from netcdf file
1193        # part below is necessary otherwise there is an index error below
1194        if self.index_x.size == 1: self.index_x = self.index_x[0]
1195        if self.index_y.size == 1: self.index_y = self.index_y[0]
1196        if self.index_z.size == 1: self.index_z = self.index_z[0]
1197        if self.index_t.size == 1: self.index_t = self.index_t[0]
1198        # then retrieve what is requested by user
1199        # each self.dim case corresponds to tests in the beginning of getdim.
1200        time0 = timelib.time()
1201        if self.verbose: print "**** OK. I am getting values from files. Please wait."
1202        if self.dim == 1: 
1203            nt = self.index_t.size ; nz = 1 ; ny = 1 ; nx = 1
1204            self.field = self.f.variables[self.var][self.index_t]
1205        elif self.dim == 2:
1206            nt = 1 ; nz = 1 ; ny = self.index_y.size ; nx = self.index_x.size
1207            self.field = self.f.variables[self.var][self.index_y,self.index_x]
1208        elif self.dim == 3:
1209            nt = self.index_t.size ; nz = 1 ; ny = self.index_y.size ; nx = self.index_x.size
1210            self.field = self.f.variables[self.var][self.index_t,self.index_y,self.index_x]
1211            # this is far faster than retrieving each term with a loop
1212        elif self.dim == 4:
1213            nt = self.index_t.size ; nz = self.index_z.size ; ny = self.index_y.size ; nx = self.index_x.size
1214            self.field = self.f.variables[self.var][self.index_t,self.index_z,self.index_y,self.index_x]
1215        else:
1216            print "!! ERROR !! field would have more than four dimensions ?" ; exit()
1217        # NB: ... always 4D array but possibly with "size 1" dimensions
1218        #     ... if one dimension is missing because 1D 2D or 3D requests, make it appear again
1219        self.field = np.reshape(self.field,(nt,nz,ny,nx))
1220        if self.verbose: print "**** OK. I got %7.1e values. This took me %6.4f seconds" % (nx*ny*nz*nt,timelib.time() - time0)
1221        if self.verbose: print "**** OK. I got var "+self.var+" with shape",self.field.shape
1222        # reduce coordinates to useful points
1223        # ... TBD: this should be ordered in the case of non-regular projections
1224        if self.method_x in ["free","comp"] and self.method_y in ["free","comp"]:
1225          # we need 2D coordinates (free) or we get broadcast problem (comp) so we use np.ix
1226          self.field_x = self.field_x[np.ix_(self.index_y2d, self.index_x2d)]
1227          self.field_y = self.field_y[np.ix_(self.index_y2d, self.index_x2d)]
1228        else:
1229          # we are OK with 1D coordinates
1230          self.field_x = self.field_x[self.index_y2d, self.index_x2d]
1231          self.field_y = self.field_y[self.index_y2d, self.index_x2d]
1232        self.field_z = self.field_z[self.index_z]
1233        self.field_t = self.field_t[self.index_t]
1234        # now have to obtain the new indexes which correspond to the extracted self.field
1235        # for it to work with unique index, ensure that any index_* is a numpy array
1236        if not isinstance(self.index_x, np.ndarray): self.index_x = np.array([self.index_x])
1237        if not isinstance(self.index_y, np.ndarray): self.index_y = np.array([self.index_y])
1238        if not isinstance(self.index_z, np.ndarray): self.index_z = np.array([self.index_z])
1239        if not isinstance(self.index_t, np.ndarray): self.index_t = np.array([self.index_t])
1240        for val in self.index_x: self.index_x2d[np.where(self.index_x2d == val)] = np.where(self.index_x == val)[0]
1241        for val in self.index_y: self.index_y2d[np.where(self.index_y2d == val)] = np.where(self.index_y == val)[0]
1242        for val in self.index_z: self.index_z  [np.where(self.index_z   == val)] = np.where(self.index_z == val)[0]
1243        for val in self.index_t: self.index_t  [np.where(self.index_t   == val)] = np.where(self.index_t == val)[0]
1244               ##### VERY EXPENSIVE
1245               ## recast self.field with 2D horizontal arrays because we might have extracted
1246               ## more than what is to be actually plot or computed, in particular for comps on 2D lat,lon coordinates
1247               #self.field = self.field[np.ix_(self.index_t,self.index_z,self.index_y2d,self.index_x2d)]
1248               #(nt,nz,ny,nx) = self.field.shape       
1249        # extract relevant horizontal points
1250        # TBD: is compfree OK with computing on irregular grid?
1251        test = self.method_x + self.method_y
1252        if test in ["fixedfixed","freefree"]:
1253          pass
1254        elif test in ["fixedfree","fixedcomp"] or test in ["freefixed","compfixed"]: 
1255          time0 = timelib.time() 
1256          # prepare the loop on all relevant horizontal points
1257          if self.method_x in ["comp","free"]:   
1258              nnn = self.index_x2d.shape[0] ; what_I_am_supposed_to_do = "keepx"
1259          elif self.method_y in ["comp","free"]: 
1260              nnn = self.index_y2d.shape[0] ; what_I_am_supposed_to_do = "keepy" 
1261          # LOOP to extract only useful values over horizontal dimensions
1262          # only take diagonal terms, do not loop on all self.index_x2d*self.index_y2d
1263          # ... this method is fast enough, perhaps there is a faster way though
1264          # ... (for sure the method with np.diag is much slower)
1265          for iii in range(nnn):
1266           ix = self.index_x2d[iii] ; iy = self.index_y2d[iii]
1267           for iz in self.index_z:
1268            for it in self.index_t:
1269              if what_I_am_supposed_to_do == "keepx":    self.field[it,iz,0,ix] = self.field[it,iz,iy,ix]
1270              elif what_I_am_supposed_to_do == "keepy":  self.field[it,iz,iy,0] = self.field[it,iz,iy,ix]
1271          if self.verbose: print "**** OK. I got to pick the right values for your request. This took me %6.4f seconds" % (timelib.time() - time0)
1272          # we only keep the one value that was modified on the dimension which is not free
1273          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))
1274          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))
1275        # make a mask in case there are non-NaN missing values. (what about NaN missing values?)
1276        # ... this is important for computations below (see ppcompute)
1277        masked = np.ma.masked_where(np.abs(self.field) > 1e25,self.field)
1278        if masked.mask.any() == True:
1279             if self.verbose: print "!! WARNING !! Values over +-1e25 are considered missing values."
1280             self.field = masked
1281             self.field.set_fill_value([np.NaN])
1282        # now ready to compute [TBD?? we would like to have e.g. mean over x,y and min over t]
1283        if self.method_t == "comp":
1284            if self.verbose: print "**** OK. Computing over t axis."
1285            if self.compute == "mean": self.field = ppcompute.mean(self.field,axis=0)
1286            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=0)
1287            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=0)
1288            else: print "!! ERROR !! operation not supported." ; exit()
1289            nt = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1290        if self.method_z == "comp": 
1291            if self.verbose: print "**** OK. Computing over z axis."
1292            if self.compute == "mean": self.field = ppcompute.mean(self.field,axis=1)
1293            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=1)
1294            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=1)
1295            nz = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1296        if self.method_y == "comp": 
1297            if self.verbose: print "**** OK. Computing over y axis."
1298            if self.compute == "mean": self.field = ppcompute.mean(self.field,axis=2)
1299            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=2)
1300            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=2)
1301            ny = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1302            if self.field_x.ndim == 2: self.field_x = self.field_x[0,:] # TBD: this is OK for regular grid but not for irregular
1303        if self.method_x == "comp":
1304            if self.verbose: print "**** OK. Computing over x axis."
1305            if self.compute == "mean": self.field = ppcompute.mean(self.field,axis=3)
1306            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=3)
1307            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=3)
1308            nx = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
1309            if self.field_y.ndim == 2: self.field_y = self.field_y[:,0] # TBD: this is OK for regular grid but not for irregular
1310        # remove all dimensions with size 1 to prepare plot (and check the resulting dimension with dimplot)
1311        self.field = np.squeeze(self.field)
1312        if self.field.ndim != self.dimplot: 
1313            print "!! ERROR !! Problem: self.field is different than plot dimensions", self.field.ndim, self.dimplot ; exit()
1314        if self.verbose: 
1315            print "**** OK. Final shape for "+self.var+" after averaging and squeezing",self.field.shape
1316
1317    # define coordinates for plot
1318    # -------------------------------
1319    def definecoord(self):
1320        I_got_abs = False ; I_got_ord = False
1321        # here is the thing. time is usually taken as an abscissa so we start with time.
1322        if self.method_t ==  "free": 
1323            self.absc = self.field_t ; self.absclab = self.name_t
1324            I_got_abs = True
1325        # then we usually have x as an abscissa.
1326        if self.method_x == "free":
1327            if I_got_abs: 
1328                self.ordi = self.field_x ; self.ordilab = self.name_x
1329                I_got_ord = True
1330            else:         
1331                self.absc = self.field_x ; self.absclab = self.name_x
1332                I_got_abs = True
1333        # ... or we have y
1334        if self.method_y == "free":
1335            if I_got_abs:   
1336                self.ordi = self.field_y ; self.ordilab = self.name_y
1337                I_got_ord = True
1338            else:         
1339                self.absc = self.field_y ; self.absclab = self.name_y
1340                I_got_abs = True
1341        # ... and we end with z because it is usually not an abscissa (profiles).
1342        if self.method_z == "free":
1343            if self.field_z[0] > self.field_z[1]:
1344                self.invert_axes = True # the axis will be turned upside-down
1345            if I_got_abs: 
1346                self.ordi = self.field_z ; self.ordilab = self.name_z
1347                I_got_ord = True
1348            else:
1349                self.absc = self.field_z ; self.absclab = self.name_z
1350                I_got_abs = True
1351                self.swap_axes = True # says that altitude is not supposed to remain as an abscissa
1352        if I_got_abs and self.verbose: print "**** OK. abscissa:",self.absclab, self.absc.shape
1353        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.