def update_input(self,vtkobjects,array1,array2=None,update=True): if vtkobjects.has_key("vtk_backend_grid"): ## Ok ths is where we update the input data vg=vtkobjects["vtk_backend_grid"] data = vcs2vtk.numpy_to_vtk_wrapper(array1.filled(0.).flat, deep=False) pData= vg.GetPointData().GetScalars() if pData is not None: vg.GetPointData().SetScalars(data) else: vg.GetCellData().SetScalars(data) if vtkobjects.has_key("vtk_backend_filter"): vtkobjects["vtk_backend_filter"].Update() if vtkobjects.has_key("vtk_backend_missing_mapper"): missingMapper,color,cellData = vtkobjects["vtk_backend_missing_mapper"] missingMapper2 = vcs2vtk.putMaskOnVTKGrid(array1,vg,color,cellData,deep=False) else: missingMapper = None if vtkobjects.has_key("vtk_backend_contours"): for c in vtkobjects["vtk_backend_contours"]: c.Update() ports=vtkobjects["vtk_backend_contours"] elif vtkobjects.has_key("vtk_backend_geofilters"): ports=vtkobjects["vtk_backend_geofilters"] else: # Vector plot ports=vtkobjects["vtk_backend_glyphfilters"] w = vcs2vtk.generateVectorArray(array1,array2,vg) vg.GetPointData().AddArray(w) ports[0].SetInputData(vg) if vtkobjects.has_key("vtk_backend_actors"): i=0 for a in vtkobjects["vtk_backend_actors"]: act = a[0] wrp = a[1] if a[1] is missingMapper: i-=1 mapper = missingMapper2 wrp = a[2] else: ## Labeled contours are a different kind if vtkobjects.has_key("vtk_backend_luts"): lut,rg = vtkobjects["vtk_backend_luts"][i] mapper = vtk.vtkPolyDataMapper() elif vtkobjects.has_key("vtk_backend_labeled_luts"): lut,rg = vtkobjects["vtk_backend_labeled_luts"][i] mapper = vtk.vtkLabeledContourMapper() if lut is None: mapper.SetInputConnection(ports[i].GetOutputPort()) else: if mapper.IsA("vtkPolyDataMapper"): mapper.SetInputConnection(ports[i].GetOutputPort()) mapper.SetLookupTable(lut) mapper.SetScalarModeToUsePointData() else: stripper = vtk.vtkStripper() stripper.SetInputConnection(ports[i].GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) stripper.Update() tprops = vtkobjects["vtk_backend_contours_labels_text_properties"] mapper.GetPolyDataMapper().SetLookupTable(lut) mapper.GetPolyDataMapper().SetScalarModeToUsePointData() mapper.GetPolyDataMapper().SetScalarRange(rg[0],rg[1]) mapper.SetLabelVisibility(1) mapper.SetTextProperties(tprops) if rg[2]: mapper.SetScalarModeToUseCellData() mapper.SetScalarRange(rg[0],rg[1]) act.SetMapper(mapper) act = vcs2vtk.doWrap(a[0],wrp) a[0].SetMapper(act.GetMapper()) i+=1 taxis = array1.getTime() if taxis is not None: tstr = str(cdtime.reltime(taxis[0],taxis.units).tocomp(taxis.getCalendar())) else: tstr = None ## Min/Max/Mean for att in ["Min","Max","Mean","crtime","crdate","zvalue"]: if vtkobjects.has_key("vtk_backend_%s_text_actor" % att): t = vtkobjects["vtk_backend_%s_text_actor" % att] if att == "Min": t.SetInput("Min %g" % array1.min()) elif att == "Max": t.SetInput("Max %g" % array1.max()) elif att == "Mean": if not inspect.ismethod(getattr(array1,'mean')): meanstring = "Mean: %s" % getattr(array1,"mean") else: try: meanstring='Mean %.4g'% float(cdutil.averager(array1, axis = " ".join(["(%s)" % S for S in array1.getAxisIds()]))) except Exception,err: meanstring='Mean %.4g'%array1.mean() t.SetInput(meanstring) elif att=="crdate" and tstr is not None: t.SetInput(tstr.split()[0].replace("-","/")) elif att=="crtime" and tstr is not None: t.SetInput(tstr.split()[1]) elif att=="zvalue": if len(array1.shape)>2: l=array1.getAxis(-3) if l.isTime(): t.SetInput(str(l.asComponentTime()[0])) else: t.SetInput("%g" % l[0])
def _plotInternal(self): """Overrides baseclass implementation.""" numLevels = len(self._contourLevels) cot = vtk.vtkContourFilter() if self._useCellScalars: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) if self._contourLevels[0] == 1.e20: self._contourLevels[0] = -1.e20 for i in range(numLevels): cot.SetValue(i, self._contourLevels[i]) cot.SetValue(numLevels, self._contourLevels[-1]) # TODO remove update cot.Update() mappers = [] lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(self._contourColors)) cmap = self._context().canvas.getcolormapname() cmap = vcs.elements["colormap"][cmap] for i, col in enumerate(self._contourColors): r, g, b = cmap.index[col] lut.SetTableValue(i, r / 100., g / 100., b / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for i, val in enumerate(self._contourLevels): tpropMap.SetTuple(i, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < numLevels: texts.append(texts[-1]) else: texts = [None] * len(self._gm.textcolors) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < numLevels: colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) for tc, colorOverride in zip(texts, colorOverrides): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), to, tt) tprops.AddItem(tprop) if colorOverride is not None: del(vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize()) tprops.AddItem(tprop) self._resultDict["vtk_backend_contours_labels_text_properties"] = \ tprops mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) mapper.SetSkipDistance(self._gm.labelskipdistance) pdMapper = mapper.GetPolyDataMapper() self._resultDict["vtk_backend_labeled_luts"] = [ [lut, [self._contourLevels[0], self._contourLevels[-1], False]]] else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper self._resultDict["vtk_backend_luts"] = \ [[lut, [self._contourLevels[0], self._contourLevels[-1], False]]] pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(self._contourLevels[0], self._contourLevels[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) self._resultDict["vtk_backend_contours"] = [cot] if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) x1, x2, y1, y2 = vcs.utils.getworldcoordinates(self._gm, self._data1.getAxis(-1), self._data1.getAxis(-2)) # And now we need actors to actually render this thing actors = [] for mapper in mappers: act = vtk.vtkActor() act.SetMapper(mapper) if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not # sure why so sticking to many mappers act = vcs2vtk.doWrap(act, [x1, x2, y1, y2], self._dataWrapModulo) # TODO See comment in boxfill. if mapper is self._maskedDataMapper: actors.append([act, self._maskedDataMapper, [x1, x2, y1, y2]]) else: actors.append([act, [x1, x2, y1, y2]]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) self._context().fitToViewport( act, [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2], wc=[x1, x2, y1, y2], geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict["vtk_backend_actors"] = actors t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None self._resultDict.update(self._context().renderTemplate(self._template, self._data1, self._gm, t, z)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] self._context().plotContinents(x1, x2, y1, y2, projection, self._dataWrapModulo, self._template)
def _plotInternal(self): """Overrides baseclass implementation.""" tmpLevels = [] tmpColors = [] tmpLineWidths = [] tmpLineTypes = [] linewidth = self._gm.linewidths self.extendAttribute(linewidth, default=1.0) linetype = self._gm.linetypes self.extendAttribute(linetype, default='solid') plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds for i, lv_tmp in enumerate(self._contourLevels): if i == 0: W = linewidth[i] S = linetype[i] C = [self._contourColors[i]] if lv_tmp == 1.e20: L = [-1.e20] else: L = [lv_tmp] else: if W == linewidth[i] and S == linetype[i]: # Ok same style and width, lets keep going L.append(lv_tmp) C.append(self._contourColors[i]) else: tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) L = [lv_tmp] C = [self._contourColors[i]] W = linewidth[i] S = linetype[i] tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) cots = [] textprops = [] luts = [] actors = [] mappers = [] if self._gm.label and (self._gm.text or self._gm.textcolors): # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < len(self._contourLevels): texts.append(texts[-1]) else: texts = [None] * len(self._contourLevels) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < len(self._contourLevels): colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) # Custom background colors and opacities: backgroundColors = self._gm.labelbackgroundcolors if backgroundColors: while len(backgroundColors) < len(self._contourLevels): backgroundColors.append(backgroundColors[-1]) backgroundOpacities = self._gm.labelbackgroundopacities if backgroundOpacities: while len(backgroundOpacities) < len(self._contourLevels): backgroundOpacities.append(backgroundOpacities[-1]) countLevels = 0 vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) dataset_renderer = None xScale, yScale = (1, 1) for i, l in enumerate(tmpLevels): numLevels = len(l) cot = vtk.vtkContourFilter() if self._hasCellData: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) for n in range(numLevels): cot.SetValue(n, l[n]) # TODO remove update cot.Update() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(tmpColors[i])) cmap = self.getColorMap() for n, col in enumerate(tmpColors[i]): r, g, b, a = self.getColorIndexOrRGBA(cmap, col) lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for n, val in enumerate(l): tpropMap.SetTuple(n, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: ttexts = texts[countLevels:(countLevels + len(l))] for idx, tc in enumerate(ttexts): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" elif isinstance(tc, str): sp = tc.split(":::") if len(sp) == 2: tt = sp[0] to = sp[1] else: # Hum don't know what do do with this if sp[0] in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) tt, to = tuple(tc.name.split(":::")) elif sp[0] in vcs.listelements( "textorientation"): to = sp[0] tt = "default" elif sp[0] in vcs.listelements("texttable"): tt = sp[0] to = "default" colorOverride = colorOverrides[countLevels + idx] if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name if backgroundColors is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundcolor = backgroundColors[ countLevels + idx] if backgroundOpacities is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundopacity = backgroundOpacities[ countLevels + idx] tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty( tprop, self._context().renWin.GetSize(), to, tt, cmap=cmap) tprops.AddItem(tprop) if colorOverride is not None: del (vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), cmap=cmap) tprops.AddItem(tprop) textprops.append(tprops) mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) mapper.SetSkipDistance(self._gm.labelskipdistance) pdMapper = mapper.GetPolyDataMapper() luts.append([lut, [l[0], l[-1], False]]) else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper luts.append([lut, [l[0], l[-1], False]]) pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(l[0], l[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) cots.append(cot) # Create actor to add to scene act = vtk.vtkActor() act.SetMapper(mapper) # Set line properties here p = act.GetProperty() p.SetLineWidth(tmpLineWidths[i]) vcs2vtk.stippleLine(p, tmpLineTypes[i]) actors.append([act, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) dataset_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=(dataset_renderer is None)) countLevels += len(l) if len(textprops) > 0: self._resultDict["vtk_backend_contours_labels_text_properties"] = \ textprops if len(luts) > 0: if self._gm.label: self._resultDict["vtk_backend_labeled_luts"] = luts else: self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) act = vtk.vtkActor() act.SetMapper(self._maskedDataMapper) actors.append( [act, self._maskedDataMapper, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict["vtk_backend_actors"] = actors t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None kwargs = { "vtk_backend_grid": self._vtkDataSet, "dataset_bounds": self._vtkDataSetBounds, "plotting_dataset_bounds": plotting_dataset_bounds, "vtk_dataset_bounds_no_mask": self._vtkDataSetBoundsNoMask, "vtk_backend_geo": self._vtkGeoTransform } if ("ratio_autot_viewport" in self._resultDict): kwargs["ratio_autot_viewport"] = vp self._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, t, z, **kwargs)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] continents_renderer, xScale, yScale = self._context( ).plotContinents(plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs)
def _plotInternal(self): """Overrides baseclass implementation.""" numLevels = len(self._contourLevels) cot = vtk.vtkContourFilter() if self._useCellScalars: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) if self._contourLevels[0] == 1.e20: self._contourLevels[0] = -1.e20 for i in range(numLevels): cot.SetValue(i, self._contourLevels[i]) cot.SetValue(numLevels, self._contourLevels[-1]) # TODO remove update cot.Update() mappers = [] lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(self._contourColors)) cmap = vcs.elements["colormap"][self._context.canvas.getcolormapname()] for i, col in enumerate(self._contourColors): r, g, b = cmap.index[col] lut.SetTableValue(i, r / 100., g / 100., b / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for i, val in enumerate(self._contourLevels): tpropMap.SetTuple(i, [ val, ]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < numLevels: texts.append(texts[-1]) else: texts = [None] * len(self._gm.textcolors) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < numLevels: colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) for tc, colorOverride in zip(texts, colorOverrides): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context.renWin.GetSize(), to, tt) tprops.AddItem(tprop) if colorOverride is not None: del (vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context.renWin.GetSize()) tprops.AddItem(tprop) self._resultDict["vtk_backend_contours_labels_text_properties"] = \ tprops mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) pdMapper = mapper.GetPolyDataMapper() self._resultDict["vtk_backend_labeled_luts"] = [[ lut, [self._contourLevels[0], self._contourLevels[-1], False] ]] else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper self._resultDict["vtk_backend_luts"] = [[ lut, [self._contourLevels[0], self._contourLevels[-1], False] ]] pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(self._contourLevels[0], self._contourLevels[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) self._resultDict["vtk_backend_contours"] = [ cot, ] if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) x1, x2, y1, y2 = vcs.utils.getworldcoordinates(self._gm, self._data1.getAxis(-1), self._data1.getAxis(-2)) # And now we need actors to actually render this thing actors = [] for mapper in mappers: act = vtk.vtkActor() act.SetMapper(mapper) if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not sure # why so sticking to many mappers act = vcs2vtk.doWrap(act, [x1, x2, y1, y2], self._dataWrapModulo) # TODO See comment in boxfill. if mapper is self._maskedDataMapper: actors.append([act, self._maskedDataMapper, [x1, x2, y1, y2]]) else: actors.append([act, [x1, x2, y1, y2]]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) ren = self._context.fitToViewport( act, [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ], wc=[x1, x2, y1, y2], geo=self._vtkGeoTransform, priority=self._template.data.priority) self._resultDict["vtk_backend_actors"] = actors t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None self._resultDict.update( self._context.renderTemplate(self._template, self._data1, self._gm, t, z)) if self._context.canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] self._context.plotContinents(x1, x2, y1, y2, projection, self._dataWrapModulo, self._template)
def _plotInternal(self): """Overrides baseclass implementation.""" tmpLevels = [] tmpColors = [] tmpLineWidths = [] tmpLineTypes = [] linewidth = self._gm.linewidths self.extendAttribute(linewidth, default=1.0) linetype = self._gm.linetypes self.extendAttribute(linetype, default='solid') plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds for i, lv_tmp in enumerate(self._contourLevels): if i == 0: W = linewidth[i] S = linetype[i] C = [self._contourColors[i]] if lv_tmp == 1.e20: L = [-1.e20] else: L = [lv_tmp] else: if W == linewidth[i] and S == linetype[i]: # Ok same style and width, lets keep going L.append(lv_tmp) C.append(self._contourColors[i]) else: tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) L = [lv_tmp] C = [self._contourColors[i]] W = linewidth[i] S = linetype[i] tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineTypes.append(S) cots = [] textprops = [] luts = [] actors = [] mappers = [] if self._gm.label and (self._gm.text or self._gm.textcolors): # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < len(self._contourLevels): texts.append(texts[-1]) else: texts = [None] * len(self._contourLevels) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < len(self._contourLevels): colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) # Custom background colors and opacities: backgroundColors = self._gm.labelbackgroundcolors if backgroundColors: while len(backgroundColors) < len(self._contourLevels): backgroundColors.append(backgroundColors[-1]) backgroundOpacities = self._gm.labelbackgroundopacities if backgroundOpacities: while len(backgroundOpacities) < len(self._contourLevels): backgroundOpacities.append(backgroundOpacities[-1]) else: backgroundOpacities = [100.0 for lev in self._contourLevels] countLevels = 0 vp = self._resultDict.get( 'ratio_autot_viewport', [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2]) # view and interactive area view = self._context().contextView area = vtk.vtkInteractiveArea() view.GetScene().AddItem(area) adjusted_plotting_bounds = vcs2vtk.getProjectedBoundsForWorldCoords( plotting_dataset_bounds, self._gm.projection) drawAreaBounds = vcs2vtk.computeDrawAreaBounds(adjusted_plotting_bounds) [renWinWidth, renWinHeight] = self._context().renWin.GetSize() geom = vtk.vtkRecti(int(round(vp[0] * renWinWidth)), int(round(vp[2] * renWinHeight)), int(round((vp[1] - vp[0]) * renWinWidth)), int(round((vp[3] - vp[2]) * renWinHeight))) vcs2vtk.configureContextArea(area, drawAreaBounds, geom) # FIXME: This render call is needed to work around a bug somewhere in the # FIXME: vtkContextTransform code, where the transformation represented by # FIXME: Map[To|From]Scene() isn't set up properly until after a render call. self._context().renWin.Render() for i, l in enumerate(tmpLevels): numLevels = len(l) cot = vtk.vtkContourFilter() cot.SetInputData(self._vtkDataSetFittedToViewport) cot.SetNumberOfContours(numLevels) for n in range(numLevels): cot.SetValue(n, l[n]) # TODO remove update cot.Update() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(tmpColors[i])) cmap = self.getColorMap() for n, col in enumerate(tmpColors[i]): r, g, b, a = self.getColorIndexOrRGBA(cmap, col) lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for n, val in enumerate(l): tpropMap.SetTuple(n, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: ttexts = texts[countLevels:(countLevels + len(l))] for idx, tc in enumerate(ttexts): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" elif isinstance(tc, str): sp = tc.split(":::") if len(sp) == 2: tt = sp[0] to = sp[1] else: # Hum don't know what do do with this if sp[0] in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) tt, to = tuple(tc.name.split(":::")) elif sp[0] in vcs.listelements("textorientation"): to = sp[0] tt = "default" elif sp[0] in vcs.listelements("texttable"): tt = sp[0] to = "default" tt = vcs.createtexttable(None, tt) colorOverride = colorOverrides[countLevels + idx] if colorOverride is not None: tt.color = colorOverride tt = tt.name if backgroundColors is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundcolor = backgroundColors[countLevels + idx] if backgroundOpacities is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundopacity = backgroundOpacities[countLevels + idx] tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), to, tt, cmap=cmap) tprops.AddItem(tprop) if colorOverride is not None: del(vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), cmap=cmap) tprop.SetBackgroundOpacity(1.0) tprops.AddItem(tprop) textprops.append(tprops) item = vtk.vtkLabeledContourPolyDataItem() item.SetTextProperties(tprops) item.SetTextPropertyMapping(tpropMap) item.SetLabelVisibility(1) item.SetSkipDistance(self._gm.labelskipdistance) mapper = vtk.vtkLabeledContourMapper() pdMapper = mapper.GetPolyDataMapper() luts.append([lut, [l[0], l[-1], False]]) else: # No isoline labels: item = vtk.vtkPolyDataItem() mapper = vtk.vtkPolyDataMapper() pdMapper = mapper luts.append([lut, [l[0], l[-1], False]]) pdMapper.SetLookupTable(lut) lut.SetRange(l[0], l[-1]) pdMapper.SetScalarRange(l[0], l[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() poly = stripper.GetOutput() mappers.append(mapper) cots.append(cot) if self._needsCellData: attrs = poly.GetCellData() scalarMode = vtk.VTK_SCALAR_MODE_USE_CELL_DATA else: attrs = poly.GetPointData() scalarMode = vtk.VTK_SCALAR_MODE_USE_POINT_DATA data = attrs.GetScalars() mappedColors = lut.MapScalars(data, vtk.VTK_COLOR_MODE_DEFAULT, 0) intValue = vtk.vtkIntArray() intValue.SetNumberOfComponents(1) intValue.SetName("StippleType") intValue.InsertNextValue(vcs2vtk.getStipple(tmpLineTypes[i])) poly.GetFieldData().AddArray(intValue) floatValue = vtk.vtkFloatArray() floatValue.SetNumberOfComponents(1) floatValue.SetName("LineWidth") floatValue.InsertNextValue(tmpLineWidths[i]) poly.GetFieldData().AddArray(floatValue) item.SetPolyData(poly) item.SetScalarMode(scalarMode) item.SetMappedColors(mappedColors) mappedColors.FastDelete() area.GetDrawAreaItem().AddItem(item) actors.append([item, plotting_dataset_bounds]) countLevels += len(l) if len(textprops) > 0: self._resultDict["vtk_backend_contours_labels_text_properties"] = \ textprops if len(luts) > 0: if self._gm.label: self._resultDict["vtk_backend_labeled_luts"] = luts else: self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) self._maskedDataMapper.Update() maskedData = self._maskedDataMapper.GetInput() maskedColors = vtk.vtkUnsignedCharArray() maskedColors.SetNumberOfComponents(4) for i in range(poly.GetNumberOfCells()): maskedColors.InsertNextTypedTuple([0, 0, 0, 255]) maskItem = vtk.vtkPolyDataItem() maskItem.SetPolyData(maskedData) maskItem.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_DATA) maskItem.SetMappedColors(maskedColors) area.GetDrawAreaItem().AddItem(maskItem) actors.append([maskItem, self._maskedDataMapper, plotting_dataset_bounds]) self._resultDict["vtk_backend_actors"] = actors z, t = self.getZandT() kwargs = { "vtk_backend_grid": self._vtkDataSet, "dataset_bounds": self._vtkDataSetBounds, "plotting_dataset_bounds": plotting_dataset_bounds, "vtk_dataset_bounds_no_mask": self._vtkDataSetBoundsNoMask, "vtk_backend_geo": self._vtkGeoTransform, "vtk_backend_draw_area_bounds": drawAreaBounds, "vtk_backend_viewport_scale": [ self._context_xScale, self._context_yScale ] } if ("ratio_autot_viewport" in self._resultDict): kwargs["ratio_autot_viewport"] = vp self._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, t, z, **kwargs)) projection = vcs.elements["projection"][self._gm.projection] kwargs['xaxisconvert'] = self._gm.xaxisconvert kwargs['yaxisconvert'] = self._gm.yaxisconvert if self._data1.getAxis(-1).isLongitude() and self._data1.getAxis(-2).isLatitude(): self._context().plotContinents(self._plot_kargs.get("continents", self._useContinents), plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs)
def _plotInternal(self): """Overrides baseclass implementation.""" tmpLevels = [] tmpColors = [] tmpLineWidths = [] tmpLineStyles = [] linewidth = self._gm.linewidths self.extendAttribute(linewidth, default=1.0) linestyle = self._gm.line self.extendAttribute(linestyle, default='solid') plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds for i, l in enumerate(self._contourLevels): if i == 0: W = linewidth[i] S = linestyle[i] C = [self._contourColors[i]] if l == 1.e20: L = [-1.e20] else: L = [l] else: if W == linewidth[i] and S == linestyle[i]: # Ok same style and width, lets keep going L.append(l) C.append(self._contourColors[i]) else: tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineStyles.append(S) L = [l] C = [self._contourColors[i]] W = linewidth[i] S = linestyle[i] tmpLevels.append(L) tmpColors.append(C) tmpLineWidths.append(W) tmpLineStyles.append(S) cots = [] textprops = [] luts = [] actors = [] mappers = [] if self._gm.label and (self._gm.text or self._gm.textcolors): # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < len(self._contourLevels): texts.append(texts[-1]) else: texts = [None] * len(self._contourLevels) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < len(self._contourLevels): colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) # Custom background colors and opacities: backgroundColors = self._gm.labelbackgroundcolors if backgroundColors: while len(backgroundColors) < len(self._contourLevels): backgroundColors.append(backgroundColors[-1]) backgroundOpacities = self._gm.labelbackgroundopacities if backgroundOpacities: while len(backgroundOpacities) < len(self._contourLevels): backgroundOpacities.append(backgroundOpacities[-1]) countLevels = 0 vp = self._resultDict.get( 'ratio_autot_viewport', [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2]) dataset_renderer = None xScale, yScale = (1, 1) for i, l in enumerate(tmpLevels): numLevels = len(l) cot = vtk.vtkContourFilter() if self._hasCellData: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) for n in range(numLevels): cot.SetValue(n, l[n]) # TODO remove update cot.Update() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(tmpColors[i])) cmap = self.getColorMap() for n, col in enumerate(tmpColors[i]): r, g, b, a = self.getColorIndexOrRGBA(cmap, col) lut.SetTableValue(n, r / 100., g / 100., b / 100., a / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for n, val in enumerate(l): tpropMap.SetTuple(n, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: ttexts = texts[countLevels:(countLevels + len(l))] for idx, tc in enumerate(ttexts): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" elif isinstance(tc, (str, unicode)): sp = tc.split(":::") if len(sp) == 2: tt = sp[0] to = sp[1] else: # Hum don't know what do do with this if sp[0] in vcs.listelements("textcombined"): tc = vcs.gettextcombined(tc) tt, to = tuple(tc.name.split(":::")) elif sp[0] in vcs.listelements("textorientation"): to = sp[0] tt = "default" elif sp[0] in vcs.listelements("texttable"): tt = sp[0] to = "default" colorOverride = colorOverrides[countLevels + idx] if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name if backgroundColors is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundcolor = backgroundColors[countLevels + idx] if backgroundOpacities is not None: texttbl = vcs.gettexttable(tt) texttbl.backgroundopacity = backgroundOpacities[countLevels + idx] tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), to, tt, cmap=cmap) tprops.AddItem(tprop) if colorOverride is not None: del(vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), cmap=cmap) tprops.AddItem(tprop) textprops.append(tprops) mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) mapper.SetSkipDistance(self._gm.labelskipdistance) pdMapper = mapper.GetPolyDataMapper() luts.append([lut, [l[0], l[-1], False]]) else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper luts.append([lut, [l[0], l[-1], False]]) pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(l[0], l[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) cots.append(cot) # Create actor to add to scene act = vtk.vtkActor() act.SetMapper(mapper) # Set line properties here p = act.GetProperty() p.SetLineWidth(tmpLineWidths[i]) vcs2vtk.stippleLine(p, tmpLineStyles[i]) if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not # sure why so sticking to many mappers act = vcs2vtk.doWrap(act, plotting_dataset_bounds, self._dataWrapModulo) actors.append([act, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) dataset_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(), geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=(dataset_renderer is None)) countLevels += len(l) if len(textprops) > 0: self._resultDict["vtk_backend_contours_labels_text_properties"] = \ textprops if len(luts) > 0: if self._gm.label: self._resultDict["vtk_backend_labeled_luts"] = luts else: self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) act = vtk.vtkActor() act.SetMapper(self._maskedDataMapper) if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not # sure why so sticking to many mappers act = vcs2vtk.doWrap(act, plotting_dataset_bounds, self._dataWrapModulo) actors.append([act, self._maskedDataMapper, plotting_dataset_bounds]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSet.GetBounds(), geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict["vtk_backend_actors"] = actors t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None kwargs = {"vtk_backend_grid": self._vtkDataSet, "dataset_bounds": self._vtkDataSetBounds, "plotting_dataset_bounds": plotting_dataset_bounds, "vtk_backend_geo": self._vtkGeoTransform} if ("ratio_autot_viewport" in self._resultDict): kwargs["ratio_autot_viewport"] = vp self._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, t, z, **kwargs)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] continents_renderer, xScale, yScale = self._context().plotContinents( plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, vtk_backend_grid=self._vtkDataSet, dataset_bounds=self._vtkDataSetBounds)
def update_input(self,vtkobjects,array1,array2=None,update=True): if vtkobjects.has_key("vtk_backend_grid"): ## Ok ths is where we update the input data vg=vtkobjects["vtk_backend_grid"] data = vcs2vtk.numpy_to_vtk_wrapper(array1.filled(0.).flat, deep=False) pData= vg.GetPointData().GetScalars() if pData is not None: vg.GetPointData().SetScalars(data) else: vg.GetCellData().SetScalars(data) if vtkobjects.has_key("vtk_backend_filter"): vtkobjects["vtk_backend_filter"].Update() if vtkobjects.has_key("vtk_backend_missing_mapper"): missingMapper,color,cellData = vtkobjects["vtk_backend_missing_mapper"] missingMapper2 = vcs2vtk.putMaskOnVTKGrid(array1,vg,color,cellData,deep=False) else: missingMapper = None if vtkobjects.has_key("vtk_backend_contours"): for c in vtkobjects["vtk_backend_contours"]: c.Update() ports=vtkobjects["vtk_backend_contours"] elif vtkobjects.has_key("vtk_backend_geofilters"): ports=vtkobjects["vtk_backend_geofilters"] else: # Vector plot ports=vtkobjects["vtk_backend_glyphfilters"] w = vcs2vtk.generateVectorArray(array1,array2,vg) vg.GetPointData().AddArray(w) vg = vcs2vtk.stripGrid(vg) ports[0].SetInputData(vg) if vtkobjects.has_key("vtk_backend_actors"): i=0 for a in vtkobjects["vtk_backend_actors"]: act = a[0] wrp = a[1] if a[1] is missingMapper: i-=1 mapper = missingMapper2 wrp = a[2] else: ## Labeled contours are a different kind if vtkobjects.has_key("vtk_backend_luts"): lut,rg = vtkobjects["vtk_backend_luts"][i] mapper = vtk.vtkPolyDataMapper() elif vtkobjects.has_key("vtk_backend_labeled_luts"): lut,rg = vtkobjects["vtk_backend_labeled_luts"][i] mapper = vtk.vtkLabeledContourMapper() if lut is None: mapper.SetInputConnection(ports[i].GetOutputPort()) else: if mapper.IsA("vtkPolyDataMapper"): mapper.SetInputConnection(ports[i].GetOutputPort()) mapper.SetLookupTable(lut) mapper.SetScalarModeToUsePointData() else: stripper = vtk.vtkStripper() stripper.SetInputConnection(ports[i].GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) stripper.Update() tprops = vtkobjects["vtk_backend_contours_labels_text_properties"] mapper.GetPolyDataMapper().SetLookupTable(lut) mapper.GetPolyDataMapper().SetScalarModeToUsePointData() mapper.GetPolyDataMapper().SetScalarRange(rg[0],rg[1]) mapper.SetLabelVisibility(1) mapper.SetTextProperties(tprops) if rg[2]: mapper.SetScalarModeToUseCellData() mapper.SetScalarRange(rg[0],rg[1]) act.SetMapper(mapper) act = vcs2vtk.doWrap(a[0],wrp) a[0].SetMapper(act.GetMapper()) i+=1 taxis = array1.getTime() if taxis is not None: tstr = str(cdtime.reltime(taxis[0],taxis.units).tocomp(taxis.getCalendar())) else: tstr = None ## Min/Max/Mean for att in ["Min","Max","Mean","crtime","crdate","zvalue"]: if vtkobjects.has_key("vtk_backend_%s_text_actor" % att): t = vtkobjects["vtk_backend_%s_text_actor" % att] if att == "Min": t.SetInput("Min %g" % array1.min()) elif att == "Max": t.SetInput("Max %g" % array1.max()) elif att == "Mean": if not inspect.ismethod(getattr(array1,'mean')): meanstring = "Mean: %s" % getattr(array1,"mean") else: try: meanstring='Mean %.4g'% float(cdutil.averager(array1, axis = " ".join(["(%s)" % S for S in array1.getAxisIds()]))) except Exception,err: meanstring='Mean %.4g'%array1.mean() t.SetInput(meanstring) elif att=="crdate" and tstr is not None: t.SetInput(tstr.split()[0].replace("-","/")) elif att=="crtime" and tstr is not None: t.SetInput(tstr.split()[1]) elif att=="zvalue": if len(array1.shape)>2: l=array1.getAxis(-3) if l.isTime(): t.SetInput(str(l.asComponentTime()[0])) else: t.SetInput("%g" % l[0])