def plot_a_ratio(s,gm,ratio):
    x=vcs.init()
    x.open()
    x.geometry(400,800)
    y=vcs.init()
    y.open()
    y.geometry(800,400)
    for X in [x,y]:
        X.plot(s,gm,ratio=ratio)
        if X.islandscape():
            orient = "ldscp"
        else:
            orient = "port"
        X.png("aspect_ratio_%s_%s.png" % (orient,ratio))
    return x
Ejemplo n.º 2
0
    def updateContents(self, inputPorts):
        """ Get the vcs canvas, setup the cell's layout, and plot """        
        spreadsheetWindow = spreadsheetController.findSpreadsheetWindow()
        spreadsheetWindow.setUpdatesEnabled(False)

        # Set the canvas
        self.canvas = inputPorts[0]
        if self.canvas is None:
            self.canvas = vcs.init()
        self.canvas.clear()

        # Place the mainwindow that the plot will be displayed in, into this
        # cell widget's layout
        self.window = VCSQtManager.window(self.windowIndex)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.window)
        self.setLayout(layout)        

        # Plot
        if len(inputPorts) > 2:
            args = inputPorts[1]
            kwargs = inputPorts[2]
            self.canvas.plot(*args, **kwargs)

        spreadsheetWindow.setUpdatesEnabled(True)
Ejemplo n.º 3
0
    def animation(self):

        import vcs,cdms,tempfile,os

        canvas=vcs.init()                  # Construct VCS object to generate image

        # Get subset of data
        cdms.setAutoReshapeMode('on')
        if (len(self.var.shape) == 4):
           a = self.var[0:12,0]
        elif (len(self.var.shape) == 3):
           a = self.var[0:12]
        else:
           a = None
        cdms.setAutoReshapeMode('off')
        
        # Create image in background
        if (a != None):
           gif_file = tempfile.mktemp() # Generate temporary file to store GIF image
           for i in range(a.shape[0]):
              canvas.plot(a[i],'default','isofill',variable=self.var,bg=1) # Generate VCS isofill image
              gif_name = canvas.gif(gif_file)                               # Generate temporary GIF image
              canvas.clear()                # Clear the VCS Canvas for next image

           f=open(gif_name,'rb')               # Open temporary GIF image
           s=f.read()                   # Read temporary GIF image
           f.close()                    # Close GIF image
           os.remove(gif_name)          # Remove temporary GIF image,
        else:
           s=None

        return s                        # Return GIF image string
Ejemplo n.º 4
0
    def execute(self): 
        import cdms2, vcs
        cdms2.setNetcdfShuffleFlag(0)
        cdms2.setNetcdfDeflateFlag(0)
        cdms2.setNetcdfDeflateLevelFlag(0)
        start_time = time.time()
        dataIn=self.loadData()[0]
        location = self.loadDomain()
        cdms2keyargs = self.domain2cdms(location)
        url = dataIn["url"]
        id = dataIn["id"]
        var_cache_id =  ":".join( [url,id] )
        dataset = self.loadFileFromURL( url )
        logging.debug( " $$$ Data Request: '%s', '%s' ", var_cache_id, str( cdms2keyargs ) )
        variable = dataset[ id ]

        read_start_time = time.time()
        result_variable = variable(**cdms2keyargs)
        result_data = result_variable.squeeze()[...]
        time_axis = result_variable.getTime()
        read_end_time = time.time()

        x = vcs.init()
        bf = x.createboxfill('new')
        x.plot( result_data, bf, 'default', variable=result_variable, bg=1 )
        x.gif(  OutputPath + '/plot.gif' )

        result_obj = {}

        result_obj['url'] = OutputDir + '/plot.gif'
        result_json = json.dumps( result_obj )
        self.result.setValue( result_json )
        final_end_time = time.time()
        logging.debug( " $$$ Execution time: %f (with init: %f) sec", (final_end_time-start_time), (final_end_time-self.init_time) )
Ejemplo n.º 5
0
def convert_to_working_copy(sb, folder_to_publish, options):
    vprint('Converting %s to working copy.' % folder_to_publish, verbosity=1)
    use_master = False
    branch = '%s%s/%s/built.%s' % (options.repo, sb.get_branch(), sb.get_top_component(), #fix_julie repo structure knowledge
                                   sb.get_targeted_platform_variant())
    if bzr_node_needs_creating(branch, 'version-info', 'branch-nick:'):
        err = vcs.init(branch)
        if err:
            return err
        use_master = True
    tmpfldr = sb.get_built_root() + '.' + sb.get_top_component() + '~tmp~'
    wr = vcs.get_working_repository()
    err = wr.create_or_update_checkout(tmpfldr, sb.get_top_component(),
                                 'built.%s' % sb.get_targeted_platform_variant(),
                                 sb.get_branch(), revision=None,
                                 use_master=use_master)
    if err:
        return err
    try:
        for x in [x for x in os.listdir(tmpfldr) if x.startswith('.bzr')]:
            dest = os.path.join(folder_to_publish, x)
            if os.path.exists(dest):
                if os.path.isfile(dest):
                    os.remove(dest)
                else:
                    vprint('Error: %s already exists.' % dest)
                    return 1
            src = os.path.join(tmpfldr, x)
            os.rename(src, dest)
    finally:
        shutil.rmtree(tmpfldr)
    return 0
Ejemplo n.º 6
0
 def __init__(self, *arg, **kw):
     super(VcsPlot, self).__init__(*arg, **kw)
     self._window = None
     self._canvas = vcs.init()
     self._plot = PlotManager(self._canvas)
     self._plot.graphics_method = vcs.getisofill()              # default
     self._plot.template = vcs.elements['template']['default']  # default
Ejemplo n.º 7
0
 def manageCanvas(self, showing):
     if showing and self.canvas is None:
         self.canvas = vcs.init(backend=self.mRenWin)
         self.canvas.open()
     if not showing and self.canvas is not None:
         self.canvas.onClosing((0, 0))
         self.canvas = None
Ejemplo n.º 8
0
 def plot_one_average (self, averager, template='default', graphics_mode='isofill'):
     import vcs, cdms
     canvas=vcs.init()                   # Construct VCS object to generate image
     cdms.setAutoReshapeMode('off')
     a, keyargs = averager(self.var)
     apply(canvas.plot, (a, template, graphics_mode), keyargs) # Generate VCS isofill image
     return gifiate(canvas)
Ejemplo n.º 9
0
    def __init__(self, parent=None, customPath=None, styles=None):
        super(UVCDATMainWindow, self).__init__(parent)
        self.root = self
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setDocumentMode(True)
        # init user options
        self.initCustomize(customPath, styles)
        self.root = self
        # self.tool_bar = mainToolbarWidget.QMainToolBarContainer(self)
        self.canvas = []

        self.canvas.append(vcs.init())
        self.colormapEditor = QColormapEditor(self)
        # Create the command recorder widget
        self.recorder = commandsRecorderWidget.QCommandsRecorderWidget(self)
        # Adds a shortcut to the record function
        self.record = self.recorder.record
        self.preferences = preferencesWidget.QPreferencesDialog(self)
        self.preferences.hide()
        self.cdmsCacheWidget = CdmsCacheWidget(self)
        #        self.regridding = regriddingWidget.QRegriddingDialog(self)
        #        self.regridding.hide()
        ###########################################################
        # Init Menu Widget
        ###########################################################
        self.mainMenu = mainMenuWidget.QMenuWidget(self)
        self.createDockWindows()
        self.createActions()
        self.updateMenuActions()
        self.embedSpreadsheet()
        self.connectSignals()
        self.resize(1150, 800)
