Ejemplo n.º 1
0
    def finalize( self, flip_x=False, flip_y=False ):
        """By the time this is called, all synchronize operations should have been done.  But even
        so, each variable has a min and max and a min and max for each of its axes.  We need to
        simplify further for the plot package.
        The options flip_x and flip_y may be set to True to flip the axis.  That is, in x right
        to left and left to right, and in y top to bottom and bottom to top."""
        # old test:
        #if self.presentation.__class__.__name__=="GYx" or\
        #        self.presentation.__class__.__name__=="Gfi":
        # interim test here and below.  Once all the is* functions work, I should
        # drop the tests on self.presentation.__class__.__name__ :
        if vcs.isscatter(self.presentation):
            ylabel, xlabel = string.split(self.title, ' vs ')
            #pdb.set_trace()
            #in the case of scatter plots there are 2 variables packed together
            var = self.vars[0]
            [xMIN, xMAX], [yMIN, yMAX] = self.make_ranges(var)

            #print xMIN, xMAX, yMIN, yMAX
            #print vcs.mkscale(xMIN, xMAX)
            #print vcs.mkscale(yMIN, yMAX)
            self.presentation.xticlabels1 = vcs.mklabels(vcs.mkscale(xMIN, xMAX))
            self.presentation.datawc_x1 = xMIN
            self.presentation.datawc_x2 = xMAX
            self.presentation.xticlabels2 = {(xMIN+xMAX)/2.: xlabel}
            if flip_y:
                self.presentation.datawc_y2 = yMIN
                self.presentation.datawc_y1 = yMAX
                self.presentation.flip = True
            else:
                self.presentation.datawc_y1 = yMIN
                self.presentation.datawc_y2 = yMAX   
            self.presentation.yticlabels1 = vcs.mklabels(vcs.mkscale(yMIN, yMAX))
            self.presentation.yticlabels2 = {(yMIN+yMAX)/2.: ylabel}
            self.presentation.linewidth = 0
            self.presentation.markercolor = 1
            self.presentation.markersize = 5
            #add overplotline is a total kludge
            self.presentation.overplotline = self.overplotline
            if flip_y:
                self.presentation.flip = True
            #self.presentation.list()              
        elif vcs.isyxvsx(self.presentation) or\
                vcs.isisofill(self.presentation) or\
                vcs.isboxfill(self.presentation) or\
                self.presentation.__class__.__name__=="GYx" or\
                self.presentation.__class__.__name__=="G1d" or\
                self.presentation.__class__.__name__=="Gv":
            #pdb.set_trace()
            if flip_y:
                self.presentation.flip = True
            var = self.vars[0]
            axmax = self.axmax[seqgetattr(var,'id','')]
            axmin = self.axmin[seqgetattr(var,'id','')]
            varmax = self.varmax[seqgetattr(var,'id','')]
            varmin = self.varmin[seqgetattr(var,'id','')]
            for v in self.vars[1:]:
                for ax in axmax.keys():
                    axmax[ax] = max(axmax[ax],self.axmax[seqgetattr(v,'id','')][ax])
                    axmin[ax] = min(axmin[ax],self.axmin[seqgetattr(v,'id','')][ax])
                varmax = max(varmax,self.varmax[v.id])
                varmin = min(varmin,self.varmin[v.id])                 
            if vcs.isyxvsx(self.presentation) or\
                    self.presentation.__class__.__name__=="GYx" or\
                    self.presentation.__class__.__name__=="G1d":
                if len(axmax.keys())<=0:
                    return None
                # VCS Yxvsx
                ax = axmax.keys()[0]
                if flip_x:
                    self.presentation.datawc_x2 = axmin[ax]
                    self.presentation.datawc_x1 = axmax[ax]
                else:
                    self.presentation.datawc_x1 = axmin[ax]
                    self.presentation.datawc_x2 = axmax[ax]
                if flip_y:
                    self.presentation.datawc_y2 = varmin
                    self.presentation.datawc_y1 = varmax
                else:
                    self.presentation.datawc_y1 = varmin
                    self.presentation.datawc_y2 = varmax
                #print "DEBUG, in finalize for line plot, datawc_{x1,x2,y1,y2}=",\
                #    self.presentation.datawc_x1, self.presentation.datawc_x2,\
                #    self.presentation.datawc_y1, self.presentation.datawc_y2
            if vcs.isisofill(self.presentation) or self.presentation.__class__.__name__=="Gfi"\
                    or vcs.isboxfill(self.presentation):
                # VCS Isofill or Boxfill

                # First we have to identify which axes will be plotted as X and Y.
                # If the axes each had an 'axis' attribute, axaxi will look something like
                # {'X':'axis1id', 'Y':'axis2id'}.  If one misses the attribute, 'axis0id':'axis0id'.
                axaxi = {ax:id for id,ax in self.axax[seqgetattr(var,'id','')].items()}
                if 'X' in axaxi.keys() and 'Y' in axaxi.keys():
                    axx = axaxi['X']
                    axy = axaxi['Y']
                elif 'Y' in axaxi.keys() and 'Z' in axaxi.keys():
                    axx = axaxi['Y']
                    axy = axaxi['Z']
                #added case of time vs variable
                elif 'T' in axaxi.keys() and 'Y' in axaxi.keys():
                    axx = axaxi['T']
                    axy = axaxi['Y']
                    if axx == 'time':
                        t=var.getTime()
                        if 'units' in dir(t) and t.units == "months since 1800":
                            time_lables = {}
                            months_names = get_month_strings(length=3)             
                            tc=t.asComponentTime()
                            for i, v in enumerate(t):
                                time_lables[v] = months_names[tc[i].month-1]
                            self.presentation.xticlabels1 = time_lables
                            self.presentation.datawc_timeunits = t.units
                            #self.presentation.list()
                elif len(axaxi.keys())==2:
                    # It's not clear what should be the X variable and what the Y variable,
                    # but it's worth trying to do something
                    axx = None
                    axy = None
                    for axetc in var.getDomain()[:]:
                        ax = axetc[0]
                        if getattr(ax,'units',None)=='mbar':
                            # probably pressure levels, a vertical axis
                            axy = ax.id
                        else:
                            axx = ax.id
                    if axx is None or axy is None:
                        # last resort
                        axy = axaxi[axaxi.keys()[0]]
                        axx = axaxi[axaxi.keys()[1]]
                else:
                    return None

                # Now send the plotted min,max for the X,Y axes to the graphics:
                # and if it is not a polar projection
                if vcs.getprojection(self.presentation.projection)._type!=-3:
                    if flip_x:
                        self.presentation.datawc_x2 = axmin[axx]
                        self.presentation.datawc_x1 = axmax[axx]
                    else:
                        self.presentation.datawc_x1 = axmin[axx]
                        self.presentation.datawc_x2 = axmax[axx]
                    if flip_y:
                        self.presentation.datawc_y2 = axmin[axy]
                        self.presentation.datawc_y1 = axmax[axy]
                    else:
                        self.presentation.datawc_y1 = axmin[axy]
                        self.presentation.datawc_y2 = axmax[axy]

                # The variable min and max, varmin and varmax, should be passed on to the graphics
                # for setting the contours.  But apparently you can't tell VCS just the min and max;
                # you have to give it all the contour levels.  So...
                if vcs.isboxfill(self.presentation):
                    self.presentation.boxfill_type = 'custom'  # without this, can't set levels
                nlevels = 16
                try:
                    levels = [float(v) for v in vcs.mkscale( varmin, varmax, nlevels )]
                    # Exceptions occur because mkscale doesn't always work.  E.g. vcs.mkscale(0,1.e35,16)
                except RuntimeWarning:
                    levels = []
                if levels==[]:
                    ## Here's how to do it with percentiles (clip out large values first).
                    #pc05 = numpy.percentile(self.vars[0],0.05)
                    #pc95 = numpy.percentile(self.vars[0],0.95)
                    #levels = [float(v) for v in vcs.mkscale( pc05, pc95, nlevels-2 )]
                    #levels = [varmin]+levels+[varmax]
                    # Evenly distributed levels, after clipping out large values:
                    # This cannot be expected to work always, but it's better than doing nothing.
                    amed = numpy.median(self.vars[0]._data)
                    vclip = amed * 1.0e6
                    print "WARNING graphics problems, clipping some data at",vclip
                    self.vars[0]._data[ self.vars[0]._data > vclip ] = vclip
                    a = numpy.sort(self.vars[0]._data.flatten())
                    asp = numpy.array_split(a,nlevels)
                    afirsts = [c[0] for c in asp]+[asp[-1][-1]]
                    alasts = [asp[0][0]]+[c[-1] for c in asp]
                    levels = [0.5*(afirsts[i]+alasts[i]) for i in range(len(afirsts))]
                    levf = levels[0]
                    levl = levels[-1]
                    levels = [ round(lv,2) for lv in levels ]
                    levels[0] = round(1.1*levels[0]-0.1*levels[1],2)
                    levels[-1] = round(1.1*levels[-1]-0.1*levels[-2],2)

                # ... mkscale returns numpy.float64, which behaves unexpectedly in _setlevels when
                # passed a tuple value
                if levels is not None and len(levels)>0:
                    self.presentation.levels = levels
                #nlevels = max(1, len(levels) - 1)
                #nlrange = range(nlevels+1)
                #nlrange.reverse()
                #self.presentation.legend = vcs.mklabels( self.presentation.levels )
                ## Once you set the levels, the VCS default color choice looks bad.  So you really
                ## have to set contour fill colors (integers from 0 through 255) too:
                #cmin = 32./nlevels
                #cmax = 255./nlevels
                ## A more flexible way to do what's going on here, thanks to Charles Doutriaux:
                ## r=10
                ## g=16
                ## b=20
                ## X.setcolorcell(16,r,g,b)
                ## colors = [16,17,18,...] etc.
                ## vcs.getcolors is useful, more complicated - see its doc string
                #colors =  [int(round(a*cmin+(nlevels-a)*cmax)) for a in nlrange]
                #self.presentation.fillareacolors = colors
                ##self.presentation.fillareacolors=[32,48,64,80,96,112,128,144,160,176,240]
            elif vcs.isvector(self.presentation) or self.presentation.__class__.__name__=="Gv":
                # axis min,max copied from isofill
                axaxi = {ax:id for id,ax in self.axax[seqgetattr(var,'id','')].items()}
                if 'X' in axaxi.keys() and 'Y' in axaxi.keys():
                    axx = axaxi['X']
                    axy = axaxi['Y']
                elif 'Y' in axaxi.keys() and 'Z' in axaxi.keys():
                    axx = axaxi['Y']
                    axy = axaxi['Z']
                self.presentation.datawc_x1 = axmin[axx]
                self.presentation.datawc_x2 = axmax[axx]
                self.presentation.datawc_y1 = axmin[axy]
                self.presentation.datawc_y2 = axmax[axy]

                vec = self.presentation
                vec.scale = min(vcsx.bgX,vcsx.bgY)/ 10.
                if hasattr(self.vars[0],'__getitem__') and not hasattr( self.vars[0], '__cdms_internals__'):
                    # generally a tuple of variables - we need 2 variables to describe a vector
                    v = self.vars[0][0]
                    w = self.vars[0][1]
                else:   # We shouldn't get here, but may as well try to make it work if possible:
                    print "WARNING trying to make a vector plot without tuples!  Variables involved are:"
                    v = self.vars[0]
                    print "variable",v.id
                    v = self.vars[1]
                    print "variable",v.id
                nlats = latAxis(v).shape[0]
                nlons = lonAxis(w).shape[0]
                nlatvs = vcsx.bgY/16   # how many vectors we want in lat direction
                nlonvs = vcsx.bgX/16
                #self.strideX = int( 0.9* vcsx.bgX/nlons )
                #self.strideY = int( 0.6* vcsx.bgY/nlats )
                self.strideX = max(1, int( nlons/nlonvs )) # stride values must be at least 1
                self.strideY = max(1, int( nlats/nlatvs ))
        else:
            print "ERROR cannot identify graphics method",self.presentation.__class__.__name__
