def getlegendlabels(self, levels): if self.legend: return self.legend if numpy.allclose(self.level_1, 1.e20) or numpy.allclose(self.level_2, 1.e20): autolevels = True else: autolevels = False if len(levels) > 12: scale = vcs.mkscale(levels[0], levels[-1]) if autolevels: return vcs.mklabels(scale) else: # Create our own scale dx = (self.level_2 - self.level_1) / float(len(scale) - 1) real_values = [self.level_1, self.level_2] float_epsilon = numpy.finfo(numpy.float32).eps levels = numpy.arange(levels[0], levels[-1] + float_epsilon, dx) else: real_values = levels # Need to line up the levels and the labels, so we'll massage the label positions max_round = 0 for l in real_values: round_pos = 0 while numpy.round(l, round_pos) != l: round_pos += 1 max_round = max(max_round, round_pos) round_values = [numpy.round(l, round_pos) for l in levels] round_labels = vcs.mklabels(round_values, "list") return {lev: label for lev, label in zip(levels, round_labels)}
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
def _updateContourLevelsAndColorsForBoxfill(self): """Set contour information for a standard boxfill.""" # Compute levels nlev = (self._gm.color_2 - self._gm.color_1) + 1 if numpy.allclose(self._gm.level_1, 1.e20) or \ numpy.allclose(self._gm.level_2, 1.e20): self._contourLevels = vcs.mkscale(self._scalarRange[0], self._scalarRange[1]) if len(self._contourLevels) == 1: # constant value ? self._contourLevels = [ self._contourLevels[0], self._contourLevels[0] + .00001 ] self._contourLabels = vcs.mklabels(self._contourLevels) dx = (self._contourLevels[-1] - self._contourLevels[0]) / nlev self._contourLevels = numpy.arange(self._contourLevels[0], self._contourLevels[-1] + dx, dx) else: if self._gm.boxfill_type == "log10": levslbls = vcs.mkscale(numpy.ma.log10(self._gm.level_1), numpy.ma.log10(self._gm.level_2)) self._contourLevels = \ vcs.mkevenlevels(numpy.ma.log10(self._gm.level_1), numpy.ma.log10(self._gm.level_2), nlev=nlev) else: levslbls = vcs.mkscale(self._gm.level_1, self._gm.level_2) self._contourLevels = vcs.mkevenlevels(self._gm.level_1, self._gm.level_2, nlev=nlev) if len(self._contourLevels) > 25: ## Too many colors/levels need to prettyfy this for legend self._contourLabels = vcs.mklabels(levslbls) ## Make sure extremes are in legd2 = vcs.mklabels( [self._contourLevels[0], self._contourLevels[-1]]) self._contourLabels.update(legd2) else: self._contourLabels = vcs.mklabels(self._contourLevels) if self._gm.boxfill_type == "log10": logLabels = {} for key in self._contourLabels.keys(): value = self._contourLabels[key] newKey = float(numpy.ma.log10(value)) logLabels[newKey] = value self._contourLabels = logLabels # Use consecutive colors: self._contourColors = range(self._gm.color_1, self._gm.color_2 + 1)
def prep_plot(self, xmn, xmx, ymn, ymx): self.save() if self.datawc_x1 != 1.e20: xmn = self.datawc_x1 if self.datawc_x2 != 1.e20: xmx = self.datawc_x2 if self.datawc_y1 != 1.e20: ymn = self.datawc_y1 if self.datawc_y2 != 1.e20: ymx = self.datawc_y2 self.datawc_x1 = xmn self.datawc_x2 = xmx self.datawc_y1 = ymn self.datawc_y2 = ymx for axes in ['x', 'y']: for sec in ['mtics', 'ticlabels']: for n in ['1', '2']: if getattr(self, axes + sec + n) == '*': sc = vcs.mkscale(getattr(self, 'datawc_' + axes + '1'), getattr(self, 'datawc_' + axes + '2')) setattr(self, axes + sec + n, vcs.mklabels(sc)) return xmn, xmx, ymn, ymx
def prep_plot(self,xmn,xmx,ymn,ymx): self.save() if self.datawc_x1!=1.e20: xmn = self.datawc_x1 if self.datawc_x2!=1.e20: xmx = self.datawc_x2 if self.datawc_y1!=1.e20: ymn = self.datawc_y1 if self.datawc_y2!=1.e20: ymx = self.datawc_y2 self.datawc_x1=xmn self.datawc_x2=xmx self.datawc_y1=ymn self.datawc_y2=ymx for axes in ['x','y']: for sec in ['mtics','ticlabels']: for n in ['1','2']: if getattr(self,axes+sec+n) == '*': sc = vcs.mkscale(getattr(self,'datawc_'+axes+'1'),getattr(self,'datawc_'+axes+'2')) setattr(self,axes+sec+n,vcs.mklabels(sc)) return xmn,xmx,ymn,ymx
def _updateContourLevelsAndColorsForBoxfill(self): """Set contour information for a standard boxfill.""" # Compute levels nlev = (self._gm.color_2 - self._gm.color_1) + 1 if numpy.allclose(self._gm.level_1, 1.e20) or \ numpy.allclose(self._gm.level_2, 1.e20): self._contourLevels = vcs.mkscale(self._scalarRange[0], self._scalarRange[1]) if len(self._contourLevels) == 1: # constant value ? self._contourLevels = [self._contourLevels[0], self._contourLevels[0] + .00001] self._contourLabels = vcs.mklabels(self._contourLevels) dx = (self._contourLevels[-1] - self._contourLevels[0]) / nlev self._contourLevels = numpy.arange(self._contourLevels[0], self._contourLevels[-1] + dx, dx) else: if self._gm.boxfill_type == "log10": levslbls = vcs.mkscale(numpy.ma.log10(self._gm.level_1), numpy.ma.log10(self._gm.level_2)) self._contourLevels = \ vcs.mkevenlevels(numpy.ma.log10(self._gm.level_1), numpy.ma.log10(self._gm.level_2), nlev=nlev) else: levslbls = vcs.mkscale(self._gm.level_1, self._gm.level_2) self._contourLevels = vcs.mkevenlevels(self._gm.level_1, self._gm.level_2, nlev=nlev) if len(self._contourLevels) > 25: ## Too many colors/levels need to prettyfy this for legend self._contourLabels = vcs.mklabels(levslbls) ## Make sure extremes are in legd2 = vcs.mklabels([self._contourLevels[0], self._contourLevels[-1]]) self._contourLabels.update(legd2) else: self._contourLabels = vcs.mklabels(self._contourLevels) if self._gm.boxfill_type == "log10": logLabels = {} for key in self._contourLabels.keys(): value = self._contourLabels[key] newKey = float(numpy.ma.log10(value)) logLabels[newKey] = value self._contourLabels = logLabels # Use consecutive colors: self._contourColors = range(self._gm.color_1, self._gm.color_2 + 1)
vcs.scriptrun(ViridisScript) colormapname = "bl_to_darkred" # colormapname = "viridis" x.setcolormap(colormapname) iso = x.createisofill() number_different_colors = 64 levels = numpy.arange(-5., 5.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(-5., 5.01, .5)) # 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 t.legend.x1 = t.data.x2 + .03 t.legend.x2 = t.legend.x1 + .03 t.legend.y1 = t.data.y1 + .05
my_tpl.xtic2.priority = 0 my_tpl.ytic2.priority = 0 my_tpl.legend.priority = 0 # Calculate "nice" x-axis labels and set them into the graphics # method, with no more than 8 ticks on the axis: # my_gm.xticlabels1 = vcs.mklabels( vcs.mkscale(min(x), max(x), 8) ) # Calculate "nice" y-axis labels, set them in the graphics method, # calculate y-axis title location based on the longest label # length, set y-axis ticks and tick label locations, and set # text-table and text-orientation for y-axis tick labels: ylabels = vcs.mklabels(vcs.mkscale(min(x), max(x))) my_gm.yticlabels1 = ylabels longest_ylabels = \ max([len(ylabels.values()[i]) for i in range(len(ylabels))]) my_tpl.ytic1.x1 = bbllx - ticklength my_tpl.ytic1.x2 = bbllx my_tpl.ylabel1.x = bbllx - ticklength \ - (longest_ylabels * ticklabel_fontht * fontht2norm) my_tpl.ylabel1.texttable = ttab_yticklabel my_tpl.ylabel1.textorientation = tori_yticklabel # Position overall title, x-axis title, and y-axis title: text_title.x = [(bburx - bbllx) / 2.0 + bbllx] text_title.y = [bbury + (1.7 * title_fontht * fontht2norm)]
def plot2D(self,data1,data2,tmpl,gm): #Preserve time and z axis for plotting these inof in rendertemplate t = data1.getTime() if data1.ndim>2: z = data1.getAxis(-3) else: z = None data1 = self.trimData2D(data1) # Ok get3 only the last 2 dims if gm.g_name!="Gfm": data2 = self.trimData2D(data2) ug,xm,xM,ym,yM,continents,wrap,geo,cellData = vcs2vtk.genGrid(data1,data2,gm,deep=False) #Now applies the actual data on each cell if isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="log10": data1=numpy.ma.log10(data1) data = vcs2vtk.numpy_to_vtk_wrapper(data1.filled(0.).flat, deep=False) if cellData: ug.GetCellData().SetScalars(data) else: ug.GetPointData().SetScalars(data) try: cmap = vcs.elements["colormap"][cmap] except: cmap = vcs.elements["colormap"][self.canvas.getcolormapname()] color = getattr(gm,"missing",None) if color is not None: color = cmap.index[color] missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,color,cellData,deep=False) lut = vtk.vtkLookupTable() mn,mx=vcs.minmax(data1) #Ok now we have grid and data let's use the mapper mapper = vtk.vtkPolyDataMapper() legend = None if isinstance(gm,(meshfill.Gfm,boxfill.Gfb)): geoFilter = vtk.vtkDataSetSurfaceFilter() if cellData: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(ug) geoFilter.SetInputConnection(p2c.GetOutputPort()) else: geoFilter.SetInputData(ug) geoFilter.Update() if isinstance(gm,(isofill.Gfi,isoline.Gi,meshfill.Gfm)) or \ (isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="custom"): #Now this filter seems to create the good polydata sFilter = vtk.vtkDataSetSurfaceFilter() if cellData: # Sets data to point instead of just cells c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(ug) c2p.Update() if self.debug: vcs2vtk.dump2VTK(c2p) #For contouring duplicate points seem to confuse it if ug.IsA("vtkUntructuredGrid"): cln = vtk.vtkCleanUnstructuredGrid() cln.SetInputConnection(c2p.GetOutputPort()) if self.debug: vcs2vtk.dump2VTK(cln) sFilter.SetInputConnection(cln.GetOutputPort()) else: sFilter.SetInputConnection(c2p.GetOutputPort()) else: sFilter.SetInputData(ug) sFilter.Update() if self.debug: vcs2vtk.dump2VTK(sFilter) if isinstance(gm,isoline.Gi): cot = vtk.vtkContourFilter() if cellData: cot.SetInputData(sFilter.GetOutput()) else: cot.SetInputData(ug) levs = gm.levels if (isinstance(gm,isoline.Gi) and numpy.allclose( levs[0],[0.,1.e20])) or numpy.allclose(levs,1.e20): levs = vcs.mkscale(mn,mx) if len(levs)==1: # constant value ? levs = [levs[0],levs[0]+.00001] Ncolors = len(levs) if isinstance(gm,(isofill.Gfi,meshfill.Gfm)): levs2 = vcs.mkscale(mn,mx) if len(levs2)==1: # constant value ? levs2 = [levs2[0],levs2[0]+.00001] levs=[] for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) else: if isinstance(gm.levels[0],(list,tuple)): if isinstance(gm,isoline.Gi): levs = [x[0] for x in gm.levels] else: levs = gm.levels else: levs = [] levs2=gm.levels if numpy.allclose(levs2[0],1.e20): levs2[0]=-1.e20 for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) if isinstance(gm,isoline.Gi): levs = levs2 Nlevs=len(levs) Ncolors = Nlevs ## Figure out colors if isinstance(gm,boxfill.Gfb): cols = gm.fillareacolors if cols is None: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,(isofill.Gfi,meshfill.Gfm)): cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs2,split=0) if isinstance(cols,(int,float)): cols=[cols,] elif isinstance(gm,isoline.Gi): cols = gm.linecolors if isinstance(gm,isoline.Gi): cot.SetNumberOfContours(Nlevs) if levs[0]==1.e20: levs[0]=-1.e20 for i in range(Nlevs): cot.SetValue(i,levs[i]) cot.SetValue(Nlevs,levs[-1]) cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) mappers = [] else: mappers = [] LEVS = [] INDX = [] COLS = [] indices = gm.fillareaindices if indices is None: indices=[1,] while len(indices)<len(cols): indices.append(indices[-1]) for i,l in enumerate(levs): if i==0: C = [cols[i],] if numpy.allclose(levs[0][0],-1.e20): ## ok it's an extension arrow L=[mn-1.,levs[0][1]] else: L = list(levs[i]) I = [indices[i],] else: if l[0] == L[-1] and I[-1]==indices[i]: # Ok same type lets keep going if numpy.allclose(l[1],1.e20): L.append(mx+1.) else: L.append(l[1]) C.append(cols[i]) else: # ok we need new contouring LEVS.append(L) COLS.append(C) INDX.append(I) C = [cols[i],] L = levs[i] I = [indices[i],] LEVS.append(L) COLS.append(C) INDX.append(I) for i,l in enumerate(LEVS): # Ok here we are trying to group together levels can be, a join will happen if: # next set of levels contnues where one left off AND pattern is identical if isinstance(gm,isofill.Gfi): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() cot = vtk.vtkBandedPolyDataContourFilter() cot.ClippingOn() cot.SetInputData(sFilter.GetOutput()) cot.SetNumberOfContours(len(l)) cot.SetClipTolerance(0.) for j,v in enumerate(l): cot.SetValue(j,v) #cot.SetScalarModeToIndex() cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) lut.SetNumberOfTableValues(len(COLS[i])) for j,color in enumerate(COLS[i]): r,g,b = cmap.index[color] lut.SetTableValue(j,r/100.,g/100.,b/100.) #print l[j],vcs.colors.rgb2str(r*2.55,g*2.55,b*2.55),l[j+1] mapper.SetLookupTable(lut) mapper.SetScalarRange(0,len(l)-1) mapper.SetScalarModeToUseCellData() else: for j,color in enumerate(COLS[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j],l[j+1]) th.SetInputConnection(geoFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r,g,b = cmap.index[color] lut.SetTableValue(0,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j],l[j+1]) mappers.append([mapper,]) #png = vtk.vtkPNGReader() #png.SetFileName("/git/uvcdat/Packages/vcs/Share/uvcdat_texture.png") #T=vtk.vtkTexture() #T.SetInputConnection(png.GetOutputPort()) if isinstance(gm,isofill.Gfi): mappers.append([mapper,]) else: #Boxfill (non custom)/Meshfill if isinstance(gm,boxfill.Gfb): if numpy.allclose(gm.level_1,1.e20) or numpy.allclose(gm.level_2,1.e20): levs = vcs.mkscale(mn,mx) if len(levs)==1: # constant value ? levs = [levs[0],levs[0]+.00001] legend = vcs.mklabels(levs) dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) levs = numpy.arange(levs[0],levs[-1]+dx,dx) else: if gm.boxfill_type=="log10": levslbls = vcs.mkscale(numpy.ma.log10(gm.level_1),numpy.ma.log10(gm.level_2)) levs = vcs.mkevenlevels(numpy.ma.log10(gm.level_1), numpy.ma.log10(gm.level_2), nlev=(gm.color_2-gm.color_1)+1) else: levslbls = vcs.mkscale(gm.level_1,gm.level_2) levs = vcs.mkevenlevels(gm.level_1,gm.level_2,nlev=(gm.color_2-gm.color_1)+1) if len(levs)>25: ## Too many colors/levels need to prettyfy this for legend legend = vcs.mklabels(levslbls) ## Make sure extremes are in legd2=vcs.mklabels([levs[0],levs[-1]]) legend.update(legd2) else: legend = vcs.mklabels(levs) if gm.boxfill_type=="log10": for k in legend.keys(): legend[float(numpy.ma.log10(legend[k]))] = legend[k] del(legend[k]) #dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) #levs = numpy.arange(levs[0],levs[-1]+dx,dx) cols = range(gm.color_1,gm.color_2+1) else: if numpy.allclose(gm.levels,1.e20): levs = vcs.mkscale(mn,mx) else: levs = gm.levels if numpy.allclose(levs[0],1.e20): levs[0]=-1.e20 cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs) Nlevs = len(levs) Ncolors = Nlevs-1 #Prep mapper mappers=[] mapper = vtk.vtkPolyDataMapper() thr = vtk.vtkThreshold() thr.SetInputConnection(geoFilter.GetOutputPort()) if not gm.ext_1 in ["y",1,True] and not gm.ext_2 in ["y",1,True] : thr.ThresholdBetween(levs[0],levs[-1]) elif gm.ext_1 in ["y",1,True] and not gm.ext_2 in ["y",1,True] : thr.ThresholdByLower(levs[-1]) elif not gm.ext_1 in ["y",1,True] and gm.ext_2 in ["y",1,True] : thr.ThresholdByUpper(levs[0]) thr.Update() geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(thr.GetOutputPort()) if gm.ext_1 in ["y",1,True] and gm.ext_2 in ["y",1,True] : mapper.SetInputConnection(geoFilter.GetOutputPort()) else: mapper.SetInputConnection(geoFilter2.GetOutputPort()) if mappers == []: # ok didn't need to have special banded contours mappers=[mapper,] ## Colortable bit # make sure length match while len(cols)<Ncolors: cols.append(cols[-1]) lut.SetNumberOfTableValues(Ncolors) for i in range(Ncolors): r,g,b = cmap.index[cols[i]] lut.SetTableValue(i,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) if numpy.allclose(levs[0],-1.e20): lmn = mn-1. else: lmn= levs[0] if numpy.allclose(levs[-1],1.e20): lmx = mx+1. else: lmx= levs[-1] mapper.SetScalarRange(lmn,lmx) if missingMapper is not None: if isinstance(gm,meshfill.Gfm): mappers.append(missingMapper) else: mappers.insert(0,missingMapper) x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM) if tmpl.data.priority != 0: # And now we need actors to actually render this thing for mapper in mappers: act = vtk.vtkActor() if isinstance(mapper,list): act.SetMapper(mapper[0]) else: mapper.Update() act.SetMapper(mapper) if geo is None: act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap) if isinstance(mapper,list): #act.GetMapper().ScalarVisibilityOff() #act.SetTexture(mapper[1]) pass # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) ren = self.createRenderer() self.renWin.AddRenderer(ren) self.setLayer(ren,tmpl.data.priority) ren.AddActor(act) vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],wc=[x1,x2,y1,y2],geo=geo) if isinstance(gm,meshfill.Gfm): tmpl.plot(self.canvas,data1,gm, bg=self.bg, X=numpy.arange(xm,xM*1.1,(xM-xm)/10.), Y=numpy.arange(ym,yM*1.1,(yM-ym)/10.)) else: self.renderTemplate(tmpl,data1,gm,t,z) if isinstance(gm,(isofill.Gfi,meshfill.Gfm,boxfill.Gfb)): if getattr(gm,"legend",None) is not None: legend = gm.legend if gm.ext_1 in ["y",1,True] and not numpy.allclose(levs[0],-1.e20): if isinstance(levs,numpy.ndarray): levs=levs.tolist() if not (isinstance(levs[0],list) and numpy.less_equal(levs[0][0],-1.e20)): levs.insert(0,-1.e20) if gm.ext_2 in ["y",1,True] and not numpy.allclose(levs[-1],1.e20): if isinstance(levs,numpy.ndarray): levs=levs.tolist() if not (isinstance(levs[-1],list) and numpy.greater_equal(levs[-1][-1],1.e20)): levs.append(1.e20) self.renderColorBar(tmpl,levs,cols,legend,cmap) if self.canvas._continents is None: continents = False if continents: projection = vcs.elements["projection"][gm.projection] self.plotContinents(x1,x2,y1,y2,projection,wrap,tmpl)
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, var, theta=None, template=None, bg=0, x=None): """ Plots a polar plot of your data. If var is an ndarray with the second dimension being 2, it will use the first value as magnitude and the second as theta. Otherwise, if theta is provided, it uses var as magnitude and the theta given. """ if x is None: if self.x is None: self.x = vcs.init() x = self.x if template is None: template = self.template if self.markercolorsource.lower() not in ("group", "magnitude", "theta"): raise ValueError( "polar.markercolorsource must be one of: 'group', 'magnitude', 'theta'" ) magnitudes, thetas, names = convert_arrays(var, theta) if not self.negative_magnitude: # negative amplitude means 180 degree shift neg = numpy.ma.less(magnitudes, 0.0) magnitudes = numpy.ma.abs(magnitudes) thetas = numpy.ma.where(neg, theta + numpy.pi, theta) if self.group_names: names = self.group_names while len(names) < len(magnitudes): names.append(None) flat_magnitude = numpy.ravel(magnitudes) canvas = x # Determine aspect ratio for plotting the circle canvas_info = canvas.canvasinfo() # Calculate aspect ratio of window window_aspect = canvas_info["width"] / float(canvas_info["height"]) if window_aspect > 1: ymul = window_aspect xmul = 1 else: ymul = 1 xmul = window_aspect # Use window_aspect to adjust size of template.data x0, x1 = template.data.x1, template.data.x2 y0, y1 = template.data.y1, template.data.y2 xdiff = abs(x1 - x0) ydiff = abs(y1 - y0) center = x0 + xdiff / 2., y0 + ydiff / 2. diameter = min(xdiff, ydiff) radius = diameter / 2. plot_kwargs = {"render": False, "bg": bg, "donotstoredisplay": True} # Outer line if template.box1.priority > 0: outer = vcs.createline(source=template.box1.line) x, y = circle_points(center, radius, ratio=window_aspect) outer.x = x outer.y = y canvas.plot(outer, **plot_kwargs) del vcs.elements["line"][outer.name] if numpy.allclose((self.datawc_y1, self.datawc_y2), 1e20): if self.magnitude_ticks == "*": m_scale = vcs.mkscale(*vcs.minmax(flat_magnitude)) else: if isinstance(self.magnitude_ticks, str): ticks = vcs.elements["list"][self.magnitude_ticks] else: ticks = self.magnitude_ticks m_scale = ticks else: m_scale = vcs.mkscale(self.datawc_y1, self.datawc_y2) if template.ytic1.priority > 0: m_ticks = vcs.createline(source=template.ytic1.line) m_ticks.x = [] m_ticks.y = [] if template.ylabel1.priority > 0: to = self.text_orientation_for_angle( self.magnitude_tick_angle + self.theta_offset, source=template.ylabel1.textorientation) m_labels = self.create_text(template.ylabel1.texttable, to) m_labels.x = [] m_labels.y = [] m_labels.string = [] if self.yticlabels1 == "*": mag_labels = vcs.mklabels(m_scale) else: mag_labels = self.yticlabels1 else: m_labels = None for lev in m_scale: lev_radius = radius * self.magnitude_from_value(lev, m_scale) x, y = circle_points(center, lev_radius, ratio=window_aspect) if m_labels is not None: if lev in mag_labels: m_labels.string.append(mag_labels[lev]) m_labels.x.append(xmul * lev_radius * numpy.cos(self.magnitude_tick_angle + self.theta_offset) + center[0]) m_labels.y.append(ymul * lev_radius * numpy.sin(self.magnitude_tick_angle + self.theta_offset) + center[1]) m_ticks.x.append(x) m_ticks.y.append(y) canvas.plot(m_ticks, **plot_kwargs) del vcs.elements["line"][m_ticks.name] if m_labels is not None: canvas.plot(m_labels, **plot_kwargs) del vcs.elements["textcombined"][m_labels.name] if template.ymintic1.priority > 0 and self.magnitude_mintics is not None: mag_mintics = vcs.createline(source=template.ymintic1.line) mag_mintics.x = [] mag_mintics.y = [] mintics = self.magnitude_mintics if isinstance(mintics, str): mintics = vcs.elements["list"][mintics] for mag in mintics: mintic_radius = radius * \ self.magnitude_from_value(mag, m_scale) x, y = circle_points(center, mintic_radius, ratio=window_aspect) mag_mintics.x.append(x) mag_mintics.y.append(y) canvas.plot(mag_mintics, **plot_kwargs) del vcs.elements["line"][mag_mintics.name] if self.xticlabels1 == "*": if numpy.allclose((self.datawc_x1, self.datawc_x2), 1e20): tick_thetas = list(numpy.arange(0, numpy.pi * 2, numpy.pi / 4)) tick_labels = {t: str(t) for t in tick_thetas} else: d_theta = (self.datawc_x2 - self.datawc_x1) / \ float(self.theta_tick_count) tick_thetas = numpy.arange(self.datawc_x1, self.datawc_x2 + .0001, d_theta) tick_labels = vcs.mklabels(tick_thetas) else: tick_thetas = sorted(list(self.xticlabels1.keys())) tick_labels = self.xticlabels1 if template.xtic1.priority > 0: t_ticks = vcs.createline(source=template.xtic1.line) t_ticks.x = [] t_ticks.y = [] if template.xlabel1.priority > 0: t_labels = [] theta_labels = tick_labels else: t_labels = None for t in tick_thetas: angle = self.theta_from_value(t) x0 = center[0] + (xmul * radius * numpy.cos(angle)) x1 = center[0] y0 = center[1] + (ymul * radius * numpy.sin(angle)) y1 = center[1] if t_labels is not None: label = self.create_text( template.xlabel1.texttable, self.text_orientation_for_angle( angle, source=template.xlabel1.textorientation)) label.string = [theta_labels[t]] label.x = [x0] label.y = [y0] t_labels.append(label) t_ticks.x.append([x0, x1]) t_ticks.y.append([y0, y1]) canvas.plot(t_ticks, **plot_kwargs) del vcs.elements["line"][t_ticks.name] if t_labels is not None: for l in t_labels: canvas.plot(l, **plot_kwargs) del vcs.elements["textcombined"][l.name] values = vcs.createmarker() values.type = self.markertypes values.size = self.markersizes values.color = self.markercolors values.colormap = self.colormap values.priority = self.markerpriority values.x = [] values.y = [] if template.legend.priority > 0: # Only labels that are set will show up in the legend label_count = len(names) - len([i for i in names if i is None]) labels = self.create_text(template.legend.texttable, template.legend.textorientation) labels.x = [] labels.y = [] labels.string = [] if self.linepriority > 0: line = vcs.createline() line.x = [] line.y = [] line.type = self.linetypes line.color = self.linecolors if self.linecolors is not None else self.markercolors line.width = self.linewidths line.priority = self.linepriority # This is up here because when it's part of the main loop, we can # lose "order" of points when we flatten them. for mag, theta in zip(magnitudes, thetas): x = [] y = [] for m, t in zip(mag, theta): t = self.theta_from_value(t) r = self.magnitude_from_value(m, m_scale) * radius if r == numpy.nan: continue x.append(xmul * numpy.cos(t) * r + center[0]) y.append(ymul * numpy.sin(t) * r + center[1]) if self.connect_groups: line.x.extend(x) line.y.extend(y) else: line.x.append(x) line.y.append(y) if self.markercolorsource.lower() in ('magnitude', "theta"): # Regroup the values using the appropriate metric mag_flat = numpy.array(magnitudes).flatten() theta_flat = numpy.array(thetas).flatten() if self.markercolorsource.lower() == "magnitude": scale = m_scale vals = mag_flat else: scale = tick_thetas vals = theta_flat indices = [ numpy.where( numpy.logical_and(vals >= scale[i], vals <= scale[i + 1])) for i in range(len(scale) - 1) ] magnitudes = [mag_flat[inds] for inds in indices] thetas = [theta_flat[inds] for inds in indices] names = vcs.mklabels(scale, output="list") names = [ names[i] + " - " + names[i + 1] for i in range(len(names) - 1) ] label_count = len(names) for mag, theta, name in zip(magnitudes, thetas, names): x = [] y = [] for m, t in zip(mag, theta): t = self.theta_from_value(t) r = self.magnitude_from_value(m, m_scale) * radius x.append(xmul * numpy.cos(t) * r + center[0]) y.append(ymul * numpy.sin(t) * r + center[1]) if template.legend.priority > 0 and name is not None: y_offset = len(labels.x) / float(label_count) * \ (template.legend.y2 - template.legend.y1) lx, ly = template.legend.x1, template.legend.y1 + y_offset x.append(lx) y.append(ly) labels.x.append(lx + .01) labels.y.append(ly) labels.string.append(str(name)) values.x.append(x) values.y.append(y) if template.legend.priority > 0: canvas.plot(labels, **plot_kwargs) del vcs.elements["textcombined"][labels.name] if self.linepriority > 0: canvas.plot(line, **plot_kwargs) del vcs.elements["line"][line.name] for el in self.to_cleanup: if vcs.istexttable(el): if el.name in vcs.elements["texttable"]: del vcs.elements["texttable"][el.name] else: if el.name in vcs.elements["textorientation"]: del vcs.elements["textorientation"][el.name] self.to_cleanup = [] # Prune unneeded levels from values to_prune = [] for ind, (x, y) in enumerate(zip(values.x, values.y)): if x and y: continue else: to_prune.append(ind) for prune_ind in to_prune[::-1]: del values.x[prune_ind] del values.y[prune_ind] if len(values.color) > prune_ind and len(values.color) > 1: del values.color[prune_ind] if len(values.size) > prune_ind and len(values.size) > 1: del values.size[prune_ind] if len(values.type) > prune_ind and len(values.type) > 1: del values.type[prune_ind] canvas.plot(values, bg=bg, donotstoredisplay=True) del vcs.elements["marker"][values.name] return canvas
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 t.legend.x1 = t.data.x2 + .03 t.legend.x2 = t.legend.x1 + .03 t.legend.y1 = t.data.y1 + .05
def axisToPngCoords(values, gm, template, axis='x1', worldCoordinates=[0, 360, -90, 90], png=None, geometry=None): """ Given a set of axis values/labels, a graphic method and a template, maps each label to an area on pmg Warning does not handle projections yet. :Example: .. doctest:: utils_axisToPngCoords >>> a=vcs.init(bg=True) >>> box=vcs.createboxfill() >>> array=[range(10) for _ in range(10)] >>> a.plot(box,array) # plot something on canvas <vcs.displayplot.Dp ...> >>> a.png('box.png', width=1536, height=1186) # make a png >>> fnm = cdat_info.get_sampledata_path()+"/clt.nc" >>> f=cdms2.open(fnm) >>> clt=f("clt",time=slice(0,1),squeeze=1) >>> box = vcs.createboxfill() >>> template = vcs.createtemplate() >>> areas = axisToPngCoords(clt.getLongitude(), box, template) """ if png is None and geometry is None: x = vcs.init() x.open() ci = x.canvasinfo() x.close() del (x) pwidth = width = ci["width"] pheight = height = ci["height"] if png is not None: pwidth, pheight = getPngDimensions(png) if geometry is None: width, height = pwidth, pheight if geometry is not None: width, height = geometry if isinstance(template, str): template = vcs.gettemplate(template) x = vcs.init(geometry=(width, height), bg=True) # x/y ratio to original png xRatio = float(width) / pwidth yRatio = float(height) / pheight # Prepare dictionary of values, labels pairs mapped = [] direction = axis[0] if direction == "x": other_direction = "y" c1 = int(width * template.data.x1 * xRatio) c2 = int(width * template.data.x2 * xRatio) else: other_direction = "x" c1 = int(height * template.data.y1 * yRatio) c2 = int(height * template.data.y2 * yRatio) location = axis[-1] datawc1 = getattr(gm, "datawc_{}1".format(direction)) if datawc1 == 1.e20: start = values[0] end = values[-1] else: start = datawc1 end = getattr(gm, "datawc_{}2".format(direction)) label = getattr(template, "{}label{}".format(direction, location)) Tt_source = label.texttable To_source = label.textorientation text = vcs.createtext(Tt_source=Tt_source, To_source=To_source) setattr(text, other_direction, getattr(label, other_direction)) if direction == "x": text.worldcoordinate = [start, end, 0, 1] else: text.worldcoordinate = [0, 1, start, end] ticlabels = getattr(gm, "{}ticlabels{}".format(direction, location)) if ticlabels == "*": lbls = vcs.mklabels(vcs.mkscale(start, end)) else: lbls = ticlabels # now loops thru all labels and get extents for v, l in lbls.items(): if start <= v and v <= end: text.string = str(l) setattr(text, direction, v) box = x.gettextbox(text)[0] if direction == "x": xs = worldToPixel(box[0], start, end, c1, c2).tolist() ys = [height * yRatio * (1 - c) for c in box[1]] else: xs = [width * xRatio * c for c in box[0]] ys = (height * yRatio - worldToPixel(box[1], start, end, c1, c2)).tolist() mapped.append([xs, ys]) return numpy.array(mapped)
s = f('Data') x = vcs.init() x.scriptrun( os.path.join( cdms.__path__[0], '..', '..', '..', '..', 'bin', 'ASD.scr')) m = x.getmeshfill('ASD') m.wrap = [0, 360] m.mesh = 'y' # mn,mx=vcs.minmax(s) levs = vcs.mkscale(-10, 30) # print levs levs = vcs.mkevenlevels(levs[0], levs[-1], 256) levs2 = levs[::25] if levs2[-1] != levs[-1]: levs2.append(levs[-1]) lbls = vcs.mklabels(levs2) # print levs m.legend = lbls m.levels = levs[::-1] m.fillareacolors = vcs.getcolors(levs) # m.list() x.plot(s, M, m, bg=support.bg) support.check_plot(x)
def plotIsos(self, template=None, bg=0): if template is None: template = "thdiags_template" elif not isinstance(template, type("")): template = template.name try: isotemplate = self.x.createtemplate(template) except: isotemplate = self.x.gettemplate(template) att = dir(isotemplate) for a in att: try: b = getattr(isotemplate, a) setattr(b, "priority", 0) except: pass isotemplate.data.priority = 1 isotemplate.box1.priority = 1 isotemplate.box1.x1 = isotemplate.data.x1 isotemplate.box1.x2 = isotemplate.data.x2 isotemplate.box1.y1 = isotemplate.data.y1 isotemplate.box1.y2 = isotemplate.data.y2 dX = self.xmax - self.xmin dY = self.ymax - self.ymin X = numpy.ma.arange(self.detail, dtype=MV2.float) X = X * dX / (self.detail - 1) + self.xmin Xaxis = cdms2.createAxis(X) X = numpy.ma.resize(X, (self.detail, self.detail)) Y = numpy.ma.arange(self.detail, dtype=MV2.float) Y = Y * dY / (self.detail - 1) + self.ymin Yaxis = cdms2.createAxis(Y) Y = numpy.ma.resize(Y, (self.detail, self.detail)) Y = numpy.ma.transpose(Y) # Computes T,P on this grid T, P = self.XY2TP(X, Y) T = MV2.array(T) # Potential Temperature Tp = T / numpy.ma.power(P / 100000.0, self.k) ws = Ws(T, P) # Seems like we need not ws after 600mb ws = numpy.ma.masked_where(numpy.ma.less(P, self.Pmaxmixingratio * 100.0), ws) T = T - 273.16 Tmin, Tmax = vcs.minmax(T) Tvalues = self.isotherms.level if Tvalues == [[0.0, 1.0000000200408773e20]]: Tvalues = vcs.mkscale(Tmin, Tmax) # Now sets the isothermsfilled Tvalues2 = [] for i in range(len(Tvalues) / 2 - 1): t1, t2 = Tvalues[2 * i], Tvalues[2 * i + 1] if isinstance(t1, (list, tuple)): t1, t2 = t1[0], t2[0] Tvalues2.append([t1, t2]) else: Tvalues2 = self.isothermsfilled.levels self.setIso(self.isotherms, Tvalues) # self.setIso(self.isothermsfilled,Tvalues2) P = P / 100.0 Pvalues = vcs.mkscale(self.datawc_y2, self.datawc_y1) self.setIso(self.isobars, Pvalues) Tp = Tp - 273.16 Tpvalues = self.dryadiabats.level if Tpvalues == [[0.0, 1.0000000200408773e20]]: min, max = vcs.minmax(Tp) Tpvalues = vcs.mkscale(min, max) self.setIso(self.dryadiabats, Tpvalues) # Pseudoadiabats Thevalues = self.pseudoadiabats.level if Thevalues == [[0.0, 1.0000000200408773e20]]: Thevalues = vcs.mkevenlevels(-40, 40, 40) self.setIso(self.pseudoadiabats, Thevalues) # Mixing Ratio ws = ws * 1000.0 wsvalues = self.mixingratio.level if wsvalues == [[0.0, 1.0000000200408773e20]]: min, max = vcs.minmax(ws) wsvalues = vcs.mkscale(min, max) self.setIso(self.mixingratio, wsvalues) # Figures out where to plot the P labels dicP = {} dicPl = vcs.mklabels(Pvalues) for p in Pvalues: X, Y = self.TP2XY(self.datawc_x1 + 273.15, p * 100) if not numpy.ma.isMA(X): dicP[Y] = dicPl[p] try: ttp = self.x.createtexttable("Plabels") except: ttp = self.x.gettexttable("Plabels") ttp.color = self.isobars.linecolors[0] isotemplate.ylabel1.texttable = ttp dicT = {} Tvalues = list(numpy.ma.array(Tvalues).filled().ravel()) dicTl = vcs.mklabels(Tvalues) for t in Tvalues: X, Y = self.TP2XY(t + 273.15, self.datawc_y1 * 100) dicT[X] = dicTl[t] try: ttp = self.x.createtexttable("Tlabels") except: ttp = self.x.gettexttable("Tlabels") ttp.color = self.isotherms.linecolors[0] isotemplate.xlabel1.texttable = ttp isotemplate.ylabel1.priority = 1 isotemplate.xlabel1.priority = 1 isotemplate.data.x1 = isotemplate.data.x1 isotemplate.data.x2 = isotemplate.data.x2 isotemplate.data.y1 = isotemplate.data.y1 isotemplate.data.y2 = isotemplate.data.y2 self.isotherms.yticlabels1 = dicP self.isotherms.xticlabels1 = dicT self.isobars.yticlabels1 = {} self.isobars.xticlabels1 = {} self.dryadiabats.yticlabels1 = {} self.dryadiabats.xticlabels1 = {} self.pseudoadiabats.yticlabels1 = {} self.pseudoadiabats.xticlabels1 = {} self.mixingratio.yticlabels1 = {} self.mixingratio.xticlabels1 = {} self.isothermsfilled.datawc_x1 = self.isothermsfilled.datawc_x1 self.isothermsfilled.datawc_x2 = self.isothermsfilled.datawc_x2 self.isothermsfilled.datawc_y1 = self.isothermsfilled.datawc_y1 self.isothermsfilled.datawc_x2 = self.isothermsfilled.datawc_y2 # Puts the dims on it T.id = "T" T.setAxis(0, Yaxis) T.setAxis(1, Xaxis) P = MV2.array(P) P.id = "P" P.setAxis(0, Yaxis) P.setAxis(1, Xaxis) Tp = MV2.array(Tp) Tp.setAxis(0, Yaxis) Tp.setAxis(1, Xaxis) ws = MV2.array(ws) ws.setAxis(0, Yaxis) ws.setAxis(1, Xaxis) # plot if self.drawisothermsfilled: if self.drawisothermsfilled: self.displays.append(self.x.plot(T, isotemplate, self.isothermsfilled, bg=bg)) if self.drawisotherms: self.displays.append(self.x.plot(T, isotemplate, self.isotherms, bg=bg)) if self.drawisobars: self.displays.append(self.x.plot(P, isotemplate, self.isobars, bg=bg)) if self.drawdryadiabats: self.displays.append(self.x.plot(Tp, isotemplate, self.dryadiabats, bg=bg)) if self.drawpseudoadiabats: self.plot_pseudo(isotemplate, bg=bg) if self.drawmixingratio: self.displays.append(self.x.plot(ws, isotemplate, self.mixingratio, bg=bg)) return
import sys import os import support f = cdms.open( os.path.join(cdms.__path__[0], '..', '..', '..', '..', 'sample_data', 'meshfill.nc')) M = f('Mesh') s = f('Data') x = vcs.init() x.scriptrun( os.path.join(cdms.__path__[0], '..', '..', '..', '..', 'bin', 'ASD.scr')) m = x.getmeshfill('ASD') m.wrap = [0, 360] m.mesh = 'y' #mn,mx=vcs.minmax(s) levs = vcs.mkscale(-10, 30) #print levs levs = vcs.mkevenlevels(levs[0], levs[-1], 256) levs2 = levs[::25] if levs2[-1] != levs[-1]: levs2.append(levs[-1]) lbls = vcs.mklabels(levs2) #print levs m.legend = lbls m.levels = levs[::-1] m.fillareacolors = vcs.getcolors(levs) ## m.list() x.plot(s, M, m, bg=support.bg) support.check_plot(x)
def plot(self, array, template=None, bg=False, render=True, x=None): """Parallel Coordinates plot array must be of shape: (...,Dim1,Nlines) """ if not array.ndim > 1: raise Exception("Array must be at least 2D") nlines = array.shape[-1] length = array.shape[-2] # Pad attributes related to Y axis for att in ["datawc_y1", "datawc_y2", "yticlabels"]: # prepare local lists exec("%s = list(self.%s)" % (att, att)) exec("while len(%s) < length: %s+=[%s[-1]]" % (att, att, att)) data = array.asma() maxs = numpy.ma.max(data, axis=-1) mins = numpy.ma.min(data, axis=-1) if template is not None: t = vcs.createtemplate(source=template) else: t = vcs.createtemplate(source=self.template) for i in range(length): levels = vcs.mkscale(mins[i], maxs[i]) # Do we need to create our range if numpy.allclose(datawc_y1[i], 1.e20): # noqa datawc_y1[i] = levels[0] # noqa datawc_y2[i] = levels[-1] # noqa maxs[i] = datawc_y2[i] # noqa mins[i] = datawc_y1[i] # noqa # Do we have tics? if yticlabels[i] == "*": # noqa yticlabels[i] = vcs.mklabels(levels) # noqa if x is None: x = self.x self.drawYAxes(mins, maxs, yticlabels, t, x, bg) # noqa ax = array.getAxis(-2) deflbls = {} for i in range(length): deflbls[float(i) / (length - 1)] = str(ax[i]) if hasattr(ax, "units") and isinstance(ax.units, (list, tuple)): deflbls[float(i) / (length - 1)] += " (%s)" % ax.units[i] if self.xticlabels1 == "*": lbls1 = deflbls else: lbls1 = self.xticlabels1 if self.xmtics1 == "": lbls1m = deflbls else: lbls1m = self.xmtics1 if self.xticlabels2 == "*": lbls2 = deflbls else: lbls2 = self.xticlabels2 if self.xmtics2 == "": lbls2m = deflbls else: lbls2m = self.xmtics2 for l_tmp, lbls in enumerate([lbls1, lbls1m, lbls2, lbls2m]): ln = x.createline(source=t.xtic1.line) xs = [] ys = [] if l_tmp % 2 == 0: if l_tmp == 0: txt = x.createtext(To_source=t.xlabel1.textorientation, Tt_source=t.xlabel1.texttable) else: txt = x.createtext(To_source=t.xlabel2.textorientation, Tt_source=t.xlabel2.texttable) txs = [] tys = [] ts = [] for loc in lbls: xs.append([loc, loc]) if l_tmp == 0: ys.append([t.xtic1.y1, t.xtic1.y2]) txs.append(loc) tys.append(t.xlabel1.y) ts.append(lbls[loc]) ln.priority = t.xtic1.priority txt.priority = t.xlabel1.priority elif l_tmp == 1: ys.append([t.xmintic1.y1, t.xmintic1.y2]) ln.priority = t.xmintic1.priority elif l_tmp == 2: ys.append([t.xtic2.y1, t.xtic2.y2]) txs.append(loc) tys.append(t.xlabel2.y) ts.append(lbls[loc]) ln.priority = t.xtic2.priority txt.priority = t.xlabel2.priority elif l_tmp == 3: ys.append([t.xmintic2.y1, t.xmintic2.y2]) ln.priority = t.xmintic2.priority ln.x = xs ln.y = ys ln.viewport = [t.data.x1, t.data.x2, 0, 1] x.plot(ln, bg=bg, render=False) if l_tmp % 2 == 0: # text on txt.viewport = ln.viewport txt.x = txs txt.y = tys txt.string = ts x.plot(txt, bg=bg, render=False) # Normalizes deltas = maxs - mins data = (data - mins[:, numpy.newaxis]) / deltas[:, numpy.newaxis] # Pad attributes related to number of lines lineAtts = ["linetypes", "linewidths", "markertypes", "markersizes"] if self.markercolors is not None: lineAtts.append("markercolors") if self.linecolors is not None: lineAtts.append("linecolors") for att in lineAtts: # prepare local lists exec("%s = list(self.%s)" % (att, att)) exec("while len(%s) < nlines: %s+=[%s[-1]]" % (att, att, att)) if self.linecolors is None: linecolors = vcs.getcolors(list(range(nlines + 1))) if self.markercolors is None: markercolors = vcs.getcolors(list(range(nlines + 1))) # Mark fully missing models scratched = [] for i in range(nlines): if data[:, i].count() > 0: scratched.append(False) else: scratched.append(True) # Now draws the legend t.drawLinesAndMarkersLegend( x, linecolors, linetypes, linewidths, # noqa markercolors, markertypes, markersizes, # noqa [str(v) for v in array.getAxis(-1)], bg=bg, render=False, scratched=scratched) lst = ["max", "min", "mean"] t.blank(lst) t.drawAttributes(x, array, self, bg=bg) t.blank() t.data.priority = 1 for i in range(nlines): if data[:, i].count() > 0: ln_tmp = vcs.create1d() ln_tmp.colormap = self.colormap ln_tmp.linecolor = linecolors[i] ln_tmp.linewidth = linewidths[i] # noqa ln_tmp.linetype = linetypes[i] # noqa ln_tmp.marker = markertypes[i] # noqa ln_tmp.markercolor = markercolors[i] ln_tmp.markersize = markersizes[i] # noqa ln_tmp.datawc_y1 = 0. ln_tmp.datawc_y2 = 1. if i < nlines - 1: x.plot(data[:, i], t, ln_tmp, bg=bg, render=False) else: x.plot(data[:, i], t, ln_tmp, bg=bg, render=render)
def createTemplateandGM(x, min, max, deltaisof=None, deltaisol=None, days_line=( 30, 6, 3, 2, ), 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 BaseException: 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.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) tmpl.legend.x1 = tmpl.data.x1 * 1.1 tmpl.legend.x2 = tmpl.data.x2 * .985 tmplnoleg = x.createtemplate(source=tmpl.name) tmplnoleg.legend.priority = 0 isof = x.createisofill() if deltaisof is None: levs2 = vcs.mkscale(min, max) else: levs2 = list(numpy.arange(min, max, deltaisof)) for i, v in enumerate(levs2): if numpy.allclose(v, 0.): levs2[i] = 0. if deltaisol is None: levs1a = vcs.mkscale(min, 0) levs1b = vcs.mkscale(0, max) else: levs1a = list(numpy.arange(min, 0, deltaisol)) levs1b = list(numpy.arange(0, max, deltaisol)) isof.levels = levs2 colors = vcs.getcolors(levs2, colors=list(range(16, 40)), white="white") lbls = vcs.mklabels(levs2) isof.legend = lbls isof.fillareacolors = colors levs1a = list(numpy.arange(min, 0, deltaisol)) levs1b = list(numpy.arange(0, max, deltaisol)) isol1 = x.createisoline() isol1.level = levs1a isol1.label = 'y' isol1.linetypes = ['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 plot(self, var, theta=None, template=None, bg=0, x=None): """ Plots a polar plot of your data. If var is an ndarray with the second dimension being 2, it will use the first value as magnitude and the second as theta. Otherwise, if theta is provided, it uses var as magnitude and the theta given. """ if x is None: if self.x is None: self.x = vcs.init() x = self.x if template is None: template = self.template if self.markercolorsource.lower() not in ("group", "magnitude", "theta"): raise ValueError("polar.markercolorsource must be one of: 'group', 'magnitude', 'theta'") magnitudes, thetas, names = convert_arrays(var, theta) if self.group_names: names = self.group_names while len(names) < len(magnitudes): names.append(None) flat_magnitude = [] for i in magnitudes: flat_magnitude.extend(i) flat_theta = [] for i in thetas: flat_theta.extend(i) canvas = x # Determine aspect ratio for plotting the circle canvas_info = canvas.canvasinfo() # Calculate aspect ratio of window window_aspect = canvas_info["width"] / float(canvas_info["height"]) if window_aspect > 1: ymul = window_aspect xmul = 1 else: ymul = 1 xmul = window_aspect # Use window_aspect to adjust size of template.data x0, x1 = template.data.x1, template.data.x2 y0, y1 = template.data.y1, template.data.y2 xdiff = abs(x1 - x0) ydiff = abs(y1 - y0) center = x0 + xdiff / 2., y0 + ydiff / 2. diameter = min(xdiff, ydiff) radius = diameter / 2. plot_kwargs = {"render": False, "bg": bg, "donotstoredisplay": True} # Outer line if template.box1.priority > 0: outer = vcs.createline(source=template.box1.line) x, y = circle_points(center, radius, ratio=window_aspect) outer.x = x outer.y = y canvas.plot(outer, **plot_kwargs) del vcs.elements["line"][outer.name] if numpy.allclose((self.datawc_y1, self.datawc_y2), 1e20): if self.magnitude_ticks == "*": m_scale = vcs.mkscale(*vcs.minmax(flat_magnitude)) else: if isinstance(self.magnitude_ticks, (str, unicode)): ticks = vcs.elements["list"][self.magnitude_ticks] else: ticks = self.magnitude_ticks m_scale = ticks else: m_scale = vcs.mkscale(self.datawc_y1, self.datawc_y2) if template.ytic1.priority > 0: m_ticks = vcs.createline(source=template.ytic1.line) m_ticks.x = [] m_ticks.y = [] if template.ylabel1.priority > 0: to = self.text_orientation_for_angle(self.magnitude_tick_angle, source=template.ylabel1.textorientation) m_labels = self.create_text(template.ylabel1.texttable, to) m_labels.x = [] m_labels.y = [] m_labels.string = [] if self.yticlabels1 == "*": mag_labels = vcs.mklabels(m_scale) else: mag_labels = self.yticlabels1 else: m_labels = None for lev in m_scale: lev_radius = radius * self.magnitude_from_value(lev, (m_scale[0], m_scale[-1])) x, y = circle_points(center, lev_radius, ratio=window_aspect) if m_labels is not None: if lev in mag_labels: m_labels.string.append(mag_labels[lev]) m_labels.x.append(xmul * lev_radius * numpy.cos(self.magnitude_tick_angle) + center[0]) m_labels.y.append(ymul * lev_radius * numpy.sin(self.magnitude_tick_angle) + center[1]) m_ticks.x.append(x) m_ticks.y.append(y) canvas.plot(m_ticks, **plot_kwargs) del vcs.elements["line"][m_ticks.name] if m_labels is not None: canvas.plot(m_labels, **plot_kwargs) del vcs.elements["textcombined"][m_labels.name] if template.ymintic1.priority > 0 and self.magnitude_mintics is not None: mag_mintics = vcs.createline(source=template.ymintic1.line) mag_mintics.x = [] mag_mintics.y = [] mintics = self.magnitude_mintics if isinstance(mintics, (str, unicode)): mintics = vcs.elements["list"][mintics] for mag in mintics: mintic_radius = radius * self.magnitude_from_value(mag, (m_scale[0], m_scale[-1])) x, y = circle_points(center, mintic_radius, ratio=window_aspect) mag_mintics.x.append(x) mag_mintics.y.append(y) canvas.plot(mag_mintics, **plot_kwargs) del vcs.elements["line"][mag_mintics.name] if self.xticlabels1 == "*": if numpy.allclose((self.datawc_x1, self.datawc_x2), 1e20): tick_thetas = list(numpy.arange(0, numpy.pi * 2, numpy.pi / 4)) tick_labels = {t: str(t) for t in tick_thetas} else: d_theta = (self.datawc_x2 - self.datawc_x1) / float(self.theta_tick_count) tick_thetas = numpy.arange(self.datawc_x1, self.datawc_x2 + .0001, d_theta) tick_labels = vcs.mklabels(tick_thetas) else: tick_thetas = self.xticlabels1.keys() tick_labels = self.xticlabels1 if template.xtic1.priority > 0: t_ticks = vcs.createline(source=template.xtic1.line) t_ticks.x = [] t_ticks.y = [] if template.xlabel1.priority > 0: t_labels = [] theta_labels = tick_labels else: t_labels = None for t in tick_thetas: angle = self.theta_from_value(t) x0 = center[0] + (xmul * radius * numpy.cos(angle)) x1 = center[0] y0 = center[1] + (ymul * radius * numpy.sin(angle)) y1 = center[1] if t_labels is not None: label = self.create_text(template.xlabel1.texttable, self.text_orientation_for_angle(angle, source=template.xlabel1.textorientation)) label.string = [theta_labels[t]] label.x = [x0] label.y = [y0] t_labels.append(label) t_ticks.x.append([x0, x1]) t_ticks.y.append([y0, y1]) canvas.plot(t_ticks, **plot_kwargs) del vcs.elements["line"][t_ticks.name] if t_labels is not None: for l in t_labels: canvas.plot(l, **plot_kwargs) del vcs.elements["textcombined"][l.name] values = vcs.createmarker() values.type = self.markers values.size = self.markersizes values.color = self.markercolors values.colormap = self.colormap values.priority = self.markerpriority values.x = [] values.y = [] if template.legend.priority > 0: # Only labels that are set will show up in the legend label_count = len(names) - len([i for i in names if i is None]) labels = self.create_text(template.legend.texttable, template.legend.textorientation) labels.x = [] labels.y = [] labels.string = [] if self.draw_lines: line = vcs.createline() line.x = [] line.y = [] line.type = self.lines line.color = self.linecolors if self.linecolors is not None else self.markercolors line.width = self.linewidths line.priority = self.linepriority # This is up here because when it's part of the main loop, we can lose "order" of points when we flatten them. for mag, theta in zip(magnitudes, thetas): x = [] y = [] for m, t in zip(mag, theta): t = self.theta_from_value(t) r = self.magnitude_from_value(m, (m_scale[0], m_scale[-1])) * radius x.append(xmul * numpy.cos(t) * r + center[0]) y.append(ymul * numpy.sin(t) * r + center[1]) if self.connect_groups: line.x.extend(x) line.y.extend(y) else: line.x.append(x) line.y.append(y) if self.markercolorsource.lower() in ('magnitude', "theta"): # Regroup the values using the appropriate metric mag_flat = numpy.array(magnitudes).flatten() theta_flat = numpy.array(thetas).flatten() if self.markercolorsource.lower() == "magnitude": scale = m_scale vals = mag_flat else: scale = theta_ticks vals = theta_flat indices = [numpy.where(numpy.logical_and(vals >= scale[i], vals <= scale[i + 1])) for i in range(len(scale) - 1)] magnitudes = [mag_flat[inds] for inds in indices] thetas = [theta_flat[inds] for inds in indices] names = vcs.mklabels(scale, output="list") names = [names[i] + " - " + names[i + 1] for i in range(len(names) - 1)] label_count = len(names) for mag, theta, name in zip(magnitudes, thetas, names): x = [] y = [] for m, t in zip(mag, theta): t = self.theta_from_value(t) r = self.magnitude_from_value(m, (m_scale[0], m_scale[-1])) * radius x.append(xmul * numpy.cos(t) * r + center[0]) y.append(ymul * numpy.sin(t) * r + center[1]) if template.legend.priority > 0 and name is not None: y_offset = len(labels.x) / float(label_count) * (template.legend.y2 - template.legend.y1) lx, ly = template.legend.x1, template.legend.y1 + y_offset x.append(lx) y.append(ly) labels.x.append(lx + .01) labels.y.append(ly) labels.string.append(str(name)) values.x.append(x) values.y.append(y) if template.legend.priority > 0: canvas.plot(labels, **plot_kwargs) del vcs.elements["textcombined"][labels.name] if self.draw_lines: canvas.plot(line, **plot_kwargs) del vcs.elements["line"][line.name] for el in self.to_cleanup: if vcs.istexttable(el): if el.name in vcs.elements["texttable"]: del vcs.elements["texttable"][el.name] else: if el.name in vcs.elements["textorientation"]: del vcs.elements["textorientation"][el.name] self.to_cleanup = [] # Prune unneeded levels from values to_prune = [] for ind, (x, y) in enumerate(zip(values.x, values.y)): if x and y: continue else: to_prune.append(ind) for prune_ind in to_prune[::-1]: del values.x[prune_ind] del values.y[prune_ind] if len(values.color) > prune_ind and len(values.color) > 1: del values.color[prune_ind] if len(values.size) > prune_ind and len(values.size) > 1: del values.size[prune_ind] if len(values.type) > prune_ind and len(values.type) > 1: del values.type[prune_ind] canvas.plot(values, bg=bg, donotstoredisplay=True) del vcs.elements["marker"][values.name] return canvas
def plot2D(self,data1,data2,tmpl,gm,ren): self.setLayer(ren,tmpl.data.priority) ug,xm,xM,ym,yM,continents,wrap = vcs2vtk.genUnstructuredGrid(data1,data2,gm) #Now applies the actual data on each cell if isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="log10": data1=numpy.ma.log10(data1) data = VN.numpy_to_vtk(data1.filled(0.).flat,deep=True) if ug.IsA("vtkUnstructuredGrid"): ug.GetCellData().SetScalars(data) else: ug.GetPointData().SetScalars(data) try: cmap = vcs.elements["colormap"][cmap] except: cmap = vcs.elements["colormap"][self.canvas.getcolormapname()] color = getattr(gm,"missing",None) if color is not None: color = cmap.index[color] missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,color) lut = vtk.vtkLookupTable() mn,mx=vcs.minmax(data1) #Ok now we have grid and data let's use the mapper mapper = vtk.vtkPolyDataMapper() legend = None if isinstance(gm,boxfill.Gfb): geoFilter = vtk.vtkGeometryFilter() if ug.IsA("vtkUnstructuredGrid"): geoFilter.SetInputData(ug) else: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(ug) geoFilter = vtk.vtkDataSetSurfaceFilter() geoFilter.SetInputConnection(p2c.GetOutputPort()) geoFilter.Update() if isinstance(gm,(isofill.Gfi,isoline.Gi,meshfill.Gfm)) or \ (isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="custom"): if ug.IsA("vtkUnstructuredGrid"): # Sets data to point instead of just cells c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(ug) c2p.Update() if self.debug: vcs2vtk.dump2VTK(c2p) #For contouring duplicate points seem to confuse it cln = vtk.vtkCleanUnstructuredGrid() cln.SetInputConnection(c2p.GetOutputPort()) if self.debug: vcs2vtk.dump2VTK(cln) #Now this filter seems to create the good polydata sFilter = vtk.vtkDataSetSurfaceFilter() if ug.IsA("vtkUnstructuredGrid"): sFilter.SetInputConnection(cln.GetOutputPort()) else: sFilter.SetInputData(ug) sFilter.Update() if self.debug: vcs2vtk.dump2VTK(sFilter) if isinstance(gm,isoline.Gi): cot = vtk.vtkContourFilter() if ug.IsA("vtkUnstructuredGrid"): cot.SetInputData(sFilter.GetOutput()) else: cot.SetInputData(ug) levs = gm.levels if (isinstance(gm,isoline.Gi) and numpy.allclose( levs[0],[0.,1.e20])) or numpy.allclose(levs,1.e20): levs = vcs.mkscale(mn,mx) Ncolors = len(levs) if isinstance(gm,(isofill.Gfi,meshfill.Gfm)): levs2 = vcs.mkscale(mn,mx) levs=[] for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) else: if isinstance(gm.levels[0],(list,tuple)): if isinstance(gm,isoline.Gi): levs = [x[0] for x in gm.levels] else: levs = gm.levels else: levs = [] levs2=gm.levels if numpy.allclose(levs2[0],1.e20): levs2[0]=-1.e20 for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) if isinstance(gm,isoline.Gi): levs = levs2 Nlevs=len(levs) Ncolors = Nlevs ## Figure out colors if isinstance(gm,boxfill.Gfb): cols = gm.fillareacolors if cols is None: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,isofill.Gfi): cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,isoline.Gi): cols = gm.linecolors if isinstance(gm,isoline.Gi): cot.SetNumberOfContours(Nlevs) if levs[0]==1.e20: levs[0]=-1.e20 for i in range(Nlevs): cot.SetValue(i,levs[i]) cot.SetValue(Nlevs,levs[-1]) cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) mappers = [] else: mappers = [] LEVS = [] INDX = [] COLS = [] indices = gm.fillareaindices if indices is None: indices=[1,] while len(indices)<len(cols): indices.append(indices[-1]) for i,l in enumerate(levs): if i==0: C = [cols[i],] if numpy.allclose(levs[0][0],-1.e20): ## ok it's an extension arrow L=[mn-1.,levs[0][1]] else: L = levs[i] I = [indices[i],] else: if l[0] == L[-1] and I[-1]==indices[i]: # Ok same type lets keep going if numpy.allclose(l[1],1.e20): L.append(mx+1.) else: L.append(l[1]) C.append(cols[i]) else: # ok we need new contouring LEVS.append(L) COLS.append(C) INDX.append(I) C = [cols[i],] L = levs[i] I = [indices[i],] LEVS.append(L) COLS.append(C) INDX.append(I) for i,l in enumerate(LEVS): # Ok here we are trying to group together levels can be, a join will happen if: # next set of levels contnues where one left off AND pattern is identical if isinstance(gm,isofill.Gfi): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() cot = vtk.vtkBandedPolyDataContourFilter() cot.ClippingOn() cot.SetInputData(sFilter.GetOutput()) cot.SetNumberOfContours(len(l)) for j,v in enumerate(l): cot.SetValue(j,v) #cot.SetScalarModeToIndex() cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) lut.SetNumberOfTableValues(len(COLS[i])) for j,color in enumerate(COLS[i]): r,g,b = cmap.index[color] lut.SetTableValue(j,r/100.,g/100.,b/100.) #print l[j],vcs.colors.rgb2str(r*2.55,g*2.55,b*2.55),l[j+1] mapper.SetLookupTable(lut) mapper.SetScalarRange(0,len(l)-1) mapper.SetScalarModeToUseCellData() else: for j,color in enumerate(COLS[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j],l[j+1]) th.SetInputConnection(geoFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r,g,b = cmap.index[color] lut.SetTableValue(0,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j],l[j+1]) mappers.append([mapper,]) #png = vtk.vtkPNGReader() #png.SetFileName("/git/uvcdat/Packages/vcs/Share/uvcdat_texture.png") #T=vtk.vtkTexture() #T.SetInputConnection(png.GetOutputPort()) if isinstance(gm,isofill.Gfi): mappers.append([mapper,]) else: #Boxfill/Meshfill mappers=[] mapper.SetInputData(geoFilter.GetOutput()) if isinstance(gm,boxfill.Gfb): if numpy.allclose(gm.level_1,1.e20) or numpy.allclose(gm.level_2,1.e20): levs = vcs.mkscale(mn,mx) legend = vcs.mklabels(levs) dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) levs = numpy.arange(levs[0],levs[-1]+dx,dx) else: if gm.boxfill_type=="log10": levs = vcs.mkscale(numpy.ma.log10(gm.level_1),numpy.ma.log10(gm.level_2)) else: levs = vcs.mkscale(gm.level_1,gm.level_2) legend = vcs.mklabels(levs) if gm.boxfill_type=="log10": for k in legend.keys(): legend[float(numpy.ma.log10(legend[k]))] = legend[k] del(legend[k]) levs = numpy.arange(levs[0],levs[1],(levs[1]-levs[0])/(gm.color_2-gm.color_1+1)) cols = range(gm.color_1,gm.color_2+1) else: if numpy.allclose(gm.levels,1.e20): levs = vcs.mkscale(mn,mx) else: levs = gm.levels if numpy.allclose(levs[0],1.e20): levs[0]=-1.e20 cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs) Nlevs = len(levs) Ncolors = Nlevs-1 if mappers == []: # ok didn't need to have special banded contours mappers=[mapper,] ## Colortable bit # make sure length match while len(cols)<Ncolors: cols.append(cols[-1]) lut.SetNumberOfTableValues(Ncolors) for i in range(Ncolors): r,g,b = cmap.index[cols[i]] lut.SetTableValue(i,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) if numpy.allclose(levs[0],-1.e20): lmn = mn-1. else: lmn= levs[0] if numpy.allclose(levs[-1],1.e20): lmx = mx+1. else: lmx= levs[-1] mapper.SetScalarRange(lmn,lmx) if missingMapper is not None: mappers.insert(0,missingMapper) x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM) if tmpl.data.priority != 0: # And now we need actors to actually render this thing for mapper in mappers: act = vtk.vtkActor() if isinstance(mapper,list): act.SetMapper(mapper[0]) else: mapper.Update() act.SetMapper(mapper) #act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap) if isinstance(mapper,list): #act.GetMapper().ScalarVisibilityOff() #act.SetTexture(mapper[1]) pass ren.AddActor(act) vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],[x1,x2,y1,y2]) self.renderTemplate(ren,tmpl,data1,gm) if isinstance(gm,(isofill.Gfi,meshfill.Gfm,boxfill.Gfb)): if getattr(gm,"legend",None) is not None: legend = gm.legend self.renderColorBar(ren,tmpl,levs,cols,legend,cmap) if self.canvas._continents is None: continents = False if continents: projection = vcs.elements["projection"][gm.projection] self.plotContinents(x1,x2,y1,y2,projection,wrap,ren,tmpl)
vcs.scriptrun(ViridisScript) colormapname = "bl_to_darkred" # colormapname = "viridis" x.setcolormap(colormapname) iso = x.createisofill() number_different_colors = 64 levels = numpy.arange(-3., 3.00001, 6. / float(number_different_colors + 1)).tolist() iso.levels = levels cols = vcs.getcolors(levels, split=0) iso.fillareacolors = cols iso.legend = vcs.mklabels(numpy.arange(-3, 3.01, .375)) # 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 t.legend.x1 = t.data.x2 + .03 t.legend.x2 = t.legend.x1 + .03 t.legend.y1 = t.data.y1 + .05
def finalize( self, flip_x=False, flip_y=False ): """By the time this is called, all synchronize operations should have been done. But even so, each variable has a min and max and a min and max for each of its axes. We need to simplify further for the plot package. The options flip_x and flip_y may be set to True to flip the axis. That is, in x right to left and left to right, and in y top to bottom and bottom to top.""" # old test: #if self.presentation.__class__.__name__=="GYx" or\ # self.presentation.__class__.__name__=="Gfi": # interim test here and below. Once all the is* functions work, I should # drop the tests on self.presentation.__class__.__name__ : if vcs.isscatter(self.presentation): ylabel, xlabel = string.split(self.title, ' vs ') #pdb.set_trace() #in the case of scatter plots there are 2 variables packed together var = self.vars[0] [xMIN, xMAX], [yMIN, yMAX] = self.make_ranges(var) #print xMIN, xMAX, yMIN, yMAX #print vcs.mkscale(xMIN, xMAX) #print vcs.mkscale(yMIN, yMAX) self.presentation.xticlabels1 = vcs.mklabels(vcs.mkscale(xMIN, xMAX)) self.presentation.datawc_x1 = xMIN self.presentation.datawc_x2 = xMAX self.presentation.xticlabels2 = {(xMIN+xMAX)/2.: xlabel} if flip_y: self.presentation.datawc_y2 = yMIN self.presentation.datawc_y1 = yMAX self.presentation.flip = True else: self.presentation.datawc_y1 = yMIN self.presentation.datawc_y2 = yMAX self.presentation.yticlabels1 = vcs.mklabels(vcs.mkscale(yMIN, yMAX)) self.presentation.yticlabels2 = {(yMIN+yMAX)/2.: ylabel} self.presentation.linewidth = 0 self.presentation.markercolor = 1 self.presentation.markersize = 5 #add overplotline is a total kludge self.presentation.overplotline = self.overplotline if flip_y: self.presentation.flip = True #self.presentation.list() elif vcs.isyxvsx(self.presentation) or\ vcs.isisofill(self.presentation) or\ vcs.isboxfill(self.presentation) or\ self.presentation.__class__.__name__=="GYx" or\ self.presentation.__class__.__name__=="G1d" or\ self.presentation.__class__.__name__=="Gv": #pdb.set_trace() if flip_y: self.presentation.flip = True var = self.vars[0] axmax = self.axmax[seqgetattr(var,'id','')] axmin = self.axmin[seqgetattr(var,'id','')] varmax = self.varmax[seqgetattr(var,'id','')] varmin = self.varmin[seqgetattr(var,'id','')] for v in self.vars[1:]: for ax in axmax.keys(): axmax[ax] = max(axmax[ax],self.axmax[seqgetattr(v,'id','')][ax]) axmin[ax] = min(axmin[ax],self.axmin[seqgetattr(v,'id','')][ax]) varmax = max(varmax,self.varmax[v.id]) varmin = min(varmin,self.varmin[v.id]) if vcs.isyxvsx(self.presentation) or\ self.presentation.__class__.__name__=="GYx" or\ self.presentation.__class__.__name__=="G1d": if len(axmax.keys())<=0: return None # VCS Yxvsx ax = axmax.keys()[0] if flip_x: self.presentation.datawc_x2 = axmin[ax] self.presentation.datawc_x1 = axmax[ax] else: self.presentation.datawc_x1 = axmin[ax] self.presentation.datawc_x2 = axmax[ax] if flip_y: self.presentation.datawc_y2 = varmin self.presentation.datawc_y1 = varmax else: self.presentation.datawc_y1 = varmin self.presentation.datawc_y2 = varmax #print "DEBUG, in finalize for line plot, datawc_{x1,x2,y1,y2}=",\ # self.presentation.datawc_x1, self.presentation.datawc_x2,\ # self.presentation.datawc_y1, self.presentation.datawc_y2 if vcs.isisofill(self.presentation) or self.presentation.__class__.__name__=="Gfi"\ or vcs.isboxfill(self.presentation): # VCS Isofill or Boxfill # First we have to identify which axes will be plotted as X and Y. # If the axes each had an 'axis' attribute, axaxi will look something like # {'X':'axis1id', 'Y':'axis2id'}. If one misses the attribute, 'axis0id':'axis0id'. axaxi = {ax:id for id,ax in self.axax[seqgetattr(var,'id','')].items()} if 'X' in axaxi.keys() and 'Y' in axaxi.keys(): axx = axaxi['X'] axy = axaxi['Y'] elif 'Y' in axaxi.keys() and 'Z' in axaxi.keys(): axx = axaxi['Y'] axy = axaxi['Z'] #added case of time vs variable elif 'T' in axaxi.keys() and 'Y' in axaxi.keys(): axx = axaxi['T'] axy = axaxi['Y'] if axx == 'time': t=var.getTime() if 'units' in dir(t) and t.units == "months since 1800": time_lables = {} months_names = get_month_strings(length=3) tc=t.asComponentTime() for i, v in enumerate(t): time_lables[v] = months_names[tc[i].month-1] self.presentation.xticlabels1 = time_lables self.presentation.datawc_timeunits = t.units #self.presentation.list() elif len(axaxi.keys())==2: # It's not clear what should be the X variable and what the Y variable, # but it's worth trying to do something axx = None axy = None for axetc in var.getDomain()[:]: ax = axetc[0] if getattr(ax,'units',None)=='mbar': # probably pressure levels, a vertical axis axy = ax.id else: axx = ax.id if axx is None or axy is None: # last resort axy = axaxi[axaxi.keys()[0]] axx = axaxi[axaxi.keys()[1]] else: return None # Now send the plotted min,max for the X,Y axes to the graphics: # and if it is not a polar projection if vcs.getprojection(self.presentation.projection)._type!=-3: if flip_x: self.presentation.datawc_x2 = axmin[axx] self.presentation.datawc_x1 = axmax[axx] else: self.presentation.datawc_x1 = axmin[axx] self.presentation.datawc_x2 = axmax[axx] if flip_y: self.presentation.datawc_y2 = axmin[axy] self.presentation.datawc_y1 = axmax[axy] else: self.presentation.datawc_y1 = axmin[axy] self.presentation.datawc_y2 = axmax[axy] # The variable min and max, varmin and varmax, should be passed on to the graphics # for setting the contours. But apparently you can't tell VCS just the min and max; # you have to give it all the contour levels. So... if vcs.isboxfill(self.presentation): self.presentation.boxfill_type = 'custom' # without this, can't set levels nlevels = 16 try: levels = [float(v) for v in vcs.mkscale( varmin, varmax, nlevels )] # Exceptions occur because mkscale doesn't always work. E.g. vcs.mkscale(0,1.e35,16) except RuntimeWarning: levels = [] if levels==[]: ## Here's how to do it with percentiles (clip out large values first). #pc05 = numpy.percentile(self.vars[0],0.05) #pc95 = numpy.percentile(self.vars[0],0.95) #levels = [float(v) for v in vcs.mkscale( pc05, pc95, nlevels-2 )] #levels = [varmin]+levels+[varmax] # Evenly distributed levels, after clipping out large values: # This cannot be expected to work always, but it's better than doing nothing. amed = numpy.median(self.vars[0]._data) vclip = amed * 1.0e6 print "WARNING graphics problems, clipping some data at",vclip self.vars[0]._data[ self.vars[0]._data > vclip ] = vclip a = numpy.sort(self.vars[0]._data.flatten()) asp = numpy.array_split(a,nlevels) afirsts = [c[0] for c in asp]+[asp[-1][-1]] alasts = [asp[0][0]]+[c[-1] for c in asp] levels = [0.5*(afirsts[i]+alasts[i]) for i in range(len(afirsts))] levf = levels[0] levl = levels[-1] levels = [ round(lv,2) for lv in levels ] levels[0] = round(1.1*levels[0]-0.1*levels[1],2) levels[-1] = round(1.1*levels[-1]-0.1*levels[-2],2) # ... mkscale returns numpy.float64, which behaves unexpectedly in _setlevels when # passed a tuple value if levels is not None and len(levels)>0: self.presentation.levels = levels #nlevels = max(1, len(levels) - 1) #nlrange = range(nlevels+1) #nlrange.reverse() #self.presentation.legend = vcs.mklabels( self.presentation.levels ) ## Once you set the levels, the VCS default color choice looks bad. So you really ## have to set contour fill colors (integers from 0 through 255) too: #cmin = 32./nlevels #cmax = 255./nlevels ## A more flexible way to do what's going on here, thanks to Charles Doutriaux: ## r=10 ## g=16 ## b=20 ## X.setcolorcell(16,r,g,b) ## colors = [16,17,18,...] etc. ## vcs.getcolors is useful, more complicated - see its doc string #colors = [int(round(a*cmin+(nlevels-a)*cmax)) for a in nlrange] #self.presentation.fillareacolors = colors ##self.presentation.fillareacolors=[32,48,64,80,96,112,128,144,160,176,240] elif vcs.isvector(self.presentation) or self.presentation.__class__.__name__=="Gv": # axis min,max copied from isofill axaxi = {ax:id for id,ax in self.axax[seqgetattr(var,'id','')].items()} if 'X' in axaxi.keys() and 'Y' in axaxi.keys(): axx = axaxi['X'] axy = axaxi['Y'] elif 'Y' in axaxi.keys() and 'Z' in axaxi.keys(): axx = axaxi['Y'] axy = axaxi['Z'] self.presentation.datawc_x1 = axmin[axx] self.presentation.datawc_x2 = axmax[axx] self.presentation.datawc_y1 = axmin[axy] self.presentation.datawc_y2 = axmax[axy] vec = self.presentation vec.scale = min(vcsx.bgX,vcsx.bgY)/ 10. if hasattr(self.vars[0],'__getitem__') and not hasattr( self.vars[0], '__cdms_internals__'): # generally a tuple of variables - we need 2 variables to describe a vector v = self.vars[0][0] w = self.vars[0][1] else: # We shouldn't get here, but may as well try to make it work if possible: print "WARNING trying to make a vector plot without tuples! Variables involved are:" v = self.vars[0] print "variable",v.id v = self.vars[1] print "variable",v.id nlats = latAxis(v).shape[0] nlons = lonAxis(w).shape[0] nlatvs = vcsx.bgY/16 # how many vectors we want in lat direction nlonvs = vcsx.bgX/16 #self.strideX = int( 0.9* vcsx.bgX/nlons ) #self.strideY = int( 0.6* vcsx.bgY/nlats ) self.strideX = max(1, int( nlons/nlonvs )) # stride values must be at least 1 self.strideY = max(1, int( nlats/nlatvs )) else: print "ERROR cannot identify graphics method",self.presentation.__class__.__name__
def plotIsos(self, template=None, bg=0): if template is None: template = 'thdiags_template' elif type(template) != type(''): template = template.name try: isotemplate = self.x.createtemplate(template) except: isotemplate = self.x.gettemplate(template) att = dir(isotemplate) for a in att: try: b = getattr(isotemplate, a) setattr(b, 'priority', 0) except: pass isotemplate.data.priority = 1 isotemplate.box1.priority = 1 isotemplate.box1.x1 = isotemplate.data.x1 isotemplate.box1.x2 = isotemplate.data.x2 isotemplate.box1.y1 = isotemplate.data.y1 isotemplate.box1.y2 = isotemplate.data.y2 dX = self.xmax - self.xmin dY = self.ymax - self.ymin X = numpy.ma.arange(self.detail, dtype=MV2.float) X = X * dX / (self.detail - 1) + self.xmin Xaxis = cdms2.createAxis(X) X = numpy.ma.resize(X, (self.detail, self.detail)) Y = numpy.ma.arange(self.detail, dtype=MV2.float) Y = Y * dY / (self.detail - 1) + self.ymin Yaxis = cdms2.createAxis(Y) Y = numpy.ma.resize(Y, (self.detail, self.detail)) Y = numpy.ma.transpose(Y) # Computes T,P on this grid T, P = self.XY2TP(X, Y) T = MV2.array(T) # Potential Temperature Tp = T / numpy.ma.power(P / 100000., self.k) ws = Ws(T, P) # Seems like we need not ws after 600mb ws = numpy.ma.masked_where( numpy.ma.less(P, self.Pmaxmixingratio * 100.), ws) T = T - 273.16 Tmin, Tmax = vcs.minmax(T) Tvalues = self.isotherms.level if Tvalues == [[0.0, 1.0000000200408773e+20]]: Tvalues = vcs.mkscale(Tmin, Tmax) ## Now sets the isothermsfilled Tvalues2 = [] for i in range(len(Tvalues) / 2 - 1): t1, t2 = Tvalues[2 * i], Tvalues[2 * i + 1] if isinstance(t1, (list, tuple)): t1, t2 = t1[0], t2[0] Tvalues2.append([t1, t2]) else: Tvalues2 = self.isothermsfilled.levels self.setIso(self.isotherms, Tvalues) ## self.setIso(self.isothermsfilled,Tvalues2) P = P / 100. Pvalues = vcs.mkscale(self.datawc_y2, self.datawc_y1) self.setIso(self.isobars, Pvalues) Tp = Tp - 273.16 Tpvalues = self.dryadiabats.level if Tpvalues == [[0.0, 1.0000000200408773e+20]]: min, max = vcs.minmax(Tp) Tpvalues = vcs.mkscale(min, max) self.setIso(self.dryadiabats, Tpvalues) ## Pseudoadiabats Thevalues = self.pseudoadiabats.level if Thevalues == [[0.0, 1.0000000200408773e+20]]: Thevalues = vcs.mkevenlevels(-40, 40, 40) self.setIso(self.pseudoadiabats, Thevalues) ## Mixing Ratio ws = ws * 1000. wsvalues = self.mixingratio.level if wsvalues == [[0.0, 1.0000000200408773e+20]]: min, max = vcs.minmax(ws) wsvalues = vcs.mkscale(min, max) self.setIso(self.mixingratio, wsvalues) # Figures out where to plot the P labels dicP = {} dicPl = vcs.mklabels(Pvalues) for p in Pvalues: X, Y = self.TP2XY(self.datawc_x1 + 273.15, p * 100) if not numpy.ma.isMA(X): dicP[Y] = dicPl[p] try: ttp = self.x.createtexttable('Plabels') except: ttp = self.x.gettexttable('Plabels') ttp.color = self.isobars.linecolors[0] isotemplate.ylabel1.texttable = ttp dicT = {} Tvalues = list(numpy.ma.array(Tvalues).filled().ravel()) dicTl = vcs.mklabels(Tvalues) for t in Tvalues: X, Y = self.TP2XY(t + 273.15, self.datawc_y1 * 100) dicT[X] = dicTl[t] try: ttp = self.x.createtexttable('Tlabels') except: ttp = self.x.gettexttable('Tlabels') ttp.color = self.isotherms.linecolors[0] isotemplate.xlabel1.texttable = ttp isotemplate.ylabel1.priority = 1 isotemplate.xlabel1.priority = 1 isotemplate.data.x1 = isotemplate.data.x1 isotemplate.data.x2 = isotemplate.data.x2 isotemplate.data.y1 = isotemplate.data.y1 isotemplate.data.y2 = isotemplate.data.y2 self.isotherms.yticlabels1 = dicP self.isotherms.xticlabels1 = dicT self.isobars.yticlabels1 = {} self.isobars.xticlabels1 = {} self.dryadiabats.yticlabels1 = {} self.dryadiabats.xticlabels1 = {} self.pseudoadiabats.yticlabels1 = {} self.pseudoadiabats.xticlabels1 = {} self.mixingratio.yticlabels1 = {} self.mixingratio.xticlabels1 = {} self.isothermsfilled.datawc_x1 = self.isothermsfilled.datawc_x1 self.isothermsfilled.datawc_x2 = self.isothermsfilled.datawc_x2 self.isothermsfilled.datawc_y1 = self.isothermsfilled.datawc_y1 self.isothermsfilled.datawc_x2 = self.isothermsfilled.datawc_y2 # Puts the dims on it T.id = 'T' T.setAxis(0, Yaxis) T.setAxis(1, Xaxis) P = MV2.array(P) P.id = 'P' P.setAxis(0, Yaxis) P.setAxis(1, Xaxis) Tp = MV2.array(Tp) Tp.setAxis(0, Yaxis) Tp.setAxis(1, Xaxis) ws = MV2.array(ws) ws.setAxis(0, Yaxis) ws.setAxis(1, Xaxis) # plot if self.drawisothermsfilled: if self.drawisothermsfilled: self.displays.append( self.x.plot(T, isotemplate, self.isothermsfilled, bg=bg)) if self.drawisotherms: self.displays.append( self.x.plot(T, isotemplate, self.isotherms, bg=bg)) if self.drawisobars: self.displays.append( self.x.plot(P, isotemplate, self.isobars, bg=bg)) if self.drawdryadiabats: self.displays.append( self.x.plot(Tp, isotemplate, self.dryadiabats, bg=bg)) if self.drawpseudoadiabats: self.plot_pseudo(isotemplate, bg=bg) if self.drawmixingratio: self.displays.append( self.x.plot(ws, isotemplate, self.mixingratio, bg=bg)) return
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 setTicksandLabels(gm,datawc_x1,datawc_x2,datawc_y1,datawc_y2,x=None,y=None): """ Sets the labels and ticks for a graphics method made in python Usage setTicksandLabels(gm,datawc_x1,datawc_x2,datawc_y1,datawc_y2,x=None,y=None) datawc are world coordinates """ if isinstance(gm,vcs.taylor.Gtd): return # Now the template stuff # first create the dictionary to remember which ones are changed dic={} for i in ('xticlabels1','xmtics1','xticlabels2','xmtics2','yticlabels1','ymtics1','yticlabels2','ymtics2'): dic[i]=False #xticklabels1 if gm.xticlabels1 is None or gm.xticlabels1=='*': if x=="longitude" and abs(datawc_x2-datawc_x1)>30: ticks="lon30" else: ticks=vcs.mkscale(datawc_x1,datawc_x2) ticks=prettifyAxisLabels(vcs.mklabels(ticks),x) ## for k in ticks.keys() : # make sure you're in the range ## if k<numpy.minimum(datawc_x1,datawc_x2) or k>numpy.maximum(datawc_x2,datawc_x1): ## del(ticks[k]) setattr(gm,'xticlabels1',ticks) dic['xticlabels1']=True #xmtics1 if gm.xmtics1 is None or gm.xmtics1=='*': ticks=vcs.mkscale(datawc_x1,datawc_x2) tick2=[] for i in range(len(ticks)-1): tick2.append((ticks[i]+ticks[i+1])/2.) ticks=prettifyAxisLabels(vcs.mklabels(tick2),x) ## for k in ticks.keys() : # make sure you're in the range ## if k<numpy.minimum(datawc_x1,datawc_x2) or k>numpy.maximum(datawc_x2,datawc_x1): ## del(ticks[k]) setattr(gm,'xmtics1',ticks) dic['xmtics1']=True #xticklabels2 if hasattr(gm,"xticlabels2") and (gm.xticlabels2 is None or gm.xticlabels2=='*'): ticks=vcs.mkscale(datawc_x1,datawc_x2) ticks=prettifyAxisLabels(vcs.mklabels(ticks),x) ## for k in ticks.keys(): ## ticks[k]='' ## if k<numpy.minimum(datawc_x1,datawc_x2) or k>numpy.maximum(datawc_x2,datawc_x1): ## del(ticks[k]) setattr(gm,'xticlabels2',ticks) dic['xticlabels2']=True #xmtics2 if hasattr(gm,"xmtics2") and (gm.xmtics2 is None or gm.xmtics2=='*'): ticks=vcs.mkscale(datawc_x1,datawc_x2) tick2=[] for i in range(len(ticks)-1): tick2.append((ticks[i]+ticks[i+1])/2.) ticks=prettifyAxisLabels(vcs.mklabels(tick2),x) ## for k in ticks.keys() : # make sure you're in the range ## if k<numpy.minimum(datawc_x1,datawc_x2) or k>numpy.maximum(datawc_x2,datawc_x1): ## del(ticks[k]) setattr(gm,'xmtics2',ticks) dic['xmtics2']=True #yticklabels1 if gm.yticlabels1 is None or gm.yticlabels1=='*': if y=="latitude" and abs(datawc_y2-datawc_y1)>20: ticks="lat20" else: ticks=vcs.mkscale(datawc_y1,datawc_y2) ticks=prettifyAxisLabels(vcs.mklabels(ticks),y) ## for k in ticks.keys() : # make sure you're in the range ## if k<numpy.minimum(datawc_y1,datawc_y2) or k>numpy.maximum(datawc_y2,datawc_y1): ## del(ticks[k]) setattr(gm,'yticlabels1',ticks) dic['yticlabels1']=True #ymtics1 if gm.ymtics1 is None or gm.ymtics1=='*': ticks=vcs.mkscale(datawc_y1,datawc_y2) tick2=[] for i in range(len(ticks)-1): tick2.append((ticks[i]+ticks[i+1])/2.) ticks=prettifyAxisLabels(vcs.mklabels(tick2),y) ## for k in ticks.keys() : # make sure you're in the range ## if k<numpy.minimum(datawc_y1,datawc_y2) or k>numpy.maximum(datawc_y2,datawc_y1): ## del(ticks[k]) setattr(gm,'ymtics1',ticks) dic['ymtics1']=True #yticklabels2 if hasattr(gm,"yticlabels2") and (gm.yticlabels2 is None or gm.yticlabels2=='*'): ticks=vcs.mkscale(datawc_y1,datawc_y2) ticks=prettifyAxisLabels(vcs.mklabels(ticks),y) ## for k in ticks.keys(): ## ticks[k]='' ## if k<numpy.minimum(datawc_y1,datawc_y2) or k>numpy.maximum(datawc_y2,datawc_y1): ## del(ticks[k]) setattr(gm,'yticlabels2',ticks) dic['yticlabels2']=True #ymtics2 if hasattr(gm,"ymtics2") and (gm.ymtics2 is None or gm.ymtics2=='*'): ticks=vcs.mkscale(datawc_y1,datawc_y2) tick2=[] for i in range(len(ticks)-1): tick2.append((ticks[i]+ticks[i+1])/2.) ticks=prettifyAxisLabels(vcs.mklabels(tick2),y) ## for k in ticks.keys() : # make sure you're in the range ## if k<numpy.minimum(datawc_y1,datawc_y2) or k>numpy.maximum(datawc_y2,datawc_y1): ## del(ticks[k]) setattr(gm,'ymtics2',ticks) dic['ymtics2']=True return dic
def plot2D(self,data1,data2,tmpl,gm): ug,xm,xM,ym,yM,continents,wrap,geo,cellData = vcs2vtk.genGrid(data1,data2,gm) #Now applies the actual data on each cell if isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="log10": data1=numpy.ma.log10(data1) data = VN.numpy_to_vtk(data1.filled(0.).flat,deep=True) if cellData: ug.GetCellData().SetScalars(data) else: ug.GetPointData().SetScalars(data) try: cmap = vcs.elements["colormap"][cmap] except: cmap = vcs.elements["colormap"][self.canvas.getcolormapname()] color = getattr(gm,"missing",None) if color is not None: color = cmap.index[color] missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,color,cellData) lut = vtk.vtkLookupTable() mn,mx=vcs.minmax(data1) #Ok now we have grid and data let's use the mapper mapper = vtk.vtkPolyDataMapper() legend = None if isinstance(gm,(meshfill.Gfm,boxfill.Gfb)): geoFilter = vtk.vtkDataSetSurfaceFilter() if cellData: p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(ug) geoFilter.SetInputConnection(p2c.GetOutputPort()) else: geoFilter.SetInputData(ug) geoFilter.Update() if isinstance(gm,(isofill.Gfi,isoline.Gi,meshfill.Gfm)) or \ (isinstance(gm,boxfill.Gfb) and gm.boxfill_type=="custom"): #Now this filter seems to create the good polydata sFilter = vtk.vtkDataSetSurfaceFilter() if cellData: # Sets data to point instead of just cells c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(ug) c2p.Update() if self.debug: vcs2vtk.dump2VTK(c2p) #For contouring duplicate points seem to confuse it if ug.IsA("vtkUntructuredGrid"): cln = vtk.vtkCleanUnstructuredGrid() cln.SetInputConnection(c2p.GetOutputPort()) if self.debug: vcs2vtk.dump2VTK(cln) sFilter.SetInputConnection(cln.GetOutputPort()) else: sFilter.SetInputConnection(c2p.GetOutputPort()) else: sFilter.SetInputData(ug) sFilter.Update() if self.debug: vcs2vtk.dump2VTK(sFilter) if isinstance(gm,isoline.Gi): cot = vtk.vtkContourFilter() if cellData: cot.SetInputData(sFilter.GetOutput()) else: cot.SetInputData(ug) levs = gm.levels if (isinstance(gm,isoline.Gi) and numpy.allclose( levs[0],[0.,1.e20])) or numpy.allclose(levs,1.e20): levs = vcs.mkscale(mn,mx) Ncolors = len(levs) if isinstance(gm,(isofill.Gfi,meshfill.Gfm)): levs2 = vcs.mkscale(mn,mx) levs=[] for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) else: if isinstance(gm.levels[0],(list,tuple)): if isinstance(gm,isoline.Gi): levs = [x[0] for x in gm.levels] else: levs = gm.levels else: levs = [] levs2=gm.levels if numpy.allclose(levs2[0],1.e20): levs2[0]=-1.e20 for i in range(len(levs2)-1): levs.append([levs2[i],levs2[i+1]]) if isinstance(gm,isoline.Gi): levs = levs2 Nlevs=len(levs) Ncolors = Nlevs ## Figure out colors if isinstance(gm,boxfill.Gfb): cols = gm.fillareacolors if cols is None: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,(isofill.Gfi,meshfill.Gfm)): cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs2,split=0) elif isinstance(gm,isoline.Gi): cols = gm.linecolors if isinstance(gm,isoline.Gi): cot.SetNumberOfContours(Nlevs) if levs[0]==1.e20: levs[0]=-1.e20 for i in range(Nlevs): cot.SetValue(i,levs[i]) cot.SetValue(Nlevs,levs[-1]) cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) mappers = [] else: mappers = [] LEVS = [] INDX = [] COLS = [] indices = gm.fillareaindices if indices is None: indices=[1,] while len(indices)<len(cols): indices.append(indices[-1]) for i,l in enumerate(levs): if i==0: C = [cols[i],] if numpy.allclose(levs[0][0],-1.e20): ## ok it's an extension arrow L=[mn-1.,levs[0][1]] else: L = levs[i] I = [indices[i],] else: if l[0] == L[-1] and I[-1]==indices[i]: # Ok same type lets keep going if numpy.allclose(l[1],1.e20): L.append(mx+1.) else: L.append(l[1]) C.append(cols[i]) else: # ok we need new contouring LEVS.append(L) COLS.append(C) INDX.append(I) C = [cols[i],] L = levs[i] I = [indices[i],] LEVS.append(L) COLS.append(C) INDX.append(I) for i,l in enumerate(LEVS): # Ok here we are trying to group together levels can be, a join will happen if: # next set of levels contnues where one left off AND pattern is identical if isinstance(gm,isofill.Gfi): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() cot = vtk.vtkBandedPolyDataContourFilter() cot.ClippingOn() cot.SetInputData(sFilter.GetOutput()) cot.SetNumberOfContours(len(l)) for j,v in enumerate(l): cot.SetValue(j,v) #cot.SetScalarModeToIndex() cot.Update() mapper.SetInputConnection(cot.GetOutputPort()) lut.SetNumberOfTableValues(len(COLS[i])) for j,color in enumerate(COLS[i]): r,g,b = cmap.index[color] lut.SetTableValue(j,r/100.,g/100.,b/100.) #print l[j],vcs.colors.rgb2str(r*2.55,g*2.55,b*2.55),l[j+1] mapper.SetLookupTable(lut) mapper.SetScalarRange(0,len(l)-1) mapper.SetScalarModeToUseCellData() else: for j,color in enumerate(COLS[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j],l[j+1]) th.SetInputConnection(geoFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r,g,b = cmap.index[color] lut.SetTableValue(0,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j],l[j+1]) mappers.append([mapper,]) #png = vtk.vtkPNGReader() #png.SetFileName("/git/uvcdat/Packages/vcs/Share/uvcdat_texture.png") #T=vtk.vtkTexture() #T.SetInputConnection(png.GetOutputPort()) if isinstance(gm,isofill.Gfi): mappers.append([mapper,]) else: #Boxfill (non custom)/Meshfill if isinstance(gm,boxfill.Gfb): if numpy.allclose(gm.level_1,1.e20) or numpy.allclose(gm.level_2,1.e20): levs = vcs.mkscale(mn,mx) legend = vcs.mklabels(levs) dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) levs = numpy.arange(levs[0],levs[-1]+dx,dx) else: if gm.boxfill_type=="log10": levs = vcs.mkscale(numpy.ma.log10(gm.level_1),numpy.ma.log10(gm.level_2)) else: levs = vcs.mkscale(gm.level_1,gm.level_2) legend = vcs.mklabels(levs) if gm.boxfill_type=="log10": for k in legend.keys(): legend[float(numpy.ma.log10(legend[k]))] = legend[k] del(legend[k]) dx = (levs[-1]-levs[0])/(gm.color_2-gm.color_1+1) levs = numpy.arange(levs[0],levs[-1]+dx,dx) cols = range(gm.color_1,gm.color_2+1) else: if numpy.allclose(gm.levels,1.e20): levs = vcs.mkscale(mn,mx) else: levs = gm.levels if numpy.allclose(levs[0],1.e20): levs[0]=-1.e20 cols = gm.fillareacolors if cols==[1,]: cols = vcs.getcolors(levs) Nlevs = len(levs) Ncolors = Nlevs-1 #Prep mapper mappers=[] mapper = vtk.vtkPolyDataMapper() thr = vtk.vtkThreshold() thr.SetInputConnection(geoFilter.GetOutputPort()) if not gm.ext_1 in ["y",1,True] and not gm.ext_2 in ["y",1,True] : thr.ThresholdBetween(levs[0],levs[-1]) elif gm.ext_1 in ["y",1,True] and not gm.ext_2 in ["y",1,True] : thr.ThresholdByLower(levs[-1]) elif not gm.ext_1 in ["y",1,True] and gm.ext_2 in ["y",1,True] : thr.ThresholdByUpper(levs[0]) thr.Update() geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(thr.GetOutputPort()) if gm.ext_1 in ["y",1,True] and gm.ext_2 in ["y",1,True] : mapper.SetInputConnection(geoFilter.GetOutputPort()) else: mapper.SetInputConnection(geoFilter2.GetOutputPort()) if mappers == []: # ok didn't need to have special banded contours mappers=[mapper,] ## Colortable bit # make sure length match while len(cols)<Ncolors: cols.append(cols[-1]) lut.SetNumberOfTableValues(Ncolors) for i in range(Ncolors): r,g,b = cmap.index[cols[i]] lut.SetTableValue(i,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) if numpy.allclose(levs[0],-1.e20): lmn = mn-1. else: lmn= levs[0] if numpy.allclose(levs[-1],1.e20): lmx = mx+1. else: lmx= levs[-1] mapper.SetScalarRange(lmn,lmx) if missingMapper is not None: mappers.insert(0,missingMapper) x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM) if tmpl.data.priority != 0: # And now we need actors to actually render this thing for mapper in mappers: act = vtk.vtkActor() if isinstance(mapper,list): act.SetMapper(mapper[0]) else: mapper.Update() act.SetMapper(mapper) if geo is None: act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap) if isinstance(mapper,list): #act.GetMapper().ScalarVisibilityOff() #act.SetTexture(mapper[1]) pass # create a new renderer for this mapper (we need one for each mapper because of cmaera flips) ren = vtk.vtkRenderer() self.renWin.AddRenderer(ren) self.setLayer(ren,tmpl.data.priority) ren.AddActor(act) vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],wc=[x1,x2,y1,y2],geo=geo) if isinstance(gm,meshfill.Gfm): tmpl.plot(self.canvas,data1,gm,bg=self.bg,X=numpy.arange(xm,xM*1.1,(xM-xm)/10.),Y=numpy.arange(ym,yM*1.1,(yM-ym)/10.)) else: self.renderTemplate(tmpl,data1,gm) if isinstance(gm,(isofill.Gfi,meshfill.Gfm,boxfill.Gfb)): if getattr(gm,"legend",None) is not None: legend = gm.legend if gm.ext_1 in ["y",1,True] and not numpy.allclose(levs[0],1.e20): if isinstance(levs,numpy.ndarray): levs=levs.tolist() levs.insert(0,-1.e20) if gm.ext_2 in ["y",1,True] and not numpy.allclose(levs[0],1.e20): if isinstance(levs,numpy.ndarray): levs=levs.tolist() levs.append(1.e20) self.renderColorBar(tmpl,levs,cols,legend,cmap) if self.canvas._continents is None: continents = False if continents: projection = vcs.elements["projection"][gm.projection] self.plotContinents(x1,x2,y1,y2,projection,wrap,tmpl)