Ejemplo n.º 10
0
Archivo: app.py Proyecto: UV-CDAT/vcdat
def plot_template():
    tmpl = json.loads(request.args["tmpl"])
    t = templ_from_json(tmpl)
    canvas = vcs.init(bg=True)
    g = vcs.createboxfill()
    g.xmtics1 = {.5 * i: "" for i in range(1,20,2)}
    g.xmtics2 = g.xmtics1
    g.ymtics1 = g.xmtics1
    g.ymtics2 = g.xmtics1
    ticlabels = {i: str(i) for i in range(10)}
    g.xticlabels1 = ticlabels
    g.yticlabels1 = ticlabels
    g.yticlabels2 = ticlabels
    g.xticlabels2 = ticlabels
    v = [[0] * 10] * 10
    v = cdms2.tvariable.TransientVariable(v)

    t.plot(canvas, v, g)
    if t.legend.priority:
        t.drawColorBar([(0,0,0,0)], [0, 1], x=canvas)
    _, tmp = tempfile.mkstemp(suffix=".png")
    # For certain templates the renWin can be None
    if(canvas.backend.renWin):
        # Only call render if renWin exists
        canvas.backend.renWin.Render()
        canvas.png(tmp)
    # create response from the tmp file, blank or otherwise
    resp = send_file(tmp)
    # Clean up file automatically after request
    wr = weakref.ref(resp, lambda x: os.remove(tmp))
    canvas.close()
    # clean up temporary boxfill and template we created
    del vcs.elements["boxfill"][g.name]
    del vcs.elements["template"][t.name]
    return resp
Ejemplo n.º 11
0
def simpleanimation():
    import vcs, cdms2, sys
    x = vcs.init()
    f = cdms2.open(vcs.prefix+"/sample_data/clt.nc")
    v = f["clt"] 
    dv3d = vcs.get3d_scalar()
    x.plot( v, dv3d )
    x.interact()
Ejemplo n.º 12
0
def init(*args, **kwargs):
    testingDir = os.path.join(os.path.dirname(__file__), "..")
    sys.path.append(testingDir)

    if ((('bg' in kwargs and kwargs['bg']) or ('bg' not in kwargs))):
        vcsinst = vcs.init(*args, **dict(kwargs, bg=1))
        if ('geometry' not in kwargs):
            vcsinst.setbgoutputdimensions(1200, 1091, units="pixels")
        else:
            xy = kwargs['geometry']
            vcsinst.setbgoutputdimensions(xy[0], xy[1], units="pixels")
    else:
        vcsinst = vcs.init(*args, **dict(kwargs, bg=0))

    vcsinst.setantialiasing(0)
    vcsinst.drawlogooff()
    return vcsinst
Ejemplo n.º 13
0
 def plot(self):
     """Plot self using first time and level only."""
     import vcs, cdms, VCSRegion
     canvas=vcs.init()                   # Construct VCS object to generate image
     cdms.setAutoReshapeMode('off')
     a, keyargs  = VCSRegion.getRegion(self.var, time=None, level=None, other=None)
     apply(canvas.plot, (a, 'default', 'isofill'), keyargs) # Generate VCS isofill image
     return gifiate(canvas)                        # Return GIF image string
Ejemplo n.º 14
0
 def preloadModules(self):
     self.splash.showMessage("Loading VCS")
     import vcs
     x = vcs.init()
     x.close()
     x = None
     self.splash.showMessage("Loading CDMS2")
     import cdms2
     self.ready()
Ejemplo n.º 15
0
def doPlotLineCEOF(rawOrAnomaly='Anomaly', filteredOrNot='Filtered',
                                  variables=['olr', 'u850', 'u200'],
                    seasons=['sum', 'win', 'all'], year=None, **kwarg):

    """
    Written By : Arulalan.T

    Date : 22.07.2013

    """

    x = kwarg.get('x', None)
    if x is None:
        x = vcs.init()
        print "x init"
    # end of if x is None:
    x.clear()
    x.portrait()
    if __vcsSlow__:
        x.pause_time = 1

    if isinstance(year, int):
        yearDir = str(year)
    elif isinstance(year, tuple):
        yearDir = str(year[0]) + '_' + str(year[1])

    inpath = os.path.join(processfilesPath, 'Level2', 'Ceof',
                        rawOrAnomaly, filteredOrNot, yearDir)
    opath = os.path.join(plotsgraphsPath, 'Level2', 'Ceof',
                        rawOrAnomaly, filteredOrNot, yearDir)
    for subName in os.listdir(inpath):
        anopath = os.path.join(inpath, subName)
        for season in os.listdir(anopath):
            sea = season.lower()[:3]
            if not sea in seasons:
                print "Though '%s' Season is available, skipping it without \
                plotting because in the arg seasons list it is not available.\
                So enable it by passing this '%s' season to seasons list " % \
                 (season, sea)
                continue
            # end of if not sea in seasons:
            ceofncpath = os.path.join(anopath, season)
            outpath = os.path.join(opath, subName, season)
            if not os.path.isdir(outpath):
                os.makedirs(outpath)
                print "The path has created ", outpath
            # end of if not os.path.isdir(outpath):

            infile = 'ceof_vars_%s_%s_%s_%s_%s.nc' % (season, yearDir,
                                 rawOrAnomaly, filteredOrNot, subName)
            file_input = os.path.join(ceofncpath, infile)
            endname = [yearDir, rawOrAnomaly, filteredOrNot, subName]
            plotfile_endname = '_'.join(endname)
            plotttitle_endname = ' '.join(endname)
            plotLineCEOF(file_input, outpath, variables, season=sea,
                    ofileEndName=plotfile_endname,
                    titleEndName=plotttitle_endname, pdf=1, x=x)
Ejemplo n.º 16
0
def doPlotPS2D(rawOrAnomaly, filteredOrNot, year,
                    seasons=['sum', 'win', 'all'], pdf=0, png=1):
    """

    Written By : Arulalan.T

    Date : 22.07.2013

    """
    v = vcs.init()
    if isinstance(year, int):
        yearDir = str(year)
    elif isinstance(year, tuple):
        yearDir = str(year[0]) + '_' + str(year[1])

    inpath = os.path.join(processfilesPath, 'Level1', 'WaveNumber',
                          rawOrAnomaly, filteredOrNot, yearDir)

    for subName in os.listdir(inpath):
        anopath = os.path.join(inpath, subName)
        opath = os.path.join(plotsgraphsPath, 'Level1', 'PowerSpectrum2D',
                                rawOrAnomaly, filteredOrNot, yearDir)
        for seasonName in os.listdir(anopath):
            wvpath = os.path.join(anopath, seasonName)
            for wavefile in os.listdir(wvpath):
                varName = wavefile.split('.')[0].split('_')[0]
                wvfile = os.path.join(wvpath, wavefile)

                outpath = os.path.join(opath, subName, varName, seasonName)
                if not os.path.isdir(outpath):
                    os.makedirs(outpath)
                    print "Path has created ", outpath
                # end of if not os.path.isdir(outpath):

                title = 'Equatorial Space Time Spectra - %s %s %s %s %s' % (varName.upper(),
                                                 seasonName, subName, yearDir, filteredOrNot)

                outfile = '%s_%s_%s_%s_%s_%s_ps2d' % (varName, seasonName, subName,
                        yearDir, filteredOrNot, rawOrAnomaly)
                imgpath = os.path.join(outpath, outfile)
                if pdf:
                    imgpath_ext = imgpath + '.pdf'
                else:
                    imgpath_ext = imgpath + '.png'
                # end of if pdf:
                if os.path.isfile(imgpath_ext):
                    print "The image file already exists in the path ", imgpath
                    print "So skipping summerVariance"
                else:
                    f = cdms2.open(wvfile)
                    data = f(varName)  # latitude=(0,8),longitude=(-0.05,0.05))
                    # options to extract needed portion # wavenumber=(0,8), frequency=(-0.05,0.05))
                    f.close()
                    plotPowerSpectrum2D(data, imgpath, seasonName, title, pdf=pdf, png=png, x=v)
                    print "Plotted power spectrum 2d", imgpath
                    # make memory free
                    del data
