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 createGraph(points): g = vtk.vtkMutableDirectedGraph() vertexes = [] alreadyConnected = [] for i in range(0, points.GetNumberOfPoints()): vertexes.append(g.AddVertex()) alreadyConnected.append(i) for i in range(0, points.GetNumberOfPoints()): index = -1 distance = float("inf") distanceOrder = 0 record = float("inf") for j in range(0, points.GetNumberOfPoints()): distance = math.sqrt( vtk.vtkMath.Distance2BetweenPoints(points.GetPoint(i), points.GetPoint(j))) if (distance > 0 and distance < record and alreadyConnected[j] != i and alreadyConnected[alreadyConnected[j]] != i): record = distance index = j elif (distance > 0 and distance < record): distanceOrder += 1 if (index != -1 and distanceOrder < 2): alreadyConnected[i] = index g.AddGraphEdge(vertexes[i], vertexes[index]) for i in range(0, points.GetNumberOfPoints()): index = -1 distance = float("inf") distanceOrder = 0 record = float("inf") for j in range(0, points.GetNumberOfPoints()): distance = math.sqrt( vtk.vtkMath.Distance2BetweenPoints(points.GetPoint(i), points.GetPoint(j))) if (distance > 0 and distance < record and alreadyConnected[j] != i and alreadyConnected[i] != j and alreadyConnected[alreadyConnected[j]] != alreadyConnected[alreadyConnected[i]]): record = distance index = j elif (distance > 0 and distance < record): distanceOrder += 1 if (index != -1 and distanceOrder < 2): alreadyConnected[i] = index g.AddGraphEdge(vertexes[i], vertexes[index]) graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(g) graphLayoutView.SetLayoutStrategy("Simple 2D") graphLayoutView.ResetCamera() graphLayoutView.Render() graphLayoutView.GetLayoutStrategy().SetRandomSeed(0) graphLayoutView.GetInteractor().Start()
def simpleVtkDiGraph(): g = vtk.vtkMutableDirectedGraph() # Create 3 vertices v1 = g.AddVertex() v2 = g.AddVertex() v3 = g.AddVertex() # Create a fully connected graph g.AddGraphEdge(v1, v2) g.AddGraphEdge(v2, v3) g.AddGraphEdge(v1, v3) # Create the edge weight array weights = vtk.vtkDoubleArray() weights.SetNumberOfComponents(1) weights.SetName("Weights") # Set the edge weights weights.InsertNextValue(1.0) weights.InsertNextValue(1.0) weights.InsertNextValue(2.0) # Add the edge weight array to the graph g.GetEdgeData().AddArray(weights) return g
def __init__(self, filename, max_num_of_vertices=-1, edge_color_filename=None): super(VTKVisualizer, self).__init__() self.vertex_id_idx_map = {} self.next_vertex_id = 0 self.edge_counter = 0 self.lookup_table = vtk.vtkLookupTable() self.lookup_table.SetNumberOfColors(int(1e8)) self.edge_color_tuples = {} self.edge_color_filename = edge_color_filename self.label_vertex_id_map = {} self.starting_vertex = None self.starting_vertex_index = -1 self.filename = filename self.max_num_of_vertices = max_num_of_vertices self.g = vtk.vtkMutableDirectedGraph() self.vertex_ids = vtk.vtkIntArray() self.vertex_ids.SetNumberOfComponents(1) self.vertex_ids.SetName(VERTEX_ID) self.labels = vtk.vtkStringArray() self.labels.SetNumberOfComponents(1) self.labels.SetName(LABELS) self.glyph_scales = vtk.vtkFloatArray() self.glyph_scales.SetNumberOfComponents(1) self.glyph_scales.SetName(SCALES) self.edge_weights = vtk.vtkDoubleArray() self.edge_weights.SetNumberOfComponents(1) self.edge_weights.SetName(WEIGHTS) self.edge_colors = vtk.vtkIntArray() self.edge_colors.SetNumberOfComponents(1) self.edge_colors.SetName(EDGE_COLORS)
def main(): # Create a graph graph = vtk.vtkMutableDirectedGraph() v1 = graph.AddVertex() v2 = graph.AddVertex() graph.AddEdge(v1, v2) # Create an array for the vertex labels vertexIDs = vtk.vtkIntArray() vertexIDs.SetNumberOfComponents(1) vertexIDs.SetName("VertexIDs") # Set the vertex labels vertexIDs.InsertNextValue(0) vertexIDs.InsertNextValue(1) # Add the array to the graph graph.GetVertexData().AddArray(vertexIDs) graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(graph) graphLayoutView.SetVertexLabelVisibility(1) rGraph = vtk.vtkRenderedGraphRepresentation() rGraph.SafeDownCast(graphLayoutView.GetRepresentation() ).GetVertexLabelTextProperty().SetColor(1, 0, 0) graphLayoutView.SetLayoutStrategyToSimple2D() graphLayoutView.SetVertexLabelArrayName("VertexIDs") graphLayoutView.ResetCamera() graphLayoutView.Render() graphLayoutView.GetInteractor().Start()
def GenerateVTKGraph(graph): ''' Take the vertices and edge list in the graph parameter and return a VTK graph. ''' g = vtk.vtkMutableDirectedGraph() # Label the vertices labels = vtk.vtkStringArray() labels.SetNumberOfComponents(1) labels.SetName("Labels") index = dict() l = list(graph[0]) # Make the vertex labels and create a dictionary with the # keys as labels and the vertex ids as the values. for i in range(0, len(l)): # Set the vertex labels labels.InsertNextValue(l[i]) index[l[i]] = g.AddVertex() g.GetVertexData().AddArray(labels) # Add edges l = list(graph[1]) for i in range(0, len(l)): ll = list(l[i]) g.AddGraphEdge(index[ll[0]], index[ll[1]]) # g.Dump() return g
def main(): graph = vtk.vtkMutableDirectedGraph() v1 = graph.AddVertex() v2 = graph.AddChild(v1) graph.AddChild(v1) graph.AddChild(v2) #equivalent to: #V1 = g.AddVertex() #V2 = g.AddVertex() #V3 = g.AddVertex() #V4 = g.AddVertex() #g.AddEdge ( V1, V2 ) #g.AddEdge ( V1, V3 ) #g.AddEdge ( V2, V4 ) tree = vtk.vtkTree() success = tree.CheckedShallowCopy(graph) print('Success?', success) #std::cout << "Success? " << success << std::endl treeLayoutView = vtk.vtkGraphLayoutView() treeLayoutView.AddRepresentationFromInput(tree) treeLayoutView.SetLayoutStrategyToTree() treeLayoutView.ResetCamera() treeLayoutView.Render() treeLayoutView.GetInteractor().Start()
def makegraph(table1, friends, clustering): graph = vtk.vtkMutableDirectedGraph() username = vtk.vtkStringArray() username.SetName("username") userid = vtk.vtkIntArray() userid.SetName("uid") classifier = vtk.vtkStringArray() classifier.SetName(clustering) v = [] ## Add vertices to graph for i in range(0, len(table1)): v.append(graph.AddVertex()) username.InsertNextValue(table1.loc[i].username) userid.InsertNextValue(table1.loc[i].userid) if clustering == "city": classifier.InsertNextValue(table1.loc[i].city) else: classifier.InsertNextValue(table1.loc[i].criminal) graph.GetVertexData().AddArray(username) graph.GetVertexData().AddArray(userid) graph.GetVertexData().AddArray(classifier) table1['vertex'] = v ## Add edges to graph, check to make sure the edge belongs in this graph ## (check that both vertices are in table1) for i in range(0, len(table1)): vertex1 = v[i] for j in friends[friends.ID1 == table1.loc[i].userid].ID2.tolist(): if table1[table1.userid == j].userid.size == 1: vertex2 = v[table1[table1.userid == j].vertex.tolist()[0]] graph.AddEdge(vertex1, vertex2) return graph
def main(): colors = vtk.vtkNamedColors() # Create a graph graph = vtk.vtkMutableDirectedGraph() v1 = graph.AddVertex() v2 = graph.AddVertex() v3 = graph.AddVertex() graph.AddEdge(v1, v2) graph.AddEdge(v2, v3) # Manually set the position of the vertices points = vtk.vtkPoints() points.InsertNextPoint(0, 0, 0) points.InsertNextPoint(1, 0, 0) points.InsertNextPoint(2, 0, 0) graph.SetPoints(points) # Create the color array vertexColors = vtk.vtkIntArray() vertexColors.SetNumberOfComponents(1) vertexColors.SetName('Color') lookupTable = vtk.vtkLookupTable() lookupTable.SetNumberOfTableValues(3) lookupTable.SetTableValue(0, colors.GetColor4d('Red')) lookupTable.SetTableValue(1, colors.GetColor4d('White')) lookupTable.SetTableValue(2, colors.GetColor4d('Lime')) lookupTable.Build() vertexColors.InsertNextValue(0) vertexColors.InsertNextValue(1) vertexColors.InsertNextValue(2) # Add the color array to the graph graph.GetVertexData().AddArray(vertexColors) # Visualize graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(graph) graphLayoutView.SetLayoutStrategyToPassThrough() graphLayoutView.SetVertexColorArrayName('Color') graphLayoutView.ColorVerticesOn() theme = vtk.vtkViewTheme() theme.SetPointLookupTable(lookupTable) graphLayoutView.ApplyViewTheme(theme) graphLayoutView.ResetCamera() graphLayoutView.GetInteractor().Initialize() graphLayoutView.GetRenderer().GetActiveCamera().Zoom(0.8) graphLayoutView.GetInteractor().Start()
def main(): graph = vtk.vtkMutableDirectedGraph() a = graph.AddVertex() b = graph.AddChild(a) c = graph.AddChild(a) d = graph.AddChild(b) e = graph.AddChild(c) f = graph.AddChild(c) vertex_labels = vtk.vtkStringArray() vertex_labels.SetName('VertexLabel') vertex_labels.InsertValue(a, 'a') vertex_labels.InsertValue(b, 'b') vertex_labels.InsertValue(c, 'c') vertex_labels.InsertValue(d, 'd') vertex_labels.InsertValue(e, 'e') vertex_labels.InsertValue(f, 'f') graph.GetVertexData().AddArray(vertex_labels) edge_labels = vtk.vtkStringArray() edge_labels.SetName('EdgeLabel') edge_labels.InsertValue(graph.GetEdgeId(a, b), 'a -> b') edge_labels.InsertValue(graph.GetEdgeId(a, c), 'a -> c') edge_labels.InsertValue(graph.GetEdgeId(b, d), 'b -> d') edge_labels.InsertValue(graph.GetEdgeId(c, e), 'c -> e') edge_labels.InsertValue(graph.GetEdgeId(c, f), 'c -> f') graph.GetEdgeData().AddArray(edge_labels) tree = vtk.vtkTree() valid_tree = tree.CheckedShallowCopy(graph) if not valid_tree: print('Invalid tree') return view = vtk.vtkGraphLayoutView() view.SetRepresentationFromInput(tree) # Apply a theme to the views theme = vtk.vtkViewTheme() view.ApplyViewTheme(theme.CreateMellowTheme()) view.SetVertexColorArrayName('VertexDegree') view.SetColorVertices(True) view.SetVertexLabelArrayName('VertexLabel') view.SetVertexLabelVisibility(True) view.SetEdgeLabelArrayName('EdgeLabel') view.SetEdgeLabelVisibility(True) view.SetLayoutStrategyToTree() view.ResetCamera() view.GetRenderWindow().SetSize(600, 600) view.GetRenderWindow().SetWindowName('CreateTree') view.GetRenderWindow().Render() view.GetInteractor().Initialize() view.GetInteractor().Start()
def generate_data(): g = vtk.vtkMutableDirectedGraph() # add vertices v = [] for i in range(6): v.append(g.AddVertex()) g.AddEdge(v[0], v[1]) g.AddEdge(v[1], v[2]) g.AddEdge(v[1], v[3]) g.AddEdge(v[0], v[4]) g.AddEdge(v[0], v[5]) weights = vtk.vtkDoubleArray() weights.SetNumberOfComponents(1) weights.SetName("Weights") X = vtk.vtkDoubleArray() X.SetNumberOfComponents(1) X.SetName("X") Y = vtk.vtkDoubleArray() Y.SetNumberOfComponents(1) Y.SetName("Y") X.InsertNextValue(0) X.InsertNextValue(0) X.InsertNextValue(1) X.InsertNextValue(-1) X.InsertNextValue(0.5) X.InsertNextValue(-0.5) Y.InsertNextValue(0) Y.InsertNextValue(1) Y.InsertNextValue(1.5) Y.InsertNextValue(2) Y.InsertNextValue(-.5) Y.InsertNextValue(-.8) weights.InsertNextValue(1.) weights.InsertNextValue(2.) weights.InsertNextValue(3.) weights.InsertNextValue(4.) weights.InsertNextValue(5.) g.GetEdgeData().AddArray(weights) g.GetVertexData().AddArray(X) g.GetVertexData().AddArray(Y) return g
def GetTree(self): """Returns a full vtkTree based on data loaded in LoadData().""" if self.data_loaded: vertex_id = vtk.vtkIdTypeArray() vertex_id.SetName('vertex_ids') for ii in range(len(self.cp)): vertex_id.InsertNextValue(ii) NINvtk = VN.numpy_to_vtk(self.NumberInNet, deep=True) NINvtk.SetName('num_in_vertex') SCALESvtk = VN.numpy_to_vtk(self.Scales, deep=True) SCALESvtk.SetName('scale') # This array will default to empty strings BLANKvtk = vtk.vtkStringArray() BLANKvtk.SetNumberOfComponents(1) BLANKvtk.SetNumberOfTuples(self.NumberInNet.shape[0]) BLANKvtk.SetName('blank') # Build tree out of CP list of "is a child of" # remembering that Matlab indices are 1-based and numpy/VTK 0-based print 'Building graph' dg = vtk.vtkMutableDirectedGraph() edge_id = vtk.vtkIdTypeArray() edge_id.SetName('edge_ids') for ii in range(self.cp.size): dg.AddVertex() for ii in range(self.cp.size): if self.cp[ii] > 0: # CP already zero-based dg.AddGraphEdge(self.cp[ii],ii) # Method for use with wrappers -- AddEdge() in C++ edge_id.InsertNextValue(ii) dg.GetVertexData().AddArray(NINvtk) dg.GetVertexData().AddArray(SCALESvtk) dg.GetVertexData().AddArray(vertex_id) dg.GetVertexData().SetActiveScalars('scale') dg.GetVertexData().SetActivePedigreeIds('vertex_ids') dg.GetEdgeData().AddArray(edge_id) dg.GetEdgeData().SetActivePedigreeIds('edge_ids') tree = vtk.vtkTree() tree.CheckedShallowCopy(dg) return tree else: raise IOError, "Can't get tree until data is loaded successfully"
def main(): colors = vtk.vtkNamedColors() graph = vtk.vtkMutableDirectedGraph() # Create a graph v1 = graph.AddVertex() v2 = graph.AddVertex() v3 = graph.AddVertex() graph.AddGraphEdge(v1, v2) graph.AddGraphEdge(v2, v3) # Create the color array edgeColors = vtk.vtkIntArray() edgeColors.SetNumberOfComponents(1) edgeColors.SetName('Color') lookupTable = vtk.vtkLookupTable() lookupTable.SetNumberOfTableValues(2) lookupTable.SetTableValue(0, colors.GetColor4d('Red')) lookupTable.SetTableValue(1, colors.GetColor4d('Lime')) lookupTable.Build() edgeColors.InsertNextValue(0) edgeColors.InsertNextValue(1) # Add the color array to the graph graph.GetEdgeData().AddArray(edgeColors) graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(graph) graphLayoutView.SetLayoutStrategy('Simple 2D') graphLayoutView.GetLayoutStrategy().SetEdgeWeightField('Graphs') graphLayoutView.GetLayoutStrategy().SetWeightEdges(1) graphLayoutView.SetEdgeColorArrayName('Color') graphLayoutView.SetEdgeLabelVisibility(1) graphLayoutView.ColorEdgesOn() theme = vtk.vtkViewTheme() theme.SetCellLookupTable(lookupTable) graphLayoutView.ApplyViewTheme(theme) graphLayoutView.ResetCamera() graphLayoutView.GetRenderer().GetActiveCamera().Zoom(0.8) graphLayoutView.Render() graphLayoutView.GetLayoutStrategy().SetRandomSeed(0) graphLayoutView.GetInteractor().Initialize() graphLayoutView.GetInteractor().Start()
def _init(self): g = vtk.vtkMutableDirectedGraph() v1 = g.AddVertex() v2 = g.AddVertex() g.AddGraphEdge(v1,v2) G_labels = vtk.vtkStringArray() G_labels.SetName("VLabels") G_labels.InsertNextValue("One") G_labels.InsertNextValue("Two") g.GetVertexData().AddArray(G_labels) G_labels = vtk.vtkStringArray() G_labels.SetName("VLabels") G_labels.InsertNextValue("Three") G_labels.InsertNextValue("Four") g.GetVertexData().AddArray(G_labels) return g
def _init(self): g = vtk.vtkMutableDirectedGraph() v1 = g.AddVertex() v2 = g.AddVertex() g.AddGraphEdge(v1, v2) G_labels = vtk.vtkStringArray() G_labels.SetName("VLabels") G_labels.InsertNextValue("One") G_labels.InsertNextValue("Two") g.GetVertexData().AddArray(G_labels) G_labels = vtk.vtkStringArray() G_labels.SetName("VLabels") G_labels.InsertNextValue("Three") G_labels.InsertNextValue("Four") g.GetVertexData().AddArray(G_labels) return g
def main(): graph = vtk.vtkMutableDirectedGraph() # Create a graph v1 = graph.AddVertex() v2 = graph.AddVertex() v3 = graph.AddVertex() graph.AddGraphEdge(v1, v2) graph.AddGraphEdge(v2, v3) # Create the color array edgeColors = vtk.vtkIntArray() edgeColors.SetNumberOfComponents(1) edgeColors.SetName("Color") lookupTable = vtk.vtkLookupTable() lookupTable.SetNumberOfTableValues(2) lookupTable.SetTableValue(0, 1.0, 0.0, 0.0) # red lookupTable.SetTableValue(1, 0.0, 1.0, 0.0) # green lookupTable.Build() edgeColors.InsertNextValue(0) edgeColors.InsertNextValue(1) # Add the color array to the graph graph.GetEdgeData().AddArray(edgeColors) graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(graph) graphLayoutView.SetLayoutStrategy("Simple 2D") graphLayoutView.GetLayoutStrategy().SetEdgeWeightField("Graphs") graphLayoutView.GetLayoutStrategy().SetWeightEdges(1) graphLayoutView.SetEdgeColorArrayName("Color") graphLayoutView.SetEdgeLabelVisibility(1) graphLayoutView.ColorEdgesOn() theme = vtk.vtkViewTheme() theme.SetCellLookupTable(lookupTable) graphLayoutView.ApplyViewTheme(theme) graphLayoutView.ResetCamera() graphLayoutView.Render() graphLayoutView.GetLayoutStrategy().SetRandomSeed(0) graphLayoutView.GetInteractor().Initialize() graphLayoutView.GetInteractor().Start()
def main(): g = vtk.vtkMutableDirectedGraph() v1 = g.AddVertex() v2 = g.AddVertex() g.AddGraphEdge(v1, v2) g.AddGraphEdge(v1, v2) graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(g) graphLayoutView.SetLayoutStrategy('Simple 2D') graphLayoutView.ResetCamera() graphLayoutView.Render() graphLayoutView.GetLayoutStrategy().SetRandomSeed(0) graphLayoutView.GetInteractor().Start()
def main(): colors = vtk.vtkNamedColors() g = vtk.vtkMutableDirectedGraph() latitude = vtk.vtkDoubleArray() latitude.SetName("latitude") longitude = vtk.vtkDoubleArray() longitude.SetName("longitude") for i in range(-90, 90, 10): for j in range(-180, 180, 20): g.AddVertex() latitude.InsertNextValue(i) longitude.InsertNextValue(j) g.GetVertexData().AddArray(latitude) g.GetVertexData().AddArray(longitude) assign = vtk.vtkGeoAssignCoordinates() assign.SetInputData(g) assign.SetLatitudeArrayName("latitude") assign.SetLongitudeArrayName("longitude") assign.SetGlobeRadius(1.0) assign.Update() mapper = vtk.vtkGraphMapper() mapper.SetInputConnection(assign.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() ren.AddActor(actor) iren = vtk.vtkRenderWindowInteractor() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetInteractor(iren) ren.SetBackground(colors.GetColor3d('MidnightBlue')) ren.ResetCamera() ren.GetActiveCamera().SetPosition(-1.02, -4.6, 3.45) ren.GetActiveCamera().SetViewUp(0.12, 0.78, 0.61) ren.GetActiveCamera().SetDistance(4.53) iren.Initialize() renWin.Render() iren.Start()
def main(): # colors = vtk.vtkNamedColors() g = vtk.vtkMutableDirectedGraph() # Create 3 vertices v1 = g.AddVertex() v2 = g.AddVertex() v3 = g.AddVertex() # Create a fully connected graph g.AddGraphEdge(v1, v2) g.AddGraphEdge(v2, v3) g.AddGraphEdge(v1, v3) # Create the edge weight array weights = vtk.vtkDoubleArray() weights.SetNumberOfComponents(1) weights.SetName("Weights") # Set the edge weights weights.InsertNextValue(1.0) weights.InsertNextValue(1.0) weights.InsertNextValue(2.0) # Add the edge weight array to the graph g.GetEdgeData().AddArray(weights) graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(g) graphLayoutView.SetLayoutStrategy("Simple 2D") graphLayoutView.GetLayoutStrategy().SetEdgeWeightField("Weights") graphLayoutView.GetLayoutStrategy().SetWeightEdges(1) graphLayoutView.SetEdgeLabelArrayName("Weights") graphLayoutView.SetEdgeLabelVisibility(1) graphLayoutView.ResetCamera() graphLayoutView.Render() graphLayoutView.GetLayoutStrategy().SetRandomSeed(0) graphLayoutView.GetInteractor().Start()
def __init__(self, name=None): """Constructor @type name: str @param name: Graph name, defaults to None """ self._name = name self._directed = False self._vertex_dict = {} self._edge_dict = {} self._weights = vtk.vtkDoubleArray() self._weights.SetName('Weights') self._weights.SetNumberOfComponents(1) self._labels = vtk.vtkStringArray() self._labels.SetNumberOfComponents(1) self._labels.SetName('labels') self._graph = vtk.vtkMutableDirectedGraph() self._color_picker = vtk.vtkColorSeries() self._color_dict = {} self._colors = [] self._vertex_types = 1
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
vertex_id.SetName('vertex_ids') for ii in range(gW['PointsInNet'][0,0].shape[1]): PIN.append(gW['PointsInNet'][0,0][0,ii][0]-1) # 0-based indices NIN.append(gW['PointsInNet'][0,0][0,ii][0].size) vertex_id.InsertNextValue(ii) NINarray = N.array(NIN) NINvtk = VN.numpy_to_vtk(NINarray) NINvtk.SetName('num_in_vertex') SCALESvtk = VN.numpy_to_vtk(gW['Scales'][0,0][0]) SCALESvtk.SetName('scale') # Build tree out of CP list of "is a child of" # remembering that Matlab indices are 1-based and numpy/VTK 0-based print 'Building graph' dg = vtk.vtkMutableDirectedGraph() edge_id = vtk.vtkIdTypeArray() edge_id.SetName('edge_ids') for ii in range(CP.size): dg.AddVertex() for ii in range(CP.size): tmp = CP[ii]-1 # 0-based indices if tmp > 0: dg.AddGraphEdge(tmp,ii) # Method for use with wrappers -- AddEdge() in C++ edge_id.InsertNextValue(ii) dg.GetVertexData().AddArray(NINvtk) dg.GetVertexData().AddArray(SCALESvtk) dg.GetVertexData().AddArray(vertex_id) dg.GetVertexData().SetActiveScalars('scale') dg.GetVertexData().SetActivePedigreeIds('vertex_ids')
It creates nodes which lose their actual value since nodes in vtkGraph are referenced strictly by their index. These nodes do retain metadata in the same way edges do (see below). It creates edges which maintain the proper association and any metadata, the caveat is that all edges are given all metadata attributes with default values. So if an edge has an integer 'distance' attribute, and another does not - the non-distanced edge will have a distance of 0. This follows suit for all of pythons defaults, bool(), str(), float(), etc. As such it requires that all keys have the same type. """ if input.is_directed(): output = vtk.vtkMutableDirectedGraph() else: output = vtk.vtkMutableUndirectedGraph() nodes = input.nodes(data=True) edges = input.edges(data=True) edge_field_types = {} node_field_types = {} # Find out fields and types for (_, data) in nodes: for key in data.keys(): data_type = type(data[key]) # Assert that every node which has key has the same type if key in node_field_types and data_type != node_field_types[key]:
return vertexid def parseClassTree(classtree, tree, names): class_to_vertex_map = dict() for (parent, child) in classtree: parentid = addToTree(parent, class_to_vertex_map, tree, names) childid = addToTree(child, class_to_vertex_map, tree, names) tree.AddGraphEdge(parentid, childid) # The tree that will hold vtk class hierarchy builder = vtk.vtkMutableDirectedGraph() names = vtk.vtkStringArray() names.SetName("name") # Allocate 100 tuples to start with. I picked this number # out of air. names.SetNumberOfTuples(100) # load vtk class information reader = csv.reader(open(VTK_DATA_ROOT + "/Data/Infovis/classes.csv", 'r')) classes = [] for row in reader: classes.append(row)
import vtk g = vtk.vtkMutableDirectedGraph() # Create 3 vertices v1 = g.AddVertex() v2 = g.AddVertex() v3 = g.AddVertex() # Create a fully connected graph g.AddGraphEdge(v1, v2) g.AddGraphEdge(v2, v3) g.AddGraphEdge(v1, v3) # Create the edge weight array weights = vtk.vtkDoubleArray() weights.SetNumberOfComponents(1) weights.SetName("Weights") # Set the edge weights weights.InsertNextValue(1.0) weights.InsertNextValue(1.0) weights.InsertNextValue(2.0) # Add the edge weight array to the graph g.GetEdgeData().AddArray(weights) graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(g) graphLayoutView.SetLayoutStrategy("Simple 2D") graphLayoutView.GetLayoutStrategy().SetEdgeWeightField("Weights")
def main(): user_file = "./data/M2/Flitter_Names.txt" friend_file = "./data/M2/Links_Table.txt" community_file = "./data/M2/People_Cities.txt" ## Read user_file and friend_file with numpy names = pd.read_csv(user_file, delimiter='\t') friends = pd.read_csv(friend_file, delimiter='\t') communities = pd.read_csv(community_file, delimiter='\t') ## Add the size of each users network to the pandas dataframe ## and the city of each user to the pandas dataframe size = [] for i in range(0, len(names)): size.append(friends[friends.ID2 == i].ID2.size + friends[friends.ID1 == i].ID1.size) names.loc[:, 'followers'] = size names.loc[:, 'city'] = communities.City.tolist() ## First round of checks, do the sizes of their networks make sense? employees = names[(names['followers'] >= 37) & (names['followers'] <= 43)] handlers = names[(names['followers'] >= 28) & (names['followers'] <= 42)] middlemen = names[(names['followers'] >= 4) & (names['followers'] <= 5)] leaders = names[(names['followers'] >= 125)] middlemen = check(middlemen, leaders, friends, 1, "ge") potentials = leaders potentials = update_suspects(potentials, handlers, employees, middlemen, leaders) allgraph = vtk.vtkMutableDirectedGraph() allgraph = makegraph(potentials, friends, "city") ## Second round of check, do they havethe appropriate links? handlers = check(handlers, handlers, friends, 2, "le") employees = check(employees, handlers, friends, 3, "eq") middlemen = check(middlemen, handlers, friends, 2, "ge") ## Finally we remove all extras based on our employees handlers = check(handlers, employees, friends, 1, "eq") middlemen = check(middlemen, handlers, friends, 1, "ge") leaders = check(leaders, middlemen, friends, 1, "ge") potentials = update_suspects(potentials, handlers, employees, middlemen, leaders) potentialgraph = vtk.vtkMutableDirectedGraph() potentialgraph = makesolution(potentials, friends, "criminal") ### VTK pipeline stuff strategy = vtk.vtkAttributeClustering2DLayoutStrategy() strategy.SetVertexAttribute("city") strategy.SetGraph(allgraph) graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(allgraph) graphLayoutView.GetRenderWindow().SetSize(1024, 1024) graphLayoutView.SetLayoutStrategy(strategy) graphLayoutView.SetVertexLabelArrayName("city") graphLayoutView.SetVertexLabelVisibility(1) graphLayoutView.ResetCamera() ## Render Just potential employees, handlers, middlemen, and leaders strategy2 = vtk.vtkAttributeClustering2DLayoutStrategy() strategy2.SetVertexAttribute("criminal") strategy2.SetGraph(potentialgraph) graphLayoutView2 = vtk.vtkGraphLayoutView() graphLayoutView2.AddRepresentationFromInput(potentialgraph) graphLayoutView2.GetRenderWindow().SetSize(1024, 1024) graphLayoutView2.SetLayoutStrategy(strategy2) graphLayoutView2.SetVertexLabelArrayName("username") graphLayoutView2.SetVertexLabelVisibility(1) graphLayoutView2.ResetCamera() ### implementing kayleigh's fancy linking code annotationlink = vtk.vtkAnnotationLink() graphLayoutView.GetRepresentation(0).SetAnnotationLink(annotationlink) graphLayoutView2.GetRepresentation(0).SetAnnotationLink(annotationlink) updater = vtk.vtkViewUpdater() updater.AddAnnotationLink(annotationlink) updater.AddView(graphLayoutView) updater.AddView(graphLayoutView2) graphLayoutView.Render() graphLayoutView.GetInteractor().Start() graphLayoutView2.Render() graphLayoutView2.GetInteractor().Start()
def displayTree(self): print ("displayTree") tree = self.segmentor.getContourTree() self.graphWidget.viewer.updateCornerAnnotation("featureAnnotation", "Features: {}".format(len(tree)/2)) graph = vtk.vtkMutableDirectedGraph() X = vtk.vtkDoubleArray() X.SetNumberOfComponents(1) X.SetName("X") Y = vtk.vtkDoubleArray() Y.SetNumberOfComponents(1) Y.SetName("Y") weights = vtk.vtkDoubleArray() weights.SetNumberOfComponents(1) weights.SetName("Weights") vertex_id = vtk.vtkDoubleArray() vertex_id.SetNumberOfComponents(1) vertex_id.SetName("VertexID") print("creating graph") # Adding to graph now N = int(len(tree) / 2) # normalise the values in Y # transpose tree treeT = list(zip(*tree)) maxY = max(treeT[1]) minY = min(treeT[1]) deltaY = maxY - minY print(minY, maxY, deltaY) maxX = max(treeT[0]) minX = min(treeT[0]) deltaX = maxX - minX print(minX, maxX, deltaX) for i in range(N): even = 2 * i odd = even + 1 if odd >= len(tree): raise ValueError('out of bounds') v = [tree[2 * i], tree[2 * i + 1]] # print(i, even, odd, "Adding",v[0],v[1]) v1 = graph.AddVertex() v2 = graph.AddVertex() graph.AddEdge(v1, v2) # Insert XY as a % of max range X.InsertNextValue((v[0][0] - minX)/deltaX ) X.InsertNextValue((v[1][0] - minX) / deltaX ) Y.InsertNextValue((v[0][1] - minY)/ deltaY) Y.InsertNextValue((v[1][1] - minY)/ deltaY ) weights.InsertNextValue(1.) vertex_id.InsertNextValue(2*i) vertex_id.InsertNextValue(2*i+1) print("Finished") # Execution reaches here, error seems to be in cleanup upon closing graph.GetVertexData().AddArray(X) graph.GetVertexData().AddArray(Y) graph.GetEdgeData().AddArray(weights) graph.GetVertexData().AddArray(vertex_id) print("Added Data") layoutStrategy = vtk.vtkAssignCoordinatesLayoutStrategy() layoutStrategy.SetYCoordArrayName('Y') layoutStrategy.SetXCoordArrayName('X') self.graphWidget.viewer.update(graph)
def openFile(self, progress_callback=None, **kwargs): """ Open file(s) based on results from QFileDialog :param (function) progress_callback: Callback funtion to emit progress percentage. """ if 'filename' not in kwargs.keys(): fn = self.fn else: fn = ([kwargs['filename']],) # If the user has pressed cancel, the first element of the tuple will be empty. # Quit the method cleanly if not fn[0]: return # Single file selection if len(fn[0]) == 1: file = fn[0][0] if progress_callback: progress_callback.emit(30) reader = vtk.vtkMetaImageReader() reader.AddObserver("ErrorEvent", self.e) reader.SetFileName(file) reader.Update() if progress_callback: progress_callback.emit(90) self.mainwindow.setStatusTip('File Read: {}'.format(reader.GetOutput().GetExtent())) # Multiple TIFF files selected else: # Make sure that the files are sorted 0 - end filenames = natsorted(fn[0]) increment = 30.0 / len(filenames) # Basic test for tiff images for n,file in enumerate(filenames,1): ftype = imghdr.what(file) if ftype != 'tiff': # A non-TIFF file has been loaded, present error message and exit method self.e('','','Problem reading file: {}'.format(file)) raise ReadError("File read error!") if progress_callback: progress_callback.emit(int(n * increment)) # Have passed basic test, can attempt to load numpy_image = Converter.pureTiff2Numpy(filenames=filenames, bounds=(256,256,256), progress_callback=progress_callback) reader = Converter.numpy2vtkImporter(numpy_image) reader.Update() if self.e.ErrorOccurred(): raise ReadError() else: self.viewerWidget.viewer.setInput3DData(reader.GetOutput()) if progress_callback: progress_callback.emit(91) self.mainwindow.setStatusTip('display 2D') if progress_callback: progress_callback.emit(92) self.viewer3DWidget.viewer.setInput3DData(reader.GetOutput()) if progress_callback: progress_callback.emit(93) self.graph_numpy_input_data = Converter.vtk2numpy(reader.GetOutput(), transpose=[2,1,0]) if progress_callback: progress_callback.emit(94) self.mainwindow.setStatusTip('convert to numpy') self.mainwindow.setStatusTip('Ready') if progress_callback: progress_callback.emit(95) self.spacing = reader.GetOutput().GetSpacing() if progress_callback: progress_callback.emit(96) self.origin = reader.GetOutput().GetOrigin() if progress_callback: progress_callback.emit(97) ### After successfully opening file, reset the interface ### # Reset linked state self.linkViewers(force_linked=True) # Reset graph if drawn self.graphWidget.viewer.update(vtk.vtkMutableDirectedGraph()) # Reset graph parameter panel if self.hasDockableWindow: for element in self.treeWidgetInitialElements: element.setEnabled(True) for element in self.treeWidgetUpdateElements: element.setEnabled(False) print ("finished openFile")
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
#!/usr/bin/env python ''' Online example from : http://www.vtk.org/Wiki/VTK/Examples/Python/Graphs/EdgeWeights Going to heavly comment out the steps to understand how to edit this into what we need to make other graphs ''' import vtk # Manditory on all python VTK g = vtk.vtkMutableDirectedGraph() # Sets up empty data structure # Create 3 vertices # Adding nodes to your graph v1 = g.AddVertex() v2 = g.AddVertex() v3 = g.AddVertex() # Create a fully connected graph # Adding in the edges between them g.AddGraphEdge(v1, v2) g.AddGraphEdge(v2, v3) g.AddGraphEdge(v1, v3) # Create the edge weight array weights = vtk.vtkDoubleArray() # This is VTK version of an array of data, # in this case weights weights.SetNumberOfComponents(1) # Since we are just doing weights it 1 dimensional weights.SetName("Weights") # Creates an name to recover later with