def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkGlyph2D(), 'Processing.', ('vtkDataSet', 'vtkPolyData'), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def render(self): """ Glyphs the input polydata points with the requested shape and replaces the input polydata with glyphed output polydata with colored cells """ self.glyph = vtk.vtkPolyData() pts = vtk.vtkPoints() pts.Allocate(6, 6) self.glyph.SetPoints(pts) verts = vtk.vtkCellArray() verts.Allocate(verts.EstimateSize(1, 1), 1) self.glyph.SetVerts(verts) lines = vtk.vtkCellArray() lines.Allocate(lines.EstimateSize(4, 2), 2) self.glyph.SetLines(lines) polys = vtk.vtkCellArray() polys.Allocate(polys.EstimateSize(1, 4), 4) self.glyph.SetPolys(polys) self.paint() self.transform_glyph() self.glyph2D = vtk.vtkGlyph2D() self.glyph2D.OrientOff() self.glyph2D.ScalingOff() self.glyph2D.SetScaleModeToDataScalingOff() self.glyph2D.SetInputData(self.patternPolyData) self.glyph2D.SetSourceData(self.glyph) self.glyph2D.Update() self.patternPolyData.DeepCopy(self.glyph2D.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkGlyph2D(), 'Processing.', ('vtkDataSet', 'vtkPolyData'), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def main(): colors = vtk.vtkNamedColors() points = vtk.vtkPoints() points.InsertNextPoint(0, 0, 0) points.InsertNextPoint(1, 1, 0) points.InsertNextPoint(2, 2, 0) polydata = vtk.vtkPolyData() polydata.SetPoints(points) # Create anything you want here, we will use a polygon for the demo. polygonSource = vtk.vtkRegularPolygonSource() # default is 6 sides glyph2D = vtk.vtkGlyph2D() glyph2D.SetSourceConnection(polygonSource.GetOutputPort()) glyph2D.SetInputData(polydata) glyph2D.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph2D.GetOutputPort()) mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d('Salmon')) # Visualize renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('SlateGray')) style = vtk.vtkInteractorStyleImage() renderWindowInteractor.SetInteractorStyle(style) renderWindow.SetWindowName('Glyph2D') renderWindow.Render() renderWindowInteractor.Start()
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() points = vtk.vtkPoints() points.InsertNextPoint(0, 0, 0) points.InsertNextPoint(1, 1, 0) points.InsertNextPoint(2, 2, 0) polyData = vtk.vtkPolyData() polyData.SetPoints(points) # Create anything you want here, we will use a polygon for the demo. polygonSource = vtk.vtkRegularPolygonSource() #default is 6 sides glyph2D = vtk.vtkGlyph2D() glyph2D.SetSourceConnection(polygonSource.GetOutputPort()) glyph2D.SetInput(polyData) glyph2D.Update() # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph2D.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def __init__(self, parent=None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() points = vtk.vtkPoints() points.InsertNextPoint(0, 0, 0) points.InsertNextPoint(1, 1, 0) points.InsertNextPoint(2, 2, 0) polyData = vtk.vtkPolyData() polyData.SetPoints(points) # Create anything you want here, we will use a polygon for the demo. polygonSource = vtk.vtkRegularPolygonSource() #default is 6 sides glyph2D = vtk.vtkGlyph2D() glyph2D.SetSourceConnection(polygonSource.GetOutputPort()) glyph2D.SetInput(polyData) glyph2D.Update() # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph2D.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def __init__(self, curveNode, sliceNode): VTKObservationMixin.__init__(self) self.glyphScale = 0.5 self.intersectionPoints_XY = vtk.vtkPolyData() self.glyphSource = slicer.vtkMarkupsGlyphSource2D() self.glyphSource.SetGlyphType( slicer.vtkMarkupsGlyphSource2D.GlyphCrossDot) self.glypher = vtk.vtkGlyph2D() self.glypher.SetInputData(self.intersectionPoints_XY) self.glypher.SetScaleFactor(1.0) self.glypher.SetSourceConnection(self.glyphSource.GetOutputPort()) self.mapper = vtk.vtkPolyDataMapper2D() self.mapper.SetInputConnection(self.glypher.GetOutputPort()) self.mapper.ScalarVisibilityOff() mapperCoordinate = vtk.vtkCoordinate() mapperCoordinate.SetCoordinateSystemToDisplay() self.mapper.SetTransformCoordinate(mapperCoordinate) self.property = vtk.vtkProperty2D() self.property.SetColor(0.4, 1.0, 1.0) self.property.SetPointSize(3.) self.property.SetLineWidth(3.) self.property.SetOpacity(1.) self.actor = vtk.vtkActor2D() self.actor.SetMapper(self.mapper) self.actor.SetProperty(self.property) self.curveNode = curveNode self.sliceNode = sliceNode self.visibility = True
def prepMarker(renWin,marker,cmap=None): n=prepPrimitive(marker) if n==0: return [] actors=[] for i in range(n): g = vtk.vtkGlyph2D() markers = vtk.vtkPolyData() x = marker.x[i] y = marker.y[i] c = marker.color[i] N = max(len(x),len(y)) for a in [x,y]: while len(a)<n: a.append(a[-1]) pts = vtk.vtkPoints() for j in range(N): pts.InsertNextPoint(x[j],y[j],0.) geo,pts = project(pts,marker.projection,marker.worldcoordinate) markers.SetPoints(pts) # Type ## Ok at this point generates the source for glpyh gs, pd = prepGlyph(g, marker, index=i) g.SetInputData(markers) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputConnection(g.GetOutputPort()) m.Update() a.SetMapper(m) p = a.GetProperty() setMarkerColor(p, marker, c, cmap) actors.append((g, gs, pd, a, geo)) return actors
def plot(self, data1, data2, tmpl, gm, grid, transform): """Overrides baseclass implementation.""" # Preserve time and z axis for plotting these inof in rendertemplate geo = None # to make flake8 happy returned = {} taxis = data1.getTime() if data1.ndim > 2: zaxis = data1.getAxis(-3) else: zaxis = None # Ok get3 only the last 2 dims data1 = self._context().trimData2D(data1) data2 = self._context().trimData2D(data2) gridGenDict = vcs2vtk.genGridOnPoints(data1, gm, deep=False, grid=grid, geo=transform) for k in ['vtk_backend_grid', 'xm', 'xM', 'ym', 'yM', 'continents', 'wrap', 'geo']: exec("%s = gridGenDict['%s']" % (k, k)) grid = gridGenDict['vtk_backend_grid'] self._dataWrapModulo = gridGenDict['wrap'] returned["vtk_backend_grid"] = grid returned["vtk_backend_geo"] = geo missingMapper = vcs2vtk.putMaskOnVTKGrid(data1, grid, None, False, deep=False) # None/False are for color and cellData # (sent to vcs2vtk.putMaskOnVTKGrid) returned["vtk_backend_missing_mapper"] = (missingMapper, None, False) w = vcs2vtk.generateVectorArray(data1, data2, grid) grid.GetPointData().AddArray(w) # Vector attempt l = gm.line if l is None: l = "default" try: l = vcs.getline(l) lwidth = l.width[0] # noqa lcolor = l.color[0] lstyle = l.type[0] # noqa except: lstyle = "solid" # noqa lwidth = 1. # noqa lcolor = 0 if gm.linewidth is not None: lwidth = gm.linewidth # noqa if gm.linecolor is not None: lcolor = gm.linecolor arrow = vtk.vtkGlyphSource2D() arrow.SetGlyphTypeToArrow() arrow.FilledOff() glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetInputData(grid) glyphFilter.SetInputArrayToProcess(1, 0, 0, 0, "vectors") glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.SetVectorModeToUseVector() # Rotate arrows to match vector data: glyphFilter.OrientOn() # Scale to vector magnitude: glyphFilter.SetScaleModeToScaleByVector() glyphFilter.SetScaleFactor(2. * gm.scale) # These are some unfortunately named methods. It does *not* clamp the # scale range to [min, max], but rather remaps the range # [min, max] --> [0, 1]. glyphFilter.ClampingOn() glyphFilter.SetRange(0.01, 1.0) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyphFilter.GetOutputPort()) act = vtk.vtkActor() act.SetMapper(mapper) cmap = self._context().canvas.getcolormapname() cmap = vcs.elements["colormap"][cmap] r, g, b = cmap.index[lcolor] act.GetProperty().SetColor(r / 100., g / 100., b / 100.) x1, x2, y1, y2 = vcs.utils.getworldcoordinates(gm, data1.getAxis(-1), data1.getAxis(-2)) act = vcs2vtk.doWrap(act, [x1, x2, y1, y2], self._dataWrapModulo) self._context().fitToViewport(act, [tmpl.data.x1, tmpl.data.x2, tmpl.data.y1, tmpl.data.y2], [x1, x2, y1, y2], priority=tmpl.data.priority, create_renderer=True) returned.update( self._context().renderTemplate(tmpl, data1, gm, taxis, zaxis)) if self._context().canvas._continents is None: continents = False if continents: projection = vcs.elements["projection"][gm.projection] self._context().plotContinents(x1, x2, y1, y2, projection, self._dataWrapModulo, tmpl) returned["vtk_backend_actors"] = [[act, [x1, x2, y1, y2]]] returned["vtk_backend_glyphfilters"] = [glyphFilter] returned["vtk_backend_luts"] = [[None, None]] return returned
def _plotInternal(self): """Overrides baseclass implementation.""" # Preserve time and z axis for plotting these inof in rendertemplate projection = vcs.elements["projection"][self._gm.projection] taxis = self._originalData1.getTime() if self._originalData1.ndim > 2: zaxis = self._originalData1.getAxis(-3) else: zaxis = None # Streamline color if (not self._gm.coloredbyvector): ln_tmp = self._gm.linetype if ln_tmp is None: ln_tmp = "default" try: ln_tmp = vcs.getline(ln_tmp) lwidth = ln_tmp.width[0] # noqa lcolor = ln_tmp.color[0] lstyle = ln_tmp.type[0] # noqa except Exception: lstyle = "solid" # noqa lwidth = 1. # noqa lcolor = [0., 0., 0., 100.] if self._gm.linewidth is not None: lwidth = self._gm.linewidth # noqa if self._gm.linecolor is not None: lcolor = self._gm.linecolor self._vtkPolyDataFilter.Update() polydata = self._vtkPolyDataFilter.GetOutput() dataLength = polydata.GetLength() if (not self._gm.evenlyspaced): # generate random seeds in a circle centered in the center of # the bounding box for the data. # by default vtkPointSource uses a global random source in vtkMath which is # seeded only once. It makes more sense to seed a random sequence each time you draw # the streamline plot. pointSequence = vtk.vtkMinimalStandardRandomSequence() pointSequence.SetSeedOnly(1177) # replicate the seed from vtkMath seed = vtk.vtkPointSource() seed.SetNumberOfPoints(self._gm.numberofseeds) seed.SetCenter(polydata.GetCenter()) seed.SetRadius(dataLength / 2.0) seed.SetRandomSequence(pointSequence) seed.Update() seedData = seed.GetOutput() # project all points to Z = 0 plane points = seedData.GetPoints() for i in range(0, points.GetNumberOfPoints()): p = list(points.GetPoint(i)) p[2] = 0 points.SetPoint(i, p) if (self._gm.integratortype == 0): integrator = vtk.vtkRungeKutta2() elif (self._gm.integratortype == 1): integrator = vtk.vtkRungeKutta4() else: if (self._gm.evenlyspaced): warnings.warn( "You cannot use RungeKutta45 for evenly spaced streamlines." "Using RungeKutta4 instead") integrator = vtk.vtkRungeKutta4() else: integrator = vtk.vtkRungeKutta45() if (self._gm.evenlyspaced): streamer = vtk.vtkEvenlySpacedStreamlines2D() streamer.SetStartPosition(self._gm.startseed) streamer.SetSeparatingDistance(self._gm.separatingdistance) streamer.SetSeparatingDistanceRatio( self._gm.separatingdistanceratio) streamer.SetClosedLoopMaximumDistance( self._gm.closedloopmaximumdistance) else: # integrate streamlines on normalized vector so that # IntegrationTime stores distance streamer = vtk.vtkStreamTracer() streamer.SetSourceData(seedData) streamer.SetIntegrationDirection(self._gm.integrationdirection) streamer.SetMinimumIntegrationStep(self._gm.minimumsteplength) streamer.SetMaximumIntegrationStep(self._gm.maximumsteplength) streamer.SetMaximumError(self._gm.maximumerror) streamer.SetMaximumPropagation(dataLength * self._gm.maximumstreamlinelength) streamer.SetInputData(polydata) streamer.SetInputArrayToProcess(0, 0, 0, 0, "vector") streamer.SetIntegrationStepUnit(self._gm.integrationstepunit) streamer.SetInitialIntegrationStep(self._gm.initialsteplength) streamer.SetMaximumNumberOfSteps(self._gm.maximumsteps) streamer.SetTerminalSpeed(self._gm.terminalspeed) streamer.SetIntegrator(integrator) # add arc_length to streamlines arcLengthFilter = vtk.vtkAppendArcLength() arcLengthFilter.SetInputConnection(streamer.GetOutputPort()) arcLengthFilter.Update() streamlines = arcLengthFilter.GetOutput() # glyph seed points contour = vtk.vtkContourFilter() contour.SetInputConnection(arcLengthFilter.GetOutputPort()) contour.SetValue(0, 0.001) if (streamlines.GetNumberOfPoints()): r = streamlines.GetPointData().GetArray("arc_length").GetRange() numberofglyphsoneside = self._gm.numberofglyphs // 2 for i in range(1, numberofglyphsoneside): contour.SetValue(i, r[1] / numberofglyphsoneside * i) else: warnings.warn( "No streamlines created. " "The 'startseed' parameter needs to be inside the domain and " "not over masked data.") contour.SetInputArrayToProcess(0, 0, 0, 0, "arc_length") # arrow glyph source glyph2DSource = vtk.vtkGlyphSource2D() glyph2DSource.SetGlyphTypeToTriangle() glyph2DSource.SetRotationAngle(-90) glyph2DSource.SetFilled(self._gm.filledglyph) # arrow glyph adjustment transform = vtk.vtkTransform() transform.Scale(1., self._gm.glyphbasefactor, 1.) transformFilter = vtk.vtkTransformFilter() transformFilter.SetInputConnection(glyph2DSource.GetOutputPort()) transformFilter.SetTransform(transform) transformFilter.Update() glyphLength = transformFilter.GetOutput().GetLength() # drawing the glyphs at the seed points glyph = vtk.vtkGlyph2D() glyph.SetInputConnection(contour.GetOutputPort()) glyph.SetInputArrayToProcess(1, 0, 0, 0, "vector") glyph.SetSourceData(transformFilter.GetOutput()) glyph.SetScaleModeToDataScalingOff() glyph.SetScaleFactor(dataLength * self._gm.glyphscalefactor / glyphLength) glyph.SetColorModeToColorByVector() glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection(glyph.GetOutputPort()) glyphActor = vtk.vtkActor() glyphActor.SetMapper(glyphMapper) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(streamer.GetOutputPort()) act = vtk.vtkActor() act.SetMapper(mapper) # color the streamlines and glyphs cmap = self.getColorMap() if (self._gm.coloredbyvector): numLevels = len(self._contourLevels) - 1 while len(self._contourColors) < numLevels: self._contourColors.append(self._contourColors[-1]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(numLevels) for i in range(numLevels): r, g, b, a = self.getColorIndexOrRGBA(cmap, self._contourColors[i]) lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.) lut.SetVectorModeToMagnitude() if numpy.allclose(self._contourLevels[0], -1.e20): lmn = self._vectorRange[0] else: lmn = self._contourLevels[0][0] if numpy.allclose(self._contourLevels[-1], 1.e20): lmx = self._vectorRange[1] else: lmx = self._contourLevels[-1][-1] lut.SetRange(lmn, lmx) mapper.ScalarVisibilityOn() mapper.SetLookupTable(lut) mapper.UseLookupTableScalarRangeOn() mapper.SetScalarModeToUsePointFieldData() mapper.SelectColorArray("vector") glyphMapper.ScalarVisibilityOn() glyphMapper.SetLookupTable(lut) glyphMapper.UseLookupTableScalarRangeOn() glyphMapper.SetScalarModeToUsePointFieldData() glyphMapper.SelectColorArray("VectorMagnitude") else: mapper.ScalarVisibilityOff() glyphMapper.ScalarVisibilityOff() if isinstance(lcolor, (list, tuple)): r, g, b, a = lcolor else: r, g, b, a = cmap.index[lcolor] act.GetProperty().SetColor(r / 100., g / 100., b / 100.) glyphActor.GetProperty().SetColor(r / 100., g / 100., b / 100.) plotting_dataset_bounds = self.getPlottingBounds() 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, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) glyph_renderer, xScale, yScale = self._context().fitToViewport( glyphActor, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=False) 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, taxis, zaxis, **kwargs)) if (self._gm.coloredbyvector): self._resultDict.update(self._context().renderColorBar( self._template, self._contourLevels, self._contourColors, None, self.getColorMap())) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: continents_renderer, xScale, yScale = self._context( ).plotContinents(plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs) self._resultDict["vtk_backend_actors"] = [[ act, plotting_dataset_bounds ]] self._resultDict["vtk_backend_luts"] = [[None, None]]
def prepMarker(renWin,ren,marker,cmap=None): n=prepPrimitive(marker) if n==0: return for i in range(n): ## Creates the glyph g = vtk.vtkGlyph2D() markers = vtk.vtkPolyData() x = marker.x[i] y=marker.y[i] c=marker.color[i] s=marker.size[i]/float(max(marker.worldcoordinate))*10. t=marker.type[i] N = max(len(x),len(y)) for a in [x,y]: while len(a)<n: a.append(a[-1]) pts = vtk.vtkPoints() for j in range(N): pts.InsertNextPoint(x[j],y[j],0.) markers.SetPoints(pts) # Type ## Ok at this point generates the source for glpyh gs = vtk.vtkGlyphSource2D() pd = None if t=='dot': gs.SetGlyphTypeToCircle() gs.FilledOn() elif t=='circle': gs.SetGlyphTypeToCircle() gs.FilledOff() elif t=='plus': gs.SetGlyphTypeToCross() gs.FilledOff() elif t=='cross': gs.SetGlyphTypeToCross() gs.SetRotationAngle(45) gs.FilledOff() elif t[:6]=='square': gs.SetGlyphTypeToSquare() gs.FilledOff() elif t[:7]=='diamond': gs.SetGlyphTypeToDiamond() gs.FilledOff() elif t[:8]=='triangle': gs.SetGlyphTypeToTriangle() if t[9]=="d": gs.SetRotationAngle(180) elif t[9]=="l": gs.SetRotationAngle(90) elif t[9]=="r": gs.SetRotationAngle(-90) elif t[9]=="u": gs.SetRotationAngle(0) elif t == "hurricane": s =s/100. ds = vtk.vtkDiskSource() ds.SetInnerRadius(.55*s) ds.SetOuterRadius(1.01*s) ds.SetCircumferentialResolution(90) ds.SetRadialResolution(30) gf = vtk.vtkGeometryFilter() gf.SetInputConnection(ds.GetOutputPort()) gf.Update() pd1 = gf.GetOutput() apd = vtk.vtkAppendPolyData() apd.AddInputData(pd1) pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polygons = vtk.vtkCellArray() add_angle = numpy.pi/360. coords = [] angle1 = .6*numpy.pi angle2 = .88*numpy.pi while angle1<=angle2: coords.append([s*2+2*s*numpy.cos(angle1),2*s*numpy.sin(angle1)]) angle1+=add_angle angle1=.79*numpy.pi angle2=.6*numpy.pi while angle1>=angle2: coords.append([s*2.25+s*4*numpy.cos(angle1),-s*2+s*4*numpy.sin(angle1)]) angle1-=add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) coords=[] angle1 = 1.6*numpy.pi angle2 = 1.9*numpy.pi while angle1 <= angle2: coords.append( [- s*2 + s*2*numpy.cos(angle1),s*2*numpy.sin(angle1)]) angle1 += add_angle angle1 = 1.8*numpy.pi angle2 = 1.6*numpy.pi while angle1 >= angle2: coords.append( [- s*2.27 + s*4*numpy.cos(angle1), s*2 + s*4*numpy.sin(angle1)]) angle1 -= add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) pd.SetPoints(pts) pd.SetPolys(polygons) apd.AddInputData(pd) apd.Update() g.SetSourceData(apd.GetOutput()) elif t in ["w%.2i" % x for x in range(203)]: ## WMO marker params = wmo[t] pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polys = vtk.vtkCellArray() lines = vtk.vtkCellArray() #Lines first for l in params["line"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=False) lines.InsertNextCell(line) for l in params["poly"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=True) polys.InsertNextCell(line) pd.SetPoints(pts) pd.SetPolys(polys) pd.SetLines(lines) g.SetSourceData(pd) else: warnings.warn("unknown marker type: %s, using dot" % t) gs.SetGlyphTypeToCircle() gs.FilledOn() if t[-5:]=="_fill": gs.FilledOn() gs.SetScale(s) gs.Update() if pd is None: g.SetSourceConnection(gs.GetOutputPort()) g.SetInputData(markers) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputConnection(g.GetOutputPort()) m.Update() a.SetMapper(m) p = a.GetProperty() #Color if cmap is None: if marker.colormap is not None: cmap = marker.colormap else: cmap = 'default' if isinstance(cmap,str): cmap = vcs.elements["colormap"][cmap] color = cmap.index[c] p.SetColor([C/100. for C in color]) ren.AddActor(a) fitToViewport(a,ren,marker.viewport,marker.worldcoordinate) return
def prepMarker(renWin,marker,cmap=None): n=prepPrimitive(marker) if n==0: return actors=[] for i in range(n): ## Creates the glyph g = vtk.vtkGlyph2D() markers = vtk.vtkPolyData() x = marker.x[i] y=marker.y[i] c=marker.color[i] s=marker.size[i]*.5 t=marker.type[i] N = max(len(x),len(y)) for a in [x,y]: while len(a)<n: a.append(a[-1]) pts = vtk.vtkPoints() geo,pts = project(pts,marker.projection,marker.worldcoordinate) for j in range(N): pts.InsertNextPoint(x[j],y[j],0.) markers.SetPoints(pts) # Type ## Ok at this point generates the source for glpyh gs = vtk.vtkGlyphSource2D() pd = None if t=='dot': gs.SetGlyphTypeToCircle() gs.FilledOn() elif t=='circle': gs.SetGlyphTypeToCircle() gs.FilledOff() elif t=='plus': gs.SetGlyphTypeToCross() gs.FilledOff() elif t=='cross': gs.SetGlyphTypeToCross() gs.SetRotationAngle(45) gs.FilledOff() elif t[:6]=='square': gs.SetGlyphTypeToSquare() gs.FilledOff() elif t[:7]=='diamond': gs.SetGlyphTypeToDiamond() gs.FilledOff() elif t[:8]=='triangle': gs.SetGlyphTypeToTriangle() gs.FilledOff() if t[9]=="d": gs.SetRotationAngle(180) elif t[9]=="l": gs.SetRotationAngle(90) elif t[9]=="r": gs.SetRotationAngle(-90) elif t[9]=="u": gs.SetRotationAngle(0) elif t == "hurricane": s =s/5. ds = vtk.vtkDiskSource() ds.SetInnerRadius(.55*s) ds.SetOuterRadius(1.01*s) ds.SetCircumferentialResolution(90) ds.SetRadialResolution(30) gf = vtk.vtkGeometryFilter() gf.SetInputConnection(ds.GetOutputPort()) gf.Update() pd1 = gf.GetOutput() apd = vtk.vtkAppendPolyData() apd.AddInputData(pd1) pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polygons = vtk.vtkCellArray() add_angle = numpy.pi/360. coords = [] angle1 = .6*numpy.pi angle2 = .88*numpy.pi while angle1<=angle2: coords.append([s*2+2*s*numpy.cos(angle1),2*s*numpy.sin(angle1)]) angle1+=add_angle angle1=.79*numpy.pi angle2=.6*numpy.pi while angle1>=angle2: coords.append([s*2.25+s*4*numpy.cos(angle1),-s*2+s*4*numpy.sin(angle1)]) angle1-=add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) coords=[] angle1 = 1.6*numpy.pi angle2 = 1.9*numpy.pi while angle1 <= angle2: coords.append( [- s*2 + s*2*numpy.cos(angle1),s*2*numpy.sin(angle1)]) angle1 += add_angle angle1 = 1.8*numpy.pi angle2 = 1.6*numpy.pi while angle1 >= angle2: coords.append( [- s*2.27 + s*4*numpy.cos(angle1), s*2 + s*4*numpy.sin(angle1)]) angle1 -= add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) pd.SetPoints(pts) pd.SetPolys(polygons) apd.AddInputData(pd) apd.Update() g.SetSourceData(apd.GetOutput()) elif t[:4] == "star": np = 5 points = starPoints(.001 * s, 0, 0, np) pts = vtk.vtkPoints() # Add all perimeter points for point in points: pts.InsertNextPoint((point[0], point[1], 0)) center_id = len(points) # Add center point pts.InsertNextPoint((0,0,0)) polygons = vtk.vtkCellArray() for ind in range(0, np*2, 2): poly = vtk.vtkPolygon() pid = poly.GetPointIds() pid.SetNumberOfIds(4) pid.SetId(0, ind) pid.SetId(1, (ind - 1) % len(points)) pid.SetId(2, center_id) pid.SetId(3, (ind + 1) % len(points)) polygons.InsertNextCell(poly) pd = vtk.vtkPolyData() pd.SetPoints(pts) pd.SetPolys(polygons) g.SetSourceData(pd) elif t in ["w%.2i" % x for x in range(203)]: ## WMO marker params = wmo[t] pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polys = vtk.vtkCellArray() lines = vtk.vtkCellArray() s*=3 #Lines first for l in params["line"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=False) lines.InsertNextCell(line) for l in params["poly"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=True) polys.InsertNextCell(line) geo,pts = project(pts,marker.projection,marker.worldcoordinate) pd.SetPoints(pts) pd.SetPolys(polys) pd.SetLines(lines) g.SetSourceData(pd) else: warnings.warn("unknown marker type: %s, using dot" % t) gs.SetGlyphTypeToCircle() gs.FilledOn() if t[-5:]=="_fill": gs.FilledOn() if pd is None: # Use the difference in x to scale the point, as later we'll use the # x range to correct the aspect ratio: dx = marker.worldcoordinate[1] - marker.worldcoordinate[0] s *= abs(float(dx))/500. gs.SetScale(s) gs.Update() if pd is None: g.SetSourceConnection(gs.GetOutputPort()) g.SetInputData(markers) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputConnection(g.GetOutputPort()) m.Update() a.SetMapper(m) p = a.GetProperty() #Color if cmap is None: if marker.colormap is not None: cmap = marker.colormap else: cmap = 'default' if isinstance(cmap,str): cmap = vcs.elements["colormap"][cmap] color = cmap.index[c] p.SetColor([C/100. for C in color]) actors.append((g,gs,pd,a,geo)) return actors
points.InsertNextPoint(j * 3, i * 3, 0) polydata = vtk.vtkPolyData() polydata.SetPoints(points) glyphSource = vtk.vtkGlyphSource2D() glyphSource.SetGlyphType(i) glyphSource.FilledOff() glyphSource.SetResolution(25) glyphSource.SetScale(fixedScales[j - 1]) if GLYPH_TYPES[i] == 'VTK_TRIANGLE_GLYPH': glyphSource.SetRotationAngle(90) glyph2D = vtk.vtkGlyph2D() glyph2D.SetSourceConnection(glyphSource.GetOutputPort()) glyph2D.SetInputData(polydata) glyph2D.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph2D.GetOutputPort()) mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) actors.append(actor) # Set up the renderer, render window, and interactor. renderer = vtk.vtkRenderer()
vectors.SetNumberOfTuples(numPoints) vectors.SetName("vectors") for i in range(numPoints): vectors.InsertTuple3(i, dx[i], dy[i], 0.0) # construct the grid grid = vtk.vtkUnstructuredGrid() grid.SetPoints(points) grid.GetPointData().AddArray(vectors) grid.GetPointData().SetActiveVectors("vectors") # make the arrow source arrow = vtk.vtkArrowSource() # make the glyph glyph = vtk.vtkGlyph2D() glyph.ScalingOn() glyph.SetScaleModeToScaleByVector() glyph.SetColorModeToColorByVector() glyph.SetScaleFactor(0.5) glyph.SetSource(arrow.GetOutput()) glyph.SetInput(grid) glyph.ClampingOff() # set up a stripper for faster rendering stripper = vtk.vtkStripper() stripper.SetInput(glyph.GetOutput()) # get the maximum norm of the data maxNorm = grid.GetPointData().GetVectors().GetMaxNorm()
def __init__(self, filename, parent=None): QtGui.QMainWindow.__init__(self, parent) # Initiate the UI as defined by Qt Designer self.ui = Ui_MainWindow() self.ui.setupUi(self) self.poly_data = None self.node_ids = None self.element_ids = None self.node_count = 0 self.read_data(filename) self.ui.txt_msg.appendPlainText("Model Loaded.") # initialize colors self.eidcolor = (0, 0.5, 0.5) self.edgecolor = (0, 0, 0) self.bgcolor1 = (0, 0, 1) self.bgcolor2 = (0.8, 0.8, 1) self.perspective = 0 self.solid = 1 self.idFilter = vtk.vtkIdFilter() self.idFilter.SetInputData(self.poly_data) self.idFilter.SetIdsArrayName("OriginalIds") self.idFilter.Update() self.surfaceFilter = vtk.vtkDataSetSurfaceFilter() self.surfaceFilter.SetInputConnection(self.idFilter.GetOutputPort()) self.surfaceFilter.Update() self.input = self.surfaceFilter.GetOutput() self.renderer = vtk.vtkRenderer() #self.renderer2 = vtk_widget.vtkRenderer() viewport = [0.0,0.0,0.15,0.15] #self.renderer2.SetViewport(viewport) #self.renderer2.Transparent() self.renderWindowInteractor = QVTKRenderWindowInteractor(self.ui.frame) self.renderWindowInteractor.GetRenderWindow().AddRenderer(self.renderer) #self.renderWindowInteractor.GetRenderWindow().AddRenderer(self.renderer2) self.renderWindowInteractor.GetRenderWindow().SetAlphaBitPlanes(1) self.axes = CoordinateAxes(self.renderWindowInteractor) self.ui.vl.addWidget(self.renderWindowInteractor) self.iren = vtk.vtkRenderWindowInteractor() self.iren = self.renderWindowInteractor.GetRenderWindow().GetInteractor() self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputData(self.input) self.mapper.ScalarVisibilityOff() self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) self.actor.GetProperty().SetPointSize(2) self.actor.GetProperty().EdgeVisibilityOn() self.actor.GetProperty().SetColor(self.eidcolor) self.actor.GetProperty().SetEdgeColor(self.edgecolor) self.camera = vtk.vtkCamera() #self.camera2 = vtk_widget.vtkCamera() # trial... add glyph pd = vtk.vtkPolyData() pts = vtk.vtkPoints() scalars = vtk.vtkFloatArray() vectors = vtk.vtkFloatArray() vectors.SetNumberOfComponents(3) pd.SetPoints(pts) pd.GetPointData().SetScalars(scalars) pd.GetPointData().SetVectors(vectors) pts.InsertNextPoint(30, 30, 0.0) scalars.InsertNextValue(1) vectors.InsertNextTuple3(1, 1, 0.0) # Create simple PolyData for glyph table cs = vtk.vtkCubeSource() cs.SetXLength(0.5) cs.SetYLength(1) cs.SetZLength(2) # Set up the glyph filter glyph = vtk.vtkGlyph3D() #glyph.SetInputConnection(elev.GetOutputPort()) point_list = vtk.vtkPoints() point_list.InsertNextPoint([30, 30, 0]) poly_data = vtk.vtkPolyData() poly_data.SetPoints(point_list) idFilter = vtk.vtkIdFilter() idFilter.SetInputData(poly_data) idFilter.SetIdsArrayName("OriginalIds") idFilter.Update() surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(idFilter.GetOutputPort()) surfaceFilter.Update() # Here is where we build the glyph table # that will be indexed into according to the IndexMode glyph.SetSourceData(0,cs.GetOutput()) #glyph.SetInputConnection(surfaceFilter.GetOutputPort()) glyph.SetInputData(pd) glyph.SetIndexModeToScalar() glyph.SetRange(0, 1) glyph.SetScaleModeToDataScalingOff() glyph.OrientOn() mapper3 = vtk.vtkPolyDataMapper() mapper3.SetInputConnection(glyph.GetOutputPort()) mapper3.SetScalarModeToUsePointFieldData() mapper3.SetColorModeToMapScalars() mapper3.ScalarVisibilityOn() mapper3.SetScalarRange(0, 1) actor3 = vtk.vtkActor() actor3.SetMapper(mapper3) #actor3.GetProperty().SetBackgroundOpacity(0.5) gs = vtk.vtkGlyphSource2D() gs.SetGlyphTypeToCircle() gs.SetScale(25) gs.FilledOff() #gs.CrossOn() gs.Update() # Create a table of glyphs glypher = vtk.vtkGlyph2D() glypher.SetInputData(pd) glypher.SetSourceData(0, gs.GetOutput()) glypher.SetIndexModeToScalar() glypher.SetRange(0, 1) glypher.SetScaleModeToDataScalingOff() mapper = vtk.vtkPolyDataMapper2D() mapper.SetInputConnection(glypher.GetOutputPort()) mapper.SetScalarRange(0, 1) actor2D = vtk.vtkActor2D() actor2D.SetMapper(mapper) self.renderer.AddActor(self.actor) #self.renderer.AddActor(mapper) #self.renderer2.AddActor(actor3) self.renderer.SetBackground(self.bgcolor1) self.renderer.SetBackground2(self.bgcolor2) self.renderer.GradientBackgroundOn() self.renderer.SetActiveCamera(self.camera) self.renderer.ResetCamera() #self.camera.ZoomOff() #self.renderer2.SetActiveCamera(self.camera) #self.renderer2.ResetCamera() #self.renderer2.SetBackground(0,0,0) #self.renderer2.GetProperty().SetBackgroundOpacity(0.5) #self.renderer2.SetLayer(1) #self.renderer2.Clear() self.areaPicker = vtk.vtkAreaPicker() self.renderWindowInteractor.SetPicker(self.areaPicker) self.style = MyInteractorStyle() self.style.SetPoints(self.input) self.style.SetDefaultRenderer(self.renderer) self.style.Data = self.idFilter.GetOutput() self.style.camera = self.camera self.style.node_ids = self.node_ids self.style.element_ids = self.element_ids self.style.node_count = self.node_count self.style.window = self self.style.print_message = self.ui.txt_msg.appendPlainText self.renderWindowInteractor.SetInteractorStyle(self.style) self.renderWindowInteractor.Start() # screenshot code:e #self.w2if = vtk_widget.vtkWindowToImageFilter() #self.w2if.SetInput(self.renWin) #self.w2if.Update() self.show() self.iren.Initialize() #self.iren.Start() # Setup Connections self.ui.btn_bgcolor1.clicked.connect(self.on_color1) self.ui.btn_bgcolor2.clicked.connect(self.on_color2) self.ui.btn_edgecolor.clicked.connect(self.on_edgecolor) self.ui.btn_elementcolor.clicked.connect(self.on_elementcolor) self.ui.btn_nofillededge.clicked.connect(self.on_nofillededge) self.ui.btn_switch.clicked.connect(self.on_switch) self.ui.btn_perspectivetoggle.clicked.connect(self.on_toggleperspective) self.ui.btn_saveimg.clicked.connect(self.on_saveimg) self.ui.btn_togglewire.clicked.connect(self.on_togglewire) # Setup a shortcuts self.setusrstyle = QtGui.QShortcut(self) self.setusrstyle.setKey(("CTRL+c")) self.setusrstyle.activated.connect(self.on_copyimg)
def _plotInternal(self): """Overrides baseclass implementation.""" # Preserve time and z axis for plotting these inof in rendertemplate projection = vcs.elements["projection"][self._gm.projection] taxis = self._originalData1.getTime() scaleFactor = 1.0 if self._originalData1.ndim > 2: zaxis = self._originalData1.getAxis(-3) else: zaxis = None scale = 1.0 lat = None lon = None latAccessor = self._data1.getLatitude() lonAccessor = self._data1.getLongitude() if latAccessor: lat = latAccessor[:] if lonAccessor: lon = lonAccessor[:] if self._vtkGeoTransform is not None: newv = vtk.vtkDoubleArray() newv.SetNumberOfComponents(3) newv.InsertTypedTuple(0, [lon.min(), lat.min(), 0]) newv.InsertTypedTuple(1, [lon.max(), lat.max(), 0]) vcs2vtk.projectArray(newv, projection, self._vtkDataSetBounds) dimMin = [0, 0, 0] dimMax = [0, 0, 0] newv.GetTypedTuple(0, dimMin) newv.GetTypedTuple(1, dimMax) maxDimX = max(dimMin[0], dimMax[0]) maxDimY = max(dimMin[1], dimMax[1]) if lat.max() != 0.0: scale = abs((maxDimY / lat.max())) if lon.max() != 0.0: temp = abs((maxDimX / lon.max())) if scale < temp: scale = temp else: scale = 1.0 # Vector attempt l = self._gm.linetype if l is None: l = "default" try: l = vcs.getline(l) lwidth = l.width[0] # noqa lcolor = l.color[0] lstyle = l.type[0] # noqa except: lstyle = "solid" # noqa lwidth = 1. # noqa lcolor = [0., 0., 0., 100.] if self._gm.linewidth is not None: lwidth = self._gm.linewidth # noqa if self._gm.linecolor is not None: lcolor = self._gm.linecolor arrow = vtk.vtkGlyphSource2D() arrow.SetGlyphTypeToArrow() arrow.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION) arrow.FilledOff() polydata = self._vtkPolyDataFilter.GetOutput() vectors = polydata.GetPointData().GetVectors() if self._gm.scaletype == 'constant' or\ self._gm.scaletype == 'constantNNormalize' or\ self._gm.scaletype == 'constantNLinear': scaleFactor = scale * 2.0 * self._gm.scale else: scaleFactor = 1.0 glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetInputData(polydata) glyphFilter.SetInputArrayToProcess(1, 0, 0, 0, "vector") glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.SetVectorModeToUseVector() # Rotate arrows to match vector data: glyphFilter.OrientOn() glyphFilter.ScalingOn() glyphFilter.SetScaleModeToScaleByVector() if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'linear' or\ self._gm.scaletype == 'constantNNormalize' or self._gm.scaletype == 'constantNLinear': # Find the min and max vector magnitudes maxNorm = vectors.GetMaxNorm() if maxNorm == 0: maxNorm = 1.0 if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'constantNNormalize': scaleFactor /= maxNorm if self._gm.scaletype == 'linear' or self._gm.scaletype == 'constantNLinear': minNorm = None maxNorm = None noOfComponents = vectors.GetNumberOfComponents() for i in range(0, vectors.GetNumberOfTuples()): norm = vtk.vtkMath.Norm(vectors.GetTuple(i), noOfComponents) if (minNorm is None or norm < minNorm): minNorm = norm if (maxNorm is None or norm > maxNorm): maxNorm = norm if maxNorm == 0: maxNorm = 1.0 scalarArray = vtk.vtkDoubleArray() scalarArray.SetNumberOfComponents(1) scalarArray.SetNumberOfValues(vectors.GetNumberOfTuples()) oldRange = maxNorm - minNorm oldRange = 1.0 if oldRange == 0.0 else oldRange # New range min, max. newRangeValues = self._gm.scalerange newRange = newRangeValues[1] - newRangeValues[0] for i in range(0, vectors.GetNumberOfTuples()): norm = vtk.vtkMath.Norm(vectors.GetTuple(i), noOfComponents) newValue = (((norm - minNorm) * newRange) / oldRange) + newRangeValues[0] scalarArray.SetValue(i, newValue) polydata.GetPointData().SetScalars(scalarArray) # Scale to vector magnitude: # NOTE: Currently we compute our own scaling factor since VTK does # it by clamping the values > max to max and values < min to min # and not remap the range. glyphFilter.SetScaleModeToScaleByScalar() glyphFilter.SetScaleFactor(scaleFactor) mapper = vtk.vtkPolyDataMapper() glyphFilter.Update() data = glyphFilter.GetOutput() mapper.SetInputData(data) mapper.ScalarVisibilityOff() act = vtk.vtkActor() act.SetMapper(mapper) cmap = self.getColorMap() if isinstance(lcolor, (list, tuple)): r, g, b, a = lcolor else: r, g, b, a = cmap.index[lcolor] act.GetProperty().SetColor(r / 100., g / 100., b / 100.) plotting_dataset_bounds = vcs2vtk.getPlottingBounds( vcs.utils.getworldcoordinates(self._gm, self._data1.getAxis(-1), self._data1.getAxis(-2)), self._vtkDataSetBounds, self._vtkGeoTransform) x1, x2, y1, y2 = plotting_dataset_bounds if self._vtkGeoTransform is None: wc = plotting_dataset_bounds else: xrange = list(act.GetXRange()) yrange = list(act.GetYRange()) wc = [xrange[0], xrange[1], yrange[0], yrange[1]] vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) # look for previous dataset_bounds different than ours and # modify the viewport so that the datasets are alligned # Hack to fix the case when the user does not specify gm.datawc_... # if geo is None: # for dp in vcs.elements['display'].values(): # if (hasattr(dp, 'backend')): # prevWc = dp.backend.get('dataset_bounds', None) # if (prevWc): # middleX = float(vp[0] + vp[1]) / 2.0 # middleY = float(vp[2] + vp[3]) / 2.0 # sideX = float(vp[1] - vp[0]) / 2.0 # sideY = float(vp[3] - vp[2]) / 2.0 # ratioX = float(prevWc[1] - prevWc[0]) / float(wc[1] - wc[0]) # ratioY = float(prevWc[3] - prevWc[2]) / float(wc[3] - wc[2]) # sideX = sideX / ratioX # sideY = sideY / ratioY # vp = [middleX - sideX, middleX + sideX, middleY - sideY, middleY + sideY] dataset_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=wc, priority=self._template.data.priority, create_renderer=True) 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, taxis, zaxis, **kwargs)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: continents_renderer, xScale, yScale = self._context( ).plotContinents(plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs) self._resultDict["vtk_backend_actors"] = [[ act, plotting_dataset_bounds ]] self._resultDict["vtk_backend_glyphfilters"] = [glyphFilter] self._resultDict["vtk_backend_luts"] = [[None, None]]
gs3.Update() gs4 = vtk.vtkGlyphSource2D() gs4.SetGlyphTypeToDiamond() gs4.SetScale(20) gs4.FilledOn() gs4.DashOn() gs4.CrossOff() gs4.Update() gs5 = vtk.vtkGlyphSource2D() gs5.SetGlyphTypeToThickArrow() gs5.SetScale(20) gs5.FilledOn() gs5.CrossOff() gs5.Update() # Create a table of glyphs glypher = vtk.vtkGlyph2D() glypher.SetInputData(pd) glypher.SetSourceData(0, gs.GetOutput()) glypher.SetSourceData(1, gs1.GetOutput()) glypher.SetSourceData(2, gs2.GetOutput()) glypher.SetSourceData(3, gs3.GetOutput()) glypher.SetSourceData(4, gs4.GetOutput()) glypher.SetSourceData(5, gs5.GetOutput()) glypher.SetIndexModeToScalar() glypher.SetRange(0, 5) glypher.SetScaleModeToDataScalingOff() mapper = vtk.vtkPolyDataMapper2D() mapper.SetInputConnection(glypher.GetOutputPort()) mapper.SetScalarRange(0, 5) glyphActor = vtk.vtkActor2D() glyphActor.SetMapper(mapper)
def _plotInternal(self): """Overrides baseclass implementation.""" # Preserve time and z axis for plotting these inof in rendertemplate projection = vcs.elements["projection"][self._gm.projection] zaxis, taxis = self.getZandT() scale = 1.0 if self._vtkGeoTransform is not None: lat = None lon = None latAccessor = self._data1.getLatitude() lonAccessor = self._data1.getLongitude() if latAccessor: lat = latAccessor[:] if lonAccessor: lon = lonAccessor[:] newv = vtk.vtkDoubleArray() newv.SetNumberOfComponents(3) newv.InsertTypedTuple(0, [lon.min(), lat.min(), 0]) newv.InsertTypedTuple(1, [lon.max(), lat.max(), 0]) vcs2vtk.projectArray(newv, projection, self._vtkDataSetBounds) dimMin = [0, 0, 0] dimMax = [0, 0, 0] newv.GetTypedTuple(0, dimMin) newv.GetTypedTuple(1, dimMax) maxDimX = max(dimMin[0], dimMax[0]) maxDimY = max(dimMin[1], dimMax[1]) if lat.max() != 0.0: scale = abs((maxDimY / lat.max())) if lon.max() != 0.0: temp = abs((maxDimX / lon.max())) if scale < temp: scale = temp else: scale = 1.0 # Vector attempt ltp_tmp = self._gm.linetype if ltp_tmp is None: ltp_tmp = "default" try: ltp_tmp = vcs.getline(ltp_tmp) lwidth = ltp_tmp.width[0] # noqa lcolor = ltp_tmp.color[0] lstyle = ltp_tmp.type[0] # noqa except Exception: lstyle = "solid" # noqa lwidth = 1. # noqa lcolor = [0., 0., 0., 100.] if self._gm.linewidth is not None: lwidth = self._gm.linewidth # noqa if self._gm.linecolor is not None: lcolor = self._gm.linecolor arrow = vtk.vtkGlyphSource2D() arrow.SetGlyphTypeToArrow() arrow.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION) arrow.FilledOff() plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) # The unscaled continent bounds were fine in the presence of axis # conversion, so save them here adjusted_plotting_bounds = vcs2vtk.getProjectedBoundsForWorldCoords( plotting_dataset_bounds, self._gm.projection) continentBounds = vcs2vtk.computeDrawAreaBounds( adjusted_plotting_bounds) # Transform the input data T = vtk.vtkTransform() T.Scale(self._context_xScale, self._context_yScale, 1.) self._vtkDataSetFittedToViewport = vcs2vtk.applyTransformationToDataset( T, self._vtkDataSetFittedToViewport) self._vtkDataSetBoundsNoMask = self._vtkDataSetFittedToViewport.GetBounds( ) polydata = self._vtkDataSetFittedToViewport # view and interactive area view = self._context().contextView area = vtk.vtkInteractiveArea() view.GetScene().AddItem(area) drawAreaBounds = vcs2vtk.computeDrawAreaBounds( self._vtkDataSetBoundsNoMask, self._context_flipX, self._context_flipY) [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) # polydata = tmpMapper.GetInput() plotting_dataset_bounds = self.getPlottingBounds() vectors = polydata.GetPointData().GetVectors() if self._gm.scaletype == 'constant' or\ self._gm.scaletype == 'constantNNormalize' or\ self._gm.scaletype == 'constantNLinear': scaleFactor = scale * self._gm.scale else: scaleFactor = 1.0 glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetInputArrayToProcess(1, 0, 0, 0, "vector") glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.SetVectorModeToUseVector() # Rotate arrows to match vector data: glyphFilter.OrientOn() glyphFilter.ScalingOn() glyphFilter.SetScaleModeToScaleByVector() maxNormInVp = None minNormInVp = None # Find the min and max vector magnitudes (minNorm, maxNorm) = vectors.GetRange(-1) if maxNorm == 0: maxNorm = 1.0 if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'linear' or\ self._gm.scaletype == 'constantNNormalize' or self._gm.scaletype == 'constantNLinear': if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'constantNNormalize': scaleFactor /= maxNorm if self._gm.scaletype == 'linear' or self._gm.scaletype == 'constantNLinear': noOfComponents = vectors.GetNumberOfComponents() scalarArray = vtk.vtkDoubleArray() scalarArray.SetNumberOfComponents(1) scalarArray.SetNumberOfValues(vectors.GetNumberOfTuples()) oldRange = maxNorm - minNorm oldRange = 1.0 if oldRange == 0.0 else oldRange # New range min, max. newRangeValues = self._gm.scalerange newRange = newRangeValues[1] - newRangeValues[0] for i in range(0, vectors.GetNumberOfTuples()): norm = vtk.vtkMath.Norm(vectors.GetTuple(i), noOfComponents) newValue = (((norm - minNorm) * newRange) / oldRange) + newRangeValues[0] scalarArray.SetValue(i, newValue) polydata.GetPointData().SetScalars(scalarArray) maxNormInVp = newRangeValues[1] * scaleFactor minNormInVp = newRangeValues[0] * scaleFactor # Scale to vector magnitude: # NOTE: Currently we compute our own scaling factor since VTK does # it by clamping the values > max to max and values < min to min # and not remap the range. glyphFilter.SetScaleModeToScaleByScalar() if (maxNormInVp is None): maxNormInVp = maxNorm * scaleFactor # minNormInVp is left None, as it is displayed only for linear scaling. cmap = self.getColorMap() if isinstance(lcolor, (list, tuple)): r, g, b, a = lcolor else: r, g, b, a = cmap.index[lcolor] # act.GetProperty().SetColor(r / 100., g / 100., b / 100.) vtk_color = [int((c / 100.) * 255) for c in [r, g, b, a]] # Using the scaled data, set the glyph filter input glyphFilter.SetScaleFactor(scaleFactor) glyphFilter.SetInputData(polydata) glyphFilter.Update() # and set the arrows to be rendered. data = glyphFilter.GetOutput() floatValue = vtk.vtkFloatArray() floatValue.SetNumberOfComponents(1) floatValue.SetName("LineWidth") floatValue.InsertNextValue(lwidth) data.GetFieldData().AddArray(floatValue) item = vtk.vtkPolyDataItem() item.SetPolyData(data) item.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_DATA) colorArray = vtk.vtkUnsignedCharArray() colorArray.SetNumberOfComponents(4) for i in range(data.GetNumberOfCells()): colorArray.InsertNextTypedTuple(vtk_color) item.SetMappedColors(colorArray) area.GetDrawAreaItem().AddItem(item) 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": continentBounds, "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, taxis, zaxis, **kwargs)) # assume that self._data1.units has the proper vector units unitString = None if (hasattr(self._data1, 'units')): unitString = self._data1.units if self._vtkGeoTransform: worldWidth = self._vtkDataSetBoundsNoMask[ 1] - self._vtkDataSetBoundsNoMask[0] else: worldWidth = self._vtkDataSetBounds[1] - self._vtkDataSetBounds[0] worldToViewportXScale = (vp[1] - vp[0]) / worldWidth maxNormInVp *= worldToViewportXScale if (minNormInVp): minNormInVp *= worldToViewportXScale vcs.utils.drawVectorLegend(self._context().canvas, self._template.legend, lcolor, lstyle, lwidth, unitString, maxNormInVp, maxNorm, minNormInVp, minNorm, reference=self._gm.reference) 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) self._resultDict["vtk_backend_actors"] = [[ item, plotting_dataset_bounds ]] self._resultDict["vtk_backend_glyphfilters"] = [glyphFilter] self._resultDict["vtk_backend_luts"] = [[None, None]]
def plotVector(self,data1,data2,tmpl,gm,ren): self.setLayer(ren,tmpl.data.priority) ug,xm,xM,ym,yM,continents,wrap = vcs2vtk.genUnstructuredGrid(data1,data2,gm) if ug.IsA("vtkUnstructuredGrid"): c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(ug) c2p.Update() #For contouring duplicate points seem to confuse it cln = vtk.vtkCleanUnstructuredGrid() cln.SetInputConnection(c2p.GetOutputPort()) missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,None) u=numpy.ma.ravel(data1) v=numpy.ma.ravel(data2) sh = list(u.shape) sh.append(1) u = numpy.reshape(u,sh) v = numpy.reshape(v,sh) z = numpy.zeros(u.shape) w = numpy.concatenate((u,v),axis=1) w = numpy.concatenate((w,z),axis=1) w = VN.numpy_to_vtk(w,deep=True) w.SetName("vectors") ug.GetPointData().AddArray(w) ## Vector attempt arrow = vtk.vtkArrowSource() l = gm.line if l is None: l = "default" try: l = vcs.getline(l) lwidth = l.width[0] lcolor = l.color[0] lstyle = l.type[0] except: lstyle = "solid" lwidth = 1. lcolor = 0 if gm.linewidth is not None: lwidth = gm.linewidth if gm.linecolor is not None: lcolor = gm.linecolor arrow.SetTipRadius(.1*lwidth) arrow.SetShaftRadius(.03*lwidth) arrow.Update() glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.OrientOn() glyphFilter.SetVectorModeToUseVector() glyphFilter.SetInputArrayToProcess(1,0,0,0,"vectors") glyphFilter.SetScaleFactor(2.*gm.scale) if ug.IsA("vtkUnstructuredGrid"): glyphFilter.SetInputConnection(cln.GetOutputPort()) else: glyphFilter.SetInputData(ug) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyphFilter.GetOutputPort()) act = vtk.vtkActor() act.SetMapper(mapper) try: cmap = vcs.elements["colormap"][cmap] except: cmap = vcs.elements["colormap"][self.canvas.getcolormapname()] r,g,b = cmap.index[lcolor] act.GetProperty().SetColor(r/100.,g/100.,b/100.) x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM) act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap) vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],[x1,x2,y1,y2]) if tmpl.data.priority!=0: ren.AddActor(act) self.renderTemplate(ren,tmpl,data1,gm) 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)
def _plotInternal(self): """Overrides baseclass implementation.""" # Preserve time and z axis for plotting these inof in rendertemplate projection = vcs.elements["projection"][self._gm.projection] taxis = self._originalData1.getTime() scaleFactor = 1.0 if self._originalData1.ndim > 2: zaxis = self._originalData1.getAxis(-3) else: zaxis = None scale = 1.0 lat = None lon = None latAccessor = self._data1.getLatitude() lonAccessor = self._data1.getLongitude() if latAccessor: lat = latAccessor[:] if lonAccessor: lon = lonAccessor[:] if self._vtkGeoTransform is not None: newv = vtk.vtkDoubleArray() newv.SetNumberOfComponents(3) newv.InsertTypedTuple(0, [lon.min(), lat.min(), 0]) newv.InsertTypedTuple(1, [lon.max(), lat.max(), 0]) vcs2vtk.projectArray(newv, projection, self._vtkDataSetBounds) dimMin = [0, 0, 0] dimMax = [0, 0, 0] newv.GetTypedTuple(0, dimMin) newv.GetTypedTuple(1, dimMax) maxDimX = max(dimMin[0], dimMax[0]) maxDimY = max(dimMin[1], dimMax[1]) if lat.max() != 0.0: scale = abs((maxDimY / lat.max())) if lon.max() != 0.0: temp = abs((maxDimX / lon.max())) if scale < temp: scale = temp else: scale = 1.0 # Vector attempt ltp_tmp = self._gm.linetype if ltp_tmp is None: ltp_tmp = "default" try: ltp_tmp = vcs.getline(ltp_tmp) lwidth = ltp_tmp.width[0] # noqa lcolor = ltp_tmp.color[0] lstyle = ltp_tmp.type[0] # noqa except Exception: lstyle = "solid" # noqa lwidth = 1. # noqa lcolor = [0., 0., 0., 100.] if self._gm.linewidth is not None: lwidth = self._gm.linewidth # noqa if self._gm.linecolor is not None: lcolor = self._gm.linecolor arrow = vtk.vtkGlyphSource2D() arrow.SetGlyphTypeToArrow() arrow.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION) arrow.FilledOff() polydata = self._vtkPolyDataFilter.GetOutput() vectors = polydata.GetPointData().GetVectors() if self._gm.scaletype == 'constant' or\ self._gm.scaletype == 'constantNNormalize' or\ self._gm.scaletype == 'constantNLinear': scaleFactor = scale * self._gm.scale else: scaleFactor = 1.0 glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetInputData(polydata) glyphFilter.SetInputArrayToProcess(1, 0, 0, 0, "vector") glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.SetVectorModeToUseVector() # Rotate arrows to match vector data: glyphFilter.OrientOn() glyphFilter.ScalingOn() glyphFilter.SetScaleModeToScaleByVector() maxNormInVp = None minNormInVp = None # Find the min and max vector magnitudes (minNorm, maxNorm) = vectors.GetRange(-1) if maxNorm == 0: maxNorm = 1.0 if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'linear' or\ self._gm.scaletype == 'constantNNormalize' or self._gm.scaletype == 'constantNLinear': if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'constantNNormalize': scaleFactor /= maxNorm if self._gm.scaletype == 'linear' or self._gm.scaletype == 'constantNLinear': noOfComponents = vectors.GetNumberOfComponents() scalarArray = vtk.vtkDoubleArray() scalarArray.SetNumberOfComponents(1) scalarArray.SetNumberOfValues(vectors.GetNumberOfTuples()) oldRange = maxNorm - minNorm oldRange = 1.0 if oldRange == 0.0 else oldRange # New range min, max. newRangeValues = self._gm.scalerange newRange = newRangeValues[1] - newRangeValues[0] for i in range(0, vectors.GetNumberOfTuples()): norm = vtk.vtkMath.Norm(vectors.GetTuple(i), noOfComponents) newValue = (((norm - minNorm) * newRange) / oldRange) + newRangeValues[0] scalarArray.SetValue(i, newValue) polydata.GetPointData().SetScalars(scalarArray) maxNormInVp = newRangeValues[1] * scaleFactor minNormInVp = newRangeValues[0] * scaleFactor # Scale to vector magnitude: # NOTE: Currently we compute our own scaling factor since VTK does # it by clamping the values > max to max and values < min to min # and not remap the range. glyphFilter.SetScaleModeToScaleByScalar() glyphFilter.SetScaleFactor(scaleFactor) if (maxNormInVp is None): maxNormInVp = maxNorm * scaleFactor # minNormInVp is left None, as it is displayed only for linear scaling. mapper = vtk.vtkPolyDataMapper() glyphFilter.Update() data = glyphFilter.GetOutput() mapper.SetInputData(data) mapper.ScalarVisibilityOff() act = vtk.vtkActor() act.SetMapper(mapper) cmap = self.getColorMap() if isinstance(lcolor, (list, tuple)): r, g, b, a = lcolor else: r, g, b, a = cmap.index[lcolor] act.GetProperty().SetColor(r / 100., g / 100., b / 100.) plotting_dataset_bounds = self.getPlottingBounds() 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, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) 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, taxis, zaxis, **kwargs)) # assume that self._data1.units has the proper vector units unitString = None if (hasattr(self._data1, 'units')): unitString = self._data1.units worldToViewportXScale = (vp[1] - vp[0]) /\ (self._vtkDataSetBoundsNoMask[1] - self._vtkDataSetBoundsNoMask[0]) maxNormInVp *= worldToViewportXScale if (minNormInVp): minNormInVp *= worldToViewportXScale vcs.utils.drawVectorLegend(self._context().canvas, self._template.legend, lcolor, lstyle, lwidth, unitString, maxNormInVp, maxNorm, minNormInVp, minNorm) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: continents_renderer, xScale, yScale = self._context( ).plotContinents(plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs) self._resultDict["vtk_backend_actors"] = [[ act, plotting_dataset_bounds ]] self._resultDict["vtk_backend_glyphfilters"] = [glyphFilter] self._resultDict["vtk_backend_luts"] = [[None, None]]
def plotVector(self,data1,data2,tmpl,gm): ug,xm,xM,ym,yM,continents,wrap,geo,cellData = vcs2vtk.genGrid(data1,data2,gm) if cellData: c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(ug) c2p.Update() #For contouring duplicate points seem to confuse it if ug.IsA("vtkUnstructuredGrid"): cln = vtk.vtkCleanUnstructuredGrid() cln.SetInputConnection(c2p.GetOutputPort()) missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,None,cellData) u=numpy.ma.ravel(data1) v=numpy.ma.ravel(data2) sh = list(u.shape) sh.append(1) u = numpy.reshape(u,sh) v = numpy.reshape(v,sh) z = numpy.zeros(u.shape) w = numpy.concatenate((u,v),axis=1) w = numpy.concatenate((w,z),axis=1) w = VN.numpy_to_vtk(w,deep=True) w.SetName("vectors") ug.GetPointData().AddArray(w) ## Vector attempt arrow = vtk.vtkArrowSource() l = gm.line if l is None: l = "default" try: l = vcs.getline(l) lwidth = l.width[0] lcolor = l.color[0] lstyle = l.type[0] except: lstyle = "solid" lwidth = 1. lcolor = 0 if gm.linewidth is not None: lwidth = gm.linewidth if gm.linecolor is not None: lcolor = gm.linecolor arrow.SetTipRadius(.1*lwidth) arrow.SetShaftRadius(.03*lwidth) arrow.Update() glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.OrientOn() glyphFilter.SetVectorModeToUseVector() glyphFilter.SetInputArrayToProcess(1,0,0,0,"vectors") glyphFilter.SetScaleFactor(2.*gm.scale) if cellData: if ug.IsA("vtkUnstructuredGrid"): glyphFilter.SetInputConnection(cln.GetOutputPort()) else: glyphFilter.SetInputConnection(c2p.GetOutputPort()) else: glyphFilter.SetInputData(ug) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyphFilter.GetOutputPort()) act = vtk.vtkActor() act.SetMapper(mapper) try: cmap = vcs.elements["colormap"][cmap] except: cmap = vcs.elements["colormap"][self.canvas.getcolormapname()] r,g,b = cmap.index[lcolor] act.GetProperty().SetColor(r/100.,g/100.,b/100.) x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM) act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap) ren=vtk.vtkRenderer() self.renWin.AddRenderer(ren) self.setLayer(ren,tmpl.data.priority) vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],[x1,x2,y1,y2]) if tmpl.data.priority!=0: ren.AddActor(act) self.renderTemplate(tmpl,data1,gm) 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 plotVector(self,data1,data2,tmpl,gm): #Preserve time and z axis for plotting these inof in rendertemplate taxis = data1.getTime() if data1.ndim>2: zaxis = data1.getAxis(-3) else: zaxis = None data1 = self.trimData2D(data1) # Ok get3 only the last 2 dims data2 = self.trimData2D(data2) ug,xm,xM,ym,yM,continents,wrap,geo = vcs2vtk.genGridOnPoints(data1,data2,gm,deep=False) missingMapper = vcs2vtk.putMaskOnVTKGrid(data1,ug,None,False,deep=False) u=numpy.ma.ravel(data1) v=numpy.ma.ravel(data2) sh = list(u.shape) sh.append(1) u = numpy.reshape(u,sh) v = numpy.reshape(v,sh) z = numpy.zeros(u.shape) w = numpy.concatenate((u,v),axis=1) w = numpy.concatenate((w,z),axis=1) # HACK The grid returned by vtk2vcs.genGrid is not the same size as the # data array. I'm not sure where the issue is...for now let's just zero-pad # data array so that we can at least test rendering until Charles gets # back from vacation: wLen = len(w) numPts = ug.GetNumberOfPoints() if wLen != numPts: warnings.warn("!!! Warning during vector plotting: Number of points does not "\ "match the number of vectors to be glyphed (%s points vs %s "\ "vectors). The vectors will be padded/truncated to match for "\ "rendering purposes, but the resulting image should not be "\ "trusted."%(numPts, wLen)) newShape = (numPts,) + w.shape[1:] w = numpy.ma.resize(w, newShape) w = vcs2vtk.numpy_to_vtk_wrapper(w,deep=False) w.SetName("vectors") ug.GetPointData().AddArray(w) ## Vector attempt l = gm.line if l is None: l = "default" try: l = vcs.getline(l) lwidth = l.width[0] lcolor = l.color[0] lstyle = l.type[0] except: lstyle = "solid" lwidth = 1. lcolor = 0 if gm.linewidth is not None: lwidth = gm.linewidth if gm.linecolor is not None: lcolor = gm.linecolor # Strip out masked points. if ug.IsA("vtkStructuredGrid"): if ug.GetCellBlanking(): visArray = ug.GetCellVisibilityArray() visArray.SetName("BlankingArray") ug.GetCellData().AddArray(visArray) thresh = vtk.vtkThreshold() thresh.SetInputData(ug) thresh.ThresholdByUpper(0.5) thresh.SetInputArrayToProcess(0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_CELLS", "BlankingArray") thresh.Update() ug = thresh.GetOutput() elif ug.GetPointBlanking(): visArray = ug.GetPointVisibilityArray() visArray.SetName("BlankingArray") ug.GetPointData().AddArray(visArray) thresh = vtk.vtkThreshold() thresh.SetInputData(ug) thresh.SetUpperThreshold(0.5) thresh.SetInputArrayToProcess(0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_POINTS", "BlankingArray") thresh.Update() ug = thresh.GetOutput() arrow = vtk.vtkGlyphSource2D() arrow.SetGlyphTypeToArrow() arrow.FilledOff() glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.SetVectorModeToUseVector() # Rotate arrows to match vector data: glyphFilter.OrientOn() # Scale to vector magnitude: glyphFilter.SetScaleModeToScaleByVector() # These are some unfortunately named methods. It does *not* clamp the scale # range to [min, max], but rather remaps the range [min, max]-->[0,1]. Bump # up min so that near-zero vectors will not be rendered, as these tend to # come out randomly oriented. glyphFilter.ClampingOn() glyphFilter.SetRange(0.01, 1.0) glyphFilter.SetInputArrayToProcess(1,0,0,0,"vectors") glyphFilter.SetScaleFactor(2.*gm.scale) #if cellData: # if ug.IsA("vtkUnstructuredGrid"): # glyphFilter.SetInputConnection(cln.GetOutputPort()) # else: # glyphFilter.SetInputConnection(c2p.GetOutputPort()) #else: # glyphFilter.SetInputData(ug) glyphFilter.SetInputData(ug) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyphFilter.GetOutputPort()) act = vtk.vtkActor() act.SetMapper(mapper) try: cmap = vcs.elements["colormap"][cmap] except: cmap = vcs.elements["colormap"][self.canvas.getcolormapname()] r,g,b = cmap.index[lcolor] act.GetProperty().SetColor(r/100.,g/100.,b/100.) x1,x2,y1,y2 = vcs2vtk.getRange(gm,xm,xM,ym,yM) act = vcs2vtk.doWrap(act,[x1,x2,y1,y2],wrap) ren = self.createRenderer() self.renWin.AddRenderer(ren) self.setLayer(ren,tmpl.data.priority) vcs2vtk.fitToViewport(act,ren,[tmpl.data.x1,tmpl.data.x2,tmpl.data.y1,tmpl.data.y2],[x1,x2,y1,y2]) if tmpl.data.priority!=0: ren.AddActor(act) self.renderTemplate(tmpl,data1,gm,taxis,zaxis) 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 plot(self, data1, data2, tmpl, gm, grid, transform): """Overrides baseclass implementation.""" #Preserve time and z axis for plotting these inof in rendertemplate returned = {} taxis = data1.getTime() if data1.ndim > 2: zaxis = data1.getAxis(-3) else: zaxis = None data1 = self._context.trimData2D(data1) # Ok get3 only the last 2 dims data2 = self._context.trimData2D(data2) gridGenDict = vcs2vtk.genGridOnPoints(data1, gm, deep=False, grid=grid, geo=transform) for k in ['vtk_backend_grid', 'xm', 'xM', 'ym', 'yM', 'continents', 'wrap', 'geo']: exec("%s = gridGenDict['%s']" % (k, k)) grid = gridGenDict['vtk_backend_grid'] returned["vtk_backend_grid"] = grid returned["vtk_backend_geo"] = geo missingMapper = vcs2vtk.putMaskOnVTKGrid(data1, grid, None, False, deep=False) # None/False are for color and cellData # (sent to vcs2vtk.putMaskOnVTKGrid) returned["vtk_backend_missing_mapper"] = (missingMapper, None, False) w = vcs2vtk.generateVectorArray(data1, data2, grid) grid.GetPointData().AddArray(w) ## Vector attempt l = gm.line if l is None: l = "default" try: l = vcs.getline(l) lwidth = l.width[0] lcolor = l.color[0] lstyle = l.type[0] except: lstyle = "solid" lwidth = 1. lcolor = 0 if gm.linewidth is not None: lwidth = gm.linewidth if gm.linecolor is not None: lcolor = gm.linecolor grid = vcs2vtk.stripGrid(grid) arrow = vtk.vtkGlyphSource2D() arrow.SetGlyphTypeToArrow() arrow.FilledOff() glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetInputData(grid) glyphFilter.SetInputArrayToProcess(1, 0, 0, 0, "vectors") glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.SetVectorModeToUseVector() # Rotate arrows to match vector data: glyphFilter.OrientOn() # Scale to vector magnitude: glyphFilter.SetScaleModeToScaleByVector() glyphFilter.SetScaleFactor(2. * gm.scale) # These are some unfortunately named methods. It does *not* clamp the # scale range to [min, max], but rather remaps the range # [min, max] --> [0, 1]. glyphFilter.ClampingOn() glyphFilter.SetRange(0.01, 1.0) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyphFilter.GetOutputPort()) act = vtk.vtkActor() act.SetMapper(mapper) cmap = vcs.elements["colormap"][self._context.canvas.getcolormapname()] r, g, b = cmap.index[lcolor] act.GetProperty().SetColor(r / 100.,g / 100.,b / 100.) x1, x2, y1, y2 = vcs.utils.getworldcoordinates(gm, data1.getAxis(-1), data1.getAxis(-2)) act = vcs2vtk.doWrap(act, [x1,x2,y1,y2], wrap) ren = self._context.fitToViewport(act, [tmpl.data.x1, tmpl.data.x2, tmpl.data.y1, tmpl.data.y2], [x1, x2, y1, y2], priority=tmpl.data.priority) returned.update( self._context.renderTemplate(tmpl, data1, gm, taxis, zaxis)) if self._context.canvas._continents is None: continents = False if continents: projection = vcs.elements["projection"][gm.projection] self._context.plotContinents(x1, x2, y1, y2, projection, wrap, tmpl) returned["vtk_backend_actors"] = [[act, [x1,x2,y1,y2]],] returned["vtk_backend_glyphfilters"] = [glyphFilter,] returned["vtk_backend_luts"] = [[None, None],] return returned
points.InsertNextPoint(j*3, i*3, 0) polydata = vtk.vtkPolyData() polydata.SetPoints(points) glyphSource = vtk.vtkGlyphSource2D() glyphSource.SetGlyphType(i) glyphSource.FilledOff() glyphSource.SetResolution(25) glyphSource.SetScale(fixedScales[j-1]) if GLYPH_TYPES[i] == 'VTK_TRIANGLE_GLYPH': glyphSource.SetRotationAngle(90) glyph2D = vtk.vtkGlyph2D() glyph2D.SetSourceConnection(glyphSource.GetOutputPort()) glyph2D.SetInputData(polydata) glyph2D.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph2D.GetOutputPort()) mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) actors.append(actor) # Set up the renderer, render window, and interactor. renderer = vtk.vtkRenderer()
def _plotInternal(self): """Overrides baseclass implementation.""" # Preserve time and z axis for plotting these inof in rendertemplate projection = vcs.elements["projection"][self._gm.projection] taxis = self._originalData1.getTime() scaleFactor = 1.0 if self._originalData1.ndim > 2: zaxis = self._originalData1.getAxis(-3) else: zaxis = None scale = 1.0 lat = None lon = None latAccessor = self._data1.getLatitude() lonAccessor = self._data1.getLongitude() if latAccessor: lat = latAccessor[:] if lonAccessor: lon = lonAccessor[:] if self._vtkGeoTransform is not None: newv = vtk.vtkDoubleArray() newv.SetNumberOfComponents(3) newv.InsertTypedTuple(0, [lon.min(), lat.min(), 0]) newv.InsertTypedTuple(1, [lon.max(), lat.max(), 0]) vcs2vtk.projectArray(newv, projection, self._vtkDataSetBounds) dimMin = [0, 0, 0] dimMax = [0, 0, 0] newv.GetTypedTuple(0, dimMin) newv.GetTypedTuple(1, dimMax) maxDimX = max(dimMin[0], dimMax[0]) maxDimY = max(dimMin[1], dimMax[1]) if lat.max() != 0.0: scale = abs((maxDimY / lat.max())) if lon.max() != 0.0: temp = abs((maxDimX / lon.max())) if scale < temp: scale = temp else: scale = 1.0 # Vector attempt l = self._gm.line if l is None: l = "default" try: l = vcs.getline(l) lwidth = l.width[0] # noqa lcolor = l.color[0] lstyle = l.type[0] # noqa except: lstyle = "solid" # noqa lwidth = 1. # noqa lcolor = 0 if self._gm.linewidth is not None: lwidth = self._gm.linewidth # noqa if self._gm.linecolor is not None: lcolor = self._gm.linecolor arrow = vtk.vtkGlyphSource2D() arrow.SetGlyphTypeToArrow() arrow.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION) arrow.FilledOff() polydata = self._vtkPolyDataFilter.GetOutput() vectors = polydata.GetPointData().GetVectors() if self._gm.scaletype == 'constant' or\ self._gm.scaletype == 'constantNNormalize' or\ self._gm.scaletype == 'constantNLinear': scaleFactor = scale * 2.0 * self._gm.scale else: scaleFactor = 1.0 glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetInputData(polydata) glyphFilter.SetInputArrayToProcess(1, 0, 0, 0, "vector") glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.SetVectorModeToUseVector() # Rotate arrows to match vector data: glyphFilter.OrientOn() glyphFilter.ScalingOn() glyphFilter.SetScaleModeToScaleByVector() if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'linear' or\ self._gm.scaletype == 'constantNNormalize' or self._gm.scaletype == 'constantNLinear': # Find the min and max vector magnitudes maxNorm = vectors.GetMaxNorm() if maxNorm == 0: maxNorm = 1.0 if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'constantNNormalize': scaleFactor /= maxNorm if self._gm.scaletype == 'linear' or self._gm.scaletype == 'constantNLinear': minNorm = None maxNorm = None noOfComponents = vectors.GetNumberOfComponents() for i in range(0, vectors.GetNumberOfTuples()): norm = vtk.vtkMath.Norm(vectors.GetTuple(i), noOfComponents) if (minNorm is None or norm < minNorm): minNorm = norm if (maxNorm is None or norm > maxNorm): maxNorm = norm if maxNorm == 0: maxNorm = 1.0 scalarArray = vtk.vtkDoubleArray() scalarArray.SetNumberOfComponents(1) scalarArray.SetNumberOfValues(vectors.GetNumberOfTuples()) oldRange = maxNorm - minNorm oldRange = 1.0 if oldRange == 0.0 else oldRange # New range min, max. newRangeValues = self._gm.scalerange newRange = newRangeValues[1] - newRangeValues[0] for i in range(0, vectors.GetNumberOfTuples()): norm = vtk.vtkMath.Norm(vectors.GetTuple(i), noOfComponents) newValue = (((norm - minNorm) * newRange) / oldRange) + newRangeValues[0] scalarArray.SetValue(i, newValue) polydata.GetPointData().SetScalars(scalarArray) # Scale to vector magnitude: # NOTE: Currently we compute our own scaling factor since VTK does # it by clamping the values > max to max and values < min to min # and not remap the range. glyphFilter.SetScaleModeToScaleByScalar() glyphFilter.SetScaleFactor(scaleFactor) mapper = vtk.vtkPolyDataMapper() glyphFilter.Update() data = glyphFilter.GetOutput() mapper.SetInputData(data) mapper.ScalarVisibilityOff() act = vtk.vtkActor() act.SetMapper(mapper) cmap = self.getColorMap() r, g, b, a = cmap.index[lcolor] act.GetProperty().SetColor(r / 100., g / 100., b / 100.) plotting_dataset_bounds = vcs2vtk.getPlottingBounds( vcs.utils.getworldcoordinates(self._gm, self._data1.getAxis(-1), self._data1.getAxis(-2)), self._vtkDataSetBounds, self._vtkGeoTransform) x1, x2, y1, y2 = plotting_dataset_bounds if self._vtkGeoTransform is None: wc = plotting_dataset_bounds else: xrange = list(act.GetXRange()) yrange = list(act.GetYRange()) wc = [xrange[0], xrange[1], yrange[0], yrange[1]] vp = self._resultDict.get('ratio_autot_viewport', [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2]) # look for previous dataset_bounds different than ours and # modify the viewport so that the datasets are alligned # Hack to fix the case when the user does not specify gm.datawc_... # if geo is None: # for dp in vcs.elements['display'].values(): # if (hasattr(dp, 'backend')): # prevWc = dp.backend.get('dataset_bounds', None) # if (prevWc): # middleX = float(vp[0] + vp[1]) / 2.0 # middleY = float(vp[2] + vp[3]) / 2.0 # sideX = float(vp[1] - vp[0]) / 2.0 # sideY = float(vp[3] - vp[2]) / 2.0 # ratioX = float(prevWc[1] - prevWc[0]) / float(wc[1] - wc[0]) # ratioY = float(prevWc[3] - prevWc[2]) / float(wc[3] - wc[2]) # sideX = sideX / ratioX # sideY = sideY / ratioY # vp = [middleX - sideX, middleX + sideX, middleY - sideY, middleY + sideY] dataset_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=wc, priority=self._template.data.priority, create_renderer=True) 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, taxis, zaxis, **kwargs)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: 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) self._resultDict["vtk_backend_actors"] = [[act, plotting_dataset_bounds]] self._resultDict["vtk_backend_glyphfilters"] = [glyphFilter] self._resultDict["vtk_backend_luts"] = [[None, None]]
xform = vtk.vtkTransformCoordinateSystems() xform.SetInputConnection(sphere.GetOutputPort()) xform.SetInputCoordinateSystemToWorld() xform.SetOutputCoordinateSystemToDisplay() xform.SetViewport(ren1) gs = vtk.vtkGlyphSource2D() gs.SetGlyphTypeToCircle() gs.SetScale(20) gs.FilledOff() gs.CrossOn() gs.Update() # Create a table of glyphs glypher = vtk.vtkGlyph2D() glypher.SetInputConnection(xform.GetOutputPort()) glypher.SetSourceData(0, gs.GetOutput()) glypher.SetScaleModeToDataScalingOff() mapper = vtk.vtkPolyDataMapper2D() mapper.SetInputConnection(glypher.GetOutputPort()) glyphActor = vtk.vtkActor2D() glyphActor.SetMapper(mapper) # Add the actors to the renderer, set the background and size # ren1.AddActor(glyphActor) ren1.SetBackground(0, 0, 0)
def plot(self, data1, data2, tmpl, grid, transform): """Overrides baseclass implementation.""" # Preserve time and z axis for plotting these inof in rendertemplate geo = None # to make flake8 happy projection = vcs.elements["projection"][self._gm.projection] returned = {} taxis = data1.getTime() if data1.ndim > 2: zaxis = data1.getAxis(-3) else: zaxis = None # Ok get3 only the last 2 dims data1 = self._context().trimData2D(data1) data2 = self._context().trimData2D(data2) scale = 1.0 lat = None lon = None latAccessor = data1.getLatitude() lonAccesrsor = data1.getLongitude() if latAccessor: lat = latAccessor[:] if lonAccesrsor: lon = lonAccesrsor[:] gridGenDict = vcs2vtk.genGridOnPoints(data1, self._gm, deep=False, grid=grid, geo=transform, data2=data2) data1 = gridGenDict["data"] data2 = gridGenDict["data2"] geo = gridGenDict["geo"] for k in ['vtk_backend_grid', 'xm', 'xM', 'ym', 'yM', 'continents', 'wrap', 'geo']: exec("%s = gridGenDict['%s']" % (k, k)) grid = gridGenDict['vtk_backend_grid'] self._dataWrapModulo = gridGenDict['wrap'] if geo is not None: newv = vtk.vtkDoubleArray() newv.SetNumberOfComponents(3) newv.InsertTupleValue(0, [lon.min(), lat.min(), 0]) newv.InsertTupleValue(1, [lon.max(), lat.max(), 0]) vcs2vtk.projectArray(newv, projection, [gridGenDict['xm'], gridGenDict['xM'], gridGenDict['ym'], gridGenDict['yM']]) dimMin = [0, 0, 0] dimMax = [0, 0, 0] newv.GetTupleValue(0, dimMin) newv.GetTupleValue(1, dimMax) maxDimX = max(dimMin[0], dimMax[0]) maxDimY = max(dimMin[1], dimMax[1]) if lat.max() != 0.0: scale = abs((maxDimY / lat.max())) if lon.max() != 0.0: temp = abs((maxDimX / lon.max())) if scale < temp: scale = temp else: scale = 1.0 returned["vtk_backend_grid"] = grid returned["vtk_backend_geo"] = geo missingMapper = vcs2vtk.putMaskOnVTKGrid(data1, grid, None, False, deep=False) # None/False are for color and cellData # (sent to vcs2vtk.putMaskOnVTKGrid) returned["vtk_backend_missing_mapper"] = (missingMapper, None, False) w = vcs2vtk.generateVectorArray(data1, data2, grid) grid.GetPointData().AddArray(w) # Vector attempt l = self._gm.line if l is None: l = "default" try: l = vcs.getline(l) lwidth = l.width[0] # noqa lcolor = l.color[0] lstyle = l.type[0] # noqa except: lstyle = "solid" # noqa lwidth = 1. # noqa lcolor = 0 if self._gm.linewidth is not None: lwidth = self._gm.linewidth # noqa if self._gm.linecolor is not None: lcolor = self._gm.linecolor arrow = vtk.vtkGlyphSource2D() arrow.SetGlyphTypeToArrow() arrow.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION) arrow.FilledOff() glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetInputData(grid) glyphFilter.SetInputArrayToProcess(1, 0, 0, 0, "vectors") glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.SetVectorModeToUseVector() # Rotate arrows to match vector data: glyphFilter.OrientOn() # Scale to vector magnitude: glyphFilter.SetScaleModeToScaleByVector() glyphFilter.SetScaleFactor(scale * 2.0 * self._gm.scale) # These are some unfortunately named methods. It does *not* clamp the # scale range to [min, max], but rather remaps the range # [min, max] --> [0, 1]. glyphFilter.ClampingOn() glyphFilter.SetRange(0.01, 1.0) mapper = vtk.vtkPolyDataMapper() glyphFilter.Update() data = glyphFilter.GetOutput() mapper.SetInputData(data) act = vtk.vtkActor() act.SetMapper(mapper) cmap = self.getColorMap() r, g, b, a = cmap.index[lcolor] act.GetProperty().SetColor(r / 100., g / 100., b / 100.) x1, x2, y1, y2 = vcs.utils.getworldcoordinates(self._gm, data1.getAxis(-1), data1.getAxis(-2)) if geo is None: wc = [x1, x2, y1, y2] else: xrange = list(act.GetXRange()) yrange = list(act.GetYRange()) wc = [xrange[0], xrange[1], yrange[0], yrange[1]] act = vcs2vtk.doWrap(act, wc, self._dataWrapModulo) self._context().fitToViewport(act, [tmpl.data.x1, tmpl.data.x2, tmpl.data.y1, tmpl.data.y2], wc=wc, priority=tmpl.data.priority, create_renderer=True) returned.update(self._context().renderTemplate(tmpl, data1, self._gm, taxis, zaxis)) if self._context().canvas._continents is None: continents = False if continents: self._context().plotContinents(x1, x2, y1, y2, projection, self._dataWrapModulo, tmpl) returned["vtk_backend_actors"] = [[act, [x1, x2, y1, y2]]] returned["vtk_backend_glyphfilters"] = [glyphFilter] returned["vtk_backend_luts"] = [[None, None]] return returned
def prepMarker(renWin, ren, marker, cmap=None): n = prepPrimitive(marker) if n == 0: return for i in range(n): ## Creates the glyph g = vtk.vtkGlyph2D() markers = vtk.vtkPolyData() x = marker.x[i] y = marker.y[i] c = marker.color[i] s = marker.size[i] / float(max(marker.worldcoordinate)) * 10. t = marker.type[i] N = max(len(x), len(y)) for a in [x, y]: while len(a) < n: a.append(a[-1]) pts = vtk.vtkPoints() geo, pts = project(pts, marker.projection, marker.worldcoordinate) for j in range(N): pts.InsertNextPoint(x[j], y[j], 0.) markers.SetPoints(pts) # Type ## Ok at this point generates the source for glpyh gs = vtk.vtkGlyphSource2D() pd = None if t == 'dot': gs.SetGlyphTypeToCircle() gs.FilledOn() elif t == 'circle': gs.SetGlyphTypeToCircle() gs.FilledOff() elif t == 'plus': gs.SetGlyphTypeToCross() gs.FilledOff() elif t == 'cross': gs.SetGlyphTypeToCross() gs.SetRotationAngle(45) gs.FilledOff() elif t[:6] == 'square': gs.SetGlyphTypeToSquare() gs.FilledOff() elif t[:7] == 'diamond': gs.SetGlyphTypeToDiamond() gs.FilledOff() elif t[:8] == 'triangle': gs.SetGlyphTypeToTriangle() if t[9] == "d": gs.SetRotationAngle(180) elif t[9] == "l": gs.SetRotationAngle(90) elif t[9] == "r": gs.SetRotationAngle(-90) elif t[9] == "u": gs.SetRotationAngle(0) elif t == "hurricane": s = s / 10. ds = vtk.vtkDiskSource() ds.SetInnerRadius(.55 * s) ds.SetOuterRadius(1.01 * s) ds.SetCircumferentialResolution(90) ds.SetRadialResolution(30) gf = vtk.vtkGeometryFilter() gf.SetInputConnection(ds.GetOutputPort()) gf.Update() pd1 = gf.GetOutput() apd = vtk.vtkAppendPolyData() apd.AddInputData(pd1) pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polygons = vtk.vtkCellArray() add_angle = numpy.pi / 360. coords = [] angle1 = .6 * numpy.pi angle2 = .88 * numpy.pi while angle1 <= angle2: coords.append([ s * 2 + 2 * s * numpy.cos(angle1), 2 * s * numpy.sin(angle1) ]) angle1 += add_angle angle1 = .79 * numpy.pi angle2 = .6 * numpy.pi while angle1 >= angle2: coords.append([ s * 2.25 + s * 4 * numpy.cos(angle1), -s * 2 + s * 4 * numpy.sin(angle1) ]) angle1 -= add_angle poly = genPoly(coords, pts, filled=True) polygons.InsertNextCell(poly) coords = [] angle1 = 1.6 * numpy.pi angle2 = 1.9 * numpy.pi while angle1 <= angle2: coords.append([ -s * 2 + s * 2 * numpy.cos(angle1), s * 2 * numpy.sin(angle1) ]) angle1 += add_angle angle1 = 1.8 * numpy.pi angle2 = 1.6 * numpy.pi while angle1 >= angle2: coords.append([ -s * 2.27 + s * 4 * numpy.cos(angle1), s * 2 + s * 4 * numpy.sin(angle1) ]) angle1 -= add_angle poly = genPoly(coords, pts, filled=True) polygons.InsertNextCell(poly) pd.SetPoints(pts) pd.SetPolys(polygons) apd.AddInputData(pd) apd.Update() g.SetSourceData(apd.GetOutput()) elif t in ["w%.2i" % x for x in range(203)]: ## WMO marker params = wmo[t] pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polys = vtk.vtkCellArray() lines = vtk.vtkCellArray() #Lines first for l in params["line"]: coords = numpy.array(zip(*l)) * s / 30. line = genPoly(coords.tolist(), pts, filled=False) lines.InsertNextCell(line) for l in params["poly"]: coords = numpy.array(zip(*l)) * s / 30. line = genPoly(coords.tolist(), pts, filled=True) polys.InsertNextCell(line) geo, pts = project(pts, marker.projection, marker.worldcoordinate) pd.SetPoints(pts) pd.SetPolys(polys) pd.SetLines(lines) g.SetSourceData(pd) else: warnings.warn("unknown marker type: %s, using dot" % t) gs.SetGlyphTypeToCircle() gs.FilledOn() if t[-5:] == "_fill": gs.FilledOn() gs.SetScale(s) gs.Update() if pd is None: g.SetSourceConnection(gs.GetOutputPort()) g.SetInputData(markers) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputConnection(g.GetOutputPort()) m.Update() a.SetMapper(m) p = a.GetProperty() #Color if cmap is None: if marker.colormap is not None: cmap = marker.colormap else: cmap = 'default' if isinstance(cmap, str): cmap = vcs.elements["colormap"][cmap] color = cmap.index[c] p.SetColor([C / 100. for C in color]) ren.AddActor(a) fitToViewport(a, ren, marker.viewport, wc=marker.worldcoordinate, geo=geo) return
for i in range(m.shape[0]): lst = vtk.vtkIdList() for j in range(4): lst.InsertNextId(i*4+j) ## ??? TODO ??? when 3D use CUBE? ug.InsertNextCell(vtk.VTK_QUAD,lst) #ug.GetPointData().SetVectors(data) if p.debug: vcs2vtk.dump2VTK(ug) ## Vector attempt arrow = vtk.vtkArrowSource() arrow.Update() glyphFilter = vtk.vtkGlyph2D() glyphFilter.SetSourceConnection(arrow.GetOutputPort()) glyphFilter.OrientOn() glyphFilter.SetVectorModeToUseVector() glyphFilter.SetInputArrayToProcess(1,0,0,0,"vectors") glyphFilter.SetScaleFactor(2) glyphFilter.SetInputData(ug) #Data range mn,mx = s.min(),s.max() #Ok now we have grid and data let's use the mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyphFilter.GetOutputPort())
import readline import rlcompleter readline.parse_and_bind("tab: complete") import vtk import vcs2vtk renWin = vtk.vtkRenderWindow() ren = vtk.vtkRenderer() renWin.AddRenderer(ren) ## glyph g=vtk.vtkGlyph2D() ##Glytph Source ##Locations pts = vtk.vtkPoints() pts.InsertNextPoint(0,0,0) pts.InsertNextPoint(5,0,0) pts.InsertNextPoint(10,0,0) pd = vtk.vtkPolyData() pd.SetPoints(pts) g.SetInputData(pd) ##Glyph Source (triangle here) psrc = vtk.vtkPoints() psrc.InsertNextPoint(0,0,0) psrc.InsertNextPoint(1,0,0) psrc.InsertNextPoint(0.5,1,0) psrc.InsertNextPoint(0,0,0)
def _plotInternal(self): """Overrides baseclass implementation.""" # Preserve time and z axis for plotting these inof in rendertemplate projection = vcs.elements["projection"][self._gm.projection] zaxis, taxis = self.getZandT() # Streamline color if (not self._gm.coloredbyvector): ln_tmp = self._gm.linetype if ln_tmp is None: ln_tmp = "default" try: ln_tmp = vcs.getline(ln_tmp) lwidth = ln_tmp.width[0] # noqa lcolor = ln_tmp.color[0] lstyle = ln_tmp.type[0] # noqa except Exception: lstyle = "solid" # noqa lwidth = 1. # noqa lcolor = [0., 0., 0., 100.] if self._gm.linewidth is not None: lwidth = self._gm.linewidth # noqa if self._gm.linecolor is not None: lcolor = self._gm.linecolor # The unscaled continent bounds were fine in the presence of axis # conversion, so save them here continentBounds = vcs2vtk.computeDrawAreaBounds( self._vtkDataSetBoundsNoMask, self._context_flipX, self._context_flipY) # Only scaling the data in the presence of axis conversion changes # the seed points in any other cases, and thus results in plots # different from the baselines but still fundamentally sound, it # seems. Always scaling the data results in no differences in the # plots between Context2D and the old baselines. # Transform the input data T = vtk.vtkTransform() T.Scale(self._context_xScale, self._context_yScale, 1.) self._vtkDataSetFittedToViewport = vcs2vtk.applyTransformationToDataset( T, self._vtkDataSetFittedToViewport) self._vtkDataSetBoundsNoMask = self._vtkDataSetFittedToViewport.GetBounds( ) polydata = self._vtkDataSetFittedToViewport plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds 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) drawAreaBounds = vcs2vtk.computeDrawAreaBounds( self._vtkDataSetBoundsNoMask, self._context_flipX, self._context_flipY) [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) dataLength = polydata.GetLength() if (not self._gm.evenlyspaced): # generate random seeds in a circle centered in the center of # the bounding box for the data. # by default vtkPointSource uses a global random source in vtkMath which is # seeded only once. It makes more sense to seed a random sequence each time you draw # the streamline plot. pointSequence = vtk.vtkMinimalStandardRandomSequence() pointSequence.SetSeedOnly(1177) # replicate the seed from vtkMath seed = vtk.vtkPointSource() seed.SetNumberOfPoints(self._gm.numberofseeds) seed.SetCenter(polydata.GetCenter()) seed.SetRadius(dataLength / 2.0) seed.SetRandomSequence(pointSequence) seed.Update() seedData = seed.GetOutput() # project all points to Z = 0 plane points = seedData.GetPoints() for i in range(0, points.GetNumberOfPoints()): p = list(points.GetPoint(i)) p[2] = 0 points.SetPoint(i, p) if (self._gm.integratortype == 0): integrator = vtk.vtkRungeKutta2() elif (self._gm.integratortype == 1): integrator = vtk.vtkRungeKutta4() else: if (self._gm.evenlyspaced): warnings.warn( "You cannot use RungeKutta45 for evenly spaced streamlines." "Using RungeKutta4 instead") integrator = vtk.vtkRungeKutta4() else: integrator = vtk.vtkRungeKutta45() if (self._gm.evenlyspaced): streamer = vtk.vtkEvenlySpacedStreamlines2D() startseed = self._gm.startseed \ if self._gm.startseed else polydata.GetCenter() streamer.SetStartPosition(startseed) streamer.SetSeparatingDistance(self._gm.separatingdistance) streamer.SetSeparatingDistanceRatio( self._gm.separatingdistanceratio) streamer.SetClosedLoopMaximumDistance( self._gm.closedloopmaximumdistance) else: # integrate streamlines on normalized vector so that # IntegrationTime stores distance streamer = vtk.vtkStreamTracer() streamer.SetSourceData(seedData) streamer.SetIntegrationDirection(self._gm.integrationdirection) streamer.SetMinimumIntegrationStep(self._gm.minimumsteplength) streamer.SetMaximumIntegrationStep(self._gm.maximumsteplength) streamer.SetMaximumError(self._gm.maximumerror) streamer.SetMaximumPropagation(dataLength * self._gm.maximumstreamlinelength) streamer.SetInputData(polydata) streamer.SetInputArrayToProcess(0, 0, 0, 0, "vector") streamer.SetIntegrationStepUnit(self._gm.integrationstepunit) streamer.SetInitialIntegrationStep(self._gm.initialsteplength) streamer.SetMaximumNumberOfSteps(self._gm.maximumsteps) streamer.SetTerminalSpeed(self._gm.terminalspeed) streamer.SetIntegrator(integrator) # add arc_length to streamlines arcLengthFilter = vtk.vtkAppendArcLength() arcLengthFilter.SetInputConnection(streamer.GetOutputPort()) arcLengthFilter.Update() streamlines = arcLengthFilter.GetOutput() # glyph seed points contour = vtk.vtkContourFilter() contour.SetInputConnection(arcLengthFilter.GetOutputPort()) contour.SetValue(0, 0.001) if (streamlines.GetNumberOfPoints()): r = streamlines.GetPointData().GetArray("arc_length").GetRange() numberofglyphsoneside = self._gm.numberofglyphs // 2 for i in range(1, numberofglyphsoneside): contour.SetValue(i, r[1] / numberofglyphsoneside * i) else: warnings.warn( "No streamlines created. " "The 'startseed' parameter needs to be inside the domain and " "not over masked data.") contour.SetInputArrayToProcess(0, 0, 0, 0, "arc_length") # arrow glyph source glyph2DSource = vtk.vtkGlyphSource2D() glyph2DSource.SetGlyphTypeToTriangle() glyph2DSource.SetRotationAngle(-90) glyph2DSource.SetFilled(self._gm.filledglyph) # arrow glyph adjustment transform = vtk.vtkTransform() transform.Scale(1., self._gm.glyphbasefactor, 1.) transformFilter = vtk.vtkTransformFilter() transformFilter.SetInputConnection(glyph2DSource.GetOutputPort()) transformFilter.SetTransform(transform) transformFilter.Update() glyphLength = transformFilter.GetOutput().GetLength() # drawing the glyphs at the seed points glyph = vtk.vtkGlyph2D() glyph.SetInputConnection(contour.GetOutputPort()) glyph.SetInputArrayToProcess(1, 0, 0, 0, "vector") glyph.SetSourceData(transformFilter.GetOutput()) glyph.SetScaleModeToDataScalingOff() glyph.SetScaleFactor(dataLength * self._gm.glyphscalefactor / glyphLength) glyph.SetColorModeToColorByVector() glyphMapper = vtk.vtkPolyDataMapper() glyphActor = vtk.vtkActor() mapper = vtk.vtkPolyDataMapper() act = vtk.vtkActor() glyph.Update() glyphDataset = glyph.GetOutput() streamer.Update() lineDataset = streamer.GetOutput() deleteLineColors = False deleteGlyphColors = False # color the streamlines and glyphs cmap = self.getColorMap() if (self._gm.coloredbyvector): numLevels = len(self._contourLevels) - 1 while len(self._contourColors) < numLevels: self._contourColors.append(self._contourColors[-1]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(numLevels) for i in range(numLevels): r, g, b, a = self.getColorIndexOrRGBA(cmap, self._contourColors[i]) lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.) lut.SetVectorModeToMagnitude() if numpy.allclose(self._contourLevels[0], -1.e20): lmn = self._vectorRange[0] else: lmn = self._contourLevels[0][0] if numpy.allclose(self._contourLevels[-1], 1.e20): lmx = self._vectorRange[1] else: lmx = self._contourLevels[-1][-1] lut.SetRange(lmn, lmx) mapper.ScalarVisibilityOn() mapper.SetLookupTable(lut) mapper.UseLookupTableScalarRangeOn() mapper.SetScalarModeToUsePointFieldData() mapper.SelectColorArray("vector") lineAttrs = lineDataset.GetPointData() lineData = lineAttrs.GetArray("vector") if lineData and numLevels: lineColors = lut.MapScalars(lineData, vtk.VTK_COLOR_MODE_DEFAULT, 0) deleteLineColors = True else: print( 'WARNING: streamline pipeline cannot map scalars for "lineData", using solid color' ) numTuples = lineDataset.GetNumberOfPoints() color = [0, 0, 0, 255] lineColors = vcs2vtk.generateSolidColorArray(numTuples, color) glyphMapper.ScalarVisibilityOn() glyphMapper.SetLookupTable(lut) glyphMapper.UseLookupTableScalarRangeOn() glyphMapper.SetScalarModeToUsePointFieldData() glyphMapper.SelectColorArray("VectorMagnitude") glyphAttrs = glyphDataset.GetPointData() glyphData = glyphAttrs.GetArray("VectorMagnitude") if glyphData and numLevels: glyphColors = lut.MapScalars(glyphData, vtk.VTK_COLOR_MODE_DEFAULT, 0) deleteGlyphColors = True else: print( 'WARNING: streamline pipeline cannot map scalars for "glyphData", using solid color' ) numTuples = glyphDataset.GetNumberOfPoints() color = [0, 0, 0, 255] glyphColors = vcs2vtk.generateSolidColorArray(numTuples, color) else: mapper.ScalarVisibilityOff() glyphMapper.ScalarVisibilityOff() if isinstance(lcolor, (list, tuple)): r, g, b, a = lcolor else: r, g, b, a = cmap.index[lcolor] act.GetProperty().SetColor(r / 100., g / 100., b / 100.) glyphActor.GetProperty().SetColor(r / 100., g / 100., b / 100.) fixedColor = [ int((r / 100.) * 255), int((g / 100.) * 255), int((b / 100.) * 255), 255 ] numTuples = lineDataset.GetNumberOfPoints() lineColors = vcs2vtk.generateSolidColorArray(numTuples, fixedColor) numTuples = glyphDataset.GetNumberOfPoints() glyphColors = vcs2vtk.generateSolidColorArray( numTuples, fixedColor) # Add the streamlines lineItem = vtk.vtkPolyDataItem() lineItem.SetPolyData(lineDataset) lineItem.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_POINT_DATA) lineItem.SetMappedColors(lineColors) if deleteLineColors: lineColors.FastDelete() area.GetDrawAreaItem().AddItem(lineItem) # Add the glyphs glyphItem = vtk.vtkPolyDataItem() glyphItem.SetPolyData(glyphDataset) glyphItem.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_POINT_DATA) glyphItem.SetMappedColors(glyphColors) if deleteGlyphColors: glyphColors.FastDelete() area.GetDrawAreaItem().AddItem(glyphItem) plotting_dataset_bounds = self.getPlottingBounds() vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) 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": continentBounds, "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, taxis, zaxis, **kwargs)) if (self._gm.coloredbyvector): self._resultDict.update(self._context().renderColorBar( self._template, self._contourLevels, self._contourColors, None, self.getColorMap())) 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) self._resultDict["vtk_backend_actors"] = [[ lineItem, plotting_dataset_bounds ]] self._resultDict["vtk_backend_luts"] = [[None, None]]