示例#1
0
def test():
   import vcs,cdms2,time,os,sys,support                # import vcs and cu
   bg=support.bg
   f=cdms2.open(os.path.join(cdms2.__path__[0],'..','..','..','..','sample_data','clt.nc'))
   u=f('u')                             # get slab u
   v=f('v')                             # get slab v
   x=vcs.init()                         # construct vcs canvas
   
   x.plot(u, v, 'default','scatter','quick',bg=bg)	# plot slab the old way
   support.check_plot(x)
   if bg==0:
      x.mode=1
      x.geometry(450,337,100,0)		# change the geometry and location
      x.flush()
      support.check_plot(x)

   
   a=x.getscatter('quick')		# get 'quick' scatter
   if not vcs.isgraphicsmethod(a):            # test object 'a' for graphics method
      raise Exception, "Error did not retrieve the gm"
   else:
      if not vcs.isscatter(a):                # test object 'a' if scatter
         raise Exception, "Error gm is not right type"
   
   a.script('test','w')                 # save 'quick' scatter as a Python script
   
   print 'yepp'
   a.xticlabels('','')                  # remove the x-axis
   support.check_plot(x)
   a.xticlabels('*')                    # put the x-axis
   support.check_plot(x)
   
   ############################################################################
   # Change the scatter marker type                                           #
   ############################################################################
   #a.marker=0
   a.marker=1				# same as a.marker='dot'
   support.check_plot(x)
   a.marker=2				# same as a.marker='plus'
   support.check_plot(x)
   a.marker=3				# same as a.marker='star'
   support.check_plot(x)
   a.marker=4				# same as a.marker='circle'
   support.check_plot(x)
   a.marker=5				# same as a.marker='cross'
   support.check_plot(x)
   a.marker=6				# same as a.marker='diamond'
   support.check_plot(x)
   a.marker=7				# same as a.marker='triangle_up'
   support.check_plot(x)
   a.marker=8				# same as a.marker='triangle_down'
   support.check_plot(x)
   a.marker=9				# same as a.marker='triangle_left'
   support.check_plot(x)
   a.marker=10				# same as a.marker='triangle_right'
   support.check_plot(x)
   a.marker=11				# same as a.marker='square'
   support.check_plot(x)
   a.marker=12				# same as a.marker='diamond_fill'
   support.check_plot(x)
   a.marker=13				# same as a.marker='triangle_up_fill'
   support.check_plot(x)
   a.marker=14				# same as a.marker='triangle_down_fill'
   support.check_plot(x)
   a.marker=15				# same as a.marker='triangle_left_fill'
   support.check_plot(x)
   a.marker=16				# same as a.marker='triangle_right_fill'
   support.check_plot(x)
   a.marker=17				# same as a.marker='square_fill'
   support.check_plot(x)
   
   ############################################################################
   # Change the scatter marker size                                           #
   ############################################################################
   a.markersize=5
   support.check_plot(x)
   a.markersize=55
   support.check_plot(x)
   a.markersize=100
   support.check_plot(x)
   a.markersize=300
   support.check_plot(x)
   a.markersize=15
   support.check_plot(x)
   
   ############################################################################
   # Change the scatter marker color                                          #
   ############################################################################
   a.markercolor=(77)
   support.check_plot(x)
   a.markercolor=16
   support.check_plot(x)
   a.markercolor=44			# same as a.markercolor=(44)
   support.check_plot(x)
   
   ############################################################################
   # Change the scatter settings to default                                   #
   ############################################################################
   a.markercolor=None
   support.check_plot(x)
   a.markersize=None
   support.check_plot(x)
   a.marker=None
   support.check_plot(x)
   
   a.marker=1                           # same as a.marker='dot'
   support.check_plot(x)
   
   x.clear()                            # clear the VCS Canvas
   x.scatter(u, v, a,'default',bg=bg)		# plot scatter using 'default' template
   support.check_plot(x)
   
   t=x.createtemplate('test')           # create template 'test' from 'default' template
   
   x.clear()                            # clear the VCS Canvas
   x.plot(t,a,u,v,bg=bg)                      # plot scatter template 't', outline 'a', and arrays 'u':'v'
   support.check_plot(x)
   x.clear()                            # clear the VCS Canvas
   x.scatter(a,u,v,t,bg=bg)                   # plot using outline 'a', array 'u':'v', and template 't'
   support.check_plot(x)
   
   m=x.getmarker('red')                	# get marker 'red'
   if vcs.issecondaryobject(m):           # check to see if it is a secondary object
      if not vcs.ismarker(m):                 # check to see if it is a fill area
         raise Exception, "Error: this is not a marker object."
   else:
      raise Exception, "Error: this is not a sceondary object."
   
   ###########################################################################
   # Use the create marker object 'm' from above and modify the line object  #
   ###########################################################################
   a.marker=m                           # use the marker object
   support.check_plot(x)
   m.color = 44                         # change the marker color
   support.check_plot(x)
   m.type ='square'                     # change the marker type
   support.check_plot(x)
   m.size=20				# change the marker size
   support.check_plot(x)
   
   e = x.listelements('scatter')         # show list of scatter
   r=x.createscatter('test2','quick')   # create scatter 'test2'
   e2 = x.listelements('scatter')         # show list of scatter
   if e2==e:
      raise Exception,"Error new scatter does not appear in list"
   e3=list(e)
   e3.append("test2")
   e3.sort()
   if e3!=e2:
      raise "Error new scatter created but not matching old list of scatter"
   x.removeobject(r)                    # remove scatter 'test2'
   e4 = x.listelements('scatter')         # show list of scatter
   if e4!=e:
      raise Exception,"Error method 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 '******   S C A T T E 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 '*************************************************************************************'