Ejemplo n.º 2
0
def test():
    import vcs, cdms2 as cdms, time, os, sys, support  # import vcs and cu
    bg = support.bg

    f = cdms.open(
        os.path.join(cdms.__path__[0], '..', '..', '..', '..', 'sample_data',
                     'clt.nc'))  # open clt file
    u = f.getslab('u', ':', ':', -10., 0., 0, 10)  # get slab u
    v = f.getslab('v', ':', ':', -10., 0., 0, 10)  # get slab v
    x = vcs.init()  # construct vcs canvas

    x.plot(u, v, 'default', 'vector', 'quick', bg=bg)  # plot slab the old way
    support.check_plot(x)
    if bg == 0:
        x.geometry(450, 337, 100, 0)  # change the geometry and location
        x.flush()
        support.check_plot(x)

    a = x.getvector('quick')  # get 'quick' vector
    if not vcs.isgraphicsmethod(a):  # test object 'a' for graphics method
        raise Exception, "Error did not retrieve the gm"
    else:
        if not vcs.isvector(a):  # test object 'a' if vector
            raise Exception, "Error gm is not right type"

    a.script('test', 'w')  # save 'quick' vector as a Python script

    a.xticlabels('', '')  # remove the x-axis
    support.check_plot(x)
    a.xticlabels('*')  # put the x-axis
    support.check_plot(x)

    ############################################################################
    # Change the vector scale                                                  #
    ############################################################################
    a.scale = 2.0
    support.check_plot(x)
    a.scale = 5.0
    support.check_plot(x)
    a.scale = 1.5
    support.check_plot(x)
    a.scale = 0.0
    support.check_plot(x)
    a.scale = -1.5
    support.check_plot(x)
    a.scale = -2.0
    support.check_plot(x)
    a.scale = -5.0
    support.check_plot(x)

    ############################################################################
    # Change the vector typeiiiiiii                                            #
    ############################################################################
    a.type = 0  # same as a.type = 'arrows'
    support.check_plot(x)
    a.type = 1  # same as a.type = 'barbs'
    support.check_plot(x)
    ##    a.type=2				# same as a.type = 'solidarrows'
    ##    support.check_plot(x)
    ##    raw_input("Done...")

    if not '--extended' in sys.argv:
        print '\n************* PARTIAL TEST *****************'
        print 'FOR COMPLETE TEST OF THIS MODULE USE '
        print '   -F (--full) or -E (--extended) option'
        print '************* PARTIAL TEST *****************\n'
        sys.exit()

    ############################################################################
    # Change the vector reference                                              #
    ############################################################################
    a.reference = 10.
    support.check_plot(x)
    a.reference = 100.
    support.check_plot(x)
    a.reference = 4.
    support.check_plot(x)
    a.reference = 5.
    support.check_plot(x)

    ############################################################################
    # Change the vector alignment                                              #
    ############################################################################
    a.alignment = 'head'  # same as a.alignment=0
    support.check_plot(x)
    a.alignment = 'center'  # same as a.alignment=1
    support.check_plot(x)
    a.alignment = 'tail'  # same as a.alignment=2
    support.check_plot(x)

    ############################################################################
    # Change the vector line                                                   #
    ############################################################################
    a.line = 0  # same as 'solid'
    support.check_plot(x)
    a.line = 1  # same as 'dash'
    support.check_plot(x)
    a.line = 2  # same as 'dot'
    support.check_plot(x)
    a.line = 3  # same as 'dash-dot'
    support.check_plot(x)
    a.line = 4  # same as 'long-dash'
    support.check_plot(x)
    a.line = None  # use default line
    support.check_plot(x)

    ############################################################################
    # Change the vector line color                                             #
    ############################################################################
    a.linecolor = (77)
    support.check_plot(x)
    a.linecolor = 16
    support.check_plot(x)
    a.linecolor = 44  # same as a.color=(44)
    support.check_plot(x)
    a.linecolor = None
    support.check_plot(x)

    x.clear()  # clear the VCS Canvas
    x.vector(u, v, a, 'default', bg=bg)  # plot vector using 'default' template
    support.check_plot(x)

    objs = x.listelements('template')  # get the list of templates
    t = x.createtemplate(
        'test')  # create template 'test' from 'default' template
    if not vcs.istemplate(t):  # test whether 't' is a template or not
        raise Exception, "Error template not created"
    else:
        a2 = x.listelements('template')  # get the list of templates
        if objs == a2:
            raise Exception, "Error template not created or added to list"

    x.clear()  # clear the VCS Canvas
    x.plot(t, a, u, v,
           bg=bg)  # plot vector template 't', outline 'a', and arrays 'u':'v'
    support.check_plot(x)
    x.clear()  # clear the VCS Canvas
    x.vector(a, u, v, t,
             bg=bg)  # plot using outline 'a', array 'u':'v', and template 't'
    support.check_plot(x)

    l = x.getline('red')  # get line 'red'
    if not vcs.issecondaryobject(
            l):  # check to see if it is a secondary object
        raise Exception, "Error did not get line"
    else:
        if not vcs.isline(l):  # check to see if it is a line
            raise Exception, "Error object created is not line"

    ###########################################################################
    # Use the create line object 'm' from above and modify the line object    #
    ###########################################################################
    a.line = l  # use the line object
    support.check_plot(x)
    l.color = 44  # change the line color
    support.check_plot(x)
    l.type = 'dot'  # change the line type
    support.check_plot(x)
    l.width = 4  # change the line size
    support.check_plot(x)

    a = x.listelements('vector')  # show list of gm
    r = x.createvector('test2', 'quick')  # create xyvsy 'test2'
    a2 = x.listelements('vector')  # show list of gm
    if a2 == a:
        raise "error gm not created or not added to list"
    x.removeobject(r)  # remove xyvsy 'test2'
    a3 = x.listelements('vector')  # show list of gm
    if a3 != a:
        raise "error gm not removed"

    #################################################################################
    # to see how x.update and x.mode work, see testoutline.py                       #
    #################################################################################
    #x.update()
    #x.mode=1
    #x.mode=0
    print '*************************************************************************************'
    print '******                                                                         ******'
    print '******   V E C T O R   T E S T   C O M P L E T E D   S U C E S S F U L L Y     ******'
    print '******                                                                         ******'
    print '*************************************************************************************'