Ejemplo n.º 17
0
    def initialize(self):
        print "initialize"
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor
        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebFileBrowser('.', '.'))
        # Create default pipeline (Only once for all the session)
        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)
        
        if not _WebCone.view:
            # # VTK specific code
            # renderer = vtk.vtkRenderer()
            # renderWindow = vtk.vtkRenderWindow()
            # renderWindow.AddRenderer(renderer)
            # renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            # renderWindowInteractor.SetRenderWindow(renderWindow)
            # renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()
            # cone = vtk.vtkConeSource()
            # mapper = vtk.vtkPolyDataMapper()
            # actor = vtk.vtkActor()
            # mapper.SetInputConnection(cone.GetOutputPort())
            # actor.SetMapper(mapper)
            # renderer.AddActor(actor)
            # renderer.ResetCamera()
            # renderWindow.Render()

            # VCS specific code
            import vcs, cdms2, sys
            x = vcs.init(bg=1)
            f = cdms2.open( vcs.sample_data+"/geos5-sample.nc" )
            v = f["uwnd"]
            dv3d = vcs.get3d_scalar()
            dv3d.ToggleClipping = ( 40, 360, -28, 90 )
            dv3d.YSlider = ( 0.0, vcs.off)
            dv3d.XSlider = ( 180.0, vcs.on )
            dv3d.ZSlider = ( 0.0, vcs.on )
            dv3d.ToggleVolumePlot = vcs.on
            dv3d.ToggleSurfacePlot = vcs.on
            dv3d.IsosurfaceValue = 31.0
            dv3d.ScaleOpacity = [0.0, 1.0]
            dv3d.BasemapOpacity = 0.5
            dv3d.Camera={ 'Position': (-161, -171, 279),
                          'ViewUp': (.29, 0.67, 0.68),
                          'FocalPoint': (146.7, 8.5, -28.6)  }
            dv3d.VerticalScaling = 5.0
            dv3d.ScaleColormap = [ -46.0, 48.0 ]
            dv3d.ScaleTransferFunction =  [ 12.0, 77.0 ]

            x.plot( v, dv3d )
            renderWindow = x.backend.renWin
            # VTK Web application specific
            _WebCone.view = renderWindow
            self.getApplication().GetObjectIdMap().SetActiveObject("VIEW", renderWindow)
Ejemplo n.º 18
0
 def plot_four_views (self, f1, f2, f3, f4, graphics_mode='isofill'):
     import vcs, cdms
     canvas=vcs.init()                   # Construct VCS object to generate image
     cdms.setAutoReshapeMode('off')
     
     for template, f in (('UL1of4',f1), ('UR2of4',f2), ('LL3of4', f3), ('LR4of4', f4)):
         a, keyargs = f(self.var)
         keyargs['long_name'] = 'Seasonal Averages'
         apply(canvas.plot, (a, template, graphics_mode), keyargs) # Generate VCS isofill image
     return gifiate(canvas)
Ejemplo n.º 19
0
def run_scalar_ctest( filename, varname, parms, template = "default" ):
    import vcs, cdms2
    x = vcs.init()
    f = cdms2.open(vcs.sample_data+"/"+filename )
    v = f[varname]
    dv3d = vcs.get3d_scalar( template )
    for item in parms.items():
        dv3d.setParameter( item[0], item[1] )
    x.plot( v, dv3d )
    x.interact()
Ejemplo n.º 20
0
def test_save_loaded_script(tmpdir):
    _ = vcs.init()
    dirpath = os.path.dirname(__file__)
    load_file = os.path.join(dirpath, "data", "clt_u_v_iso.py")
    save_file = tmpdir.join("clt_u_v_iso.py")

    loaded = import_script(load_file)

    canvases = [vcs.init() for _ in range(loaded.num_canvases)]
    canvas_displays = loaded.plot(canvases)
    for canvas in canvases:
        canvas.close()

    plot_managers = []
    for display_group in canvas_displays:
        pm_group = []
        for display in display_group:
            pm = PlotManager(mocks.PlotInfo)
            # Determine which of the graphics methods created in loaded
            gm = vcs.getgraphicsmethod(display.g_type, display.g_name)
            pm.graphics_method = closest(gm, loaded.graphics_methods)
            pm.template = vcs.gettemplate(display._template_origin)
            pm.variables = display.array
            pm_group.append(pm)
        plot_managers.append(pm_group)
    mocks.PlotInfo.canvas.close()

    export_script(str(save_file), loaded.variables.values(), plot_managers)

    saved = import_script(str(save_file))

    assert saved.rows == loaded.rows
    assert saved.columns == loaded.columns
    assert saved.num_canvases == loaded.num_canvases
    assert len(saved.files) == len(loaded.files)
    assert saved.files[0].id == loaded.files[0].id
    assert len(saved.variables) == len(loaded.variables)

    for save_var, load_var in zip(saved.variables.values(), loaded.variables.values()):
        assert save_var.id == load_var.id

    assert len(saved.graphics_methods) == len(loaded.graphics_methods)
    assert len(saved.templates) == len(loaded.templates)
Ejemplo n.º 21
0
def simplevector():
    import vcs, cdms2, sys
    x = vcs.init()
    f = cdms2.open(vcs.prefix+"/sample_data/clt.nc")
    v = f["v"]
    u = f["u"]  
    dv3d = vcs.get3d_vector()
    dv3d.BasemapOpacity = 0.15
    x.plot( u, v, dv3d )
    x.interact()
Ejemplo n.º 22
0
Archivo: uweb.py Proyecto: imclab/uvis
 def __init__(self):
     self._netcdfFile = None
     self._initRender = False
     self._plotType = None
     self._plotTemplate= "default"
     self._canvas = vcs.init()
     self._viewSelection = None
     self._variable = None
     self.f = None
     self.image_width=864.0
     self.image_height=646.0
Ejemplo n.º 23
0
def plot_a_ratio(s,gm,ratio):
    ret = 0
    x=vcs.init()
    x.open()
    x.geometry(400,800)
    y=vcs.init()
    y.open()
    y.geometry(800,400)
    for X in [x,y]:
        X.plot(s,gm,ratio=ratio)
        if X.islandscape():
            orient = "ldscp"
        else:
            orient = "port"
        fnm = "aspect_ratio_%s_%s.png" % (orient,ratio)
        X.png(fnm)
        print "fnm:",fnm
        src = os.path.join(pth0,fnm)
        print "src:",src
        ret += checkimage.check_result_image(fnm,src,checkimage.defaultThreshold)
    return ret
Ejemplo n.º 24
0
 def __init__(self, controller):
   animate_helper.StoppableThread.__init__(self)
   self.controller = controller
   self.create_prefix()
   self.canvas = vcs.init()
   self.canvas.bgX, self.canvas.bgY = controller.vcs_self.backend.renWin.GetSize()
   # Animation resizing is broken right now; this will give us some buffer space to work with.
   self.canvas.bgX *= 2
   self.canvas.bgY *= 2
   self.controller.animation_created = True
   import atexit
   atexit.register(self.close)
Ejemplo n.º 25
0
def genIsoFill(levels=None, colorlist=None, latlabel='lat5', lonlabel='lon5'):

    global x
    if not (x and isinstance(x, vcs.Canvas.Canvas)):
        # initializing vcs
        x = vcs.init()
        # auto update vcs
        x.mode = 1
        print "one time initializing of vcs obj x"

    if 'genIsoFill' in x.listelements('isofill'):
        # get the 'genIsoFill' template object from temporary memory of vcs
        # isoline template
        isofilltemp = x.getisofill('genIsoFill')
    else:
        # get the lat,lon label according to the passed string
        latlabel, lonlabel = getLatLonLabel(latlabel, lonlabel)

        isofilltemp = x.createisofill('genIsoFill', 'quick')
        isofilltemp.line = ['solid']
        isofilltemp.linewidths = [1.0]
        isofilltemp.label = 'y'
        isofilltemp.xticlabels1 = lonlabel   # set bottom longitude values
        isofilltemp.xticlabels2 = ''         # set top longitude values
        isofilltemp.yticlabels1 = latlabel   # set left latitude values
        isofilltemp.yticlabels2 = ''         # set right latitude values
        if levels:
            # setting isofill levels if user passed
            isofilltemp.levels = levels
            # enable the extensions of legend
            isofilltemp.ext_1 = 'y'         # setting ext in legend after
            isofilltemp.ext_2 = 'y'         # setting levels only
        if colorlist:
            # setting isofill colors if user passed
            isofilltemp.fillareacolors = colorlist

        # saving the 'genIsoFill' into temporary python memory
        x.set('isofill', 'genIsoFill')
    # make isotypelevels for checking purpose, i.e. check the already created
    # template levels and user passed levels are same or not
    isotypelevels = [[lev, 0] for lev in levels]
    if (isofilltemp.levels != isotypelevels or isofilltemp.fillareacolors != colorlist):
        # setting isofill levels, colorlist if user passed
        isofilltemp.levels = levels
        isofilltemp.fillareacolors = colorlist
        # enable the extensions of legend
        isofilltemp.ext_1 = 'y' # setting ext in legend after setting levels only
        isofilltemp.ext_2 = 'y' # if levels changed means again need to set ext
    # checking the lat,lon label and reset if needed
    isofilltemp = checkLatLonLabel(isofilltemp, latlabel, lonlabel)
    # return the genIsoFill object
    return isofilltemp
