def initVCS(x,levs1,levs2,split): x.setcolormap("bl_to_darkred") iso1 = x.createisofill() #iso = x.createboxfill() #iso.boxfill_type="custom" iso1.levels = levs1 iso1.ext_1 = True iso1.ext_2 = True cols = vcs.getcolors(iso1.levels,split=split) iso1.fillareacolors = cols iso2 = x.createisofill() levs = levs2 iso2.levels = levs iso2.ext_1 = True iso2.ext_2 = True cols = vcs.getcolors(iso2.levels,split=1) iso2.fillareacolors = cols leg = x.createtextorientation() leg.halign = "left" leg.height = 8 tmpl = x.createtemplate() tmpl.blank() tmpl.scalefont(.9) oldOrientation = tmpl.legend.textorientation tmpl.legend.textorientation = leg for a in ["data","legend","box1","xlabel1","xtic1","ylabel1","ytic1"]: setattr(getattr(tmpl,a),"priority",1) Ez = EzTemplate.Multi(rows=3,columns=1,x=x,template=tmpl) Ez.legend.direction ='vertical' Ez.margins.left =.05 Ez.margins.right =.05 Ez.margins.top =.05 Ez.margins.bottom =.05 title = x.createtext() title.height = 14 title.halign = "center" title.x = [.5] title.y = [.975] t1 = Ez.get(legend="local") t2 = Ez.get(legend="local") t3 = Ez.get(legend="local") del(Ez) ; # Purge EzTemplate object vcs.removeobject(vcs.elements['textorientation'][oldOrientation]) return iso1,iso2,title,t1,t2,t3,tmpl
def _updateContourLevelsAndColorsForCustomBoxfill(self): """Set contour information for a custom boxfill.""" self._contourLevels = self._gm.levels if numpy.allclose(self._contourLevels[0], [0., 1.e20]) or \ numpy.allclose(self._contourLevels, 1.e20): levs2 = vcs.mkscale(self._scalarRange[0], self._scalarRange[1]) if len(levs2) == 1: # constant value ? levs2 = [levs2[0], levs2[0] + .00001] self._contourLevels = [] if self._gm.ext_1: ## user wants arrow at the end levs2[0] = -1.e20 if self._gm.ext_2: ## user wants arrow at the end levs2[-1] = 1.e20 for i in range(len(levs2) - 1): self._contourLevels.append([levs2[i], levs2[i+1]]) else: if not isinstance(self._gm.levels[0], (list, tuple)): self._contourLevels = [] levs2 = self._gm.levels if numpy.allclose(levs2[0], 1.e20): levs2[0] = 0 for i in range(len(levs2) - 1): self._contourLevels.append([levs2[i], levs2[i+1]]) # Contour colors: self._contourColors = self._gm.fillareacolors if self._contourColors is None: # TODO BUG levs2 may not be defined here... self._contourColors = vcs.getcolors(levs2, split=0)
def vcs_colors(self): """Used internally, don't worry about it.""" levs = self.levels if self._gm.fillareacolors: colors = self._gm.fillareacolors return colors else: real_levs = levs if self.ext_left: levs = levs[1:] if self.ext_right: levs = levs[:-1] colors = vcs.getcolors(levs, colors=range(self.color_1, self.color_2)) levs = real_levs if len(colors) < len(levs): # Pad out colors to the right number of buckets diff = len(levs) - len(colors) colors += diff * colors[-1:] return sorted(colors)
def _updateContourLevelsAndColorsGeneric(self): # Contour values: self._contourLevels = self._gm.levels if numpy.allclose(self._contourLevels[0], [0., 1.e20]) or \ numpy.allclose(self._contourLevels, 1.e20): levs2 = vcs.mkscale(self._scalarRange[0], self._scalarRange[1]) if len(levs2) == 1: # constant value ? levs2 = [levs2[0], levs2[0] + .00001] self._contourLevels = [] if self._gm.ext_1: # user wants arrow at the end levs2[0] = -1.e20 if self._gm.ext_2: # user wants arrow at the end levs2[-1] = 1.e20 for i in range(len(levs2) - 1): self._contourLevels.append([levs2[i], levs2[i + 1]]) else: if not isinstance(self._gm.levels[0], (list, tuple)): self._contourLevels = [] levs2 = self._gm.levels if numpy.allclose(levs2[0], 1.e20): levs2[0] = -1.e20 for i in range(len(levs2) - 1): self._contourLevels.append([levs2[i], levs2[i + 1]]) else: levs2 = self._gm.levels if isinstance(self._contourLevels, numpy.ndarray): self._contourLevels = self._contourLevels.tolist() # Figure out colors self._contourColors = self._gm.fillareacolors if self._contourColors == [1] or self._contourColors is None: # TODO BUG It's possible that levs2 may not exist here... self._contourColors = vcs.getcolors(levs2, split=0) if isinstance(self._contourColors, (int, float)): self._contourColors = [self._contourColors]
def _updateContourLevelsAndColors(self): """Overrides baseclass implementation.""" # Contour values: self._contourLevels = self._gm.levels if numpy.allclose(self._contourLevels[0], [0., 1.e20]) or \ numpy.allclose(self._contourLevels, 1.e20): levs2 = vcs.mkscale(self._scalarRange[0], self._scalarRange[1]) if len(levs2) == 1: # constant value ? levs2 = [levs2[0], levs2[0] + .00001] self._contourLevels = [] if self._gm.ext_1: # user wants arrow at the end levs2[0] = -1.e20 if self._gm.ext_2: # user wants arrow at the end levs2[-1] = 1.e20 for i in range(len(levs2) - 1): self._contourLevels.append([levs2[i], levs2[i+1]]) else: if not isinstance(self._contourLevels[0], (list, tuple)): self._contourLevels = [] levs2 = self._gm.levels if numpy.allclose(levs2[0], 1.e20): levs2[0] = -1.e20 for i in range(len(levs2) - 1): self._contourLevels.append([levs2[i], levs2[i+1]]) # Contour colors: self._contourColors = self._gm.fillareacolors if self._contourColors == [1]: # TODO BUG levs2 may be uninitialized here self._contourColors = vcs.getcolors(levs2, split=0) if isinstance(self._contourColors, (int, float)): self._contourColors = [self._contourColors] if isinstance(self._contourLevels, numpy.ndarray): self._contourLevels = self._contourLevels.tolist()
def histogram(canvas, values, xaxis=None, yaxis=None): fa = canvas.createfillarea() t = canvas.gettemplate("default") fa.viewport = [t.data.x1, t.data.x2, t.data.y1, t.data.y2] num_fills = len(values) fa.color = vcs.getcolors(range(num_fills)) x, y = [], [] for i in range(num_fills): point1, point2 = i / float(num_fills), (i + 1) / float(num_fills) xl = [point1, point1, point2, point2] yl = [0, values[i], values[i], 0] x.append(xl) y.append(yl) fa.x = x fa.y = y outline = vcs.createline(source="default") outline.viewport = fa.viewport outline.x = x outline.y = y canvas.plot(fa) canvas.plot(outline)
def main(): # User options --- #exp = 'cmip5' #exp = 'cmip6' exp = 'cmip5+6' #stat = 'rmse' stat = 'stdv_ratio' SideBySide = True # ---------------- if stat == 'rmse': Normalize = True plotTitle = 'RMS using CBF approach with 20CR' elif stat == 'stdv_ratio': Normalize = False plotTitle = 'Ratio of Model CBF and Obs PC std with 20CR' # ---------------- imgName = 'PortraitPlot_' + exp + '_' + stat # ---------------- if exp in ['cmip5', 'cmip6']: stat_xy = getData(exp, stat) stat_xy.id = stat elif exp in ['cmip5+6']: stat_xy_0 = getData('cmip5', stat) stat_xy_1 = getData('cmip6', stat) if SideBySide: # CMIP5 and CMIP6 side by side if from same model family # Merge x-axis model_run_cmip5 = list(stat_xy_0.getAxis(1)[:]) model_run_cmip6 = list(stat_xy_1.getAxis(1)[:]) model_run_all = model_run_cmip5 + model_run_cmip6 model_run_all = sort_human(model_run_all) model_run_selected = [] for c, model_run in enumerate(model_run_all): model_header = ''.join([ i for i in model_run.split('_')[0].split('-')[0] if not i.isdigit() ]) #print(model_header) if model_run in model_run_cmip5 and any( model_header in s for s in model_run_cmip6): idx = model_run_cmip5.index(model_run) try: empty_array = np.concatenate( (empty_array, stat_xy_0[:, idx])) except: empty_array = stat_xy_0[:, idx].copy() model_run_selected.append(model_run) elif model_run in model_run_cmip6: idx = model_run_cmip6.index(model_run) try: empty_array = np.concatenate( (empty_array, stat_xy_1[:, idx])) except: empty_array = stat_xy_1[:, idx].copy() model_run_selected.append('* ' + model_run) #xaxis_label = model_run_all xaxis_label = model_run_selected #imgName = imgName+'_SideBySide' imgName = imgName + '_SideBySide_selected' stat_xy = np.transpose( np.reshape(empty_array, (len(xaxis_label), len(stat_xy_0.getAxis(0))))) print(stat_xy.shape) print(len(xaxis_label)) else: # Add empty column for clear separation btw cmip 5 and 6 empty_col = np.empty((len(stat_xy_0.getAxis(0)), 3)) empty_col[:] = np.nan stat_xy = np.concatenate((stat_xy_0, empty_col, stat_xy_1), axis=1) # Customize x-axis label xaxis_label = ( ['[CMIP5] ' + stat_xy_0.getAxis(1)[0]] # cmip5, 1st model + [r for r in list(stat_xy_0.getAxis(1)[1:])] # cmip5, rest + [' '] * 3 # separation + ['[CMIP6] ' + stat_xy_1.getAxis(1)[0]] + [r for r in list(stat_xy_1.getAxis(1)[1:])]) # Decorate axes X = cdms2.createAxis(xaxis_label) Y = cdms2.createAxis(stat_xy_0.getAxis(0)[:]) stat_xy = MV2.array(stat_xy, axes=(Y, X), id=stat) else: sys.exit('Error: exp ' + exp + ' not defined') # Normalize rows by its median if Normalize: # Normalize by median value stat_xy = normalize_by_median(stat_xy) # Revise image file name imgName = imgName + '_normalized' # Colormap to be used if stat == 'rmse': colormap = "bl_to_darkred" clevels = [ -1.e20, -.5, -.4, -.3, -.2, -.1, 0, .1, .2, .3, .4, .5, 1.e20 ] ccolors = vcs.getcolors(clevels, split=0, colors=range(16, 240)) elif stat == 'stdv_ratio': colormap = "bl_to_darkred" clevels = [r / 10. for r in list(range(5, 16, 1))] clevels.insert(0, -1.e20) clevels.append(1.e20) ccolors = vcs.getcolors(clevels, split=0, colors=range(16, 240)) ccolors[4:8] = ['lightgreen', 'green', 'green', 'darkgreen'] # # Portrait plot # plot_portrait( stat_xy, imgName, plotTitle=plotTitle, colormap=colormap, clevels=clevels, ccolors=ccolors, parea=(.05, .88, .25, .9), img_length=2600, img_height=800, xtic_textsize=10, ytic_textsize=10, missing_color='grey', logo=False, )
# 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))*1000. # Set longitude range to Blue Marble image d.units='%' # Set isofill level isofill = vcs.createisofill() isofill.levels = [6,8,10,12,14,16,18,20,22,24,26] colors = vcs.getcolors(isofill.levels) for i in range(0,len(colors)): colors[i]='white' isofill.fillareacolors = colors isofill.fillareaopacity = range(10,100,100/len(colors)) # Option for getting background image Blue_marble_download = True #Blue_marble_download = False Nighttimeimage = True #Nighttimeimage = False if Blue_marble_download: # Download background image for map; http://visibleearth.nasa.gov/ bg_image_link = 'http://eoimages.gsfc.nasa.gov/images/imagerecords/74000/74393/world.topo.200407.3x5400x2700.png'
pr = f("precip_trend") x = vcs.init() vcs.scriptrun(ViridisScript) colormapname = "bl_to_darkred" # colormapname = "viridis" x.setcolormap(colormapname) iso = x.createisofill() number_different_colors = 64 levels = numpy.arange(-1., 1.00001, 2. / float(number_different_colors + 1)).tolist() iso.levels = levels cols = vcs.getcolors(levels, split=0) iso.fillareacolors = cols iso.legend = vcs.mklabels(numpy.arange(-1, 1.01, .125)) # Now create a template to move things around a bit t = x.createtemplate() t.xmintic1.priority = 1 # turn on bottom sub ticks t.xmintic2.priority = 1 # turn on top sub ticks t.ymintic1.priority = 1 # turn on left sub ticks t.ymintic2.priority = 1 # turn on right sub ticks t.scale(.9, "x") t.scale(1.8, "y") t.moveto(.05, .1) # Move legend
# 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' levels = range(20,81,10) boxfill.levels=levels boxfill.ext_1="y" boxfill.ext_2="y" boxfill.fillareacolors=vcs.getcolors(boxfill.levels) 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] testFile = "test_boxfill_custom_ext1_ext2.png" canvas.png(testFile) ret = checkimage.check_result_image(testFile, baseline, checkimage.defaultThreshold) sys.exit(ret)
def test_portrait(self): 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 self.x.portrait() # 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", "PCMDILogo-old_348x300px_72dpi.png") P.PLOT_SETTINGS.logo.y = .95 P.PLOT_SETTINGS.logo.x = .93 P.PLOT_SETTINGS.logo.width = 85 P.PLOT_SETTINGS.time_stamp = None P.PLOT_SETTINGS.draw_mesh = 'n' # P.PLOT_SETTINGS.tictable.font = 3 self.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) # USING TWO OR MORE REFERENCE DATA SETS P.plot(out1_rel, x=self.x) fnm = os.path.join(os.getcwd(), "testPortrait.png") self.checkImage(fnm)
sys.path.append(pth) f=cdms2.open(os.path.join(vcs.sample_data,"clt.nc")) s=f("clt",slice(0,12)) # read only 12 times steps to speed up things x=vcs.init() x.setantialiasing(0) x.drawlogooff() x.setbgoutputdimensions(1200,1091,units="pixels") iso=x.createisoline() iso.label='y' levs = range(0,101,10) iso.level=levs # add dummy values to levs to get the correct number of cols cols=vcs.getcolors(levs+[56,]) print levs print cols iso.textcolors = cols iso.linecolors = cols x.plot(s,iso,bg=1) x.animate.create() print "Saving now" prefix= os.path.split(__file__)[1][:-3] x.animate.save("%s.mp4"%prefix) pngs = x.animate.close(preserve_pngs = True) # so we can look at them again src_pth = sys.argv[1] pth = os.path.join(src_pth,prefix) ret = 0 for p in pngs: print "Checking:",p
## Create a new template and scale it t=x.createtemplate('new') t.scale(.56,axis='x',font=1) ## Create isofill graphic method iso=x.createisofill('new') ## Create vector graphic method vc=y.createvector('new') vc=x.createvector('vector') ## Adjust levels and colors levs=[-1.E20,-15,-12,-10,-8,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,8,10,12,15,1.e20] cols=vcs.getcolors(levs,colors=range(50,240),split=1) iso.levels=levs iso.fillareacolors=cols vc.linecolor=3 ## Create a new projection of type orthographic p=x.createprojection('new') p.type='orthographic' p.centerlatitude=60 ## Assign it to isfill and vector graphic methods iso.projection=p vc.projection=p ## Documentation for projection print p.__doc__
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' levels = range(20, 81, 10) boxfill.levels = levels boxfill.ext_1 = "y" levels = range(20, 81, 5) boxfill.fillareacolors = vcs.getcolors(levels) try: canvas.plot(clt, boxfill, bg=1) failed = False except Warning: failed = True except: failed = False raise if not failed: raise RuntimeError("This test did not issue warning as expected")
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)
canvas = vcs.init() canvas.bgX = 1500 canvas.bgY = 750 levs = levels(var, partition_count=10) stat_iso = vcs.createisofill() int_levs = [] for l in levs: int_levs.append(int(l)) stat_iso.levels = int_levs stat_iso.ext_2 = True stat_iso.ext_1 = True stat_iso.missing = 1 stat_iso.fillareacolors = vcs.getcolors(stat_iso.levels, split=0) iso = vcs.createisofill() v_min, v_max = vcs.minmax(var[0]) scale = vcs.mkscale(v_min, v_max) iso.levels = scale iso.ext_2 = True iso.ext_1 = True iso.missing = 1 iso.fillareacolors = vcs.getcolors(iso.levels, split=0) flat = var.flatten().data stats_variance, stats_binned = calculate_variance(levs, flat) auto_variance, auto_binned = calculate_variance(scale, flat) stats_counts = [] auto_counts = []
def createTemplateandGM(x,min,max,deltaisof,deltaisol,days_line,ntemplate=1,orientation='landscape'): ## x.scriptrun('resol_24.scr') ## x.setcolormap('cmap') dot=x.createline() dot.type='dot' if orientation[0].lower()=='p': x.portrait() tmpl=x.createtemplate() ## Turns off everything for a in dir(tmpl): try: setattr(getattr(tmpl,a),'priority',0) except: pass ## Turns on what we want tmpl.data.priority=1 tmpl.box1.priority=1 tmpl.legend.priority=1 tmpl.xlabel1.priority=1 tmpl.xlabel2.priority=1 tmpl.ylabel1.priority=2 tmpl.ylabel2.priority=2 tmpl.xtic1.priority=2 tmpl.xtic2.priority=2 tmpl.ytic1.priority=2 tmpl.ytic2.priority=2 tmpl.xname.priority=1 tmpl.yname.priority=1 tmpl.dataname.priority=1 if ntemplate==2: tmpl.reset('x',.06,.44,tmpl.data.x1,tmpl.data.x2) else: tmpl.reset('x',.2,.9,tmpl.data.x1,tmpl.data.x2) tmpl.reset('y',.2,.9,tmpl.data.y1,tmpl.data.y2) tmpl.ytic2.x1=tmpl.data.x1 tmpl.ytic2.x2=tmpl.data.x2 tmpl.ytic2.line=dot to=x.createtextorientation() to.halign='center' tmpl.dataname.x=(tmpl.data.x1+tmpl.data.x2)/2. tmpl.dataname.y=tmpl.data.y2+.03 tmpl.dataname.textorientation=to tmpl.legend.x1=.3 tmpl.legend.x2=.7 tmpl.yname.x=tmpl.yname.x-.01 tmpl.xname.y=tmpl.xname.y-.075 tmpl.xtic2.y1=tmpl.data.y1 tmpl.xtic2.y2=tmpl.data.y2 tmpl.xtic2.line=dot tmpl.scalefont(.8) tmplnoleg=x.createtemplate(source=tmpl.name) tmplnoleg.legend.priority=0 isof=x.createisofill() levs2=list(numpy.arange(min,max,deltaisof)) levs1a=list(numpy.arange(min,0,deltaisol)) levs1b=list(numpy.arange(0,max,deltaisol)) isof.levels=levs2 isof.fillareacolors=vcs.getcolors(levs2,colors=range(16,40)) levs1a=list(numpy.arange(min,0,deltaisol)) levs1b=list(numpy.arange(0,max,deltaisol)) isol1=x.createisoline() isol1.level=levs1a isol1.label='y' isol1.line=['dot'] isol2=x.createisoline() isol2.level=levs1b isol2.label='y' tick2={} for i in days_line: tick2[1./i]=str(i)+' days' tick1={} for i in (0,): tick1[i]=' ' for gm in [isof,isol1,isol2]: gm.datawc_x1=-15 gm.datawc_x2=15 gm.datawc_y1=0. gm.datawc_y2=.8 gm.yticlabels2=tick2 gm.xticlabels2=tick1 return tmpl,tmplnoleg,isof,isol1,isol2
def set_animation_min_max(self, min, max, i): from vcs import mkscale, mklabels, getcolors animation_info = self.animate_info_from_python() gtype = animation_info["gtype"][i].lower() levs = mkscale(min, max) dic = mklabels(levs) cols = getcolors(levs) if gtype == "boxfill": gm = self.vcs_self.getboxfill(animation_info['gname'][i]) if gm.boxfill_type == 'custom': gm.fillareacolors = cols gm.levels = levs else: gm.level_1 = levs[0] gm.level_2 = levs[-1] gm.legend = None elif (gtype == "meshfill"): gm = self.vcs_self.getmeshfill(animation_info['gname'][i]) if (min == 1e20) and (max == 1e20): gm.levels = (1e20, 1e20) else: gm.levels = levs gm.fillareacolors = cols elif (gtype == "isofill"): gm = self.vcs_self.getisofill(animation_info['gname'][i]) if (min == 1e20) and (max == 1e20): gm.levels = (1e20, 1e20) else: gm.levels = levs gm.fillareacolors = cols elif (gtype == "isoline"): gm = self.vcs_self.getisoline(animation_info['gname'][i]) if (min == 1e20) and (max == 1e20): gm.levels = (1e20, 1e20) else: gm.levels = levs gm.fillareacolors = cols elif (gtype == "yxvsx"): gm = self.vcs_self.getyxvsx(animation_info['gname'][i]) if (min != 1e20) and (max != 1e20): gm.yticlabels1 = dic gm.yticlabels2 = dic min = levs[0] max = levs[-1] gm.datawc_y1 = min gm.datawc_y2 = max elif (gtype == "xyvsy"): gm = self.vcs_self.getxyvsy(animation_info['gname'][i]) if (min != 1e20) and (max != 1e20): gm.xticlabels1 = dic gm.xticlabels2 = dic min = levs[0] max = levs[-1] gm.datawc_x1 = min gm.datawc_x2 = max elif (gtype == "vector"): gm = self.vcs_self.getvector(animation_info['gname'][i]) mean_veloc = 1e20 if (min != 1e20) and (max != 1e20): mean_veloc = float(int(numpy.sqrt((min**2) + (max**2)))) gm.reference = mean_veloc animation_info['gname'][i] = gm.name
import sys import os f = cdms2.open(os.path.join(sys.prefix, "sample_data", "clt.nc")) s = f("clt", time=slice(0, 1), squeeze=1) print s.shape #s[:23,:36] = 0. #s[:23,36:] = 25. #s[23:,36:] = 60. #s[23:,:36] = 100. x = vcs.init() cmap = x.getcolormap("rainbow") x.setcolormap("rainbow") iso = x.createisofill() #iso=x.createboxfill() #iso.boxfill_type = "custom" #iso=x.createisoline() #iso.levels=[0,33,50,66,100] #levs=[-1.e20,10,50,60,70,80,90,1.e20] levs = [[10, 40], [60, 65], [65, 80], [90, 100]] cols = vcs.getcolors(levs) print cols iso.levels = levs iso.fillareacolors = cols #iso.legend = {60:"SIXTY",80:"EIGHTY"} #iso.linecolors = [242,243,244,245,246] #iso.list() x.plot(s, iso) x.png("contours") raw_input("Press Enter")
f=cdms2.open(os.path.join(vcs.prefix,'sample_data','clt.nc')) if gm_type=="meshfill": s=f("sample") else: s=f("clt",**xtra) if gm_type=="boxfill": gm.level_1=20 gm.level_2=80 else: if gm_type=="isofill": levels = [20, 30, 40, 50, 60, 70, 80] else: levels = [300,500,800,1000,1200] gm.levels=levels gm.colors = vcs.getcolors(levels) tmpl = x.createtemplate() if args.orientation=="vertical": tmpl.data.x2=.8 tmpl.box1.x2=.8 tmpl.ytic2.x1=.8 tmpl.ytic2.x2=.815 tmpl.legend.x1=.86 tmpl.legend.x2=.9 tmpl.legend.y1=.3 tmpl.legend.y2=.8 if args.ext1=="y": gm.ext_1="y" if args.ext2=="y": gm.ext_2="y"
import sys,cdms2,vcs x=vcs.init() f=cdms2.open(vcs.prefix+"/sample_data/clt.nc") s=f("clt",time=slice(0,23)) #f=cdms2.open(sys.prefix+"/sample_data/sampleCurveGrid4.nc") #f=cdms2.open(sys.prefix+"/sample_data/sampleGenGrid3.nc") #s=f("sample") gm = x.createisofill() gm = x.createboxfill() #gm=x.createisoline() levs = vcs.mkevenlevels(20,80) gm.levels= levs gm.fillareacolors = vcs.getcolors(levs) #gm = x.createmeshfill() d = x.plot(s,gm) #d = x.plot(s.filled()) raw_input("Press enter") x.animate.create(thread_it=False,min=20,max=80) x.animate.fps(5000) x.animate.run() raw_input("Press enter to end") x.animate.stop()
grid_dest=dummy.getGrid() s.id="orig" s_regrid2 = s.regrid(grid_dest,regridTool="regrid2") s_regrid2.id="regrid2" s_esmf_lin = s.regrid(grid_dest) s_esmf_lin.id = "ESMF Linear" s_esmf_con = s.regrid(grid_dest,regridTool="esmf",regridMethod="conservative") s_esmf_lin.id = "ESMF Conservative" x=regression.init() t=x.createtemplate() t.blank() t.data.priority=1 t.legend.priority=1 t.dataname.priority=1 t.dataname.y=t.dataname.y*.95 M=EzTemplate.Multi(template=t,x=x,rows=2,columns=2) gm=x.createboxfill() levels= vcs.mkscale(*vcs.minmax(s)) cols = vcs.getcolors(levels) gm.boxfill_type = "custom" gm.fillareacolors = cols gm.levels = levels x.plot(s,M.get(),gm,bg=1) x.plot(s_regrid2,M.get(),gm,bg=1) x.plot(s_esmf_lin,M.get(),gm,bg=1) x.plot(s_esmf_con,M.get(),gm,bg=1) ret = regression.run(x, "esmf_issue_1125.png", png)
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) iso.ext_2 = 'y' # control colorbar edge (arrow extention on/off) cols = vcs.getcolors(iso.levels) iso.fillareacolors = cols iso.missing = 0 # Set missing value color as same as background # Map projection --- p = vcs.createprojection() p.type = int('-3') iso.projection = p xtra = {} xtra['latitude'] = (90.0, 0.0) # For Northern Hemisphere # Plot --- canvas.plot(eof[0](**xtra), iso, template) # Title --- plot_title = vcs.createtext()
def set_animation_min_max(self, min, max, i): from vcs import mkscale, mklabels, getcolors animation_info = self.animate_info_from_python() gtype = animation_info["gtype"][i].lower() levs = mkscale(min, max) dic = mklabels(levs) cols = getcolors(levs) if gtype == "boxfill": gm = self.vcs_self.getboxfill(animation_info['gname'][i]) if gm.boxfill_type == 'custom': gm.fillareacolors = cols gm.levels = levs else: gm.level_1 = levs[0] gm.level_2 = levs[-1] gm.legend = None elif (gtype == "meshfill"): gm = self.vcs_self.getmeshfill(animation_info['gname'][i]) if (min == 1e20) and (max == 1e20): gm.levels = (1e20, 1e20) else: gm.levels = levs gm.fillareacolors = cols elif (gtype == "isofill"): gm = self.vcs_self.getisofill(animation_info['gname'][i]) if (min == 1e20) and (max == 1e20): gm.levels = (1e20, 1e20) else: gm.levels = levs gm.fillareacolors = cols elif (gtype == "isoline"): gm = self.vcs_self.getisoline(animation_info['gname'][i]) if (min == 1e20) and (max == 1e20): gm.levels = (1e20, 1e20) else: gm.levels = levs gm.fillareacolors = cols elif (gtype == "yxvsx"): gm = self.vcs_self.getyxvsx(animation_info['gname'][i]) if (min != 1e20) and (max != 1e20): gm.yticlabels1 = dic gm.yticlabels2 = dic min = levs[0] max = levs[-1] gm.datawc_y1 = min gm.datawc_y2 = max elif (gtype == "xyvsy"): gm = self.vcs_self.getxyvsy(animation_info['gname'][i]) if (min != 1e20) and (max != 1e20): gm.xticlabels1 = dic gm.xticlabels2 = dic min = levs[0] max = levs[-1] gm.datawc_x1 = min gm.datawc_x2 = max elif (gtype == "vector"): gm = self.vcs_self.getvector(animation_info['gname'][i]) mean_veloc = 1e20 if (min != 1e20) and (max != 1e20): mean_veloc = float(int(numpy.sqrt((min ** 2) + (max ** 2)))) gm.reference = mean_veloc animation_info['gname'][i] = gm.name
def plot(self,data=None,mesh=None,template=None,meshfill=None,x=None,bg=0,multiple=1.1): # Create the vcs canvas if x is None: x=vcs.init() ## Continents bug x.setcontinentstype(0) # gets the thing to plot ! if data is None: data=self.get() # Do we use a predefined template ? if template is None: template=x.createtemplate() # Now sets all the things for the template... # Sets a bunch of template attributes to off for att in [ 'line1','line2','line3','line4', 'box2','box3','box4', 'min','max','mean', 'xtic1','xtic2', 'ytic1','ytic2', 'xvalue','yvalue','zvalue','tvalue', 'xunits','yunits','zunits','tunits', 'source','title','dataname', ]: a=getattr(template,att) setattr(a,'priority',0) for att in [ 'xname','yname', ]: a=getattr(template,att) setattr(a,'priority',0) template.data.x1=self.PLOT_SETTINGS.x1 template.data.x2=self.PLOT_SETTINGS.x2 template.data.y1=self.PLOT_SETTINGS.y1 template.data.y2=self.PLOT_SETTINGS.y2 template.box1.x1=self.PLOT_SETTINGS.x1 template.box1.x2=self.PLOT_SETTINGS.x2 template.box1.y1=self.PLOT_SETTINGS.y1 template.box1.y2=self.PLOT_SETTINGS.y2 template.xname.y=self.PLOT_SETTINGS.y2+.02 template.yname.x=self.PLOT_SETTINGS.x2+.01 template.xlabel1.y=self.PLOT_SETTINGS.y1 template.xlabel2.y=self.PLOT_SETTINGS.y2 template.xlabel1.texttable=self.PLOT_SETTINGS.tictable template.xlabel2.texttable=self.PLOT_SETTINGS.tictable template.xlabel1.textorientation=self.PLOT_SETTINGS.xticorientation template.xlabel2.textorientation=self.PLOT_SETTINGS.xticorientation template.ylabel1.x=self.PLOT_SETTINGS.x1 template.ylabel2.x=self.PLOT_SETTINGS.x2 template.ylabel1.texttable=self.PLOT_SETTINGS.tictable template.ylabel2.texttable=self.PLOT_SETTINGS.tictable template.ylabel1.textorientation=self.PLOT_SETTINGS.yticorientation template.ylabel2.textorientation=self.PLOT_SETTINGS.yticorientation if self.PLOT_SETTINGS.xtic1y1 is not None: template.xtic1.y1=self.PLOT_SETTINGS.xtic1y1 template.xtic1.priority=1 if self.PLOT_SETTINGS.xtic1y2 is not None: template.xtic1.y2=self.PLOT_SETTINGS.xtic1y2 template.xtic1.priority=1 if self.PLOT_SETTINGS.xtic2y1 is not None: template.xtic2.y1=self.PLOT_SETTINGS.xtic2y1 template.xtic2.priority=1 if self.PLOT_SETTINGS.xtic2y2 is not None: template.xtic2.y2=self.PLOT_SETTINGS.xtic2y2 template.xtic2.priority=1 if self.PLOT_SETTINGS.ytic1x1 is not None: template.ytic1.x1=self.PLOT_SETTINGS.ytic1x1 template.ytic1.priority=1 if self.PLOT_SETTINGS.ytic1x2 is not None: template.ytic1.x2=self.PLOT_SETTINGS.ytic1x2 template.ytic1.priority=1 if self.PLOT_SETTINGS.ytic2x1 is not None: template.ytic2.priority=1 template.ytic2.x1=self.PLOT_SETTINGS.ytic2x1 if self.PLOT_SETTINGS.ytic2x2 is not None: template.ytic2.priority=1 template.ytic2.x2=self.PLOT_SETTINGS.ytic2x2 template.legend.x1=self.PLOT_SETTINGS.legend_x1 template.legend.x2=self.PLOT_SETTINGS.legend_x2 template.legend.y1=self.PLOT_SETTINGS.legend_y1 template.legend.y2=self.PLOT_SETTINGS.legend_y2 try: tmp = x.createtextorientation('crap22') except: tmp = x.gettextorientation('crap22') tmp.height = 12 #tmp.halign = 'center' # template.legend.texttable = tmp template.legend.textorientation = tmp else: if isinstance(template,vcs.template.P): tid=template.name elif isinstance(template,str): tid=template else: raise 'Error cannot understand what you mean by template='+str(template) template=x.createtemplate() # Do we use a predefined meshfill ? if meshfill is None: mtics={} for i in range(100): mtics[i-.5]='' icont = 1 meshfill=x.createmeshfill() meshfill.xticlabels1=eval(data.getAxis(1).names) meshfill.yticlabels1=eval(data.getAxis(0).names) meshfill.datawc_x1=-.5 meshfill.datawc_x2=data.shape[1]-.5 meshfill.datawc_y1=-.5 meshfill.datawc_y2=data.shape[0]-.5 meshfill.mesh=self.PLOT_SETTINGS.draw_mesh meshfill.missing=self.PLOT_SETTINGS.missing_color meshfill.xticlabels2=mtics meshfill.yticlabels2=mtics if self.PLOT_SETTINGS.colormap is None: self.set_colormap(x) elif x.getcolormapname()!=self.PLOT_SETTINGS.colormap: x.setcolormap(self.PLOT_SETTINGS.colormap) if self.PLOT_SETTINGS.levels is None: min,max=vcs.minmax(data) if max!=0: max=max+.000001 levs=vcs.mkscale(min,max) else: levs=self.PLOT_SETTINGS.levels if len(levs)>1: meshfill.levels=levs if self.PLOT_SETTINGS.fillareacolors is None: cols=vcs.getcolors(levs,range(16,40),split=1) meshfill.fillareacolors=cols else: meshfill.fillareacolors=self.PLOT_SETTINGS.fillareacolors ## self.setmeshfill(x,meshfill,levs) ## if self.PLOT_SETTINGS.legend is None: ## meshfill.legend=vcs.mklabels(levs) ## else: ## meshfill.legend=self.PLOT_SETTINGS.legend # Now creates the mesh associated n=int(multiple) ntot=int((multiple-n)*10+.1) ## data=data sh=list(data.shape) sh.append(2) I=MV2.indices((sh[0],sh[1])) Y=I[0] X=I[1] ## if ntot>1: ## meshfill.mesh='y' if ntot == 1: sh.append(4) M=MV2.zeros(sh) M[:,:,0,0]=Y-.5 M[:,:,1,0]=X-.5 M[:,:,0,1]=Y-.5 M[:,:,1,1]=X+.5 M[:,:,0,2]=Y+.5 M[:,:,1,2]=X+.5 M[:,:,0,3]=Y+.5 M[:,:,1,3]=X-.5 M=MV2.reshape(M,(sh[0]*sh[1],2,4)) elif ntot==2: sh.append(3) M=MV2.zeros(sh) M[:,:,0,0]=Y-.5 M[:,:,1,0]=X-.5 M[:,:,0,1]=Y+.5-(n-1) M[:,:,1,1]=X-0.5+(n-1) M[:,:,0,2]=Y+.5 M[:,:,1,2]=X+.5 M=MV2.reshape(M,(sh[0]*sh[1],2,3)) elif ntot==3: design=int((multiple-n)*100+.1) if design==33: sh.append(3) M=MV2.zeros(sh) if n==1: M[:,:,0,0]=Y-.5 M[:,:,1,0]=X-.5 M[:,:,0,1]=Y+.5 M[:,:,1,1]=X M[:,:,0,2]=Y+.5 M[:,:,1,2]=X-.5 elif n==2: M[:,:,0,0]=Y-.5 M[:,:,1,0]=X-.5 M[:,:,0,1]=Y+.5 M[:,:,1,1]=X M[:,:,0,2]=Y-.5 M[:,:,1,2]=X+.5 elif n==3: M[:,:,0,0]=Y+.5 M[:,:,1,0]=X+.5 M[:,:,0,1]=Y+.5 M[:,:,1,1]=X M[:,:,0,2]=Y-.5 M[:,:,1,2]=X+.5 M=MV2.reshape(M,(sh[0]*sh[1],2,3)) elif design==32: sh.append(5) M=MV2.zeros(sh) M[:,:,0,0]=Y M[:,:,1,0]=X d=.5/MV2.sqrt(3.) if n==1: M[:,:,0,1]=Y+.5 M[:,:,1,1]=X M[:,:,0,2]=Y+.5 M[:,:,1,2]=X-.5 M[:,:,0,3]=Y-d M[:,:,1,3]=X-.5 # dummy point for n==1 or 3 M[:,:,0,4]=Y M[:,:,1,4]=X if n==2: M[:,:,0,1]=Y-d M[:,:,1,1]=X-.5 M[:,:,0,2]=Y-.5 M[:,:,1,2]=X-.5 M[:,:,0,3]=Y-.5 M[:,:,1,3]=X+.5 M[:,:,0,4]=Y-d M[:,:,1,4]=X+.5 elif n==3: M[:,:,0,1]=Y+.5 M[:,:,1,1]=X M[:,:,0,2]=Y+.5 M[:,:,1,2]=X+.5 M[:,:,0,3]=Y-d M[:,:,1,3]=X+.5 # dummy point for n==1 or 3 M[:,:,0,4]=Y M[:,:,1,4]=X M=MV2.reshape(M,(sh[0]*sh[1],2,5)) else: sh.append(5) M=MV2.zeros(sh) M[:,:,0,0]=Y M[:,:,1,0]=X d=1./3. if n==1: M[:,:,0,1]=Y+.5 M[:,:,1,1]=X M[:,:,0,2]=Y+.5 M[:,:,1,2]=X-.5 M[:,:,0,3]=Y-d M[:,:,1,3]=X-.5 # dummy point for n==1 or 3 M[:,:,0,4]=Y M[:,:,1,4]=X if n==2: M[:,:,0,1]=Y-d M[:,:,1,1]=X-.5 M[:,:,0,2]=Y-.5 M[:,:,1,2]=X-.5 M[:,:,0,3]=Y-.5 M[:,:,1,3]=X+.5 M[:,:,0,4]=Y-d M[:,:,1,4]=X+.5 elif n==3: M[:,:,0,1]=Y+.5 M[:,:,1,1]=X M[:,:,0,2]=Y+.5 M[:,:,1,2]=X+.5 M[:,:,0,3]=Y-d M[:,:,1,3]=X+.5 # dummy point for n==1 or 3 M[:,:,0,4]=Y M[:,:,1,4]=X M=MV2.reshape(M,(sh[0]*sh[1],2,5)) elif ntot==4: sh.append(3) M=MV2.zeros(sh) M[:,:,0,0]=Y M[:,:,1,0]=X if n==1: M[:,:,0,1]=Y+.5 M[:,:,1,1]=X+.5 M[:,:,0,2]=Y+.5 M[:,:,1,2]=X-.5 elif n==2: M[:,:,0,1]=Y+.5 M[:,:,1,1]=X-.5 M[:,:,0,2]=Y-.5 M[:,:,1,2]=X-.5 elif n==3: M[:,:,0,1]=Y-.5 M[:,:,1,1]=X-.5 M[:,:,0,2]=Y-.5 M[:,:,1,2]=X+.5 elif n==4: M[:,:,0,1]=Y-.5 M[:,:,1,1]=X+.5 M[:,:,0,2]=Y+.5 M[:,:,1,2]=X+.5 M=MV2.reshape(M,(sh[0]*sh[1],2,3)) else: if isinstance(meshfill,vcs.meshfill.P): tid=mesh.id elif isinstance(meshfill,str): tid=mesh else: raise 'Error cannot understand what you mean by meshfill='+str(meshfill) meshfill=x.createmeshfill() if mesh is None: x.plot(MV2.ravel(data),M,template,meshfill,bg=bg) else: x.plot(MV2.ravel(data),mesh,template,meshfill,bg=bg) # Now prints the rest of the title, etc... # but only if n==1 if n==1: axes_param=[] for a in data.getAxis(0).id.split('___'): axes_param.append(a) for a in data.getAxis(1).id.split('___'): axes_param.append(a) nparam=0 for p in self.parameters_list: if not p in self.dummies and not p in self.auto_dummies and not p in axes_param: nparam+=1 if self.verbose: print 'NPARAM:',nparam if nparam>0: for i in range(nparam): j=MV2.ceil(float(nparam)/(i+1.)) if j<=i: break npc=i # number of lines npl=int(j) # number of coulmns if npc*npl<nparam : npl+=1 # computes space between each line dl=(.95-template.data.y2)/npl dc=.9/npc npci=0 # counter for columns npli=0 # counter for lines for p in self.parameters_list: if not p in self.dummies and not p in self.auto_dummies and not p in axes_param: txt=x.createtext(None,self.PLOT_SETTINGS.parametertable.name,None,self.PLOT_SETTINGS.parameterorientation.name) value=getattr(self,p) if (isinstance(value,(list,tuple)) and len(value)==1): txt.string=p+':'+str(self.makestring(p,value[0])) display=1 elif isinstance(value,(str,int,float,long)): txt.string=p+':'+str(self.makestring(p,value)) display=1 else: display=0 if display: # Now figures out where to put these... txt.x=[(npci)*dc+dc/2.+.05] txt.y=[1.-(npli)*dl-dl/2.] npci+=1 if npci>=npc: npci=0 npli+=1 if p in self.altered.keys(): dic=self.altered[p] if dic['size'] is not None: txt.size=dic['size'] if dic['color'] is not None: txt.color=dic['color'] if dic['x'] is not none: txt.x=dic['x'] if dic['y'] is not none: txt.y=dic['y'] x.plot(txt,bg=bg,continents=0) if not self.PLOT_SETTINGS.logo is None: x.plot(self.PLOT_SETTINGS.logo,bg=bg,continents=0) if not self.PLOT_SETTINGS.time_stamp is None: import time sp=time.ctime().split() sp=sp[:3]+[sp[-1]] self.PLOT_SETTINGS.time_stamp.string=''.join(sp) x.plot(self.PLOT_SETTINGS.time_stamp,bg=bg,continents=0)
def test_portrait(self): try: import vcs except: raise RuntimeError( "Sorry your python is not build with VCS support cannot geenrate portrait plots") import json # CDAT MODULES import pcmdi_metrics import pcmdi_metrics.graphics.portraits import MV2 import numpy from genutil import statistics import os import sys import glob # CREATES VCS OBJECT AS A PORTAIT PLOT AND LOADS PLOT SETTINGS FOR # EXAMPLE x = vcs.init() 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.xtic2y1 = P.PLOT_SETTINGS.y1 P.PLOT_SETTINGS.xtic2y2 = P.PLOT_SETTINGS.y2 P.PLOT_SETTINGS.ytic2x1 = P.PLOT_SETTINGS.x1 P.PLOT_SETTINGS.ytic2x2 = P.PLOT_SETTINGS.x2 # P.PLOT_SETTINGS.missing_color = 3 # P.PLOT_SETTINGS.logo = None P.PLOT_SETTINGS.time_stamp = None P.PLOT_SETTINGS.draw_mesh = 'n' # P.PLOT_SETTINGS.tictable.font = 3 x.scriptrun( os.path.join( pcmdi_metrics.__path__[0], "..", "..", "..", "..", "share", "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 # LIST OF VARIABLES TO BE USED IN PORTRAIT PLOT vars = [ 'pr', 'rsut', 'rsutcs', 'rlutcs', 'tas', 'tos', 'sos', 'zos', 'ua-850', 'ua-200', 'zg-500'] vars = [] # LOAD METRICS DICTIONARIES FROM JSON FILES FOR EACH VAR AND STORE AS A # SINGLE DICTIONARY var_cmip5_dics = {} mods = set() json_files = glob.glob( os.path.join( pcmdi_metrics.__path__[0], "..", "..", "..", "..", "share", "CMIP_metrics_results", "CMIP5", "amip", "*.json")) for fnm in json_files: f = open(fnm) d = json.load(f) var = os.path.basename(fnm).split("_")[0] vars.append(var) for m in d.keys(): mods.add(m) if var in var_cmip5_dics: var_cmip5_dics[var].update(d) else: var_cmip5_dics[var] = d vars.sort() mods = sorted(list(mods)) print "Models:",mods for bad in ["GridInfo", "References", "RegionalMasking", "metrics_git_sha1", "uvcdat_version"]: if bad in mods: mods.remove(bad) else: print "Not removing column %s (not present)" % bad # ORGANIZE METRICS INTO A VARIABLES X MODELS MATRIX out1_rel = MV2.zeros( (len(vars), len(mods)), MV2.float32) # DEFINE ARRAY vn = -1 # VARIABLE INDEX for var in vars: # LOOP OVER VARIABLE vn = vn + 1 vals = [] for mod in mods: # LOOP OVER MODEL try: rms = var_cmip5_dics[var][mod]["defaultReference"][ "r1i1p1"]["global"]['rms_xyt_ann_GLB'] if P.verbose: print var, ' ', mod, ' ', repr(rms), ' WITH global' except: rms = 1.e20 if P.verbose: print var, ' ', mod, ' ', repr(rms), ' missing' rms = float(rms) vals.append(rms) vars_ar = MV2.array(vals) # COMPUTE MEDIAN RESULT FOR PORTRAIT NORMALIZATION med_rms = statistics.median(vars_ar)[0] mn = -1 # MODEL INDEX for mod in mods: mn = mn + 1 try: out1_rel[vn, mn] = (float(var_cmip5_dics[var][mod]["defaultReference"][ "r1i1p1"]["global"]['rms_xyt_ann_GLB']) - med_rms) / med_rms # RELATIVE ERROR except: out1_rel[vn, mn] = numpy.ma.masked # ADD SPACES FOR LABELS TO ALIGN AXIS LABELS WITH PLOT modsAxis = mods varsAxis = vars # LOOP THROUGH LISTS TO ADD SPACES for i in range(len(modsAxis)): modsAxis[i] = modsAxis[i] + ' ' for i in range(len(varsAxis)): varsAxis[i] = varsAxis[i] + ' ' yax = [s.encode('utf-8') for s in mods] # CHANGE FROM UNICODE TO BYTE STRINGS xax = vars # GENERATE PLOT P.decorate(out1_rel, xax, yax) # P.plot(out1_rel,x=x,multiple=1.1,bg=0) # FOR PLOTTING TRIANGLES WHEN # USING TWO OR MORE REFERENCE DATA SETS P.plot(out1_rel, bg=1, x=x) # 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 = checkimage.check_result_image( fnm, src, checkimage.defaultThreshold) if ret != 0: sys.exit(ret)
# 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() isofill.levels = [6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26] colors = vcs.getcolors(isofill.levels) for i in range(0, len(colors)): colors[i] = 'white' isofill.fillareacolors = colors isofill.fillareaopacity = range(10, 100, 100 / len(colors)) if Blue_marble_download: # Download background image for map; http://visibleearth.nasa.gov/ bg_image_link = 'http://eoimages.gsfc.nasa.gov/images/imagerecords/74000/74393/world.topo.200407.3x5400x2700.png' if Nighttimeimage: bg_image_link = 'http://eoimages.gsfc.nasa.gov/images/imagerecords/79000/79765/dnb_land_ocean_ice.2012.3600x1800.jpg' bg_image = 'bg_image_blue_marble.png' bg_image_frame = open(bg_image, 'wb') bg_image_frame.write(urllib.urlopen(bg_image_link).read()) bg_image_frame.close()
def plot(self, data=None, mesh=None, template=None, meshfill=None, x=None, bg=0, multiple=1.1): self.bg = bg # Create the vcs canvas if x is not None: self.x = x # Continents bug # x.setcontinentstype(0) # gets the thing to plot ! if data is None: data = self.get() # Do we use a predefined template ? if template is None: template = self.generateTemplate() else: if isinstance(template, vcs.template.P): tid = template.name elif isinstance(template, str): tid = template else: raise 'Error cannot understand what you mean by template=' + \ str(template) template = vcs.createtemplate(source=tid) # Do we use a predefined meshfill ? if meshfill is None: mtics = {} for i in range(100): mtics[i - .5] = '' meshfill = vcs.createmeshfill() meshfill.xticlabels1 = eval(data.getAxis(1).names) meshfill.yticlabels1 = eval(data.getAxis(0).names) meshfill.datawc_x1 = -.5 meshfill.datawc_x2 = data.shape[1] - .5 meshfill.datawc_y1 = -.5 meshfill.datawc_y2 = data.shape[0] - .5 meshfill.mesh = self.PLOT_SETTINGS.draw_mesh meshfill.missing = self.PLOT_SETTINGS.missing_color meshfill.xticlabels2 = mtics meshfill.yticlabels2 = mtics if self.PLOT_SETTINGS.colormap is None: self.set_colormap() elif self.x.getcolormapname() != self.PLOT_SETTINGS.colormap: self.x.setcolormap(self.PLOT_SETTINGS.colormap) if self.PLOT_SETTINGS.levels is None: min, max = vcs.minmax(data) if max != 0: max = max + .000001 levs = vcs.mkscale(min, max) else: levs = self.PLOT_SETTINGS.levels if len(levs) > 1: meshfill.levels = levs if self.PLOT_SETTINGS.fillareacolors is None: if self.PLOT_SETTINGS.colormap is None: # Default colormap only use range 16->40 cols = vcs.getcolors(levs, list(range(16, 40)), split=1) else: cols = vcs.getcolors(levs, split=1) meshfill.fillareacolors = cols else: meshfill.fillareacolors = self.PLOT_SETTINGS.fillareacolors # Now creates the mesh associated n = int(multiple) ntot = int((multiple - n) * 10 + .1) sh = list(data.shape) sh.append(2) Indx = MV2.indices((sh[0], sh[1])) Y = Indx[0] X = Indx[1] if ntot == 1: sh.append(4) M = MV2.zeros(sh) M[:, :, 0, 0] = Y - .5 M[:, :, 1, 0] = X - .5 M[:, :, 0, 1] = Y - .5 M[:, :, 1, 1] = X + .5 M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M[:, :, 0, 3] = Y + .5 M[:, :, 1, 3] = X - .5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 4)) elif ntot == 2: sh.append(3) M = MV2.zeros(sh) M[:, :, 0, 0] = Y - .5 M[:, :, 1, 0] = X - .5 M[:, :, 0, 1] = Y + .5 - (n - 1) M[:, :, 1, 1] = X - 0.5 + (n - 1) M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 3)) elif ntot == 3: design = int((multiple - n) * 100 + .1) if design == 33: sh.append(3) M = MV2.zeros(sh) if n == 1: M[:, :, 0, 0] = Y - .5 M[:, :, 1, 0] = X - .5 M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X - .5 elif n == 2: M[:, :, 0, 0] = Y - .5 M[:, :, 1, 0] = X - .5 M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X + .5 elif n == 3: M[:, :, 0, 0] = Y + .5 M[:, :, 1, 0] = X + .5 M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X + .5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 3)) elif design == 32: sh.append(5) M = MV2.zeros(sh) M[:, :, 0, 0] = Y M[:, :, 1, 0] = X d = .5 / MV2.sqrt(3.) if n == 1: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X - .5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X - .5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X if n == 2: M[:, :, 0, 1] = Y - d M[:, :, 1, 1] = X - .5 M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X - .5 M[:, :, 0, 3] = Y - .5 M[:, :, 1, 3] = X + .5 M[:, :, 0, 4] = Y - d M[:, :, 1, 4] = X + .5 elif n == 3: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X + .5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X M = MV2.reshape(M, (sh[0] * sh[1], 2, 5)) else: sh.append(5) M = MV2.zeros(sh) M[:, :, 0, 0] = Y M[:, :, 1, 0] = X d = 1. / 3. if n == 1: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X - .5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X - .5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X if n == 2: M[:, :, 0, 1] = Y - d M[:, :, 1, 1] = X - .5 M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X - .5 M[:, :, 0, 3] = Y - .5 M[:, :, 1, 3] = X + .5 M[:, :, 0, 4] = Y - d M[:, :, 1, 4] = X + .5 elif n == 3: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X + .5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X M = MV2.reshape(M, (sh[0] * sh[1], 2, 5)) elif ntot == 4: sh.append(3) M = MV2.zeros(sh) M[:, :, 0, 0] = Y M[:, :, 1, 0] = X if n == 1: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X + .5 M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X - .5 elif n == 2: M[:, :, 0, 1] = Y + .5 M[:, :, 1, 1] = X - .5 M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X - .5 elif n == 3: M[:, :, 0, 1] = Y - .5 M[:, :, 1, 1] = X - .5 M[:, :, 0, 2] = Y - .5 M[:, :, 1, 2] = X + .5 elif n == 4: M[:, :, 0, 1] = Y - .5 M[:, :, 1, 1] = X + .5 M[:, :, 0, 2] = Y + .5 M[:, :, 1, 2] = X + .5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 3)) else: if isinstance(meshfill, vcs.meshfill.P): tid = mesh.id elif isinstance(meshfill, str): tid = mesh else: raise 'Error cannot understand what you mean by meshfill=' + \ str(meshfill) meshfill = vcs.createmeshfill(source=tid) if mesh is None: mesh = M raveled = MV2.ravel(data) self.x.plot(raveled, mesh, template, meshfill, bg=self.bg) # If required plot values if self.PLOT_SETTINGS.values.show: self.draw_values(raveled, mesh, meshfill, template) # Now prints the rest of the title, etc... # but only if n==1 if n == 1: axes_param = [] for a in data.getAxis(0).id.split('___'): axes_param.append(a) for a in data.getAxis(1).id.split('___'): axes_param.append(a) nparam = 0 for p in self.parameters_list: if p not in self.dummies and \ p not in self.auto_dummies and \ p not in axes_param: nparam += 1 if self.verbose: print('NPARAM:', nparam) if nparam > 0: for i in range(nparam): j = MV2.ceil(float(nparam) / (i + 1.)) if j <= i: break npc = i # number of lines npl = int(j) # number of coulmns if npc * npl < nparam: npl += 1 # computes space between each line dl = (.95 - template.data.y2) / npl dc = .9 / npc npci = 0 # counter for columns npli = 0 # counter for lines for p in self.parameters_list: if p not in self.dummies and \ p not in self.auto_dummies and \ p not in axes_param: txt = self.x.createtext( None, self.PLOT_SETTINGS.parametertable.name, None, self.PLOT_SETTINGS.parameterorientation.name) value = getattr(self, p) if (isinstance(value, (list, tuple)) and len(value) == 1): txt.string = p + ':' + \ str(self.makestring(p, value[0])) display = 1 elif isinstance(value, (str, int, float)): txt.string = p + ':' + \ str(self.makestring(p, value)) display = 1 else: display = 0 if display: # Now figures out where to put these... txt.x = [(npci) * dc + dc / 2. + .05] txt.y = [1. - (npli) * dl - dl / 2.] npci += 1 if npci >= npc: npci = 0 npli += 1 if p in list(self.altered.keys()): dic = self.altered[p] if dic['size'] is not None: txt.size = dic['size'] if dic['color'] is not None: txt.color = dic['color'] if dic['x'] is not None: txt.x = dic['x'] if dic['y'] is not None: txt.y = dic['y'] self.x.plot(txt, bg=self.bg, continents=0) if self.PLOT_SETTINGS.time_stamp is not None: sp = time.ctime().split() sp = sp[:3] + [sp[-1]] self.PLOT_SETTINGS.time_stamp.string = ''.join(sp) self.x.plot( self.PLOT_SETTINGS.time_stamp, bg=self.bg, continents=0) if self.PLOT_SETTINGS.logo is not None: self.PLOT_SETTINGS.logo.plot(self.x, bg=self.bg) return mesh, template, meshfill
"north_polar": (66, 90), "north_temperate": (22, 66), "tropics": (-22, 22), "south_temperate": (-66, -22), "south_polar": (-90, -66) } def get_region_avg(var, r, axis="xy"): avg = cdutil.averager(var(latitude=regions[r]), axis=axis) avg.id = r return avg magnitudes = [get_region_avg(averaged_seasons, region) for region in regions] thetas = [range(4) * 27] * 5 polar = vcsaddons.getpolar("seasonal") polar.datawc_y1 = 0 polar.datawc_y2 = 100 polar.markers = ["dot"] polar.markersizes = [3] polar.markercolors = vcs.getcolors([-90, -66, -22, 22, 66, 90], split=False) polar.magnitude_tick_angle = numpy.pi / 4 polar.plot(magnitudes, thetas, bg=True, x=x) fnm = "test_vcs_addons_polar_seasonal.png" x.png(fnm) ret = regression.check_result_image(fnm, src) sys.exit(ret)
import vcs import cdms2 import os f = cdms2.open(os.path.join(vcs.sample_data, "clt.nc")) s = f("clt", time=slice(0, 1), squeeze=1) print s.shape x = vcs.init() cmap = x.getcolormap("rainbow") x.setcolormap("rainbow") iso = x.createisofill() levs = [[10, 40], [60, 65], [65, 80], [90, 100]] cols = vcs.getcolors(levs) print cols iso.levels = levs iso.fillareacolors = cols x.plot(s, iso) x.png("contours") raw_input("Press Enter")
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__ : # We want missing value to be white try: self.presentation.missing = "grey" except: # Some presentation do not have missing attribute pass if vcs.isscatter(self.presentation): #ylabel, xlabel = string.split(self.title, ' vs ') #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 = 10 #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": 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() or 'Z' in axaxi.keys()): axx = axaxi['T'] if 'Y' in axaxi.keys(): axy = axaxi['Y'] else: axy = axaxi['Z'] if axx == 'time': t=var.getTime() if 'units' in dir(t) and t.units.find("months since 1800")==0: 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) in ['mbar', 'millibars']: # 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 if self.levels: levels = self.levels else: nlevels = 16 try: #changed by Charles on 4/15/16 to support Chris if varmin<0 and varmax>0 and hasattr(var,"RMSE"): mx = max(-varmin,varmax) #temporarily disabled from dicsussion with J. Potter on 4/28/16 #levels = [float(v) for v in vcs.mkscale( -mx,mx, nlevels, zero=-1 )] levels = [float(v) for v in vcs.mkscale( varmin,varmax, nlevels, zero=-1 )] else: levels = [float(v) for v in vcs.mkscale( varmin, varmax, nlevels, zero=1 )] # Exceptions occur because mkscale doesn't always work. E.g. vcs.mkscale(0,1.e35,16) except RuntimeWarning,err: 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 logger.warning("Graphics problems, clipping some data at %s",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 if varmin<0 and varmax>0 and hasattr(var,"model"): self.presentation.fillareacolors=vcs.getcolors(levels,colors=range(16,240),split=1) #nlevels = max(1, len(levels) - 1) #self.presentation.list() #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. # Former scale factor, didn't work on more than one variable. # That is, 100 workrf for moisture transport, 10 for wind stress: vec.scale = min(vcsx.bgX,vcsx.bgY)/ 100. 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] vm = max(abs(v.min()),abs(v.max())) wm = max(abs(w.min()),abs(w.max())) vec.scale = 10 / math.sqrt( math.sqrt( vm**2 + wm**2 )) else: # We shouldn't get here, but may as well try to make it work if possible: logger.warning("Trying to make a vector plot without tuples! Variables involved are:") v = self.vars[0] v = self.vars[1] nlats = latAxis(v).shape[0] nlons = lonAxis(w).shape[0] # vector density factor of 32 works for moisture transport, 16 for wind stress nlatvs = vcsx.bgY/32 # how many vectors we want in lat direction nlonvs = vcsx.bgX/32 #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 ))
def test_portrait_values(self): 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 self.x.portrait() # 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(egg_pth, "graphics", "png", "PCMDILogo-old_348x300px_72dpi.png") P.PLOT_SETTINGS.logo.y = .95 P.PLOT_SETTINGS.logo.x = .93 P.PLOT_SETTINGS.logo.width = 85 P.PLOT_SETTINGS.time_stamp = None P.PLOT_SETTINGS.draw_mesh = 'n' # P.PLOT_SETTINGS.tictable.font = 3 self.x.scriptrun( os.path.join( egg_pth, "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, list(range(144, 156)), split=1) P.PLOT_SETTINGS.fillareacolors = cols P.PLOT_SETTINGS.parametertable.expansion = 100 P.PLOT_SETTINGS.values.show = True P.PLOT_SETTINGS.values.text.color = "red" P.PLOT_SETTINGS.values.text.angle = -45 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 = [str(s) for s in mods] # GENERATE PLOT P.decorate(out1_rel, variables, yax) # USING TWO OR MORE REFERENCE DATA SETS P.PLOT_SETTINGS.values.array = out1_rel + 2. P.PLOT_SETTINGS.values.lightcolor = "green" P.PLOT_SETTINGS.values.darkcolor = "red" P.plot(out1_rel, x=self.x, multiple=1.3) fnm = os.path.join(os.getcwd(), "testValuesOnPortrait.png") self.checkImage(fnm)
import vcs, cdms2, os vcs.download_sample_data_files() # An example demonstrating patterns with meshfill cltfile = cdms2.open(os.path.join(vcs.sample_data, "clt.nc")) clt = cltfile("clt") canvas = vcs.init() iso = canvas.createisofill() iso.fillareastyle = "hatch" # Refer to http://uvcdat.llnl.gov/examples/pattern_chart.html for a list of patterns iso.fillareaindices = [1, 2, 3, 4, 5] iso.levels = [0, 20, 40, 60, 80, 100] iso.fillareaopacity = [50.0, 85.1, 23.5, 99.9, 100] iso.fillareacolors = vcs.getcolors(iso.levels) canvas.plot(clt, iso) canvas.png("isofill_pattern")
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 = [-1, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] iso.ext_1 = 'y' # control colorbar edge (arrow extention on/off) iso.ext_2 = 'y' # control colorbar edge (arrow extention on/off) cols = vcs.getcolors(iso.levels) iso.fillareacolors = cols iso.missing = 0 # Set missing value color as same as background # Map projection --- p = vcs.createprojection() p.type = 'robinson' iso.projection = p # Plot --- canvas.plot(eof[0],iso,template) # Title --- plot_title = vcs.createtext() plot_title.x = .5 plot_title.y = .97
#Filter the variable by lat and long s = s(lat = (25., 75.6), lon = (25., 85.)) # Initialize a canvas x = vcs.init() # Set canvas resolution # Set canvas colormap x.setcolormap("bl_to_darkred") # Set up some levels to filter data by levs = [-1e20, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, -.5, 0, .5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 1e20] # Retrieve the colors that would best spread the supplied range of colors cols = vcs.getcolors(levs, range(239, 11, -1)) # Create and initilize an isofill iso = x.createisofill() iso.levels = levs # Draw the extension arrows on either side of the color legend iso.ext_1 = "y" iso.ext_2 = "y" # Set the fill colors to the ones we retrieved earlier iso.fillareacolors = cols # Create a label txt = x.createtext() txt.string = "Moscow"
P.PLOT_SETTINGS.y1 = .22 P.PLOT_SETTINGS.y2 = .95 P.PLOT_SETTINGS.xtic2y1=P.PLOT_SETTINGS.y1 P.PLOT_SETTINGS.xtic2y2=P.PLOT_SETTINGS.y2 P.PLOT_SETTINGS.ytic2x1=P.PLOT_SETTINGS.x1 P.PLOT_SETTINGS.ytic2x2=P.PLOT_SETTINGS.x2 #P.PLOT_SETTINGS.missing_color = 240 # Logo is simply a vcs text object, set to None for off P.PLOT_SETTINGS.logo = None # timestamp is simply a vcs text object, set to None for off P.PLOT_SETTINGS.time_stamp = None P.PLOT_SETTINGS.draw_mesh='y' #P.PLOT_SETTINGS.tictable.font = 3 x.scriptrun(os.path.join(sys.prefix,"share","graphics",'vcs','portraits.scr')) P.PLOT_SETTINGS.colormap = 'bl_rd_12' cols=vcs.getcolors(P.PLOT_SETTINGS.levels,range(144,156),split=1) P.PLOT_SETTINGS.fillareacolors = cols P.PLOT_SETTINGS.parametertable.expansion = 100 ####################### # LIST OF VARIABLES TO BE USED IN PORTRAIT PLOT # REDUCED LIST FOR TEST CASE vars = ['pr','tas','psl','rlut','rsut','ua-850','ua-200','va-850','va-200','zg-500'] # LOAD METRICS DICTIONARIES FROM JSON FILES FOR EACH VAR AND STORE AS A SINGLE DICTIONARY var_cmip5_dics = {} mods = set() # CMIP5 METRICS RESULTS - CURRENTLY USING FOR CONTROL SIMULATIONS json_files = glob.glob(os.path.join(sys.prefix,"share","CMIP_metrics_results","CMIP5","piControl","*.json"))
# isofill will use the naive minmax approach isofill = vcs.createisofill("minmax", "reduced") # Extract the minimum and maximum levels of sphu # This will extract the minimum and maximum values from # all time slices, which may be an issue for your dataset. # If you want to do an animation, it's a good appraoch. # If you're just looking at a single time slice, you're better off # using our automatic level generator. minval, maxval = vcs.minmax(sphu) # Automatically create levels based on a minimum and maximum value # It will round to surround the min and max isofill.levels = vcs.mkscale(minval, maxval) # Automatically retrieve colors for the scale isofill.fillareacolors = vcs.getcolors(isofill.levels) # isofill2 uses curated levels # I used the built-in levels, took a look at the visualization, and selected # the band of values that took up the most space in the heatmap. isofill2 = vcs.createisofill("manual", "reduced") isofill2.levels = vcs.mkscale(.2 * 10 ** -5, .5 * 10 ** -5) # Since there are values outside of the upper and lower bounds I provided, # let's turn on extensions to allow those values to be accomodated for. isofill2.ext_1 = True isofill2.ext_2 = True isofill2.fillareacolors = vcs.getcolors(isofill2.levels) # Now we'll drop some labels onto the plots... plot_titles = vcs.createtext()
import os, sys, vcs, cdms2, testing.regression as regression f = cdms2.open(vcs.sample_data+"/clt.nc") s = f("clt", time=slice(0, 1), squeeze=1) x = regression.init() iso = vcs.createisofill("isoleg") iso.levels = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] iso.fillareastyle = "pattern" iso.fillareacolors = vcs.getcolors([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) iso.fillareaindices = [1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] x.plot(s, iso, bg=1) fnm = "test_vcs_patterns.png" regression.run(x, fnm, threshold=regression.defaultThreshold+5.)
def plot( self, data=None, mesh=None, template=None, meshfill=None, x=None, bg=0, multiple=1.1, ): self.bg = bg # Create the vcs canvas if x is not None: self.x = x # Continents bug # x.setcontinentstype(0) # gets the thing to plot ! if data is None: data = self.get() # Do we use a predefined template ? if template is None: template = self.generateTemplate() else: if isinstance(template, vcs.template.P): tid = template.name elif isinstance(template, str): tid = template else: raise "Error cannot understand what you mean by template=" + str( template) template = vcs.createtemplate(source=tid) # Do we use a predefined meshfill ? if meshfill is None: mtics = {} for i in range(100): mtics[i - 0.5] = "" meshfill = vcs.createmeshfill() meshfill.xticlabels1 = eval(data.getAxis(1).names) meshfill.yticlabels1 = eval(data.getAxis(0).names) meshfill.datawc_x1 = -0.5 meshfill.datawc_x2 = data.shape[1] - 0.5 meshfill.datawc_y1 = -0.5 meshfill.datawc_y2 = data.shape[0] - 0.5 meshfill.mesh = self.PLOT_SETTINGS.draw_mesh meshfill.missing = self.PLOT_SETTINGS.missing_color meshfill.xticlabels2 = meshfill.xticlabels1 meshfill.yticlabels2 = meshfill.yticlabels1 meshfill.xmtics2 = mtics meshfill.ymtics2 = mtics if self.PLOT_SETTINGS.colormap is None: self.set_colormap() elif self.x.getcolormapname() != self.PLOT_SETTINGS.colormap: self.x.setcolormap(self.PLOT_SETTINGS.colormap) if self.PLOT_SETTINGS.levels is None: min, max = vcs.minmax(data) if max != 0: max = max + 0.000001 levs = vcs.mkscale(min, max) else: levs = self.PLOT_SETTINGS.levels if len(levs) > 1: meshfill.levels = levs if self.PLOT_SETTINGS.fillareacolors is None: if self.PLOT_SETTINGS.colormap is None: # Default colormap only use range 16->40 cols = vcs.getcolors(levs, list(range(144, 156)), split=1) else: cols = vcs.getcolors(levs, split=1) meshfill.fillareacolors = cols else: meshfill.fillareacolors = self.PLOT_SETTINGS.fillareacolors # Now creates the mesh associated n = int(multiple) ntot = int((multiple - n) * 10 + 0.1) sh = list(data.shape) sh.append(2) Indx = MV2.indices((sh[0], sh[1])) Y = Indx[0] X = Indx[1] if ntot == 1: sh.append(4) M = MV2.zeros(sh) M[:, :, 0, 0] = Y - 0.5 M[:, :, 1, 0] = X - 0.5 M[:, :, 0, 1] = Y - 0.5 M[:, :, 1, 1] = X + 0.5 M[:, :, 0, 2] = Y + 0.5 M[:, :, 1, 2] = X + 0.5 M[:, :, 0, 3] = Y + 0.5 M[:, :, 1, 3] = X - 0.5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 4)) elif ntot == 2: sh.append(3) M = MV2.zeros(sh) M[:, :, 0, 0] = Y - 0.5 M[:, :, 1, 0] = X - 0.5 M[:, :, 0, 1] = Y + 0.5 - (n - 1) M[:, :, 1, 1] = X - 0.5 + (n - 1) M[:, :, 0, 2] = Y + 0.5 M[:, :, 1, 2] = X + 0.5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 3)) elif ntot == 3: design = int((multiple - n) * 100 + 0.1) if design == 33: sh.append(3) M = MV2.zeros(sh) if n == 1: M[:, :, 0, 0] = Y - 0.5 M[:, :, 1, 0] = X - 0.5 M[:, :, 0, 1] = Y + 0.5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + 0.5 M[:, :, 1, 2] = X - 0.5 elif n == 2: M[:, :, 0, 0] = Y - 0.5 M[:, :, 1, 0] = X - 0.5 M[:, :, 0, 1] = Y + 0.5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y - 0.5 M[:, :, 1, 2] = X + 0.5 elif n == 3: M[:, :, 0, 0] = Y + 0.5 M[:, :, 1, 0] = X + 0.5 M[:, :, 0, 1] = Y + 0.5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y - 0.5 M[:, :, 1, 2] = X + 0.5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 3)) elif design == 32: sh.append(5) M = MV2.zeros(sh) M[:, :, 0, 0] = Y M[:, :, 1, 0] = X d = 0.5 / MV2.sqrt(3.0) if n == 1: M[:, :, 0, 1] = Y + 0.5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + 0.5 M[:, :, 1, 2] = X - 0.5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X - 0.5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X if n == 2: M[:, :, 0, 1] = Y - d M[:, :, 1, 1] = X - 0.5 M[:, :, 0, 2] = Y - 0.5 M[:, :, 1, 2] = X - 0.5 M[:, :, 0, 3] = Y - 0.5 M[:, :, 1, 3] = X + 0.5 M[:, :, 0, 4] = Y - d M[:, :, 1, 4] = X + 0.5 elif n == 3: M[:, :, 0, 1] = Y + 0.5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + 0.5 M[:, :, 1, 2] = X + 0.5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X + 0.5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X M = MV2.reshape(M, (sh[0] * sh[1], 2, 5)) else: sh.append(5) M = MV2.zeros(sh) M[:, :, 0, 0] = Y M[:, :, 1, 0] = X d = 1.0 / 3.0 if n == 1: M[:, :, 0, 1] = Y + 0.5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + 0.5 M[:, :, 1, 2] = X - 0.5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X - 0.5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X if n == 2: M[:, :, 0, 1] = Y - d M[:, :, 1, 1] = X - 0.5 M[:, :, 0, 2] = Y - 0.5 M[:, :, 1, 2] = X - 0.5 M[:, :, 0, 3] = Y - 0.5 M[:, :, 1, 3] = X + 0.5 M[:, :, 0, 4] = Y - d M[:, :, 1, 4] = X + 0.5 elif n == 3: M[:, :, 0, 1] = Y + 0.5 M[:, :, 1, 1] = X M[:, :, 0, 2] = Y + 0.5 M[:, :, 1, 2] = X + 0.5 M[:, :, 0, 3] = Y - d M[:, :, 1, 3] = X + 0.5 # dummy point for n==1 or 3 M[:, :, 0, 4] = Y M[:, :, 1, 4] = X M = MV2.reshape(M, (sh[0] * sh[1], 2, 5)) elif ntot == 4: sh.append(3) M = MV2.zeros(sh) M[:, :, 0, 0] = Y M[:, :, 1, 0] = X if n == 1: M[:, :, 0, 1] = Y + 0.5 M[:, :, 1, 1] = X + 0.5 M[:, :, 0, 2] = Y + 0.5 M[:, :, 1, 2] = X - 0.5 elif n == 2: M[:, :, 0, 1] = Y + 0.5 M[:, :, 1, 1] = X - 0.5 M[:, :, 0, 2] = Y - 0.5 M[:, :, 1, 2] = X - 0.5 elif n == 3: M[:, :, 0, 1] = Y - 0.5 M[:, :, 1, 1] = X - 0.5 M[:, :, 0, 2] = Y - 0.5 M[:, :, 1, 2] = X + 0.5 elif n == 4: M[:, :, 0, 1] = Y - 0.5 M[:, :, 1, 1] = X + 0.5 M[:, :, 0, 2] = Y + 0.5 M[:, :, 1, 2] = X + 0.5 M = MV2.reshape(M, (sh[0] * sh[1], 2, 3)) else: raise RuntimeError( "Portrait plot support only up to 4 subcells at the moment" ) else: if isinstance(meshfill, vcs.meshfill.P): tid = mesh.id elif isinstance(meshfill, str): tid = mesh else: raise "Error cannot understand what you mean by meshfill=" + str( meshfill) meshfill = vcs.createmeshfill(source=tid) if mesh is None: mesh = M raveled = MV2.ravel(data) self.x.plot(raveled, mesh, template, meshfill, bg=self.bg, continents=0) # If required plot values if self.PLOT_SETTINGS.values.show: self.draw_values(raveled, mesh, meshfill, template) # Now prints the rest of the title, etc... # but only if n==1 if n == 1: axes_param = [] for a in data.getAxis(0).id.split("___"): axes_param.append(a) for a in data.getAxis(1).id.split("___"): axes_param.append(a) nparam = 0 for p in self.parameters_list: if (p not in self.dummies and p not in self.auto_dummies and p not in axes_param): nparam += 1 if self.verbose: print("NPARAM:", nparam) if nparam > 0: for i in range(nparam): j = MV2.ceil(float(nparam) / (i + 1.0)) if j <= i: break npc = i # number of lines npl = int(j) # number of coulmns if npc * npl < nparam: npl += 1 # computes space between each line dl = (0.95 - template.data.y2) / npl dc = 0.9 / npc npci = 0 # counter for columns npli = 0 # counter for lines for p in self.parameters_list: if (p not in self.dummies and p not in self.auto_dummies and p not in axes_param): txt = self.x.createtext( None, self.PLOT_SETTINGS.parametertable.name, None, self.PLOT_SETTINGS.parameterorientation.name, ) value = getattr(self, p) if isinstance(value, (list, tuple)) and len(value) == 1: txt.string = p + ":" + str( self.makestring(p, value[0])) display = 1 elif isinstance(value, (str, int, float)): txt.string = p + ":" + str( self.makestring(p, value)) display = 1 else: display = 0 if display: # Now figures out where to put these... txt.x = [(npci) * dc + dc / 2.0 + 0.05] txt.y = [1.0 - (npli) * dl - dl / 2.0] npci += 1 if npci >= npc: npci = 0 npli += 1 if p in list(self.altered.keys()): dic = self.altered[p] if dic["size"] is not None: txt.size = dic["size"] if dic["color"] is not None: txt.color = dic["color"] if dic["x"] is not None: txt.x = dic["x"] if dic["y"] is not None: txt.y = dic["y"] self.x.plot(txt, bg=self.bg, continents=0) if self.PLOT_SETTINGS.time_stamp is not None: # sp = time.ctime().split() # sp = sp[:3] + [sp[-1]] # self.PLOT_SETTINGS.time_stamp.string = ''.join(sp) sp = "{:v%Y%m%d}".format(datetime.datetime.now()) self.PLOT_SETTINGS.time_stamp.string = sp self.x.plot(self.PLOT_SETTINGS.time_stamp, bg=self.bg, continents=0) if self.PLOT_SETTINGS.logo is not None: self.PLOT_SETTINGS.logo.plot(self.x, bg=self.bg) return mesh, template, meshfill