Ejemplo n.º 3
0
def test():
   import vcs,cdms2 as cdms,time,os,sys,support          # import vcs and cu
   bg=support.bg
   
   f=cdms.open(os.path.join(cdms.__path__[0],'..','..','..','..','sample_data','clt.nc')) # open clt file
   u=f.getslab('u',':',':',-10.,0.,0,10)# get slab u
   v=f.getslab('v',':',':',-10.,0.,0,10)# get slab v
   x=vcs.init()                         # construct vcs canvas
   
   x.plot(u, v, 'default','vector','quick',bg=bg)	# plot slab the old way
   support.check_plot(x)
   if bg==0:
      x.geometry(450,337,100,0)		# change the geometry and location
      x.flush()
      support.check_plot(x)
   
   a=x.getvector('quick')		# get 'quick' vector
   if not vcs.isgraphicsmethod(a):            # test object 'a' for graphics method
      raise Exception, "Error did not retrieve the gm"
   else:
      if not vcs.isvector(a):                 # test object 'a' if vector
         raise Exception, "Error gm is not right type"
   
   a.script('test','w')                 # save 'quick' vector as a Python script
   
   
   a.xticlabels('','')                  # remove the x-axis
   support.check_plot(x)
   a.xticlabels('*')                    # put the x-axis
   support.check_plot(x)
   
   ############################################################################
   # Change the vector scale                                                  #
   ############################################################################
   a.scale=2.0
   support.check_plot(x)
   a.scale=5.0
   support.check_plot(x)
   a.scale=1.5
   support.check_plot(x)
   a.scale=0.0
   support.check_plot(x)
   a.scale=-1.5
   support.check_plot(x)
   a.scale=-2.0
   support.check_plot(x)
   a.scale=-5.0
   support.check_plot(x)
   
   ############################################################################
   # Change the vector typeiiiiiii                                            #
   ############################################################################
   a.type=0				# same as a.type = 'arrows'
   support.check_plot(x)
   a.type=1				# same as a.type = 'barbs'
   support.check_plot(x)