Ejemplo n.º 26
0
def isoFillPlot(var, levels, colorlist, name, path=None, svg=1, png=0,
                         latlabel='lat5', lonlabel='lon5', style='portrait'):

    global x
    if not (x and isinstance(x, vcs.Canvas.Canvas)):
        # initializing vcs
        x = vcs.init()
        # auto update vcs
        x.mode = 1
        print "one time initializing of vcs obj x"
    if style == 'portrait':
        x.portrait()
        gentemp = genTemplate(xscale = 0.98, yscale = 1.2,
                          xmove = 0.02, ymove = -0.075)
    elif style == 'landscape':
        x.landscape()
        gentemp.legend.priority = 1
        gentemp.legend.x1 = 0.9
        gentemp.legend.y1 = 0.06
        gentemp.legend.x2 = 0.1
        gentemp.legend.y2 = 0.1

        gentemp = genTemplate(xscale = 0.98, yscale = 0.9,
                          xmove = 0.02, ymove = -0.075)
    else:
        raise ValueError("style must be either portrait or landscape")
        
    
    #gentemp.legend.priority = 1 # on the legend
    isofilltemp = genIsoFill(levels, colorlist, latlabel, lonlabel)
    x.plot(var, isofilltemp, gentemp, title = name, continents =6, bg = 1)
    filename = name.replace(' ', '_')

    if not path:
        # get the current workig directory
        path = os.getcwd()
    if not os.path.isdir(path):
        raise RuntimeError("The passed path doesnot exists to store the \
                            vector plots")
    if not path.endswith('/'):
        path += '/'
    if svg:
        x.svg(path + filename + '.svg')
        print "plotted and saved the %s%s.svg" % (path, filename)
    if png:
        x.png(path + filename + '.png')
        print "plotted and saved the %s%s.png" % (path, filename)
    if not (svg or png):
        raise RuntimeError("Can not set both svg, png options are zero/None.\
                            Enable any one to store the isoFillPlot")
    # clear the vcs object
    x.clear()
Ejemplo n.º 27
0
def doPlotEEof(rawOrAnomaly='Anomaly', filteredOrNot='Unfiltered',
                             variables=['precip'],
                         seasons=['jjas'], year=None, v=None):

    """
    Written By : Arulalan.T

    Date : 22.07.2013

    """

    v = vcs.init()
    if __vcsSlow__:
        v.pause_time = 1
    if isinstance(year, int):
        yearDir = str(year)
    elif isinstance(year, tuple):
        yearDir = str(year[0]) + '_' + str(year[1])

    inpath = os.path.join(processfilesPath, 'miso', 'EEof', rawOrAnomaly,
                                                filteredOrNot, yearDir)
    opath = os.path.join(plotsgraphsPath, 'miso', 'EEof', rawOrAnomaly,
                                                filteredOrNot, yearDir)
    for subName in os.listdir(inpath):
        anopath = os.path.join(inpath, subName)
        for season in os.listdir(anopath):
            sea = season.lower()[:4]
            if not sea in seasons:
                print "Though '%s' Season is available, skipping it without \
                plotting because in the arg seasons list it is not available.\
                So enable it by passing this '%s' season to seasons list " % \
                 (season, sea)

                continue
            # end of if not sea in seasons:
            eeofncpath = os.path.join(anopath, season)
            outpath = os.path.join(opath, subName, season)
            if not os.path.isdir(outpath):
                os.makedirs(outpath)
                print "The path has created ", outpath
            # end of if not os.path.isdir(outpath):

            infile = 'eeof_vars_%s_%s_%s_%s_%s.nc' % (season, yearDir, rawOrAnomaly,
                                                   filteredOrNot, subName)
            file_input = os.path.join(eeofncpath, infile)
            endname = [yearDir, rawOrAnomaly, filteredOrNot, subName]
            plotfile_endname = '_'.join(endname)
            plotttitle_endname = ' '.join(endname)
            plotEEof(file_input, outpath, variables, season=sea, NEOF=2,
                    ofileEndName=plotfile_endname,
                    titleEndName=plotttitle_endname, pdf=1, x=v)
Ejemplo n.º 28
0
def genTaylor(reference, colors=None, symbols=None, maxvalue=None, quadrans=1):

    global x
    if not (x and isinstance(x, vcs.Canvas.Canvas)):
        # initializing vcs
        x = vcs.init()
        # auto update vcs
        x.mode = 1
        print "one time initializing of vcs obj x"


    if 'genTaylor' in x.listelements('taylordiagram'):
        tytemp = x.gettaylordiagram('genTaylor')
    else:
        tytemp = x.createtaylordiagram('genTaylor')
        # setting the color to the rms error/deviaton isolines.        
        tytemp.skillColor = 'green'
    # set taylordiagram properties
    
    # setting the truth dotted reference std value 
    tytemp.referencevalue = reference
    if colors:
        # setting the colors
        tytemp.Marker.color = colors
    if symbols:
        # setting the symbols
        tytemp.Marker.symbol= symbols
    if maxvalue:
        # set the max value in std        
        tytemp.max = maxvalue
    # set the quadrans
    tytemp.quadrans = quadrans
    
    if False:
        # this block should do, change the x-axis std labels as 
        # alternative to the y-axis labels. 
        # But in future, we are going to remove this block, since 
        # we are going to keep both x-y axis std labels are same.
        
        # make the skip value either 1, or 2, or 3 or so on ., 
        skip = 1 if maxvalue <=10 else (maxvalue/10)+1 
        # generate & set the x-axis standard deviation labels
        mjrstd1 = vcs.mklabels(numpy.arange(0.5, maxvalue + 2, skip))
        tytemp.xticlabels1 = mjrstd1
        # generate & set the y-axis standard deviation labels
        mjrstd2 = vcs.mklabels(range(0, maxvalue + 1, skip))
        tytemp.yticlabels1 = mjrstd2
   
    # return the genTaylor object
    return tytemp
Ejemplo n.º 29
0
 def __init__(self, canvas, *arg, **kw):
     self._width = kw.get('width', 800)
     self._height = kw.get('height', 600)
     if (canvas != None):
         self._canvas = canvas
     else:
         self._canvas = vcs.init(
             geometry={'width': self._width, 'height':self._height}, bg=1)
         self._canvas.open()
         self._canvas.backend.renWin.AddObserver("ModifiedEvent", self.modifiedEvent)
     self._plot = PlotManager(self._canvas)
     self._plot.graphics_method = vcs.getisofill()              # default
     self._plot.template = vcs.gettemplate('default')  # default
     self._insideModifiedEvent = False
Ejemplo n.º 30
0
    def initialize_create_canvas(self):
        # create a new canvas for each frame
        self.create_canvas = vcs.init()
        self.create_canvas.setcolormap(self.vcs_self.getcolormapname())

        dims = self.canvas_info
        if dims['height'] < 500:
            factor = 2
        else:
            factor = 1
        self.create_canvas.setbgoutputdimensions(width=dims['width'] * factor,
                                                 height=dims[
                                                     'height'] * factor,
                                                 units='pixel')
