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(): colors = vtk.vtkNamedColors() g = vtk.vtkMutableUndirectedGraph() v1 = g.AddVertex() v2 = g.AddVertex() g.AddEdge(v1, v2) g.AddEdge(v1, v2) scales = vtk.vtkFloatArray() scales.SetNumberOfComponents(1) scales.SetName('Scales') scales.InsertNextValue(2.0) scales.InsertNextValue(5.0) # Add the scale array to the graph g.GetVertexData().AddArray(scales) # Create the color array vertexColors = vtk.vtkIntArray() vertexColors.SetNumberOfComponents(1) vertexColors.SetName('Color') lookupTable = vtk.vtkLookupTable() lookupTable.SetNumberOfTableValues(2) lookupTable.SetTableValue(0, colors.GetColor4d('Yellow')) lookupTable.SetTableValue(1, colors.GetColor4d('Lime')) lookupTable.Build() vertexColors.InsertNextValue(0) vertexColors.InsertNextValue(1) # Add the color array to the graph g.GetVertexData().AddArray(vertexColors) theme = vtk.vtkViewTheme() theme.SetPointLookupTable(lookupTable) layoutView = vtk.vtkGraphLayoutView() layoutView.AddRepresentationFromInput(g) layoutView.ApplyViewTheme(theme) layoutView.ScaledGlyphsOn() layoutView.SetScalingArrayName('Scales') layoutView.SetVertexColorArrayName('Color') layoutView.ColorVerticesOn() rGraph = vtk.vtkRenderedGraphRepresentation() gGlyph = vtk.vtkGraphToGlyphs() rGraph.SafeDownCast(layoutView.GetRepresentation()).SetGlyphType(gGlyph.CIRCLE) layoutView.ResetCamera() layoutView.Render() layoutView.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 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 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 __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.WordleView = vtkvtg.vtkQtWordleDebugView() # Set widget for the wordle view self.ui.centralWidget.layout().addWidget(self.WordleView.GetWidget()) data_dir = '/Users/emonson/Data/Fodava/EMoGWDataSets/' data_file = data_dir + 'sciNews_20110216.mat' print 'Trying to load data set from .mat file...' try: MatInput = scipy.io.loadmat(data_file, struct_as_record=True, chars_as_strings=True) except: raise IOError, "Can't load supplied matlab file" self.mat_terms = MatInput['terms'].T[0] self.WavBases = [] # Wavelet bases self.Centers = [] # Center of each node # NodeWavCoeffs = [] # NodeScalCoeffs = [] for ii in range(MatInput['PointsInNet'].shape[1]): self.WavBases.append(N.mat(MatInput['WavBases'][0,ii])) # matrix self.Centers.append(N.mat(MatInput['Centers'][0,ii][0])) # matrix terms = vtk.vtkStringArray() terms.SetName('dictionary') terms.SetNumberOfComponents(1) for term in self.mat_terms: terms.InsertNextValue(term[0]) self.basis_idx = 0 coeffs = VN.numpy_to_vtk(self.WavBases[self.basis_idx][::-1,0]*100, deep=True) coeffs.SetName('coefficient') c_sign = VN.numpy_to_vtk(N.sign(self.WavBases[self.basis_idx][::-1,0]), deep=True) c_sign.SetName('sign') # Create a table with some points in it... self.table = vtk.vtkTable() self.table.AddColumn(terms) self.table.AddColumn(coeffs) self.table.AddColumn(c_sign) vt = vtk.vtkViewTheme() lut = vtk.vtkLookupTable() lut.SetHueRange(0, 0.66) lut.SetValueRange(0.7, 0.7) lut.SetSaturationRange(1, 1) lut.Build() # Set value for no color by array vt.SetPointColor(0,0,0) # Set LUT for color by array vt.SetPointLookupTable(lut) # ViewTheme Background color is black by default vt.SetBackgroundColor(1,1,1) self.WordleView.AddRepresentationFromInput(self.table) self.WordleView.SetFieldType(vtkvtg.vtkQtWordleView.ROW_DATA) self.WordleView.SetColorByArray(True) self.WordleView.SetColorArrayName('sign') self.WordleView.SetTermsArrayName('dictionary') self.WordleView.SetSizeArrayName('coefficient') self.WordleView.ApplyViewTheme(vt) self.WordleView.SetMaxNumberOfWords(150); self.WordleView.SetFontFamily("Rockwell") self.WordleView.SetFontStyle(vtkvtg.vtkQtWordleView.StyleNormal) self.WordleView.SetFontWeight(99) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HORIZONTAL) self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_HORIZONTAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HALF_AND_HALF) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_VERTICAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.VERTICAL) self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.CIRCULAR_PATH) # self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.SQUARE_PATH) QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.fileExit) # Do first update before changing to debug mode... self.WordleView.Update() self.WordleView.ZoomToBounds() # while(True): # self.table.Modified() # self.WordleView.Update() # DEBUG self.WordleView.SetWatchLayout(True) self.WordleView.SetWatchCollision(True) self.WordleView.SetWatchQuadTree(True) self.WordleView.SetWatchDelay(50000)
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.WordleView = vtkvtg.vtkQtWordleView() # Set widget for the wordle view self.ui.centralWidget.layout().addWidget(self.WordleView.GetWidget()) term_list = [ "straw", "gold", "name", "miller", "manikin", "daughter", "little", "queen", "man", "came", "girl", "give", "spin", "full", "whirr", "spun", "night", "one", "child", "king", "room", "answered", "morning", "names", "took", "began", "thought", "time", "find", "world", "day", "leg", "whole", "another", "three", "rumpelstiltskin", "knew", "left", "help", "still", "crying", "gave", "good", "round", "wheel", "second", "opened", "messenger", "ever", "told", "quite", "alone", "mistress", "larger", "became", "first", "brought", "put", "ring", "devil", "next", "house", "taken", "life", "door", "fire", "reel", "glad", "must", "beautiful", "heard", "promised", "saw", "perhaps", "also", "poor", "shall", "third", "wife", "necklace", "bring", "daybreak", "earth", "hopped", "inquiries", "cried", "dearer", "front", "far", "bid", "early", "every", "hands", "foot", "course", "always", "cry", "become", "conrad", "art", "hare", "hard", "back", "alive", "die", "curious", "bake", "even", "appear", "fox", "enough", "finger", "harry", "caspar", "greedy", "found", "country", "days", "asked", "already", "afterwards", "burning", "imagine", "delighted", "frightened", "appeared", "idea", "clever", "else", "alas", "astonished", "grew", "happened", "heart", "deep", "high", "evening", "anger", "commanded", "happen", "beyond", "end", "able", "forest", "jumping", "brew", "important", "balthazar", "inquire", "glittering" ] size_list = [ 12.0, 10.0, 10.0, 9.0, 9.0, 9.0, 9.0, 8.0, 8.0, 8.0, 7.0, 7.0, 6.0, 6.0, 6.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ] terms = vtk.vtkStringArray() terms.SetName('dictionary') terms.SetNumberOfComponents(1) for term in term_list: terms.InsertNextValue(term) coeffs = vtk.vtkDoubleArray() coeffs.SetName('coefficient') coeffs.SetNumberOfComponents(1) for size in size_list: coeffs.InsertNextValue(size) # Create a table with some points in it... self.table = vtk.vtkTable() self.table.AddColumn(terms) self.table.AddColumn(coeffs) self.vt = vtk.vtkViewTheme() lut = vtk.vtkLookupTable() lut.SetHueRange(0,0) lut.SetValueRange(0,1) lut.SetSaturationRange(1,1) lut.Build() # Set value for no color by array self.vt.SetPointColor(0,0,0) # Set LUT for color by array self.vt.SetPointLookupTable(lut) # ViewTheme Background color is black by default self.vt.SetBackgroundColor(1,1,1) self.vt2 = vtk.vtkViewTheme() lut2 = vtk.vtkLookupTable() lut2.SetHueRange(0, 0.66) lut2.SetValueRange(0.7, 0.7) lut2.SetSaturationRange(1, 1) lut2.Build() # Set value for no color by array self.vt2.SetPointColor(0,0,0) # Set LUT for color by array self.vt2.SetPointLookupTable(lut2) # ViewTheme Background color is black by default self.vt2.SetBackgroundColor(1,1,1) self.WordleView.AddRepresentationFromInput(self.table) self.WordleView.SetFieldType(vtkvtg.vtkQtWordleView.ROW_DATA) self.WordleView.SetColorByArray(True) self.WordleView.SetColorArrayName('coefficient') self.WordleView.SetTermsArrayName('dictionary') self.WordleView.SetSizeArrayName('coefficient') self.WordleView.SetOutputImageDataDimensions(200, 200) self.WordleView.ApplyViewTheme(self.vt) self.WordleView.SetMaxNumberOfWords(150); self.WordleView.SetFontFamily("Rockwell") self.WordleView.SetFontStyle(vtkvtg.vtkQtWordleView.StyleNormal) self.WordleView.SetFontWeight(99) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HORIZONTAL) self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_HORIZONTAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HALF_AND_HALF) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_VERTICAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.VERTICAL) self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.CIRCULAR_PATH) # self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.SQUARE_PATH) self.WordleView.Update() self.WordleView.ZoomToBounds() self.color_by_array = True self.font_flag = True QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.fileExit)
def DisplayGraph(graph): ''' Display the graph. ''' theme = vtk.vtkViewTheme() theme.SetBackgroundColor(0, 0, .1) theme.SetBackgroundColor2(0, 0, .5) # Layout the graph # Pick a strategy you like. # strategy = vtk.vtkCircularLayoutStrategy() strategy = vtk.vtkSimple2DLayoutStrategy() # strategy = vtk.vtkRandomLayoutStrategy() layout = vtk.vtkGraphLayout() layout.SetLayoutStrategy(strategy) layout.SetInputData(graph) view = vtk.vtkGraphLayoutView() view.AddRepresentationFromInputConnection(layout.GetOutputPort()) # Tell the view to use the vertex layout we provide. view.SetLayoutStrategyToPassThrough() view.SetEdgeLabelVisibility(True) view.SetVertexLabelArrayName("Labels") view.SetVertexLabelVisibility(True) view.ApplyViewTheme(theme) # Manually create an actor containing the glyphed arrows. # Get the edge geometry edgeGeom = vtk.vtkGraphToPolyData() edgeGeom.SetInputConnection(layout.GetOutputPort()) edgeGeom.EdgeGlyphOutputOn() # Set the position (0: edge start, 1: edge end) where # the edge arrows should go. # edgeGeom.SetEdgeGlyphPosition(0.8) edgeGeom.SetEdgeGlyphPosition(0.85) # Make a simple edge arrow for glyphing. # arrowSource = vtk.vtkGlyphSource2D() # arrowSource.SetGlyphTypeToEdgeArrow() # arrowSource.SetScale(0.075) # Or use a cone. coneSource = vtk.vtkConeSource() coneSource.SetRadius(0.025) coneSource.SetHeight(0.1) coneSource.SetResolution(12) # Use Glyph3D to repeat the glyph on all edges. arrowGlyph = vtk.vtkGlyph3D() arrowGlyph.SetInputConnection(0, edgeGeom.GetOutputPort(1)) # arrowGlyph.SetInputConnection(1, arrowSource.GetOutputPort()) arrowGlyph.SetInputConnection(1, coneSource.GetOutputPort()) # Add the edge arrow actor to the view. arrowMapper = vtk.vtkPolyDataMapper() arrowMapper.SetInputConnection(arrowGlyph.GetOutputPort()) arrowActor = vtk.vtkActor() arrowActor.SetMapper(arrowMapper) view.GetRenderer().AddActor(arrowActor) view.ResetCamera() view.Render() view.SetInteractionModeTo3D() view.GetInteractor().Initialize() view.GetInteractor().Start()
terms.InsertNextValue(term[0]) basis_idx = 0 coeffs = VN.numpy_to_vtk(WavBases[basis_idx][::-1, 0] * 100, deep=True) coeffs.SetName("coefficient") c_sign = VN.numpy_to_vtk(N.sign(WavBases[basis_idx][::-1, 0]), deep=True) c_sign.SetName("sign") # Create a table with some points in it... table = vtk.vtkTable() table.AddColumn(terms) table.AddColumn(coeffs) table.AddColumn(c_sign) vt = vtk.vtkViewTheme() lut = vtk.vtkLookupTable() lut.SetHueRange(0, 0.66) lut.SetValueRange(0.7, 0.7) lut.SetSaturationRange(1, 1) lut.Build() # Set value for no color by array vt.SetPointColor(0, 0, 0) # Set LUT for color by array vt.SetPointLookupTable(lut) # ViewTheme Background color is black by default vt.SetBackgroundColor(1, 1, 1) WordleView.AddRepresentationFromInput(table) WordleView.SetFieldType(vtkvtg.vtkQtWordleView.ROW_DATA) WordleView.SetColorByArray(True)
def LoadData(self): """Routine that does the actual data loading and some format conversion. If a valid file name is given in the constructor, then this routine is called automatically. If you haven't given a file name in the constructor then you'll have to call SetFileName() before calling this.""" # ---------- # Load and construct whole graph and multi-resolution data from Matlab structure print 'Trying to load data set from .mat file... ', self.data_file if len(self.data_file) == 0: print "No data file name error!!!" raise IOError, "No data file name: Use SetFileName('file.mat') before LoadData()" print 'Trying to really load now...' try: MatInput = scipy.io.loadmat(self.data_file, struct_as_record=True, chars_as_strings=True) except: print 'loadmat crapping out for some reason...' raise IOError, "Can't load supplied matlab file" # return # Get variables out of Matlab structure print 'Transferring variables from Matlab structures' # Now using single structure, S, to save important variables from Matlab S = None if MatInput.has_key('S'): S = MatInput['S'] else: raise IOError, "Matlab file doesn't have S structure. Must be from old gen file..." # NOTE: Accessing data from S to a convenient numpy array / value # 2D arrays: xx = S['xx'].flat[0] # 1D arrays: xx = S['xx'].flat[0].flatten() # Scalars: xx = S['xx'].flat[0].flatten()[0] def s_2Darray(name): return S[name].flat[0] def s_1Darray(name): return S[name].flat[0].flatten() def s_listOf1Darrays(name): tmp = S[name].flat[0].flatten().tolist() if tmp[0].shape[1] == 1: return [xx.T[0] for xx in tmp] else: return [xx[0] for xx in tmp] def s_listOf2Darrays(name): return S[name].flat[0].flatten().tolist() def s_listOfStrings(name): return [xx[0] for xx in S[name].flat[0].flatten().tolist()] def s_listOf1DarraysOffset(name): tmp = S[name].flat[0].flatten().tolist() if tmp[0].shape[1] == 1: return [xx.T[0]-1 for xx in tmp] else: return [xx[0]-1 for xx in tmp] def s_scalar(name): return S[name].flat[0].flatten()[0] def s_logical(name): return (S[name].flat[0].flatten()[0] != 0) # Flags self.isImageData = s_logical('isImageData') self.isTextData = s_logical('isTextData') self.isCompressed = s_logical('isCompressed') self.hasLabels = s_logical('hasLabels') self.hasLabelMeanings = s_logical('hasLabelMeanings') self.hasLabelSetNames = s_logical('hasLabelSetNames') self.hasDocTitles = s_logical('hasDocTitles') self.hasDocFileNames = s_logical('hasDocFileNames') self.X = N.mat(s_2Darray('X')) # Test if original images are downsampled in this data if self.isCompressed: self.V = N.mat(s_2Darray('V')) self.cm = N.mat(s_1Darray('cm')) # not sure if should be matrix or array... # Various plain matrices # NOTE: Have to be careful of anything that can have a 0 value in Matlab # because it might be naturally imported as an unsigned int, and then # when you subtract 1 from it you don't get a negative number as you'd expect self.cp = (s_1Darray('cp').astype('int16') - 1) # change here to zero-based indexing self.IniLabels = (s_1Darray('IniLabels') - 1) # change here to zero-based indexing self.NumberInNet = s_1Darray('NumberInNet') self.Scales = (s_1Darray('Scales') - 1) # zero-based self.IsALeaf = s_1Darray('IsALeaf').astype('bool') self.LeafNodes = (s_1Darray('LeafNodes') - 1) # zero-based # LeafNodesImap maps LeafNode entries, which are node indices, to indices of # arrays like CelWavCoeffs and CelScalCoeffs (in the non-scale, first dimension) self.LeafNodesImap = (s_1Darray('LeafNodesImap').astype('int16') - 1) # zero-based self.EigenVecs = s_2Darray('EigenVecs') self.EigenVals = s_1Darray('EigenVals') self.CelWavCoeffs = s_2Darray('CelWavCoeffs') self.CelScalCoeffs = s_2Darray('CelScalCoeffs') if self.isImageData: self.imR = s_scalar('imR') self.imC = s_scalar('imC') else: # Not sure whether will set this in Matlab or here... self.imR = 200 self.imC = 200 # Load in category labels, but map them to sequential integers starting at 0 if self.hasLabels: labels_array = s_2Darray('Labels') # ncats x npoints 2d array self.cat_labels = N.zeros_like(labels_array) for ii in range(labels_array.shape[0]): cl_unique = set(labels_array[ii,:]) cl_map = {} for jj,vv in enumerate(cl_unique): cl_map[vv] = jj self.cat_labels[ii,:] = N.array([cl_map[vv] for vv in labels_array[ii,:]]) if self.hasLabels: self.label_names = [] # Check whether there are labels names and if there are the right number if self.hasLabelSetNames: names_array = s_1Darray('LabelSetNames') if names_array.size == self.cat_labels.shape[0]: for name_ar in names_array: self.label_names.append(name_ar[0] + '_ids') # Else generate fake names else: for ii in range(self.cat_labels.shape[0]): self.label_names.append('label_' + str(ii) + '_ids') if self.hasLabelMeanings: self.LabelMeanings = s_listOfStrings('LabelMeanings') # Need the max number of dims at each scale to fill in zeros for pcoords plot # Create copies for both wavelet coeffs and scaling functions since these often # have different dimensionalities self.WavMaxDim = N.zeros(self.CelWavCoeffs.shape[1],dtype='int') for row in range(self.CelWavCoeffs.shape[0]): for col in range(self.CelWavCoeffs.shape[1]): if self.WavMaxDim[col] < self.CelWavCoeffs[row,col].shape[1]: self.WavMaxDim[col] = self.CelWavCoeffs[row,col].shape[1] self.ScalMaxDim = N.zeros(self.CelScalCoeffs.shape[1],dtype='int') for row in range(self.CelScalCoeffs.shape[0]): for col in range(self.CelScalCoeffs.shape[1]): if self.ScalMaxDim[col] < self.CelScalCoeffs[row,col].shape[1]: self.ScalMaxDim[col] = self.CelScalCoeffs[row,col].shape[1] # Gather helpful statistics to be used by other classes print 'Calulating extrema of coefficients' self.WavCoeffMax = -1e200 self.WavCoeffMin = 1e200 self.ScalCoeffMax = -1e200 self.ScalCoeffMin = 1e200 for ii in range(self.CelWavCoeffs.shape[0]): for jj in range(self.CelWavCoeffs.shape[1]): if (self.CelWavCoeffs[ii,jj].size > 0): wmax = N.amax(self.CelWavCoeffs[ii,jj]) wmin = N.amin(self.CelWavCoeffs[ii,jj]) if (wmax > self.WavCoeffMax): self.WavCoeffMax = wmax if (wmin < self.WavCoeffMin): self.WavCoeffMin = wmin if (self.CelScalCoeffs[ii,jj].size > 0): smax = N.amax(self.CelScalCoeffs[ii,jj]) smin = N.amin(self.CelScalCoeffs[ii,jj]) if (smax > self.ScalCoeffMax): self.ScalCoeffMax = smax if (smin < self.ScalCoeffMin): self.ScalCoeffMin = smin # NumPts = Number of data points (here number of individual images) self.NumPts = self.IniLabels.shape[0] self.AmbientDimension = s_scalar('AmbientDimension') # used to call this D # Converting cell arrays to lists of numpy arrays self.PointsInNet = s_listOf1DarraysOffset('PointsInNet') # Points In Net, 0-based indices self.ScalFuns = s_listOf2Darrays('ScalFuns') # Scaling functions self.WavBases = s_listOf2Darrays('WavBases') # Wavelet bases self.Centers = s_listOf1Darrays('Centers') # Center of each node # Creating a storage space for ordering of leaf nodes in icicle view with # default values of ordering according to Matlab-saved LeafNodes ice_leaf_ids = self.LeafNodes ice_leaf_xmins = N.arange(ice_leaf_ids.size) ice_ids_mapped = self.LeafNodesImap[ice_leaf_ids] self.mapped_leaf_pos = N.zeros_like(ice_leaf_xmins) self.mapped_leaf_pos[ice_ids_mapped] = ice_leaf_xmins # Flag to set whether generic routines should return Wavelet or Scaling Function # coefficients / images -- "wav" or "scal" self.SetCoeffSource("wavelet") # -- Wordle -- # Flag to indicate whether images should be generated directly # or by passing terms through QtWordleView self.WordleImages = False self.qinit = None self.WordleView = None self.WordleTable = None self.Terms = None if self.isTextData: print "Starting text data area" self.WordleImages = True mat_terms = s_listOfStrings('Terms') self.Terms = vtk.vtkStringArray() self.Terms.SetName('dictionary') self.Terms.SetNumberOfComponents(1) for term in mat_terms: self.Terms.InsertNextValue(term) if self.hasDocTitles: self.DocTitles = s_listOfStrings('DocTitles') print "Creating initial table" # Init Table and put in some sample data that will be replaced later basis_idx = 0 coeffs = VN.numpy_to_vtk(self.WavBases[basis_idx][:,0]*100, deep=True) coeffs.SetName('coefficient') c_sign = VN.numpy_to_vtk(N.sign(self.WavBases[basis_idx][:,0]), deep=True) c_sign.SetName('sign') # Create a table with some points in it... self.WordleTable = vtk.vtkTable() self.WordleTable.AddColumn(self.Terms) self.WordleTable.AddColumn(coeffs) self.WordleTable.AddColumn(c_sign) # self.qinit = vtk.vtkQtInitialization() self.WordleView = vtkvtg.vtkQtWordleView() vt = vtk.vtkViewTheme() lut = self.GetDivergingLUT() # Set value for no color by array vt.SetPointColor(0,0,0) # Set LUT for color by array vt.SetPointLookupTable(lut) # ViewTheme Background color is black by default vt.SetBackgroundColor(1,1,1) self.WordleView.SetFieldType(vtkvtg.vtkQtWordleView.ROW_DATA) self.WordleView.AddRepresentationFromInput(self.WordleTable) self.WordleView.SetColorByArray(True) self.WordleView.ApplyViewTheme(vt) self.WordleView.SetColorArrayName('sign') self.WordleView.SetTermsArrayName('dictionary') self.WordleView.SetSizeArrayName('coefficient') self.WordleView.SetOutputImageDataDimensions(200, 200) self.WordleView.SetMaxNumberOfWords(50); self.WordleView.SetFontFamily("Rockwell") self.WordleView.SetFontStyle(vtkvtg.vtkQtWordleView.StyleNormal) self.WordleView.SetFontWeight(99) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HORIZONTAL) self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_HORIZONTAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HALF_AND_HALF) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_VERTICAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.VERTICAL) # self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.CIRCULAR_PATH) self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.SQUARE_PATH) self.data_loaded = True
outlineActor.PickableOff() outlineActor.GetProperty().SetRepresentationToWireframe() outlineActor.GetProperty().SetPointSize(vertActor.GetProperty().GetPointSize()+2) outlineActor.GetProperty().SetColor(theme.GetOutlineColor()) outlineActor.GetProperty().SetOpacity(theme.GetPointOpacity()) outlineActor.SetPosition(0, 0, -0.001) # ---------- # Current ExtIdxs MS Graph Node nodeGraph = vtk.vtkMutableUndirectedGraph() nodeGraph.AddVertex() currIdx = ExtIdxs[basisNum]-1 # Matlab 1-based and Numpy 0-based indexing currPt = VN.numpy_to_vtk(ptsMatrix[currIdx,:]) nodeGraph.GetPoints().SetData(currPt) ntheme = vtk.vtkViewTheme() ntheme.SetPointSize(13) ntheme.SetOutlineColor(0.2, 0.2, 0.2) ntheme.SetPointColor(0.1, 0.1, 0.1) ntheme.SetPointOpacity(1.0) nodeMapper = vtk.vtkGraphMapper() nodeMapper.SetInput(nodeGraph) nodeMapper.SetColorEdges(False) nodeMapper.ApplyViewTheme(ntheme) nodeActor = vtk.vtkActor() nodeActor.SetMapper(nodeMapper) nodeActor.SetPosition(0,0,-0.0025) # ----------
def main(): colors = vtk.vtkNamedColors() g = vtk.vtkMutableUndirectedGraph() v1 = g.AddVertex() v2 = g.AddVertex() g.AddEdge(v1, v2) g.AddEdge(v1, v2) scales = vtk.vtkFloatArray() scales.SetNumberOfComponents(1) scales.SetName('Scales') scales.InsertNextValue(2.0) scales.InsertNextValue(5.0) # Add the scale array to the graph g.GetVertexData().AddArray(scales) # Create the color array vertexColors = vtk.vtkIntArray() vertexColors.SetNumberOfComponents(1) vertexColors.SetName('Color') lookupTable = vtk.vtkLookupTable() lookupTable.SetNumberOfTableValues(2) lookupTable.SetTableValue(0, colors.GetColor4d('Yellow')) lookupTable.SetTableValue(1, colors.GetColor4d('Lime')) lookupTable.Build() vertexColors.InsertNextValue(0) vertexColors.InsertNextValue(1) # Add the color array to the graph g.GetVertexData().AddArray(vertexColors) theme = vtk.vtkViewTheme() theme.SetPointLookupTable(lookupTable) force_directed = vtk.vtkForceDirectedLayoutStrategy() layout_view = vtk.vtkGraphLayoutView() # If we create a layout object directly, just set the pointer through this method. # graph_layout_view.SetLayoutStrategy(force_directed) layout_view.SetLayoutStrategyToForceDirected() layout_view.AddRepresentationFromInput(g) layout_view.ApplyViewTheme(theme) layout_view.ScaledGlyphsOn() layout_view.SetScalingArrayName('Scales') layout_view.SetVertexColorArrayName('Color') layout_view.ColorVerticesOn() rGraph = vtk.vtkRenderedGraphRepresentation() gGlyph = vtk.vtkGraphToGlyphs() rGraph.SafeDownCast(layout_view.GetRepresentation()).SetGlyphType( gGlyph.CIRCLE) layout_view.GetRenderer().SetBackground(colors.GetColor3d('Navy')) layout_view.GetRenderer().SetBackground2(colors.GetColor3d('MidnightBlue')) layout_view.GetRenderWindow().SetWindowName('ScaleVertices') layout_view.Render() layout_view.ResetCamera() layout_view.GetInteractor().Start()
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()