##    a.type=2				# same as a.type = 'solidarrows'
##    support.check_plot(x)
##    raw_input("Done...")


   if not '--extended' in sys.argv:
     print '\n************* PARTIAL TEST *****************'
     print 'FOR COMPLETE TEST OF THIS MODULE USE '
     print '   -F (--full) or -E (--extended) option'
     print '************* PARTIAL TEST *****************\n'
     sys.exit()


 



   ############################################################################
   # Change the vector reference                                              #
   ############################################################################
   a.reference=10.
   support.check_plot(x)
   a.reference=100.
   support.check_plot(x)
   a.reference=4.
   support.check_plot(x)
   a.reference=5.
   support.check_plot(x)
   
   ############################################################################
   # Change the vector alignment                                              #
   ############################################################################
   a.alignment='head'      		# same as a.alignment=0
   support.check_plot(x)
   a.alignment='center'    		# same as a.alignment=1
   support.check_plot(x)
   a.alignment='tail'      		# same as a.alignment=2
   support.check_plot(x)
   
   ############################################################################
   # Change the vector line                                                   #
   ############################################################################
   a.line=0        			# same as 'solid'
   support.check_plot(x)
   a.line=1       			# same as 'dash'
   support.check_plot(x)
   a.line=2        			# same as 'dot'
   support.check_plot(x)
   a.line=3        			# same as 'dash-dot'
   support.check_plot(x)
   a.line=4        			# same as 'long-dash'
   support.check_plot(x)
   a.line=None        			# use default line   
   support.check_plot(x)
   
   ############################################################################
   # Change the vector line color                                             #
   ############################################################################
   a.linecolor=(77)
   support.check_plot(x)
   a.linecolor=16
   support.check_plot(x)
   a.linecolor=44  # same as a.color=(44)
   support.check_plot(x)
   a.linecolor=None
   support.check_plot(x)
   
   x.clear()                            # clear the VCS Canvas
   x.vector(u, v, a,'default',bg=bg)		# plot vector using 'default' template
   support.check_plot(x)
   
   objs =x.listelements('template')                   # get the list of templates
   t=x.createtemplate('test')           # create template 'test' from 'default' template
   if not vcs.istemplate(t):                  # test whether 't' is a template or not
      raise Exception,"Error template not created"
   else:
      a2 =x.listelements('template')                   # get the list of templates
      if objs==a2:
         raise Exception,"Error template not created or added to list"
   
   x.clear()                            # clear the VCS Canvas
   x.plot(t,a,u,v,bg=bg)                      # plot vector template 't', outline 'a', and arrays 'u':'v'
   support.check_plot(x)
   x.clear()                            # clear the VCS Canvas
   x.vector(a,u,v,t,bg=bg)                    # plot using outline 'a', array 'u':'v', and template 't'
   support.check_plot(x)
   
   l=x.getline('red')                	# get line 'red'
   if not vcs.issecondaryobject(l):           # check to see if it is a secondary object
      raise Exception,"Error did not get line"
   else:
      if not vcs.isline(l):                  	# check to see if it is a line
         raise Exception, "Error object created is not line"
   
   ###########################################################################
   # Use the create line object 'm' from above and modify the line object    #
   ###########################################################################
   a.line=l                             # use the line object
   support.check_plot(x)
   l.color = 44                         # change the line color
   support.check_plot(x)
   l.type ='dot'                    # change the line type
   support.check_plot(x)
   l.width=4 				# change the line size
   support.check_plot(x)
   
   a = x.listelements('vector')                      # show list of gm
   r=x.createvector('test2','quick')     # create xyvsy 'test2'
   a2 = x.listelements('vector')                      # show list of gm
   if a2==a:
      raise "error gm not created or not added to list"
   x.removeobject(r)                    # remove xyvsy 'test2'
   a3 = x.listelements('vector')                      # show list of gm
   if a3!=a:
      raise "error gm not removed"
   
   #################################################################################
   # to see how x.update and x.mode work, see testoutline.py                       #
   #################################################################################
   #x.update()
   #x.mode=1
   #x.mode=0
   print '*************************************************************************************'
   print '******                                                                         ******'
   print '******   V E C T O R   T E S T   C O M P L E T E D   S U C E S S F U L L Y     ******'
   print '******                                                                         ******'
   print '*************************************************************************************'