Ejemplo n.º 31
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'))
    s = f('clt')  # get slab clt
    x = vcs.init()  # construct vcs canvas

    x.plot(s, 'default', 'isofill', 'quick', bg=bg)  # plot slab the old way
    support.check_plot(x)
    if bg == 0:
        x.geometry(450, 337, 0, 0)  # change the geometry
        x.flush()
        support.check_plot(x)
    x.getcolormapname()  # get the active colormap name

    x.setcolormap("AMIP")  # change the colormap
    support.check_plot(x)

    cont = False
    for anarg in sys.argv:
        if anarg in ['--extended', '--full', '-E', '-F']:
            cont = True
            break
    if cont is False:
        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 color map cell 31.			      #
    ############################################################
    colors = {}
    cols = [31, 47, 63, 79, 95, 111, 127, 143, 159, 175, 191]
    for c in cols:
        colors[c] = [
            int(float(c - 16) / (191 - 16) * 100.),
        ] * 3
    for c in cols:
        vals = colors[c]
        x.setcolorcell(c, vals[0], vals[1], vals[2])
        support.check_plot(x)

    for c in colors.keys():
        okvals = colors[c]
        vals = x.getcolorcell(c)
        if vals != okvals:
            raise Exception(
                "Error setting color %i, should have been : %s, but is %s" %
                (c, str(okvals), str(vals)))

    ##################################################################
    # Retrieve the color map RGB values for the given cell numbers.  #
    ##################################################################

    ##################################################################
    # Using colormap objects.                                        #
    ##################################################################
    # show the list of line secondary objects
    c = x.getcolormap('AMIP')  # get 'quick' colormap object
    # check to see if it is a secondary object
    if not vcs.issecondaryobject(c):
        raise Exception("Error did not get colormap as secondary obj")
    else:
        # check to see if it is a line
        if not vcs.iscolormap(c):
            raise Exception("Error object created is not colormap")

    a = x.listelements('colormap')  # show list of xyvsy
    r = x.createcolormap('new')  # create colormap
    a2 = x.listelements('colormap')  # show list of xyvsy
    if a2 == a:
        raise "error cm not created or not added to list"
    x.removeobject(r)  # remove xyvsy 'test2'
    a3 = x.listelements('colormap')  # show list of xyvsy
    if a3 != a:
        raise Exception("error cm not removed")
    c3 = x.createcolormap('new')  # create a new colormap object from default
    x.setcolormap('new')  # change the colormap to 'new' colormap
    c3.index  # show just the colormap RGB values
    for c in colors.keys():
        vals = colors[c]
        c3.index[c] = vals  # change color cell

    for c in colors.keys():
        okvals = colors[c]
        vals = x.getcolorcell(c)
        if vals != okvals:
            raise Exception(
                "Error setting color %i, should have been : %s, but is %s" %
                (c, str(okvals), str(vals)))

    c3.script('test.scr', 'w')  # save 'new' colormap as a VCS script
    c3.script('test', 'w')  # save 'new' colormap as a Python script
    if support.dogui is True:
        x.colormapgui()  # display the colormap GUI

    print '***************************************************************************************'
    print '******                                                                           ******'
    print '******   C O L O R M A P   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.º 32
0
def test():
    import vcs
    import cdms2 as cdms
    import os
    import support  # import vcs and cu
    bg = support.bg

    f = cdms.open(os.path.join(vcs.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
    # test object 'a' for graphics method
    if not vcs.isgraphicsmethod(a):
        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")

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

    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 '--extended' not 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)

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

    x.clear()  # clear the VCS Canvas
    # plot vector 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.vector(a, u, v, t, bg=bg)
    support.check_plot(x)

    l = x.getline('red')  # get line 'red'
    # check to see if it is a secondary object
    if not vcs.issecondaryobject(l):
        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.º 33
0
w = vtk.vtkRenderWindow()
i = vtk.vtkRenderWindowInteractor()
i.SetRenderWindow(w)
w.SetOffScreenRendering(True)
w.SetSize(200, 1000)

initial_font = "default"

font_set_to = [initial_font]


def set_font(f):
    font_set_to.append(f)

# Init vcs to get fonts loaded
x = vcs.init(backend=w)

# Create toolbar on the window for passing into the font editor
tb = vtk_ui.Toolbar(i, "Test")
# Create the font editor
fe = editors.font.FontEditor(tb, set_font, current_font=initial_font)

assert len(tb.widgets) > 0, "FontEditor not added to toolbar"
assert len(tb.widgets) == 1, "FontEditor added to wrong toolbar"
assert len(tb.bars) == 1, "FontEditor didn't set up toolbar correctly"

f_tb = tb.bars["Fonts"]
previous_buttons = []

for ind, button in enumerate(f_tb.widgets):
Ejemplo n.º 34
0
    def __init__(self,
                 canvas=None,
                 gui_parent=None,
                 dialog_parent=None,
                 master=None,
                 name='default',
                 Parent=None):
        self.gui_parent = gui_parent
        self.dialog_parent = dialog_parent
        self.master = master

        #        print 'PASSED INSIDE:',gui_parent
        if canvas is None:
            ##             import Canvas
            ##             self.canvas = Canvas.Canvas()
            self.canvas = vcs.init()
        else:
            self.canvas = canvas

        self.projection = self.canvas.getprojection(name)
        if self.projection is None:
            raise 'Erro invalid projection name'

        self.parent = Parent
        ## Saves original values
        self.orig = []
        self.save_vals()

        Proj_color = gui_support.gui_color.Proj_color

        #################################################################################################
        # At the moment, this will never happen. When we need to pop this editor up on its own, then we
        # will revist this case.
        ##         if self.gui_parent is None:
        ##             self.gui_parent=Tkinter.Toplevel()
        ##             #self.gui_parent=Tkinter.Tk(":0.0") # Use the localhost:0.0 for the DISPLAY and screen
        ##             self.gui_parent.withdraw()
        #################################################################################################

        title = 'Projection Editor - ' + self.projection.name
        self.dialog = Pmw.Dialog(
            master,
            title=title,
            buttons=(),
        )
        self.dialog.withdraw()

        if gui_support.root_exists():
            root = gui_support.root()
            self.top_parent = root
        else:
            root = gui_support.root()
            self.top_parent = None
        self.root = root
        parent = self.dialog.interior()
        parent.configure(bg=Proj_color)
        self.cmain_menu = Pmw.MenuBar(parent,
                                      hull_relief='raised',
                                      hull_borderwidth=2,
                                      balloon=gui_support.balloon)
        self.cmain_menu.pack(side='top', fill='both')

        self.cmain_menu.addmenu('File', 'Open/Save VCS Projections', tearoff=1)
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            'Open projection file',
            label='Open Projection File',
            command=self.evt_open_file,
        )

        self.cmain_menu.addmenuitem('File', 'separator')

        #
        # Create the cascade "Save Colormap" menu and its items
        ##         self.cmain_menu.addmenuitem('File', 'command', 'Select projection',
        ##                                     label = 'Select',
        ##                                     command = self.evt_loadproj,
        ##                                     )
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            'Save projection',
            label='Save (i.e Apply changes)',
            command=self.setprojection,
        )
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            'Copy projection',
            label='Copy Projection',
            command=self.evt_save_as,
        )
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            'Save as file',
            label='Save To File',
            command=self.evt_save_to_file,
        )

        # Create the cascade "Exit" menu
        self.cmain_menu.addmenuitem('File', 'separator')
        self.cmain_menu.addmenuitem(
            'File',
            'command',
            statusHelp='Close Projection Editor',
            label="Exit Projection Editor",
            command=self.dialog.destroy,
        )

        ##         self.ftype=Tkinter.Frame(parent)
        ##         self.ftype.pack(side='top')
        projs = self.canvas.listelements('projection')
        projs.sort()

        self.projections = Pmw.OptionMenu(
            parent,
            items=projs,
            labelpos='w',
            label_text='Name: ',
            command=self.loadproj,
            initialitem=self.projection.name,
            label_bg=Proj_color,
            hull_bg=Proj_color,
            menu_bg=Proj_color,
            menu_activebackground=Proj_color,
            menubutton_bg=Proj_color,
            menubutton_activebackground=Proj_color,
        )
        self.projections.pack()

        self.fprop = Pmw.Group(parent,
                               tag_text='Properties',
                               tagindent=10,
                               tag_bg=Proj_color,
                               ring_bg=Proj_color,
                               hull_bg=Proj_color)
        self.fprop.pack(expand='yes', fill='both')
        inter = self.fprop.interior()
        inter.configure(bg=Proj_color)
        self.fproperties = Tkinter.Frame(inter, bg=Proj_color)
        self.fbuttons = Tkinter.Frame(parent, bg=Proj_color)
        self.fbuttons.pack()

        self.projtypes = [
            "polar (non gctp)",
            "mollweide (non gctp)",
            "robinson (non gctp)",
            "linear",
            "utm",
            "state plane",
            "albers equal area",
            "lambert",
            "mercator",
            "polar stereographic",
            "polyconic",
            "equid conic",
            "transverse mercator",
            "stereographic",
            "lambert azimuthal",
            "azimuthal",
            "gnomonic",
            "orthographic",
            "gen. vert. near per",
            "sinusoidal",
            "equirectangular",
            "miller cylindrical",
            "van der grinten",
            "hotin oblique",
            "robinson",
            "space oblique",
            "alaska conformal",
            "interrupted goode",
            "mollweide",
            "interrupted mollweide",
            "hammer",
            "wagner iv",
            "wagner vii",
            "oblated equal area",
        ]

        self.projtype = Pmw.OptionMenu(
            inter,
            labelpos='w',
            label_text='Projection Type',
            label_bg=Proj_color,
            hull_bg=Proj_color,
            menu_bg=Proj_color,
            menu_activebackground=Proj_color,
            menubutton_bg=Proj_color,
            menubutton_activebackground=Proj_color,
            items=self.projtypes,
            command=self.settype,
        )
        self.projtype.pack()
        b1 = Tkinter.Button(self.fbuttons, text='Cancel', command=self.cancel)
        b1.pack(side='left')
        b2 = Tkinter.Button(self.fbuttons, text='Apply', command=self.exit)
        b2.pack(side='left')
        b3 = Tkinter.Button(self.fbuttons, text='Revert', command=self.reset)
        b3.pack(side='left')

        self.setgui()

        # Position dialog popup
        if dialog_parent is not None:
            parent_geom = dialog_parent.geometry()
            geom = string.split(parent_geom, '+')
            d1 = string.atoi(geom[1])
            d2 = string.atoi(geom[2])
            self.dialog.activate(geometry="+%d+%d" % (d1, d2))
        else:
            self.dialog.activate(geometry='centerscreenalways')

        return