示例#2
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__
示例#3
0
def test():
    import vcs
    import cdms2
    import os
    import support                # import vcs and cu
    bg = support.bg
    f = cdms2.open(os.path.join(vcs.sample_data, 'clt.nc'))
    u = f('u')                             # get slab u
    v = f('v')                             # get slab v
    x = vcs.init()                         # construct vcs canvas

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

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

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

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

    ##########################################################################
    # Change the scatter marker type                                           #
    ##########################################################################
    # a.marker=0
    a.marker = 1				# same as a.marker='dot'
    support.check_plot(x)
    a.marker = 2				# same as a.marker='plus'
    support.check_plot(x)
    a.marker = 3				# same as a.marker='star'
    support.check_plot(x)
    a.marker = 4				# same as a.marker='circle'
    support.check_plot(x)
    a.marker = 5				# same as a.marker='cross'
    support.check_plot(x)
    a.marker = 6				# same as a.marker='diamond'
    support.check_plot(x)
    a.marker = 7				# same as a.marker='triangle_up'
    support.check_plot(x)
    a.marker = 8				# same as a.marker='triangle_down'
    support.check_plot(x)
    a.marker = 9				# same as a.marker='triangle_left'
    support.check_plot(x)
    a.marker = 10				# same as a.marker='triangle_right'
    support.check_plot(x)
    a.marker = 11				# same as a.marker='square'
    support.check_plot(x)
    a.marker = 12				# same as a.marker='diamond_fill'
    support.check_plot(x)
    a.marker = 13				# same as a.marker='triangle_up_fill'
    support.check_plot(x)
    a.marker = 14				# same as a.marker='triangle_down_fill'
    support.check_plot(x)
    a.marker = 15				# same as a.marker='triangle_left_fill'
    support.check_plot(x)
    a.marker = 16				# same as a.marker='triangle_right_fill'
    support.check_plot(x)
    a.marker = 17				# same as a.marker='square_fill'
    support.check_plot(x)

    ##########################################################################
    # Change the scatter marker size                                           #
    ##########################################################################
    a.markersize = 5
    support.check_plot(x)
    a.markersize = 55
    support.check_plot(x)
    a.markersize = 100
    support.check_plot(x)
    a.markersize = 300
    support.check_plot(x)
    a.markersize = 15
    support.check_plot(x)

    ##########################################################################
    # Change the scatter marker color                                          #
    ##########################################################################
    a.markercolor = (77)
    support.check_plot(x)
    a.markercolor = 16
    support.check_plot(x)
    a.markercolor = 44			# same as a.markercolor=(44)
    support.check_plot(x)

    ##########################################################################
    # Change the scatter settings to default                                   #
    ##########################################################################
    a.markercolor = None
    support.check_plot(x)
    a.markersize = None
    support.check_plot(x)
    a.marker = None
    support.check_plot(x)

    a.marker = 1                           # same as a.marker='dot'
    support.check_plot(x)

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

    # create template 'test' from 'default' template
    t = x.createtemplate('test')

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

    m = x.getmarker('red')                	# get marker 'red'
    # check to see if it is a secondary object
    if vcs.issecondaryobject(m):
        # check to see if it is a fill area
        if not vcs.ismarker(m):
            raise Exception("Error: this is not a marker object.")
    else:
        raise Exception("Error: this is not a sceondary object.")

    ###########################################################################
    # Use the create marker object 'm' from above and modify the line object  #
    ###########################################################################
    a.marker = m                           # use the marker object
    support.check_plot(x)
    m.color = 44                         # change the marker color
    support.check_plot(x)
    m.type = 'square'                     # change the marker type
    support.check_plot(x)
    m.size = 20				# change the marker size
    support.check_plot(x)

    e = x.listelements('scatter')         # show list of scatter
    r = x.createscatter('test2', 'quick')   # create scatter 'test2'
    e2 = x.listelements('scatter')         # show list of scatter
    if e2 == e:
        raise Exception("Error new scatter does not appear in list")
    e3 = list(e)
    e3.append("test2")
    e3.sort()
    if e3 != e2:
        raise "Error new scatter created but not matching old list of scatter"
    x.removeobject(r)                    # remove scatter 'test2'
    e4 = x.listelements('scatter')         # show list of scatter
    if e4 != e:
        raise Exception("Error method 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 '******   S C A T T E 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 '*************************************************************************************'