def main(): g = vtk.vtkMutableDirectedGraph() v1 = g.AddVertex() v2 = g.AddVertex() v3 = g.AddVertex() g.AddEdge(v1, v2) g.AddEdge(v2, v3) g.AddEdge(v3, v1) # Do layout manually before handing graph to the view. # This allows us to know the positions of edge arrows. graphLayoutView = vtk.vtkGraphLayoutView() layout = vtk.vtkGraphLayout() strategy = vtk.vtkSimple2DLayoutStrategy() layout.SetInputData(g) layout.SetLayoutStrategy(strategy) # Tell the view to use the vertex layout we provide graphLayoutView.SetLayoutStrategyToPassThrough() # The arrows will be positioned on a straight line between two # vertices so tell the view not to draw arcs for parallel edges graphLayoutView.SetEdgeLayoutStrategyToPassThrough() # Add the graph to the view. This will render vertices and edges, # but not edge arrows. graphLayoutView.AddRepresentationFromInputConnection(layout.GetOutputPort()) # Manually create an actor containing the glyphed arrows. graphToPoly = vtk.vtkGraphToPolyData() graphToPoly.SetInputConnection(layout.GetOutputPort()) graphToPoly.EdgeGlyphOutputOn() # Set the position (0: edge start, 1: edge end) where # the edge arrows should go. graphToPoly.SetEdgeGlyphPosition(0.98) # Make a simple edge arrow for glyphing. arrowSource = vtk.vtkGlyphSource2D() arrowSource.SetGlyphTypeToEdgeArrow() arrowSource.SetScale(0.1) arrowSource.Update() # Use Glyph3D to repeat the glyph on all edges. arrowGlyph = vtk.vtkGlyph3D() arrowGlyph.SetInputConnection(0, graphToPoly.GetOutputPort(1)) arrowGlyph.SetInputConnection(1, arrowSource.GetOutputPort()) # Add the edge arrow actor to the view. arrowMapper = vtk.vtkPolyDataMapper() arrowMapper.SetInputConnection(arrowGlyph.GetOutputPort()) arrowActor = vtk.vtkActor() arrowActor.SetMapper(arrowMapper) graphLayoutView.GetRenderer().AddActor(arrowActor) graphLayoutView.ResetCamera() graphLayoutView.Render() graphLayoutView.GetInteractor().Start()
def __init__ (self, mod_m): debug ("In VelocityVector::__init__ ()") Common.state.busy () Base.Objects.Module.__init__ (self, mod_m) self.glyph2d_src = vtk.vtkGlyphSource2D () self.cone = vtk.vtkConeSource () self.arrow = vtk.vtkArrowSource () self.glyph_src = self.cone self.glyph3d = vtk.vtkGlyph3D () self.mapper = self.map = vtk.vtkPolyDataMapper () self.actor = self.act = vtk.vtkActor () # used to orient the cone properly self.glph_trfm = vtk.vtkTransformFilter () self.glph_trfm.SetTransform (vtk.vtkTransform ()) self.data_out = self.mod_m.GetOutput () # Point of glyph that is attached -- -1 is tail, 0 is center, # 1 is head. self.glyph_pos = -1 self.scale = 1.0 self.color_mode = 2 #2 is vector, 1 is scalar, -1 none self._initialize () self._gui_init () self.renwin.Render () Common.state.idle ()
def _arrow_glyph(grid, factor): glyph = vtk.vtkGlyphSource2D() glyph.SetGlyphTypeToArrow() glyph.FilledOff() glyph.Update() geom = glyph.GetOutput() # fix position tr = vtk.vtkTransform() tr.Translate(0.5, 0., 0.) trp = vtk.vtkTransformPolyDataFilter() trp.SetInputData(geom) trp.SetTransform(tr) trp.Update() geom = trp.GetOutput() polydata = _glyph( grid, scale_mode='vector', scalars=False, orient='vec', factor=factor, geom=geom, ) return pyvista.wrap(polydata)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkGlyphSource2D(), 'Processing.', (), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def _arrow_glyph(grid, factor): glyph = vtk.vtkGlyphSource2D() glyph.SetGlyphTypeToArrow() glyph.FilledOff() glyph.Update() # fix position tr = vtk.vtkTransform() tr.Translate(0.5, 0., 0.) trp = vtk.vtkTransformPolyDataFilter() trp.SetInputConnection(glyph.GetOutputPort()) trp.SetTransform(tr) trp.Update() alg = _glyph( grid, scale_mode='vector', scalars=False, orient='vec', factor=factor, geom=trp.GetOutputPort(), ) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(alg.GetOutputPort()) return mapper
def draw2Dgraph(source): """ draws the 2D graph from the given data. """ # Do layout manually before handing graph to the view. graphLayoutView = vtk.vtkGraphLayoutView() layout = vtk.vtkGraphLayout() strategy = vtk.vtkSimple2DLayoutStrategy() layout.SetInputData(source) layout.SetLayoutStrategy(strategy) # Tell the view to use the vertex layout we provide graphLayoutView.SetLayoutStrategyToPassThrough() # The arrows will be positioned on a straight line between two # vertices so tell the view not to draw arcs for parallel edges graphLayoutView.SetEdgeLayoutStrategyToPassThrough() # Add the graph to the view. This will render vertices and edges, # but not edge arrows. graphLayoutView.AddRepresentationFromInputConnection( layout.GetOutputPort()) # Manually create an actor containing the glyphed arrows. graphToPoly = vtk.vtkGraphToPolyData() graphToPoly.SetInputConnection(layout.GetOutputPort()) graphToPoly.EdgeGlyphOutputOn() # Set the position graphToPoly.SetEdgeGlyphPosition(0.98) # Make a simple edge arrow for glyphing. arrowSource = vtk.vtkGlyphSource2D() arrowSource.SetGlyphTypeToEdgeArrow() arrowSource.SetScale(1) arrowSource.Update() # Use Glyph3D to repeat the glyph on all edges. arrowGlyph = vtk.vtkGlyph3D() arrowGlyph.SetInputConnection(0, graphToPoly.GetOutputPort(1)) arrowGlyph.SetInputConnection(1, arrowSource.GetOutputPort()) # Add the edge arrow actor to the view. arrowMapper = vtk.vtkPolyDataMapper() arrowMapper.SetInputConnection(arrowGlyph.GetOutputPort()) arrowActor = vtk.vtkActor() arrowActor.SetMapper(arrowMapper) graphLayoutView.GetRenderer().AddActor(arrowActor) # Add edge weights & vertex labels graphLayoutView.SetVertexLabelVisibility(1) graphLayoutView.SetEdgeLabelVisibility(1) graphLayoutView.SetVertexLabelArrayName("VertexLabels") graphLayoutView.SetEdgeLabelArrayName("EdgeWeights") return graphLayoutView
def __init__ (self, mod_m): debug ("In Glyph::__init__ ()") Common.state.busy () Base.Objects.Module.__init__ (self, mod_m) self.glyph_src = vtk.vtkGlyphSource2D () self.glyph = vtk.vtkGlyph3D () self.mapper = self.map = vtk.vtkPolyDataMapper () self.actor = self.act = vtk.vtkActor () self.data_out = self.mod_m.GetOutput () self._initialize () self._gui_init () self.renwin.Render () Common.state.idle ()
def GlyphSource2D(self, currentElement): gsource = vtk.vtkGlyphSource2D() #if 'SetGlyphType' in currentElement.keys(): gsource.SetGlyphTypeToArrow () if 'SetFilled' in currentElement.keys(): try: gsource.SetFilled( int(currentElement.get('SetFilled')) ) except: self.logger.error(' .. <GlyphSource2D> failed to SetFilled') if 'SetScale' in currentElement.keys(): try: gsource.SetScale( float(currentElement.get('SetScale')) ) except: self.logger.error(' .. <GlyphSource2D> failed to SetScale') return gsource
def set_glyph_mode (self, event=None): debug ("In Glyph::set_glyph_mode ()") Common.state.busy () val = self.glyph_var.get () if val == 0: # 2d glyph self.glyph_src = vtk.vtkGlyphSource2D () self.glyph_src.SetGlyphTypeToArrow () elif val == 1: # Cone self.glyph_src = vtk.vtkConeSource() elif val == 2: # Sphere self.glyph_src = vtk.vtkSphereSource() self.glyph_src.SetPhiResolution(4) self.glyph_src.SetThetaResolution(4) elif val == 3: # Cube self.glyph_src = vtk.vtkCubeSource() elif val == 4: # Cylinder self.glyph_src = vtk.vtkCylinderSource() elif val == 5: # 3D arrow self.glyph_src = vtk.vtkArrowSource() self.glyph.SetSource (self.glyph_src.GetOutput ()) self.renwin.Render () Common.state.idle ()
vectors.SetNumberOfComponents(3) pd.SetPoints(pts) pd.GetPointData().SetScalars(scalars) pd.GetPointData().SetVectors(vectors) math = vtk.vtkMath() size = 500 i = 0 while i < 100: pts.InsertNextPoint(math.Random(0, size - 1), math.Random(0, size - 1), 0.0) scalars.InsertNextValue(math.Random(0.0, 5)) vectors.InsertNextTuple3(math.Random(-1, 1), math.Random(-1, 1), 0.0) i += 1 gs = vtk.vtkGlyphSource2D() gs.SetGlyphTypeToCircle() gs.SetScale(20) gs.FilledOff() gs.CrossOn() gs.Update() gs1 = vtk.vtkGlyphSource2D() gs1.SetGlyphTypeToTriangle() gs1.SetScale(20) gs1.FilledOff() gs1.CrossOn() gs1.Update() gs2 = vtk.vtkGlyphSource2D() gs2.SetGlyphTypeToSquare()
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() g = vtk.vtkMutableDirectedGraph() v1 = g.AddVertex() v2 = g.AddVertex() v3 = g.AddVertex() ### g.AddEdge(v1, v2) g.AddGraphEdge(v1, v2) g.AddGraphEdge(v2, v3) g.AddGraphEdge(v3, v1) # Do layout manually before handing graph to the view. # This allows us to know the positions of edge arrows. graphLayoutView = vtk.vtkGraphLayoutView() layout = vtk.vtkGraphLayout() strategy = vtk.vtkSimple2DLayoutStrategy() layout.SetInput(g) layout.SetLayoutStrategy(strategy) # Tell the view to use the vertex layout we provide graphLayoutView.SetLayoutStrategyToPassThrough() # The arrows will be positioned on a straight line between two # vertices so tell the view not to draw arcs for parallel edges graphLayoutView.SetEdgeLayoutStrategyToPassThrough() # Add the graph to the view. This will render vertices and edges, # but not edge arrows. graphLayoutView.AddRepresentationFromInputConnection(layout.GetOutputPort()) # Manually create an actor containing the glyphed arrows. graphToPoly = vtk.vtkGraphToPolyData() graphToPoly.SetInputConnection(layout.GetOutputPort()) graphToPoly.EdgeGlyphOutputOn() # Set the position (0: edge start, 1:edge end) where # the edge arrows should go. graphToPoly.SetEdgeGlyphPosition(0.98) # Make a simple edge arrow for glyphing. arrowSource = vtk.vtkGlyphSource2D() arrowSource.SetGlyphTypeToEdgeArrow() arrowSource.SetScale(0.1) arrowSource.Update() # Use Glyph3D to repeat the glyph on all edges. arrowGlyph = vtk.vtkGlyph3D() arrowGlyph.SetInputConnection(0, graphToPoly.GetOutputPort(1)) arrowGlyph.SetInputConnection(1, arrowSource.GetOutputPort()) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(arrowGlyph.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # pipeline stuff # sphere = vtk.vtkSphereSource() sphere.SetPhiResolution(10) sphere.SetThetaResolution(20) 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())
def prepGlyph(g, marker, index=0): t, s = marker.type[index], marker.size[index] * .5 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() g.SetSourceConnection(gs.GetOutputPort()) return gs, pd
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] 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 _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]]
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
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 _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]]
def plot(self, struct): # creates self. data1, legend, filename, fieldname, dim, has_field, tracker, revision if not self.call_config(struct): return self.update_field_type('vector', True) self.update_legend_data() # creates self.src if not self.call_src(): return self.ugrid = self.construct_data(self.src) self.src_vc = vtk.vtkAssignAttribute() #self.src_vc.Assign(aname, 0, pc) # 0 scalar 1 vector ; 0 point 1 cell if vtk.vtkVersion.GetVTKMajorVersion() < 6: self.src_vc.SetInput(self.ugrid) else: self.src_vc.SetInputData(self.ugrid) res = self.apply_data(self.lastmode) # necesario, se non da erro vtk # self.wireM = vtk.vtkDataSetMapper() # self.wireM.SetInputConnection(self.src.GetOutputPort()) # print 'rango o:', self.src.GetOutput().GetScalarRange() #test # print 'rango d:', self.src.GetOutputAsDataSet().GetScalarRange() #test #so para xml (vtu) # self.wireM.SetScalarRange(self.src.GetOutput().GetScalarRange()) # reverse rainbow [red->blue] -> [blue->red] # look = self.wireM.GetLookupTable() # self.add_scalarbar_2(look) self.add_outline_2(self.src_vc) if self.data1.get( 'fielddomain' ) == 'cell': # vtk does not seem to support cell vectors self.cellcenters = vtk.vtkCellCenters() self.cellcenters.SetInputConnection(self.src_vc.GetOutputPort()) self.cellcenters_click = vtk.vtkCellCenters() # ALPHA-vc self.cellcenters_click.SetInputConnection( self.src.GetOutputPort()) # ALPHA-vc if False: # vector self.gl = vtk.vtkArrowSource() else: # simple arrow self.gl = vtk.vtkGlyphSource2D() self.gl.SetGlyphTypeToArrow() self.gl.FilledOff() print 'arrow center', self.gl.GetCenter(), '->', self.gl.SetCenter(0.5, 0, 0) print self.gl.GetCenter() #Prueba para representar flechas 3d (descomentar) # cyl = vtk.vtkCylinderSource() # cyl.SetResolution(6) # cyl.SetRadius(.05) # cyl.SetHeight(1) # cylTrans = vtk.vtkTransform() # cylTrans.Identity() # cylTrans.RotateZ(90) # cylTrans.Translate(0,-1,0) # cylTransFilter = vtk.vtkTransformPolyDataFilter() # cylTransFilter.SetInput(cyl.GetOutput()) # cylTransFilter.SetTransform(cylTrans) # cone = vtk.vtkConeSource() # cone.SetResolution(6) # cone.SetCenter(2,0,0) # cone.SetAngle(15) # arrow = vtk.vtkAppendPolyData() # arrow.AddInput(cylTransFilter.GetOutput()) # arrow.AddInput(cone.GetOutput()) # arrow.Update() # self.gl = arrow #Prueba para representar flechas 3d self.lin = vtk.vtkGlyph3D() if self.data1.get( 'fielddomain' ) == 'cell': # vtk does not seem to support cell vectors if vtk.vtkVersion.GetVTKMajorVersion() < 6: self.lin.SetInput( self.cellcenters.GetOutput()) #amañar cambio new else: self.lin.SetInputConnection( self.cellcenters.GetOutputPort()) #amañar cambio new #lutrange = self.src_vc.GetOutput().GetCellData().GetVectors().GetRange(-1) else: if vtk.vtkVersion.GetVTKMajorVersion() < 6: self.lin.SetInput(self.src_vc.GetOutput()) else: self.lin.SetInputConnection(self.src_vc.GetOutputPort()) #lutrange = self.src_vc.GetOutput().GetPointData().GetVectors().GetRange(-1) lut = vtk.vtkLookupTable() lut.SetRampToLinear() lut.SetScaleToLinear() # When using vector magnitude for coloring lut.SetVectorModeToMagnitude() lut.Build() # When using a vector component for coloring #lut.SetVectorModeToComponent() #lut.SetVectorComponent(1) if self.vectors is not None: lutrange = self.vectors.GetRange(-1) lut.SetTableRange(lutrange) self.lin.SetSourceConnection(self.gl.GetOutputPort()) self.lin.SetScaleModeToScaleByVector() # self.lin.SetScaleFactor(1.0) self.lin.SetColorModeToColorByVector() # flechas de cores self.lin.OrientOn() self.lin.Update() self.pdM = vtk.vtkPolyDataMapper() self.pdM.SetInputConnection(self.lin.GetOutputPort()) #coloreado de vectores # self.pdM.SetScalarRange(lutrange) self.pdM.ScalarVisibilityOn() self.pdM.SetLookupTable(lut) self.pdM.InterpolateScalarsBeforeMappingOff() # self.pdM.UseLookupTableScalarRangeOn() self.pdM.Update() self.linA = vtk.vtkActor() self.linA.SetMapper(self.pdM) # self.linA.GetProperty().SetColor(Plot.arrow_color) #para mostrar surface e wireframe ao mesmo tempo self.wireM2 = vtk.vtkDataSetMapper() self.wireM2.SetInputConnection(self.src_vc.GetOutputPort()) self.wireM2.ScalarVisibilityOff() self.wireA2 = vtk.vtkActor() self.wireA2.SetMapper(self.wireM2) self.wireA2.GetProperty().SetRepresentationToWireframe() self.wireA2.GetProperty().SetColor(Plot.edges_color) # self.wireA = vtk.vtkActor() # self.wireA.SetMapper(self.wireM) # self.wireA.GetProperty().SetRepresentationToSurface() # self.wireA.GetProperty().SetColor(Plot.edges_color) # self.rens[0].AddActor(self.wireA) self.add_opacity_2([self.linA, self.wireA2]) # Opacity: 100%/75%/50%/25%/0% self.rens[0].AddActor(self.wireA2) self.rens[0].AddActor(self.linA) if interactive: self.set_iren() if self.data1.get('fielddomain') == 'cell': self.clicker.set_point_cell('point') # así ok self.clicker.set_objects(self.cellcenters_click, self.rens[0], self.iren, self.widget) # ALPHA-vc else: self.clicker.set_point_cell(self.data1.get('fielddomain')) self.clicker.set_objects(self.src, self.rens[0], self.iren, self.widget) # ALPHA-vc self.clicker.set_props([self.wireA2]) self.clicker.setup() newlast = self.read_params(struct) ##### if newlast[0] is not None: self.lastscale = newlast[0] if newlast[1] is not None: self.lastmode = newlast[1] self.apply_params() for ren in self.rens: # WORKAROUND (aparecia non centrada) // + outline ren.ResetCamera() if self.vectors is not None: self.scalarrange.local_set(lutrange) self.add_scalarbar_1() self.add_scalarbar_2(lut) self.done = True
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
reader.SetFileName('/Users/emonson/Programming/VTK_cvs/vtkVTG/Examples/Python/SingleFiberPoints1.vtk') reader.Update() ug = reader.GetOutputDataObject(0) points = ug.GetPoints() ptArray = VN.vtk_to_numpy(points.GetData()) pdata = ug.GetPointData() dir = pdata.GetArray('fibers_fibers_direction') dirArray = VN.vtk_to_numpy(dir) line = vtk.vtkLineSource() line.SetPoint1(0,0,0) line.SetPoint2(1,0,0) line.SetResolution(2) vert = vtk.vtkGlyphSource2D() vert.SetGlyphTypeToVertex() vert.SetCenter(1,0,0) lineGlyph = vtk.vtkGlyph3D() lineGlyph.SetInputConnection(reader.GetOutputPort(0)) lineGlyph.SetSource(line.GetOutput()) lineGlyph.ScalingOn() lineGlyph.SetScaleModeToScaleByVector() lineGlyph.SetScaleFactor(1.0) lineGlyph.OrientOn() lineGlyph.SetVectorModeToUseVector() tube = vtk.vtkTubeFilter() tube.SetInputConnection(lineGlyph.GetOutputPort()) tube.SetRadius(0.05)
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
probe3 = vtk.vtkProbeFilter() probe3.SetInputConnection(tf3.GetOutputPort()) probe3.SetSourceData(output) appendF = vtk.vtkAppendPolyData() appendF.AddInputData(probe.GetPolyDataOutput()) appendF.AddInputData(probe2.GetPolyDataOutput()) appendF.AddInputData(probe3.GetPolyDataOutput()) tuber = vtk.vtkTubeFilter() tuber.SetInputConnection(appendF.GetOutputPort()) tuber.SetRadius(0.1) lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputConnection(tuber.GetOutputPort()) lineActor = vtk.vtkActor() lineActor.SetMapper(lineMapper) # probe the line and plot it triangle = vtk.vtkGlyphSource2D() triangle.SetGlyphTypeToTriangle() triangle.Update() cross = vtk.vtkGlyphSource2D() cross.SetGlyphTypeToCross() cross.Update() xyplot = vtk.vtkXYPlotActor() xyplot.AddDataSetInputConnection(probe.GetOutputPort()) xyplot.AddDataSetInputConnection(probe2.GetOutputPort()) xyplot.AddDataSetInputConnection(probe3.GetOutputPort()) xyplot.GetPositionCoordinate().SetValue(0.0,0.67,0) xyplot.GetPosition2Coordinate().SetValue(1.0,0.33,0) #relative to Position xyplot.SetXValuesToArcLength() xyplot.SetNumberOfXLabels(6) xyplot.SetTitle("Pressure vs. Arc Length (Zoomed View)")
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) pd2 = vtk.vtkPolyData() pd2.SetPoints(psrc) psrc = vtk.vtkGlyphSource2D() psrc.SetScale(1.) psrc.SetColor(1.,0.,0.) psrc.SetGlyphTypeToCircle() g.SetSourceConnection(psrc.GetOutputPort()) m = vtk.vtkPolyDataMapper() m.SetInputConnection(g.GetOutputPort()) m.Update() ga = vtk.vtkActor() ga.SetMapper(m) ren.AddActor(ga) ren.SetBackground(.2,.3,.4)
probe3.SetInputConnection(tf3.GetOutputPort()) probe3.SetSourceData(output) probe3.Update() appendF = vtk.vtkAppendPolyData() appendF.AddInputConnection(probe.GetOutputPort()) appendF.AddInputConnection(probe2.GetOutputPort()) appendF.AddInputConnection(probe3.GetOutputPort()) tuber = vtk.vtkTubeFilter() tuber.SetInputConnection(appendF.GetOutputPort()) tuber.SetRadius(0.1) lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputConnection(tuber.GetOutputPort()) lineActor = vtk.vtkActor() lineActor.SetMapper(lineMapper) # probe the line and plot it triangle = vtk.vtkGlyphSource2D() triangle.SetGlyphTypeToTriangle() triangle.Update() cross = vtk.vtkGlyphSource2D() cross.SetGlyphTypeToCross() cross.Update() xyplot = vtk.vtkXYPlotActor() xyplot.AddDataSetInputConnection(probe.GetOutputPort()) xyplot.AddDataSetInputConnection(probe2.GetOutputPort()) xyplot.AddDataSetInputConnection(probe3.GetOutputPort()) xyplot.GetPositionCoordinate().SetValue(0.0, 0.67, 0) xyplot.GetPosition2Coordinate().SetValue(1.0, 0.33, 0) #relative to Position xyplot.SetXValuesToArcLength() xyplot.SetNumberOfXLabels(6) xyplot.SetTitle("Pressure vs. Arc Length (Zoomed View)")
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]]
def loadGraph(): # ---------- # Load and construct whole graph and multi-resolution data from Matlab structure dataDir = '/Users/emonson/Programming/Matlab/EMonson/Fodava/DocumentAnalysis/Analysis/' filename = dataDir + 'X20_042709b.mat' # filename = '/Users/emonson/Programming/Python/VTK/X20_040609b.mat' X = scipy.io.loadmat(filename) # Get graph structure G out of matlab variables G = X['G'] # ---------- # Set multi-resolution level bounds in GUI sliders levelMax = G.Tree.shape[0]-1 ui_window.hSlider_level.setMinimum(1) ui_window.hSlider_level.setMaximum(levelMax) ui_window.spinBox_level.setMinimum(1) ui_window.spinBox_level.setMaximum(levelMax) # Start setting up basis function for display as subgraph ExtBasis = GTree[level,0]['ExtBasis'][0][0][0] basisMax = ExtBasis.shape[1]-1 # zero-based indices # Set particular level basis function bounds in GUI sliders ui_window.hSlider_basisIndex.setMinimum(0) ui_window.hSlider_basisIndex.setMaximum(basisMax) ui_window.spinBox_basisIndex.setMinimum(0) ui_window.spinBox_basisIndex.setMaximum(basisMax) # Build table which will become graph table = vtk.vtkTable() col0 = vtk.vtkIntArray() col0.SetName('index1') col1 = vtk.vtkIntArray() col1.SetName('index2') val = vtk.vtkDoubleArray() val.SetName('weight') Tmat = G.T # Tmat = G.W for ii in range(Tmat.nzmax): col0.InsertNextValue(Tmat.rowcol(ii)[0]) col1.InsertNextValue(Tmat.rowcol(ii)[1]) val.InsertNextValue(abs(Tmat.getdata(ii))) table.AddColumn(col0) table.AddColumn(col1) table.AddColumn(val) # Vertex links need to be done with index2 first or indexing won't be right... # TODO: Make this foolproof so that graph always ends up with correct ordering of indices... tgraph = vtk.vtkTableToGraph() tgraph.SetInput(table) tgraph.AddLinkVertex('index2', 'stuff', False) tgraph.AddLinkVertex('index1', 'stuff', False) tgraph.AddLinkEdge('index2', 'index1') rawGraph = tgraph.GetOutput() rawGraph.Update() # print graph # Load and assign whole graph pre-layout coordinates ptsFile = os.path.splitext(filename)[0] + '_pts.vtp' if os.path.exists(ptsFile): polyreader = vtk.vtkXMLPolyDataReader() polyreader.SetFileName(ptsFile) polyreader.Update() pts = polyreader.GetOutput().GetPoints() rawGraph.SetPoints(pts) # print pts strategy = vtk.vtkPassThroughLayoutStrategy() layout = vtk.vtkGraphLayout() layout.SetInput(rawGraph) layout.SetLayoutStrategy(strategy) edgeLayout = vtk.vtkEdgeLayout() edgeStrategy = vtk.vtkArcParallelEdgeStrategy() edgeStrategy.SetNumberOfSubdivisions(50) edgeLayout.SetInputConnection(layout.GetOutputPort()) edgeLayout.SetLayoutStrategy(edgeStrategy) graph = edgeLayout.GetOutput() graph.Update() # -------- # Add ExtBasis to graph data & Select particular basis function # print 'ExtBasis shape: ' + str(ExtBasis[:,basisNum].data.shape) + ' (level,basis) (' + str(level) + ',' + str(basisNum) + ')' # Indexing of ExtBasis is backwards from graph, so need to reverse with [::-1] # and array not "contiguous" if don't do .copy() Esub = ExtBasis[:,basisNum].data[::-1].copy() EsubSq = Esub**2 # Esub = N.random.random(ExtBasis[:,basisNum].data.shape[0]) # SubIdxs = (Esub > 0.001).nonzero() # SubIdxs = (Esub**2 > 0.8).nonzero() # Set ExtBasis vertex data from numpy array basisFunc = VN.numpy_to_vtk(Esub) basisFunc.SetName('ExtBasis') basisFuncSq = VN.numpy_to_vtk(EsubSq) basisFuncSq.SetName('ExtBasisSq') vertexData = graph.GetVertexData() vertexData.AddArray(basisFunc) vertexData.AddArray(basisFuncSq) selection = vtk.vtkSelectionSource() selection.SetContentType(7) # vtkSelection::THRESHOLDS # selection.SetContentType(2) # vtkSelection::PEDIGREE_IDS selection.SetFieldType(3) # vtkSelection::VERTEX selection.SetArrayName("ExtBasisSq") selection.AddThreshold(basisCutoff, 10) # TODO: There was something wrong with the indexing in the PEDIGREE_IDS selection... # for ii in SubIdxs[0]: # selection.AddID(0,ii) minmax = "(%3.2e, %3.2e)" % (EsubSq.min(), EsubSq.max()) ui_window.label_basisCutoff_minmax.setText(minmax) selection.Update() # ---------- # Back to pipeline degree = vtk.vtkVertexDegree() degree.SetInput(graph) subgraph = vtk.vtkExtractSelectedGraph() subgraph.SetRemoveIsolatedVertices(False) subgraph.SetInputConnection(degree.GetOutputPort()) subgraph.SetSelectionConnection(selection.GetOutputPort()) # +++++++++++++ graphToPoly = vtk.vtkGraphToPolyData() graphToPoly.SetInputConnection(subgraph.GetOutputPort()) edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputConnection(graphToPoly.GetOutputPort()) edgeMapper.SetScalarModeToUseCellData() edgeMapper.SetScalarVisibility(False) edgeMapper.SetImmediateModeRendering(True) edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.SetPosition(0, 0, -0.003); lut = vtk.vtkLookupTable() lutNum = 256 lut.SetNumberOfTableValues(lutNum) ctf = vtk.vtkColorTransferFunction() ctf.SetColorSpaceToDiverging() ctf.AddRGBPoint(0.0, 0, 0, 1.0) ctf.AddRGBPoint(1.0, 1.0, 0, 0) for ii,ss in enumerate([float(xx)/float(lutNum) for xx in range(lutNum)]): cc = ctf.GetColor(ss) lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0) vertGlyph = vtk.vtkVertexGlyphFilter() vertGlyph.SetInputConnection(subgraph.GetOutputPort()) vertMapper = vtk.vtkPolyDataMapper() vertMapper.SetInputConnection(vertGlyph.GetOutputPort()) vertMapper.SetImmediateModeRendering(True) vertMapper.SetScalarModeToUsePointFieldData() vertMapper.SetLookupTable(lut) vertMapper.SelectColorArray('ExtBasis') vertMapper.Update() vertRange = vertMapper.GetInput().GetPointData().GetArray(vertMapper.GetArrayName()).GetRange() vertMapper.SetScalarRange(-1.0*vertRange[1], vertRange[1]) vertActor = vtk.vtkActor() vertActor.SetMapper(vertMapper) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetScalarVisibility(False) outlineMapper.SetImmediateModeRendering(True) outlineMapper.SetInputConnection(vertGlyph.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.PickableOff() outlineActor.SetPosition(0, 0, -0.001) outlineActor.GetProperty().SetRepresentationToWireframe() outlineActor.SetMapper(outlineMapper) # Create an Actor Collection for applying visibility to group basisActorCollection = vtk.vtkActorCollection() basisActorCollection.AddItem(vertActor) # basisActorCollection.AddItem(edgeActor) basisActorCollection.AddItem(outlineActor) # Apply a theme to the views theme = vtk.vtkViewTheme.CreateMellowTheme() theme.SetLineWidth(3) theme.SetPointSize(5) theme.SetSelectedCellColor(1,1,1) theme.SetSelectedPointColor(1,1,1) theme.SetOutlineColor(0.8, 0.8, 0.8) # theme.SetPointColor(0.9, 0.7, 0.3) theme.SetCellColor(0.9, 0.7, 0.3) # theme.SetPointOpacity(0.5) # theme.SetPointHueRange(0.0, 0.15) # theme.SetPointSaturationRange(0.6, 0.8) # theme.SetPointValueRange(0.4,0.8) # theme.SetPointAlphaRange(0.2,0.8) # theme.SetPointAlphaRange(1.0,1.0) # Apply theme # vertActor.GetProperty().SetColor(theme.GetPointColor()) # vertActor.GetProperty().SetOpacity(theme.GetPointOpacity()) vertActor.GetProperty().SetPointSize(theme.GetPointSize()) outlineActor.GetProperty().SetPointSize(vertActor.GetProperty().GetPointSize()+2) outlineActor.GetProperty().SetColor(theme.GetOutlineColor()) outlineActor.GetProperty().SetOpacity(theme.GetPointOpacity()) edgeActor.GetProperty().SetColor(theme.GetCellColor()) edgeActor.GetProperty().SetOpacity(theme.GetCellOpacity()) edgeActor.GetProperty().SetLineWidth(theme.GetLineWidth()) # ---------- # Background graph skeleton graphMapper = vtk.vtkGraphMapper() graphMapper.SetInputConnection(0, degree.GetOutputPort(0)) # Apply a theme to the background graph gtheme = vtk.vtkViewTheme() gtheme.SetLineWidth(1) gtheme.SetPointSize(0) gtheme.SetCellColor(0.8, 0.8, 0.8) gtheme.SetCellOpacity(0.2) gtheme.SetOutlineColor(0.8, 0.8, 0.8) gtheme.SetPointColor(0.8, 0.8, 0.8) gtheme.SetPointOpacity(0.0) graphMapper.ApplyViewTheme(gtheme) graphActor = vtk.vtkActor() graphActor.SetMapper(graphMapper) graphActor.SetPosition(0,0,-0.005) # ---------- # Background vertices graphPoly = vtk.vtkGraphToPolyData() graphPoly.SetInputConnection(0, tgraph.GetOutputPort(0)) vertGlyph = vtk.vtkGlyph3D() vertGlyph.SetInputConnection(0, graphPoly.GetOutputPort()) glyphSource = vtk.vtkGlyphSource2D() glyphSource.SetGlyphTypeToVertex() # glyphSource.SetGlyphTypeToCircle() # glyphSource.SetScale(0.025) vertGlyph.SetInputConnection(1, glyphSource.GetOutputPort()) vertexMapper = vtk.vtkPolyDataMapper() vertexMapper.SetInputConnection(vertGlyph.GetOutputPort()) vertexActor = vtk.vtkActor() vertexActor.SetMapper(vertexMapper) vertexActor.GetProperty().SetPointSize(4) vertexActor.GetProperty().SetOpacity(0.5) vertexActor.GetProperty().SetColor(0.6, 0.6, 0.6) vertexActor.SetPosition(0, 0, -0.004) # ---------- # Vertex index labels labelMapper = vtk.vtkDynamic2DLabelMapper() labelMapper.SetInputConnection(0, graphPoly.GetOutputPort(0)) labelMapper.SetLabelModeToLabelFieldData() labelMapper.SetFieldDataName("label") labelMapper.SetLabelFormat("%s") labelMapper.GetLabelTextProperty().SetColor(0.0, 0.0, 0.0) labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # ---------- # MultiScale Graph msGraph = buildSubGraph(level) msMapper = vtk.vtkGraphMapper() msMapper.SetInput(msGraph) msMapper.SetColorEdges(True) msMapper.SetEdgeColorArrayName('weight') # Apply a theme to the background graph mtheme = vtk.vtkViewTheme() mtheme.SetLineWidth(3) mtheme.SetPointSize(11) # mtheme.SetCellColor(0.5, 0.5, 0.7) # mtheme.SetCellOpacity(0.5) mtheme.SetOutlineColor(0.8, 0.8, 0.8) mtheme.SetPointColor(0.3, 0.3, 0.6) mtheme.SetPointOpacity(1.0) mtheme.SetCellHueRange(0.67, 0.67) mtheme.SetCellSaturationRange(0.6, 0.1) mtheme.SetCellValueRange(0.5,1.0) mtheme.SetCellAlphaRange(0.2,0.8) msMapper.ApplyViewTheme(mtheme) msActor = vtk.vtkActor() msActor.SetMapper(msMapper) msActor.SetPosition(0,0,-0.002) # ---------- # Set up window and add actors view.SetLayoutStrategyToPassThrough() # view.ApplyViewTheme(theme) # view.SetupRenderWindow(win) view.GetRenderer().SetBackground(theme.GetBackgroundColor()) view.GetRenderer().SetBackground2(theme.GetBackgroundColor2()) view.GetRenderer().SetGradientBackground(True) view.GetRenderer().AddActor(vertActor) view.GetRenderer().AddActor(outlineActor) view.GetRenderer().AddActor(edgeActor) view.GetRenderer().AddActor(graphActor) view.GetRenderer().AddActor(vertexActor) view.GetRenderer().AddActor(labelActor) view.GetRenderer().AddActor(msActor) # ---------- # General interactor isty = vtk.vtkInteractorStyleRubberBand2D() # RubberBand2D assumes/needs parallel projection ON view.GetRenderer().GetActiveCamera().ParallelProjectionOn() iren = view.GetRenderWindow().GetInteractor() iren.SetInteractorStyle(isty) # Interactor style must be set before scalar bar can be shown # view.SetVertexScalarBarVisibility(True) sbActor = vtk.vtkScalarBarActor() sbActor.SetLookupTable(vertMapper.GetLookupTable()) sbActor.SetTitle(vertMapper.GetArrayName()) sbActor.SetNumberOfLabels(3) vertexScalarBar = vtk.vtkScalarBarWidget() vertexScalarBar.SetScalarBarActor(sbActor) vertexScalarBar.SetInteractor(iren) vertexScalarBar.SetDefaultRenderer(view.GetRenderer()) vertexScalarBar.SetCurrentRenderer(view.GetRenderer()) vertexScalarBar.SetEnabled(True) scalarBarRep = vertexScalarBar.GetRepresentation() scalarBarRep.SetOrientation(1) # 0 = Horizontal, 1 = Vertical scalarBarRep.GetPositionCoordinate().SetValue(0.05,0.05) scalarBarRep.GetPosition2Coordinate().SetValue(0.15,0.25) # Adding it this way gets it to show up, but it's not interactive view.GetRenderer().AddActor(sbActor) view.ResetCamera() view.Render() # ---------- # Add Actors to QListWidget to allow check and uncheck for visibility listItem0 = QtGui.QListWidgetItem() listItem0.setText('Index Labels') listItem0.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) labelActor.SetVisibility(0) listItem0.setCheckState(QtCore.Qt.Unchecked) # Put actor it in as data in the list widget item listItem0.setData(QtCore.Qt.UserRole, QtCore.QVariant(labelActor)) ui_window.listWidget.insertItem(0,listItem0) # Test retrieval of actor from list widget item # tmpItem = ui_window.listWidget.item(0) # tmpQtActor = tmpItem.data(QtCore.Qt.UserRole) # tmpActor = tmpQtActor.toPyObject() # tmpActor.SetVisibility(0) # Shorter way to add item to list widget listItem1 = QtGui.QListWidgetItem('Vertices (background)', ui_window.listWidget) listItem1.setData(QtCore.Qt.UserRole, QtCore.QVariant(vertexActor)) listItem1.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem1.setCheckState(QtCore.Qt.Checked) listItem2 = QtGui.QListWidgetItem('Graph (background)', ui_window.listWidget) listItem2.setData(QtCore.Qt.UserRole, QtCore.QVariant(graphActor)) listItem2.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem2.setCheckState(QtCore.Qt.Checked) listItem3 = QtGui.QListWidgetItem() listItem3.setText('Basis Function Vertices') listItem3.setData(QtCore.Qt.UserRole, QtCore.QVariant(basisActorCollection)) listItem3.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem3.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(1,listItem3) listItem6 = QtGui.QListWidgetItem() listItem6.setText('Basis Function Edges') listItem6.setData(QtCore.Qt.UserRole, QtCore.QVariant(edgeActor)) listItem6.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem6.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(2,listItem6) listItem4 = QtGui.QListWidgetItem() listItem4.setText('MultiScale Graph') listItem4.setData(QtCore.Qt.UserRole, QtCore.QVariant(msActor)) listItem4.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem4.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(3,listItem4) listItem5 = QtGui.QListWidgetItem() listItem5.setText('Basis Function Scale Bar') listItem5.setData(QtCore.Qt.UserRole, QtCore.QVariant(sbActor)) listItem5.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem5.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(3,listItem5) iren.Initialize() iren.Start()
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]]
iren.SetRenderWindow(renWin) # create pipeline # pl3d = vtk.vtkPLOT3DReader() pl3d.SetXYZFileName( vtkGetDataRoot() + '/Data/combxyz.bin' ) pl3d.SetQFileName( vtkGetDataRoot() + '/Data/combq.bin' ) pl3d.SetScalarFunctionNumber( 100 ) pl3d.SetVectorFunctionNumber( 202 ) pl3d.Update() eg = vtk.vtkExtractGrid() eg.SetInputConnection(pl3d.GetOutputPort()) eg.SetSampleRate(4,4,4) gs = vtk.vtkGlyphSource2D() gs.SetGlyphTypeToThickArrow() gs.SetScale( 1 ) gs.FilledOff() gs.CrossOff() glyph = vtk.vtkGlyph3D() glyph.SetInputConnection(eg.GetOutputPort()) glyph.SetSource(gs.GetOutput()) glyph.SetScaleFactor( 0.75 ) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper)
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 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 _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]]
pd.SetPoints(pts) pd.GetPointData().SetScalars(scalars) pd.GetPointData().SetVectors(vectors) math = vtk.vtkMath() size = 500 i = 0 while i < 100: pts.InsertNextPoint( math.Random(0, expr.expr(globals(), locals(), ["size", "-", "1"])), math.Random(0, expr.expr(globals(), locals(), ["size", "-", "1"])), 0.0) scalars.InsertNextValue(math.Random(0.0, 5)) vectors.InsertNextTuple3(math.Random(-1, 1), math.Random(-1, 1), 0.0) i = i + 1 gs = vtk.vtkGlyphSource2D() gs.SetGlyphTypeToCircle() gs.SetScale(20) gs.FilledOff() gs.CrossOn() gs.Update() gs1 = vtk.vtkGlyphSource2D() gs1.SetGlyphTypeToTriangle() gs1.SetScale(20) gs1.FilledOff() gs1.CrossOn() gs1.Update() gs2 = vtk.vtkGlyphSource2D() gs2.SetGlyphTypeToSquare() gs2.SetScale(20) gs2.FilledOff()
sphereActor = vtk.vtkActor() sphereActor.SetMapper(sphereMapper) sphereActor.GetProperty().SetColor(0,0,0) # Voronoi flower represented by sampled points fMapper = vtk.vtkPointGaussianMapper() fMapper.SetInputConnection(voronoi.GetOutputPort(1)) fMapper.EmissiveOff() fMapper.SetScaleFactor(0.0) fActor = vtk.vtkActor() fActor.SetMapper(fMapper) fActor.GetProperty().SetColor(0,0,1) # Voronoi flower circles circle = vtk.vtkGlyphSource2D() circle.SetResolution(64) circle.SetGlyphTypeToCircle() cGlyph = vtk.vtkGlyph3D() cGlyph.SetInputConnection(voronoi.GetOutputPort(2)) cGlyph.SetSourceConnection(circle.GetOutputPort()) cGlyph.SetScaleFactor(2.0) cMapper = vtk.vtkPolyDataMapper() cMapper.SetInputConnection(cGlyph.GetOutputPort()) cMapper.ScalarVisibilityOff() cActor = vtk.vtkActor() cActor.SetMapper(cMapper) cActor.GetProperty().SetColor(0,0,0)
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 __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() g = vtk.vtkMutableDirectedGraph() v1 = g.AddVertex() v2 = g.AddVertex() v3 = g.AddVertex() ### g.AddEdge(v1, v2) g.AddGraphEdge(v1, v2) g.AddGraphEdge(v2, v3) g.AddGraphEdge(v3, v1) # Do layout manually before handing graph to the view. # This allows us to know the positions of edge arrows. graphLayoutView = vtk.vtkGraphLayoutView() layout = vtk.vtkGraphLayout() strategy = vtk.vtkSimple2DLayoutStrategy() layout.SetInput(g) layout.SetLayoutStrategy(strategy) # Tell the view to use the vertex layout we provide graphLayoutView.SetLayoutStrategyToPassThrough() # The arrows will be positioned on a straight line between two # vertices so tell the view not to draw arcs for parallel edges graphLayoutView.SetEdgeLayoutStrategyToPassThrough() # Add the graph to the view. This will render vertices and edges, # but not edge arrows. graphLayoutView.AddRepresentationFromInputConnection( layout.GetOutputPort()) # Manually create an actor containing the glyphed arrows. graphToPoly = vtk.vtkGraphToPolyData() graphToPoly.SetInputConnection(layout.GetOutputPort()) graphToPoly.EdgeGlyphOutputOn() # Set the position (0: edge start, 1:edge end) where # the edge arrows should go. graphToPoly.SetEdgeGlyphPosition(0.98) # Make a simple edge arrow for glyphing. arrowSource = vtk.vtkGlyphSource2D() arrowSource.SetGlyphTypeToEdgeArrow() arrowSource.SetScale(0.1) arrowSource.Update() # Use Glyph3D to repeat the glyph on all edges. arrowGlyph = vtk.vtkGlyph3D() arrowGlyph.SetInputConnection(0, graphToPoly.GetOutputPort(1)) arrowGlyph.SetInputConnection(1, arrowSource.GetOutputPort()) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(arrowGlyph.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False