Ejemplo n.º 35
0
import cdms2
import os
import sys
import vcs

# Load the clt data:
dataFile = cdms2.open(os.path.join(vcs.prefix, "sample_data/clt.nc"))
clt = dataFile("clt")
clt = clt(latitude=(-90.0, 90.0), longitude=(-180., 175.), squeeze=1,
          time=('1979-1-1 0:0:0.0', '1988-12-1 0:0:0.0'))

# Initialize canvas:
canvas = vcs.init()
canvas.setbgoutputdimensions(1200,1091,units="pixels")
canvas.drawlogooff()

# Create and plot quick boxfill with default settings:
boxfill=canvas.createboxfill()

# Change the type
boxfill.boxfill_type = 'custom'

canvas.plot(clt, boxfill, bg=1)

# Load the image testing module:
testingDir = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(testingDir)
import checkimage

# Create the test image and compare:
baseline = sys.argv[1]
Ejemplo n.º 36
0
    def test_portrait(self):

        # CDAT MODULES
        import pcmdi_metrics.graphics.portraits
        import MV2
        import numpy
        import genutil
        import vcs

        print
        print
        print
        print
        print "---------------------------------------------------"
        print "RUNNING: Portrait test"
        print "---------------------------------------------------"
        print
        print
        print
        print
        # CREATES VCS OBJECT AS A PORTAIT PLOT AND LOADS PLOT SETTINGS FOR
        # EXAMPLE
        x = vcs.init(geometry=(814, 606), bg=bg)
        x.portrait()
        # Turn off antialiasing for test suite
        x.setantialiasing(0)

        # PARAMETERS STUFF
        P = pcmdi_metrics.graphics.portraits.Portrait()

        # Turn off verbosity
        P.verbose = False

        P.PLOT_SETTINGS.levels = [
            -1.e20, -.5, -.4, -.3, -.2, -.1, 0., .1, .2, .3, .4, .5, 1.e20
        ]

        P.PLOT_SETTINGS.x1 = .1
        P.PLOT_SETTINGS.x2 = .85
        P.PLOT_SETTINGS.y1 = .12
        P.PLOT_SETTINGS.y2 = .95

        P.PLOT_SETTINGS.xtic2.y1 = P.PLOT_SETTINGS.y1
        P.PLOT_SETTINGS.xtic2.y2 = P.PLOT_SETTINGS.y2
        P.PLOT_SETTINGS.ytic2.x1 = P.PLOT_SETTINGS.x1
        P.PLOT_SETTINGS.ytic2.x2 = P.PLOT_SETTINGS.x2

        # P.PLOT_SETTINGS.missing_color = 3
        P.PLOT_SETTINGS.logo = os.path.join(sys.prefix, "share", "pmp",
                                            "graphics", "png",
                                            "160915_PCMDI_logo_348x300px.png")
        P.PLOT_SETTINGS.logo.y = .95
        P.PLOT_SETTINGS.logo.x = .93
        P.PLOT_SETTINGS.time_stamp = None
        P.PLOT_SETTINGS.draw_mesh = 'n'
        # P.PLOT_SETTINGS.tictable.font = 3

        x.scriptrun(
            os.path.join(sys.prefix, "share", "pmp", "graphics", 'vcs',
                         'portraits.scr'))
        P.PLOT_SETTINGS.colormap = 'bl_rd_12'
        # cols=vcs.getcolors(P.PLOT_SETTINGS.levels,range(16,40),split=1)
        cols = vcs.getcolors(P.PLOT_SETTINGS.levels, range(144, 156), split=1)
        P.PLOT_SETTINGS.fillareacolors = cols

        P.PLOT_SETTINGS.parametertable.expansion = 100

        J = self.loadJSON()

        mods = sorted(J.getAxis("model")[:])
        variables = sorted(J.getAxis("variable")[:])
        print "MODELS:", len(mods), mods
        print "VARS:", len(variables), variables
        # Get what we need
        out1_rel = J(statistic=["rms_xyt"], season=["ann"],
                     region="global")(squeeze=1)

        out1_rel, med = genutil.grower(
            out1_rel,
            genutil.statistics.median(out1_rel, axis=1)[0])

        out1_rel[:] = (out1_rel.asma() - med.asma()) / med.asma()

        # ADD SPACES FOR LABELS TO ALIGN AXIS LABELS WITH PLOT
        modsAxis = mods
        variablesAxis = variables

        # LOOP THROUGH LISTS TO ADD SPACES
        for i in range(len(modsAxis)):
            modsAxis[i] = modsAxis[i] + '  '
        for i in range(len(variablesAxis)):
            variablesAxis[i] = variablesAxis[i] + '  '

        yax = [s.encode('utf-8')
               for s in mods]  # CHANGE FROM UNICODE TO BYTE STRINGS

        # GENERATE PLOT
        P.decorate(out1_rel, variables, yax)
        # P.plot(out1_rel,x=x,multiple=1.1,bg=bg)  # FOR PLOTTING TRIANGLES WHEN
        # USING TWO OR MORE REFERENCE DATA SETS
        P.plot(out1_rel, bg=bg, x=x)
        if not bg:
            raw_input("Press enter")
        # x.backend.renWin.Render()

        # END OF PLOTTING

        # SAVE PLOT
        src = os.path.join(os.path.dirname(__file__), "testPortrait.png")
        print src
        fnm = os.path.join(os.getcwd(), "testPortrait.png")
        x.png(fnm)
        ret = vcs.testing.regression.check_result_image(fnm, src)
        if ret != 0:
            sys.exit(ret)
