Ignore:
Timestamp:
Mar 30, 2013, 11:21:01 AM (12 years ago)
Author:
aslmd
Message:

UTIL PYTHON planetoplot_v2. added meanarea possibility for averages ponderate with areas. see aire.py (and set_ppclass.txt for presets). corrected a bug with customplot. separated getfield from computations.

Location:
trunk/UTIL/PYTHON/planetoplot_v2
Files:
1 added
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/UTIL/PYTHON/planetoplot_v2/pp.py

    r920 r921  
    3636parser.add_option('-o','--output',action='store',dest='filename',type="string",default="myplot",help="name of output files")
    3737parser.add_option('-d','--directory',action='store',dest='folder',type="string",default="./",help="directory of output files")
     38parser.add_option('-u','--compute',action='store',dest='compute',type="string",default="mean",help='')
    3839# plot --> upper case
    3940# -- generic
  • trunk/UTIL/PYTHON/planetoplot_v2/ppclass.py

    r920 r921  
    3333zefile = "set_ppclass.txt"
    3434glob_listx = [] ; glob_listy = [] ; glob_listz = [] ; glob_listt = []
     35glob_listarea = []
    3536try:
    3637    f = open(whereset+zefile, 'r') ; lines = f.readlines()
     
    3940    for stuff in lines[11].strip().split(';'): glob_listz.append(stuff)
    4041    for stuff in lines[14].strip().split(';'): glob_listt.append(stuff)
     42    for stuff in lines[17].strip().split(';'): glob_listarea.append(stuff)
    4143except IOError:
    4244    print "warning: "+zefile+" not in "+whereset+" ; no presets."
     
    151153        self.nplot = 0
    152154        self.p = None
     155        self.customplot = False
    153156        ## what could be defined by the user
    154157        self.file = file
     
    497500              obj.method_z = mz ; obj.method_t = mt           
    498501              ### get index
    499               obj.getindextime(st,t,self.stridet)
    500               obj.getindexvert(sz,z,self.stridez)
    501               obj.getindexhori(sx,sy,x,y,self.stridex,self.stridey)
     502              obj.getindextime(dalist=st,ind=t,stride=self.stridet)
     503              obj.getindexvert(dalist=sz,ind=z,stride=self.stridez)
     504              obj.getindexhori(dalistx=sx,dalisty=sy,indx=x,indy=y,stridex=self.stridex,stridey=self.stridey)
    502505        # change status
    503506        self.status = "defined"
     
    518521        ## first get fields
    519522        ## ... only what is needed is extracted from the files
    520         ## ... and averages are computed
     523        ## ... and computations are performed
    521524        for i in range(self.nfin):
    522525         for j in range(self.nvin):
     
    527530              obj = self.request[i][j][t][z][y][x]
    528531              obj.getfield()
     532              obj.computations()
    529533        # change status
    530534        self.status = "retrieved"
     
    731735            ## adapted space for labels etc
    732736            ## ... except for ortho because there is no label anyway
    733             customplot = self.p[0].field.ndim == 2 \
     737            self.customplot = self.p[0].field.ndim == 2 \
    734738                        and self.p[0].mapmode == True \
    735739                        and self.p[0].proj not in ["ortho"]
    736             if customplot:
     740            if self.customplot:
    737741                margin = 0.07
    738742                self.fig.subplots_adjust(left=margin,right=1-margin,bottom=margin,top=1-margin)
     
    744748            self.n = self.plotin.n
    745749            self.howmanyplots = self.plotin.howmanyplots
     750            self.customplot = self.plotin.customplot
    746751        # LOOP on all subplots
    747752        # NB: cannot use 'for pl in self.p' if self.plotin not None
     
    780785        print "**** Done step: makeplot"
    781786        if (self.n == self.howmanyplots):
    782             ppplot.save(mode=self.out,filename=self.filename,folder=self.folder,custom=customplot)
     787            ppplot.save(mode=self.out,filename=self.filename,folder=self.folder,custom=self.customplot)
    783788            mpl.close()
    784789        # SAVE A PICKLE FILE WITH THE self.p ARRAY OF OBJECTS
     
    979984            print '!! ERROR !! File '+self.file+' does not contain variable: '+self.var
    980985            print '..... try instead with ',self.f.variables.keys() ; exit()
     986
     987    # copy attributes from another existing object
     988    # --------------------------------------------
     989    def copy(self,source):
     990        for k, v in vars(source).items():
     991            setattr(self,k,v)
    981992
    982993    # get x,y,z,t dimensions from NETCDF file
     
    10771088    ### TBD: il faudrait ne prendre que les indices qui correspondent a l interieur d un plot (dans all)
    10781089    # -------------------------------
    1079     def getindextime(self,dalist,ind,stride):
     1090    def getindextime(self,dalist=None,ind=None,stride=1):
    10801091        if self.method_t == "free":
    10811092            self.index_t = np.arange(0,self.dim_t,stride)
     
    11011112    ### TBD: il faudrait ne prendre que les indices qui correspondent a l interieur d un plot (dans all)
    11021113    # -------------------------------
    1103     def getindexvert(self,dalist,ind,stride):
     1114    def getindexvert(self,dalist=None,ind=None,stride=1):
    11041115        if self.method_z == "free":
    11051116            self.index_z = np.arange(0,self.dim_z,stride)
     
    11291140    ### TBD: il faudrait ne prendre que les indices qui correspondent a l interieur d un plot (dans all)
    11301141    # -------------------------------
    1131     def getindexhori(self,dalistx,dalisty,indx,indy,stridex,stridey):
     1142    def getindexhori(self,dalistx=None,dalisty=None,indx=None,indy=None,stridex=1,stridey=1):
    11321143        ## get what is the method over x and y axis
    11331144        test = self.method_x+self.method_y
     
    13091320             self.field = masked
    13101321             self.field.set_fill_value([np.NaN])
    1311         # now ready to compute [TBD?? we would like to have e.g. mean over x,y and min over t]
     1322
     1323    # perform computations
     1324    # -------------------------------
     1325    # available: mean, max, min, meanarea
     1326    # TB: integrals? for derivatives, define a function self.dx()
     1327    def computations(self): 
     1328        nt,nz,ny,nx = self.field.shape
     1329        # treat the case of mean on fields normalized with grid mesh area
     1330        # ... this is done in the .area() method.
     1331        # after that self.field contains field*area/totarea
     1332        if "area" in self.compute: self.area()
     1333        # now ready to compute [TBD: we would like to have e.g. mean over x,y and min over t ??]
    13121334        if self.method_t == "comp":
    13131335            if self.verbose: print "**** OK. Computing over t axis."
    1314             if self.compute == "mean": self.field = ppcompute.mean(self.field,axis=0)
     1336            if "mean" in self.compute: self.field = ppcompute.mean(self.field,axis=0)
    13151337            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=0)
    13161338            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=0)
     
    13191341        if self.method_z == "comp":
    13201342            if self.verbose: print "**** OK. Computing over z axis."
    1321             if self.compute == "mean": self.field = ppcompute.mean(self.field,axis=1)
     1343            if "mean" in self.compute: self.field = ppcompute.mean(self.field,axis=1)
    13221344            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=1)
    13231345            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=1)
     1346            else: print "!! ERROR !! operation not supported." ; exit()
    13241347            nz = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
    13251348        if self.method_y == "comp":
     
    13281351            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=2)
    13291352            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=2)
     1353            elif self.compute == "meanarea": self.field = ppcompute.sum(self.field,axis=2)
     1354            else: print "!! ERROR !! operation not supported." ; exit()
    13301355            ny = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
    13311356            if self.field_x.ndim == 2: self.field_x = self.field_x[0,:] # TBD: this is OK for regular grid but not for irregular
     
    13351360            elif self.compute == "min": self.field = ppcompute.min(self.field,axis=3)
    13361361            elif self.compute == "max": self.field = ppcompute.max(self.field,axis=3)
     1362            elif self.compute == "meanarea": self.field = ppcompute.sum(self.field,axis=3)
     1363            else: print "!! ERROR !! operation not supported." ; exit()
    13371364            nx = 1 ; self.field = np.reshape(self.field,(nt,nz,ny,nx))
    13381365            if self.field_y.ndim == 2: self.field_y = self.field_y[:,0] # TBD: this is OK for regular grid but not for irregular
     
    13431370        if self.verbose:
    13441371            print "**** OK. Final shape for "+self.var+" after averaging and squeezing",self.field.shape
     1372   
     1373    # get areas for computations and ponderate field by those areas
     1374    # -------------------------------------------------------------
     1375    def area(self):
     1376        if self.verbose: print "**** OK. Get area array for computations."
     1377        # create a request object for area
     1378        # ... and copy known attributes from self
     1379        aire = onerequest()
     1380        aire.copy(self)
     1381        # get area field name
     1382        aire.var = "nothing"
     1383        for c in glob_listarea:
     1384         if c in aire.f.variables.keys():
     1385            aire.var = c
     1386        # do not try to calculate areas automatically
     1387        if aire.var == "nothing":
     1388            print "!! ERROR !! area variable not found... needs to be added in set_ppclass.txt?"
     1389            exit()
     1390        # define area request dimensions
     1391        aire.getdim()
     1392        # ensure this is a 2D horizontal request and define indexes
     1393        #    ... areas are not supposed to vary with time and height
     1394        aire.method_x = "free" ; aire.method_y = "free"
     1395        aire.getindexhori() ; aire.dimplot = 2
     1396        aire.method_z = "fixed" ; aire.field_z = np.array([0]) ; aire.index_z = np.array([0])
     1397        aire.method_t = "fixed" ; aire.field_t = np.array([0]) ; aire.index_t = np.array([0])
     1398        # read the 2D area array in netCDF file
     1399        aire.getfield()
     1400        # normalize by total area
     1401        aire.field = np.squeeze(aire.field)
     1402        totarea = ppcompute.sum(ppcompute.sum(aire.field,axis=1),axis=0)
     1403        if self.verbose: print "**** OK. Total area is: ",totarea
     1404        aire.field = aire.field / totarea
     1405        # reduce with self horizontal indexes
     1406        if "fixed" in self.method_x+self.method_y:
     1407            aire.field = aire.field[self.index_y,self.index_x]
     1408        # tile area array over self t and z axis so that area field could be multiplied with self.field
     1409        aire.field = np.tile(aire.field,(self.index_t.size,self.index_z.size,1,1))
     1410        if self.field.shape != aire.field.shape:
     1411            print "!! ERROR !! Problem in area(). Check array shapes." ; exit()
     1412        else:
     1413            self.field = self.field*aire.field
    13451414
    13461415    # define coordinates for plot
  • trunk/UTIL/PYTHON/planetoplot_v2/set_ppclass.txt

    r910 r921  
    1414  #
    1515Times;time;Time;time_counter
     16  # area: possible names to search for. add in the line with a separating ;
     17  #
     18area;aire
Note: See TracChangeset for help on using the changeset viewer.