Ejemplo n.º 37
0
def plot(reference, test, diff, metrics_dict, parameter):
    vcs_canvas = vcs.init(bg=True,
                          geometry=(parameter.canvas_size_w,
                                    parameter.canvas_size_h))
    parameter.case_id

    file_path = os.path.join(acme_diags.INSTALL_PATH, 'lat_lon')
    vcs_canvas.scriptrun(os.path.join(file_path, 'plot_set_5.json'))
    vcs_canvas.scriptrun(os.path.join(file_path, 'plot_set_5_new.json'))

    template_test = vcs_canvas.gettemplate('plotset5_0_x_0')
    template_ref = vcs_canvas.gettemplate('plotset5_0_x_1')
    template_diff = vcs_canvas.gettemplate('plotset5_0_x_2')

    utils.set_units(test, parameter.test_units)
    utils.set_units(reference, parameter.reference_units)
    utils.set_units(diff, parameter.diff_units)

    test.long_name = parameter.test_title
    reference.long_name = parameter.reference_title
    diff.long_name = parameter.diff_title

    test.id = parameter.test_name_yrs
    reference.id = parameter.reference_name
    diff.id = parameter.diff_name

    # model and observation graph
    utils.plot_min_max_mean(textcombined_objs, vcs_canvas, metrics_dict,
                            'test')
    utils.plot_min_max_mean(textcombined_objs, vcs_canvas, metrics_dict, 'ref')
    utils.plot_min_max_mean(textcombined_objs, vcs_canvas, metrics_dict,
                            'diff')

    reference_isofill = vcs.getisofill('reference_isofill')
    reference_isofill.missing = 'grey'
    reference_isofill.yticlabels1 = {
        -90: "90$^\circ$S",
        -60: "60$^\circ$S",
        -30: "30$^\circ$S",
        0: "0$^\circ$",
        30: "30$^\circ$N",
        60: "60$^\circ$N",
        90: "90$^\circ$N"
    }
    test_isofill = vcs.getisofill('test_isofill')
    test_isofill.missing = 'grey'
    test_isofill.yticlabels1 = {
        -90: "90$^\circ$S",
        -60: "60$^\circ$S",
        -30: "30$^\circ$S",
        0: "0$^\circ$",
        30: "30$^\circ$N",
        60: "60$^\circ$N",
        90: "90$^\circ$N"
    }
    diff_isofill = vcs.getisofill('diff_isofill')
    diff_isofill.missing = 'grey'
    diff_isofill.yticlabels1 = {
        -90: "90$^\circ$S",
        -60: "60$^\circ$S",
        -30: "30$^\circ$S",
        0: "0$^\circ$",
        30: "30$^\circ$N",
        60: "60$^\circ$N",
        90: "90$^\circ$N"
    }

    utils.set_levels_of_graphics_method(reference_isofill,
                                        parameter.contour_levels, reference,
                                        test)
    utils.set_levels_of_graphics_method(test_isofill, parameter.contour_levels,
                                        test, reference)
    utils.set_levels_of_graphics_method(diff_isofill, parameter.diff_levels,
                                        diff)

    if parameter.arrows:
        reference_isofill.ext_1 = True
        reference_isofill.ext_2 = True
        test_isofill.ext_1 = True
        test_isofill.ext_2 = True
        diff_isofill.ext_1 = True
        diff_isofill.ext_2 = True

    utils.set_colormap_of_graphics_method(vcs_canvas,
                                          parameter.reference_colormap,
                                          reference_isofill, parameter)
    utils.set_colormap_of_graphics_method(vcs_canvas, parameter.test_colormap,
                                          test_isofill, parameter)
    utils.set_colormap_of_graphics_method(vcs_canvas, parameter.diff_colormap,
                                          diff_isofill, parameter)

    vcs_canvas.plot(utils.add_cyclic(test), template_test, test_isofill)
    vcs_canvas.plot(utils.add_cyclic(reference), template_ref,
                    reference_isofill)
    vcs_canvas.plot(utils.add_cyclic(diff), template_diff, diff_isofill)

    utils.plot_rmse_and_corr(textcombined_objs, vcs_canvas, metrics_dict)
    # for some reason, this needs to be before a call to vcs_canvas.plot()
    vcs_canvas.portrait()

    # Plotting the main title
    main_title = utils.managetextcombined(textcombined_objs, 'main_title',
                                          'main_title', vcs_canvas)
    main_title.string = parameter.main_title
    vcs_canvas.plot(main_title)

    if not parameter.logo:
        vcs_canvas.drawlogooff()

    fnm = os.path.join(get_output_dir(parameter.current_set, parameter),
                       parameter.output_file)
    for f in parameter.output_format:
        f = f.lower().split('.')[-1]
        if f == 'png':
            vcs_canvas.png(fnm)
        elif f == 'pdf':
            vcs_canvas.pdf(fnm)
        elif f == 'svg':
            vcs_canvas.svg(fnm)
        # Get the filename that the user has passed in and display that.
        # When running in a container, the paths are modified.
        fnm = os.path.join(
            get_output_dir(parameter.current_set,
                           parameter,
                           ignore_container=True), parameter.output_file)
        print('Plot saved in: ' + fnm + '.' + f)
    vcs_canvas.clear()
Ejemplo n.º 38
0
# Legend's bg
    if legend_bg_color is not None:
        bg_boxes = canvas.createfillarea("bg")
        bg_boxes.x = [t.legend.x1, t.legend.x1, t.legend.x2, t.legend.x2]
        bg_boxes.y = [t.legend.y1, t.legend.y2, t.legend.y2, t.legend.y1]
        bg_boxes.color = [legend_bg_color]
        canvas.plot(bg_boxes)

    plot_args = [data, data2, t, gm]
    kwargs = {"continents": continents}

    return canvas.plot(*[p for p in plot_args if p is not None], **kwargs)

if __name__ == "__main__":
    # The blue marble file I found has an aspect ratio of 2x1, so we'll use that aspect for the canvas
    canvas = vcs.init(size=2)

    # Open file
    odir = '/cmip5_css02/data/cmip5/output1/NIMR-KMA/HadGEM2-AO/historical/mon/atmos/Amon/r1i1p1/huss/1/'  # Put your local directory here
    nc = 'huss_Amon_HadGEM2-AO_historical_r1i1p1_186001-200512.nc'
    f = cdms.open(odir + nc)

    # Load variable
    d = f('huss',
          longitude=(-180, 180))  # Set longitude range to Blue Marble image
    d = MV2.multiply(d, 1000.)
    d.id = 'huss'
    d.units = '%'

    # Set isofill level
    isofill = vcs.createisofill()
Ejemplo n.º 39
0
import string, numpy, time, MV2, sys, os
from regrid2 import Regridder

# Open data file
file1 = os.path.join(vcs.sample_data, 'hadcrut2_sample.nc')
a = cdms2.open(file1)
print a.listvariable()

# get the start and end time steps
start_time = a.getAxis('time').asComponentTime()[0]
end_time = a.getAxis('time').asComponentTime()[-1]
# get the data
data = a('temanom', time=(start_time, end_time), latitude=(-90, 90))
print data.shape

x = vcs.init()
x.setcolormap('default')
x.plot(data)

# get grid for regridding
grid1 = data.getGrid()
# see how it looks like
print grid1.info()

# get "spatial missing mask"
mask1 = data.mask
# get metadata for final desired data (e.g. latitudes,longitudes,time)
lat = data.getLatitude()
lon = data.getLongitude()
tim = data.getTime()
# close the file
Ejemplo n.º 40
0
# EOF (take only first variance mode...) ---
solver = Eof(d_DJF, weights='area')
eof = solver.eofsAsCovariance(neofs=1)
pc = solver.pcs(npcs=1, pcscaling=1)  # pcscaling=1: scaled to unit variance
# (divided by the square-root of their eigenvalue)
frac = solver.varianceFraction()

# Sign control if needed ---
eof = eof * -1
pc = pc * -1

#===========================================================================================================
# Plot
#-----------------------------------------------------------------------------------------------------------
# Create canvas ---
canvas = vcs.init(geometry=(900, 800))

canvas.open()
template = canvas.createtemplate()

# Turn off no-needed information -- prevent overlap
template.blank([
    'title', 'mean', 'min', 'max', 'dataname', 'crdate', 'crtime', 'units',
    'zvalue', 'tvalue', 'xunits', 'yunits', 'xname', 'yname'
])

# Color setup ---
canvas.setcolormap('bl_to_darkred')
iso = canvas.createisofill()
iso.levels = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
iso.ext_1 = 'y'  # control colorbar edge (arrow extention on/off)
import sys, os
import vcs
import sys
import cdms2
import vtk
import os
import MV2
bg = not False
x = vcs.init()

x.setcolormap("rainbow")

gm = vcs.create1d()

xtra = {}
f = cdms2.open(os.path.join(vcs.prefix, 'sample_data', 'clt.nc'))
s = f("clt", **xtra)
s = MV2.masked_greater(s, 78.)
s = s(latitude=(20, 20, "cob"), longitude=(112, 112, "cob"), squeeze=1)
s2 = MV2.sin(s)
x.plot(s, gm, bg=bg)

x.png('test_vcs_basic_oned_masked.png')
Ejemplo n.º 42
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
    s = f('clt')  # get slab clt
    x = vcs.init()  # construct vcs canvas

    x.plot(s, 'default', 'isoline', 'quick',
           bg=support.bg)  # plot slab the old way
    support.check_plot(x)
    if bg == 0:
        x.geometry(450, 337, 0, 0)  # change geometry and location
        support.check_plot(x)
        x.geometry(900, 675, 10, 0)  # change geometry and location
        support.check_plot(x)
        x.flush()
        support.check_plot(x)

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

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

    a.xticlabels('lon30', 'lon30')  # change the x-axis
    support.check_plot(x)
    a.xticlabels('', '')  # remove the x-axis
    support.check_plot(x)
    a.xticlabels('*')  # put the x-axis back
    support.check_plot(x)
    a.datawc(-45.0, 45.0, -90.0, 90.0)  # change the region
    support.check_plot(x)
    a.datawc(1e20, 1e20, 1e20, 1e20)  # put the region back
    support.check_plot(x)

    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()

    #########################################################################
    # Set the isoline level vales	     				   #
    #########################################################################
    a.level = ([20, 0.0], [30, 0], [50, 0], [60,
                                             0])  # change the isoline values
    support.check_plot(x)
    a.level = [[20, 0.0], [30, 0], [50, 0]]  # change the isoline values
    support.check_plot(x)
    a.level = ((20, 0.0), (30, 0), (50, 0), (60, 0), (70, 0)
               )  # change the isoline values
    support.check_plot(x)
    a.level = (25, 35, 45, 55)  # change the isoline values
    support.check_plot(x)
    a.level = [(22, 33, 44, 55, 66)]  # change the isoline values
    support.check_plot(x)
    a.level = [
        (23, 32, 45, 50, 76),
    ]  # change the isoline values
    support.check_plot(x)
    a.level = [0]  # same as a.level=(0,)
    support.check_plot(x)
    a.level = [[0, 1e20]]  # same as a.level=((0,1e20),), use default settings
    support.check_plot(x)

    #########################################################################
    # Turn on and off the isoline level labels  				   #
    #########################################################################
    a.label = 'y'  # same as a.label=1
    support.check_plot(x)
    a.label = 'n'  # same as a.label=0
    support.check_plot(x)

    #########################################################################
    # Set the line style and line color        		 		   #
    #########################################################################
    a.level = ((20, 0.0), (30, 0), (50, 0), (60, 0), (70, 0)
               )  # change the isoline values
    support.check_plot(x)
    a.line = [1, 3, 0, 4]  # same as a.line=(1,3,0,4)
    support.check_plot(x)
    a.line = (['dash', 'long-dash', 'solid'])  # same as a.line=([2,4,0])
    support.check_plot(x)
    a.line = [2, 4, 1, 3, 2, 0]
    support.check_plot(x)
    a.linecolors = ([22, 33, 44, 55, 66, 77])  # change the line color
    support.check_plot(x)
    a.linecolors = (16, 19, 33, 44)  # change the line color
    support.check_plot(x)
    a.linecolors = None  # use the default line color
    support.check_plot(x)
    a.line = None  # use the default line style, which is solid
    support.check_plot(x)

    #########################################################################
    # Set the text font and text color         		 		   #
    #########################################################################
    a.label = 'y'  # same as a.label=1
    support.check_plot(x)
    a.text = (1, 2, 3, 4, 5, 6, 7, 8, 9)  # select fonts from 1 through 9
    support.check_plot(x)
    a.text = [9, 8, 7, 6, 5, 4, 3, 2, 1]
    support.check_plot(x)
    a.text = ([1, 3, 5, 6, 9, 2])
    support.check_plot(x)
    a.textcolors = ([22, 33, 44, 55, 66, 77])  # set the text color
    support.check_plot(x)
    a.textcolors = (16, 19, 33, 44)
    support.check_plot(x)
    a.textcolors = None  # use default text color, black
    support.check_plot(x)
    a.text = None  # use default font, 1
    support.check_plot(x)

    #########################################################################
    # Create template 'test' from the default template			   #
    #########################################################################
    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"

    #########################################################################
    # Create line object 'l' from the default line    			   #
    #########################################################################
    l = x.createline('test')
    objs = x.listelements('line')  # show the list of line secondary objects
    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"

    x.clear()  # clear the VCS Canvas
    x.isoline(
        s, a, t,
        bg=support.bg)  # plot the array using the template and isoline object
    support.check_plot(x)
    x.clear()  # clear the VCS Canvas
    x.plot(t, a, s, bg=support.bg)  # plot again using the new way
    support.check_plot(x)

    #########################################################################
    # Use the create line object 'l' from above and modify the line object  #
    #########################################################################
    a.line = [1, 3, 0, 4]  # same as a.line=(1,3,0,4)
    support.check_plot(x)
    a.line = ([2, 4, 0])  # same as a.line=(['dash', 'long-dash', 'solid'])
    support.check_plot(x)
    a.line = (l, 4, l, 0)  # use the line object
    support.check_plot(x)
    a.line = (l, 3, 4, 2, 0)
    support.check_plot(x)
    l.color = 44  # change the line color
    support.check_plot(x)
    l.type = 'dash'  # change the line type
    support.check_plot(x)

    #########################################################################
    # Create the three types of text objects                                #
    #########################################################################
    tc = x.createtextcombined('testc', 'std', 'testc', '7left')
    if not vcs.istextcombined(tc):
        raise Exception, "Error not textcombined!"

    tt = x.createtexttable('testt', 'default')
    if not vcs.istexttable(tt):
        raise Exception, "Error not texttable"

    to = x.createtextorientation('testo')
    if not vcs.istextorientation(to):
        raise Exception, "Error not textorientation"

    #########################################################################
    # Use the text objects in the isoline plot                              #
    #########################################################################
    a.label = 'y'  # make sure that the labels are turn on
    support.check_plot(x)
    a.text = ([1, 3, 5, 6, 9, 2])  # set the font
    support.check_plot(x)
    a.text = ([tc, tt, to, 6, 9, 2])  # use the created text objects and fonts
    support.check_plot(x)

    #########################################################################
    # Change the text object values                                         #
    #########################################################################
    tc.font = 3  # changing isoline level 20
    support.check_plot(x)
    tc.height = 15
    support.check_plot(x)
    tc.angle = 180
    support.check_plot(x)
    tc.color = 242
    support.check_plot(x)
    tt.font = 2  # changing isoline level 30
    support.check_plot(x)
    tt.spacing = 20
    support.check_plot(x)
    to.height = 15  # changing isoline level 50
    support.check_plot(x)
    to.path = 'down'
    support.check_plot(x)

    a.text = None  # use default font, which is font 1
    support.check_plot(x)
    a.line = None  # use default line, which is solid
    support.check_plot(x)

    a = x.listelements('isoline')  # show list of gm
    r = x.createisoline('test2', 'quick')  # create xyvsy 'test2'
    a2 = x.listelements('isoline')  # 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('isoline')  # show list of gm
    if a3 != a:
        raise "error gm not removed"

    #################################################################################
    # to see how x.update and x.mode work, see testisoline.py                       #
    #################################################################################
    #x.update()
    #x.mode=1
    #x.mode=0
    print '*************************************************************************************'
    print '******                                                                         ******'
    print '******   I S O L I N E   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 '*************************************************************************************'