def main(): # Use the specified filename output_filename = get_program_parameters() # Construct an empty table table = vtk.vtkTable() for i in range(0, 3): col = vtk.vtkVariantArray() col_name = "column-" + str(i) col.SetName(col_name) col.InsertNextValue(vtk.vtkVariant(0.0)) col.InsertNextValue(vtk.vtkVariant(0.0)) col.InsertNextValue(vtk.vtkVariant(0.0)) table.AddColumn(col) # Fill the table with values counter = 0 for r in range(0, table.GetNumberOfRows()): for c in range(table.GetNumberOfColumns()): table.SetValue(r, c, vtk.vtkVariant(counter)) counter += 1 writer = vtk.vtkDelimitedTextWriter() writer.SetFileName(output_filename) writer.SetInputData(table) writer.Write()
def ugrid_from_nastran(ugrid): # type(UGrid)->None cell_data = ugrid.GetCellData() card_ids = vtk.vtkVariantArray() card_ids.SetName('card_ids') global_ids_0 = vtk.vtkIntArray() global_ids_0.SetName('global_ids_0') global_ids = vtk.vtkIntArray() global_ids.SetName('global_ids') original_ids = vtk.vtkIntArray() original_ids.SetName('original_ids') visible = vtk.vtkIntArray() visible.SetName('visible') card_categories = vtk.vtkIntArray() card_categories.SetName('card_categories') card_types = vtk.vtkIntArray() card_types.SetName('card_types') cell_data.AddArray(card_ids) cell_data.AddArray(global_ids_0) cell_data.AddArray(global_ids) cell_data.AddArray(original_ids) cell_data.AddArray(visible) cell_data.AddArray(card_categories) cell_data.AddArray(card_types) element_id = cell_data.GetArray('element_id') elem_types = ugrid.elem_types cell_count = ugrid.GetNumberOfCells() card_ids.SetNumberOfValues(cell_count) global_ids_0.SetNumberOfValues(cell_count) global_ids.SetNumberOfValues(cell_count) original_ids.SetNumberOfValues(cell_count) visible.SetNumberOfValues(cell_count) card_categories.SetNumberOfValues(cell_count) card_types.SetNumberOfValues(cell_count) for i in range(ugrid.GetNumberOfCells()): elem_type = elem_types[i] elem_id = element_id.GetValue(i) card_info_obj = card_info.get_data(elem_type) category = card_info_obj.category category_index = card_info.categories(category) card_index = card_info_obj.index global_id = card_info.from_global_id(elem_id, category_index) card_ids.SetValue(i, elem_type) global_ids_0.SetValue(i, elem_id) global_ids.SetValue(i, global_id) original_ids.SetValue(i, i) visible.SetValue(i, 1) card_categories.SetValue(i, category_index) card_types.SetValue(i, card_index)
def _numpy_to_variant(a): av = vtk.vtkVariantArray() av.SetNumberOfComponents(1 if a.ndim == 1 else a.shape[1]) av.SetNumberOfValues(a.size) for i, s in enumerate(a.ravel()): av.SetValue(i, s) return av
def testPassByValueReturnByReference(self): """Pass vtkVariant by value, return by reference""" a = vtk.vtkVariantArray() a.SetNumberOfValues(1) v = vtk.vtkVariant(1) a.SetValue(0, v) u = a.GetValue(0) self.assertEqual(u.ToInt(), v.ToInt()) self.assertEqual(u.GetType(), v.GetType()) self.assertEqual(u.IsValid(), v.IsValid())
def testGhostForClass(self): """Ghost an object to save the class""" o = vtkCustomObject() a = vtk.vtkVariantArray() a.InsertNextValue(o) i = id(o) del o o = vtk.vtkObject() o = a.GetValue(0).ToVTKObject() # make sure the id has changed, but class the same self.assertEqual(o.__class__, vtkCustomObject) self.assertNotEqual(i, id(o))
def testGhostForDict(self): """Ghost an object to save the dict""" o = vtk.vtkObject() o.customattr = 'hello' a = vtk.vtkVariantArray() a.InsertNextValue(o) i = id(o) del o o = vtk.vtkObject() o = a.GetValue(0).ToVTKObject() # make sure the id has changed, but dict the same self.assertEqual(o.customattr, 'hello') self.assertNotEqual(i, id(o))
def testArgumentConversion(self): """Test argument conversion via implicit constructors""" # automatic conversion to vtkVariant a = vtk.vtkVariantArray() a.InsertNextValue(2.5) a.InsertNextValue(vtk.vtkObject()) self.assertEqual(a.GetValue(0), vtk.vtkVariant(2.5)) self.assertEqual(a.GetValue(1).GetType(), vtk.VTK_OBJECT) # same, but this one is via "const vtkVariant&" argument a = vtk.vtkDenseArray[float]() a.Resize(1) a.SetVariantValue(0, 2.5) self.assertEqual(a.GetVariantValue(0).ToDouble(), 2.5)
def testAutomaticArgConversion(self): """Automatic construction of variants to resolve args""" # use with one of vtkVariant's own constructors v = vtk.vtkVariant('10', vtk.VTK_INT) self.assertEqual(v.ToInt(), 10) self.assertEqual(v.GetType(), vtk.VTK_INT) # use with vtkVariantArray a = vtk.vtkVariantArray() i = a.InsertNextValue(10) v = a.GetValue(i) self.assertEqual(v.GetType(), vtk.VTK_INT) self.assertEqual(v.ToInt(), 10) i = a.InsertNextValue(10.0) v = a.GetValue(i) self.assertEqual(v.GetType(), vtk.VTK_DOUBLE) self.assertEqual(v.ToDouble(), 10.0) i = a.InsertNextValue('10') v = a.GetValue(i) self.assertEqual(v.GetType(), vtk.VTK_STRING) self.assertEqual(v.ToString(), '10')
print("UShort variant: %r, '%s'" % (v2, v2.GetTypeAsString())) # Type checking if v2.IsUnsignedShort(): print("v2 is UnsignedShort") else: print("v2 is not UnsignedShort, it is", v2.GetTypeAsString()) # Explicit value extraction s = v2.ToString() print("String value: %s, %s" % (s, type(s))) i = v2.ToInt() print("Int value: %i, %s" % (i, type(i))) # Automatic argument conversion a = vtk.vtkVariantArray() a.InsertNextValue(vtk.vtkVariant()) a.InsertNextValue(1) a.InsertNextValue(2.0) a.InsertNextValue("hello") a.InsertNextValue(u"there") a.InsertNextValue(vtk.vtkVariantArray()) print("Variant array:") for i in range(a.GetNumberOfValues()): v = a.GetValue(i) print("%i: %r, '%s'" % (i, v, v.GetTypeAsString())) # Comparison if v2 == vtk.vtkVariant(2): print "v2 is equal to 2" if v2 > vtk.vtkVariant(1):
def DisplaySurface(st): ''' Make and display the surface. :param: st - the surface to display. :return The vtkRenderWindowInteractor. ''' surface = st.upper() if (not(surface in SURFACE_TYPE) ): print(st, "is not a surface.") iren = vtk.vtkRenderWindowInteractor() return iren # ------------------------------------------------------------ # Create the surface, lookup tables, contour filter etc. # ------------------------------------------------------------ src = vtk.vtkPolyData() if (surface == "PLANE"): src = MakePlane() elif (surface == "SPHERE"): src = MakeSphere() elif (surface == "PARAMETRIC_SURFACE"): src = MakeParametricSource() # The scalars are named "Scalars"by default # in the parametric surfaces, so change the name. src.GetPointData().GetScalars().SetName("Elevation"); scalarRange = src.GetScalarRange() lut = MakeLUT() lut.SetTableRange(scalarRange) numberOfBands = lut.GetNumberOfTableValues() # bands = MakeIntegralBands(scalarRange) bands = MakeBands(scalarRange, numberOfBands, False) # Let's do a frequency table. # The number of scalars in each band. #print Frequencies(bands, src) # We will use the midpoint of the band as the label. labels = [] for i in range(len(bands)): labels.append('{:4.2f}'.format(bands[i][1])) # Annotate values = vtk.vtkVariantArray() for i in range(len(labels)): values.InsertNextValue(vtk.vtkVariant(labels[i])) for i in range(values.GetNumberOfTuples()): lut.SetAnnotation(i, values.GetValue(i).ToString()); # Create a lookup table with the colors reversed. lutr = ReverseLUT(lut) # Create the contour bands. bcf = vtk.vtkBandedPolyDataContourFilter() bcf.SetInputData(src) # Use either the minimum or maximum value for each band. for i in range(0, numberOfBands): bcf.SetValue(i, bands[i][2]) # We will use an indexed lookup table. bcf.SetScalarModeToIndex() bcf.GenerateContourEdgesOn() # Generate the glyphs on the original surface. glyph = MakeGlyphs(src,False) # ------------------------------------------------------------ # Create the mappers and actors # ------------------------------------------------------------ srcMapper = vtk.vtkPolyDataMapper() srcMapper.SetInputConnection(bcf.GetOutputPort()) srcMapper.SetScalarRange(scalarRange) srcMapper.SetLookupTable(lut) srcMapper.SetScalarModeToUseCellData() srcActor = vtk.vtkActor() srcActor.SetMapper(srcMapper) srcActor.RotateX(-45) srcActor.RotateZ(45) # Create contour edges edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputData(bcf.GetContourEdgesOutput()) edgeMapper.SetResolveCoincidentTopologyToPolygonOffset() edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.GetProperty().SetColor(0, 0, 0) edgeActor.RotateX(-45) edgeActor.RotateZ(45) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection(glyph.GetOutputPort()) glyphMapper.SetScalarModeToUsePointFieldData() glyphMapper.SetColorModeToMapScalars() glyphMapper.ScalarVisibilityOn() glyphMapper.SelectColorArray('Elevation') # Colour by scalars. glyphMapper.SetScalarRange(scalarRange) glyphActor = vtk.vtkActor() glyphActor.SetMapper(glyphMapper) glyphActor.RotateX(-45) glyphActor.RotateZ(45) # Add a scalar bar. scalarBar = vtk.vtkScalarBarActor() # scalarBar.SetLookupTable(lut) # Use this LUT if you want the highest value at the top. scalarBar.SetLookupTable(lutr) scalarBar.SetTitle('Elevation (m)') # ------------------------------------------------------------ # Create the RenderWindow, Renderer and Interactor # ------------------------------------------------------------ ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() renWin.AddRenderer(ren) iren.SetRenderWindow(renWin) # add actors ren.AddViewProp(srcActor) ren.AddViewProp(edgeActor) ren.AddViewProp(glyphActor) ren.AddActor2D(scalarBar) ren.SetBackground(0.7, 0.8, 1.0) renWin.SetSize(800, 800) renWin.Render() ren.GetActiveCamera().Zoom(1.5) return iren
def DisplaySurface(st): ''' Make and display the surface. :param: st - the surface to display. :return The vtkRenderWindowInteractor. ''' surface = st.upper() if (not(surface in SURFACE_TYPE) ): print st, "is not a surface." iren = vtk.vtkRenderWindowInteractor() return iren # ------------------------------------------------------------ # Create the surface, lookup tables, contour filter etc. # ------------------------------------------------------------ src = vtk.vtkPolyData() if (surface == "TORUS"): src = MakeTorus() elif (surface == "PARAMETRIC_TORUS"): src = MakeParametricTorus() elif (surface == "PARAMETRIC_HILLS"): src = Clipper(MakeParametricHills(),0.5,0.5,0.0) # Here we are assuming that the active scalars are the curvatures. curvatureName = src.GetPointData().GetScalars().GetName() # Use this range to color the glyphs for the normals by elevation. src.GetPointData().SetActiveScalars('Elevation') scalarRangeElevation = src.GetScalarRange() src.GetPointData().SetActiveScalars(curvatureName) scalarRangeCurvatures = src.GetScalarRange() scalarRange = scalarRangeCurvatures lut = MakeLUT() numberOfBands = lut.GetNumberOfTableValues() bands = MakeBands(scalarRange, numberOfBands, False) if surface == "PARAMETRIC_HILLS": # Comment this out if you want to see how allocating # equally spaced bands works. bands = MakeCustomBands(scalarRange, numberOfBands) # Adjust the number of table values numberOfBands = len(bands) lut.SetNumberOfTableValues(numberOfBands) lut.SetTableRange(scalarRange) # We will use the midpoint of the band as the label. labels = [] for i in range(numberOfBands): labels.append('{:4.2f}'.format(bands[i][1])) # Annotate values = vtk.vtkVariantArray() for i in range(len(labels)): values.InsertNextValue(vtk.vtkVariant(labels[i])) for i in range(values.GetNumberOfTuples()): lut.SetAnnotation(i, values.GetValue(i).ToString()); # Create a lookup table with the colors reversed. lutr = ReverseLUT(lut) # Create the contour bands. bcf = vtk.vtkBandedPolyDataContourFilter() bcf.SetInputData(src) # Use either the minimum or maximum value for each band. for i in range(0, numberOfBands): bcf.SetValue(i, bands[i][2]) # We will use an indexed lookup table. bcf.SetScalarModeToIndex() bcf.GenerateContourEdgesOn() # Generate the glyphs on the original surface. glyph = MakeGlyphs(src,False) # ------------------------------------------------------------ # Create the mappers and actors # ------------------------------------------------------------ srcMapper = vtk.vtkPolyDataMapper() srcMapper.SetInputConnection(bcf.GetOutputPort()) srcMapper.SetScalarRange(scalarRange) srcMapper.SetLookupTable(lut) srcMapper.SetScalarModeToUseCellData() srcActor = vtk.vtkActor() srcActor.SetMapper(srcMapper) srcActor.RotateX(-45) srcActor.RotateZ(45) # Create contour edges edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputData(bcf.GetContourEdgesOutput()) edgeMapper.SetResolveCoincidentTopologyToPolygonOffset() edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.GetProperty().SetColor(0, 0, 0) edgeActor.RotateX(-45) edgeActor.RotateZ(45) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection(glyph.GetOutputPort()) glyphMapper.SetScalarModeToUsePointFieldData() glyphMapper.SetColorModeToMapScalars() glyphMapper.ScalarVisibilityOn() glyphMapper.SelectColorArray('Elevation') # Colour by scalars. glyphMapper.SetScalarRange(scalarRangeElevation) glyphActor = vtk.vtkActor() glyphActor.SetMapper(glyphMapper) glyphActor.RotateX(-45) glyphActor.RotateZ(45) # Add a scalar bar. scalarBar = vtk.vtkScalarBarActor() # This LUT puts the lowest value at the top of the scalar bar. # scalarBar->SetLookupTable(lut); # Use this LUT if you want the highest value at the top. scalarBar.SetLookupTable(lutr) scalarBar.SetTitle('Gaussian\nCurvature') # ------------------------------------------------------------ # Create the RenderWindow, Renderer and Interactor # ------------------------------------------------------------ ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() renWin.AddRenderer(ren) iren.SetRenderWindow(renWin) # add actors ren.AddViewProp(srcActor) ren.AddViewProp(edgeActor) ren.AddViewProp(glyphActor) ren.AddActor2D(scalarBar) ren.SetBackground(0.7, 0.8, 1.0) renWin.SetSize(800, 800) renWin.Render() ren.GetActiveCamera().Zoom(1.5) return iren
def DisplaySurface(st): """ Make and display the surface. :param: st - the surface to display. :return The vtkRenderWindowInteractor. """ surface = st.upper() if not (surface in SURFACE_TYPE): print(st, "is not a surface.") iren = vtk.vtkRenderWindowInteractor() return iren # ------------------------------------------------------------ # Create the surface, lookup tables, contour filter etc. # ------------------------------------------------------------ # src = vtk.vtkPolyData() # src = Clipper(MakeParametricHills(), 0.5, 0.5, 0.0) # src = MakeParametricHills() src, linesrc, temps = MakeStrip(1001, 101) # Here we are assuming that the active scalars are the curvatures. src.GetPointData().SetActiveScalars('Temps') scalarRange = src.GetScalarRange() lut = MakeLUT() # lut.SetNumberOfTableValues(20) numberOfBands = lut.GetNumberOfTableValues() bands = MakeBands(scalarRange, numberOfBands, False) lut.SetTableRange(scalarRange) # We will use the midpoint of the band as the label. labels = [] for i in range(numberOfBands): labels.append('{:4.2f}'.format(bands[i][1])) # Annotate values = vtk.vtkVariantArray() for i in range(len(labels)): values.InsertNextValue(vtk.vtkVariant(labels[i])) for i in range(values.GetNumberOfTuples()): lut.SetAnnotation(i, values.GetValue(i).ToString()) # Create the contour bands. bcf = vtk.vtkBandedPolyDataContourFilter() bcf.SetInputData(src) # Use either the minimum or maximum value for each band. for i in range(0, numberOfBands): bcf.SetValue(i, bands[i][2]) # We will use an indexed lookup table. bcf.SetScalarModeToIndex() bcf.GenerateContourEdgesOn() # ------------------------------------------------------------ # Create the mappers and actors # ------------------------------------------------------------ srcMapper = vtk.vtkPolyDataMapper() srcMapper.SetInputConnection(bcf.GetOutputPort()) srcMapper.SetScalarRange(scalarRange) srcMapper.SetLookupTable(lut) srcMapper.SetScalarModeToUseCellData() srcActor = vtk.vtkActor() srcActor.SetMapper(srcMapper) lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputData(linesrc) lineActor = vtk.vtkActor() lineActor.SetMapper(lineMapper) lineActor.GetProperty().SetColor(0, 0, 1) # Create contour edges edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputData(bcf.GetContourEdgesOutput()) edgeMapper.SetResolveCoincidentTopologyToPolygonOffset() edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.GetProperty().SetColor(0, 0, 0) # ------------------------------------------------------------ # Create the RenderWindow, Renderer and Interactor # ------------------------------------------------------------ ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() renWin.AddRenderer(ren) iren.SetRenderWindow(renWin) # add actors ren.AddViewProp(srcActor) ren.AddViewProp(edgeActor) # ren.AddViewProp(lineActor) ren.SetBackground(0.7, 0.8, 1.0) renWin.SetSize(800, 800) renWin.Render() ren.GetActiveCamera().Zoom(1.5) return iren
def update(self, **kwargs): """ Update the line object because of data of settings changed. """ super(Line, self).update(**kwargs) # Extract x,y data if not self.getOption('append'): self._vtktable.SetNumberOfRows(0) # Get the x,y data and reset to None so that data doesn't append over and over x = self.getOption('x') y = self.getOption('y') if (x and y) and (len(x) == len(y)): for i in range(len(x)): #pylint: disable=consider-using-enumerate array = vtk.vtkVariantArray() array.SetNumberOfTuples(2) array.SetValue(0, x[i]) array.SetValue(1, y[i]) self._vtktable.InsertNextRow(array) self._vtktable.Modified() elif (x and y) and (len(x) != len(y)): mooseutils.MooseException( "Supplied x and y data must be same length.") # Apply the line/point settings if self.isOptionValid('color'): self._vtkplot.SetColor(*self.getOption('color')) if self.isOptionValid('width'): self._vtkplot.SetWidth(self.getOption('width')) if self.isOptionValid('label'): self._vtkplot.SetLabel(self.getOption('label')) vtk_marker = getattr(vtk.vtkPlotLine, self.getOption('marker').upper()) self._vtkplot.SetMarkerStyle(vtk_marker) # Label if not self.isOptionValid('label'): self._vtkplot.LegendVisibilityOff() else: self._vtkplot.LegendVisibilityOn() # Handle single point data if self._vtktable.GetNumberOfRows() == 1: self._vtktable.InsertNextRow(self._vtktable.GetRow(0)) # Tracers if self._xtracer: ax = self._vtkplot.GetYAxis() rmin = ax.GetMinimum() rmax = ax.GetMaximum() value = self._vtktable.GetValue( self._vtktable.GetNumberOfRows() - 1, 0) self._xtracer.update(x=[value, value], y=[rmin, rmax]) if self._ytracer: ax = self._vtkplot.GetXAxis() rmin = ax.GetMinimum() rmax = ax.GetMaximum() value = self._vtktable.GetValue( self._vtktable.GetNumberOfRows() - 1, 1) self._ytracer.update(x=[rmin, rmax], y=[value, value])
print("UShort variant: %r, '%s'" % (v2, v2.GetTypeAsString())) # Type checking if v2.IsUnsignedShort(): print("v2 is UnsignedShort") else: print("v2 is not UnsignedShort, it is", v2.GetTypeAsString()) # Explicit value extraction s = v2.ToString() print("String value: %s, %s" % (s, type(s))) i = v2.ToInt() print("Int value: %i, %s" % (i, type(i))) # Automatic argument conversion a = vtk.vtkVariantArray() a.InsertNextValue(vtk.vtkVariant()) a.InsertNextValue(1) a.InsertNextValue(2.0) a.InsertNextValue("hello") a.InsertNextValue(unicodeEtre) a.InsertNextValue(vtk.vtkVariantArray()) print("Variant array:") for i in range(a.GetNumberOfValues()): v = a.GetValue(i) print("%i: %r, '%s'" % (i, v, v.GetTypeAsString())) # Comparison if v2 == vtk.vtkVariant(2): print("v2 is equal to 2") if v2 > vtk.vtkVariant(1):
def main(): colors = vtk.vtkNamedColors() filename = get_program_parameters() # Create the reader for the data. print('Loading ', filename) reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) reader.Update() extractEdges = vtk.vtkExtractEdges() extractEdges.SetInputConnection(reader.GetOutputPort()) legendValues = vtk.vtkVariantArray() it = reader.GetOutput().NewCellIterator() it.InitTraversal() while not it.IsDoneWithTraversal(): cell = vtk.vtkGenericCell() it.GetCell(cell) cellName = vtk.vtkCellTypes.GetClassNameFromTypeId(cell.GetCellType()) print(cellName, 'NumberOfPoints:', cell.GetNumberOfPoints(), 'CellDimension:', cell.GetCellDimension()) legendValues.InsertNextValue(cellName) it.GoToNextCell() # Tube the edges tubes = vtk.vtkTubeFilter() tubes.SetInputConnection(extractEdges.GetOutputPort()) tubes.SetRadius(.05) tubes.SetNumberOfSides(21) edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputConnection(tubes.GetOutputPort()) edgeMapper.SetScalarRange(0, 26) edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.GetProperty().SetSpecular(0.6) edgeActor.GetProperty().SetSpecularPower(30) # Glyph the points sphere = vtk.vtkSphereSource() sphere.SetPhiResolution(21) sphere.SetThetaResolution(21) sphere.SetRadius(0.08) pointMapper = vtk.vtkGlyph3DMapper() pointMapper.SetInputConnection(reader.GetOutputPort()) pointMapper.SetSourceConnection(sphere.GetOutputPort()) pointMapper.ScalingOff() pointMapper.ScalarVisibilityOff() pointActor = vtk.vtkActor() pointActor.SetMapper(pointMapper) pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d('Banana')) pointActor.GetProperty().SetSpecular(0.6) pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0) pointActor.GetProperty().SetSpecularPower(100) # Label the points labelMapper = vtk.vtkLabeledDataMapper() labelMapper.SetInputConnection(reader.GetOutputPort()) labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # The geometry geometryShrink = vtk.vtkShrinkFilter() geometryShrink.SetInputConnection(reader.GetOutputPort()) geometryShrink.SetShrinkFactor(0.8) # NOTE: We must copy the originalLut because the CategoricalLegend # needs an indexed lookup table, but the geometryMapper uses a # non-index lookup table categoricalLut = vtk.vtkLookupTable() originalLut = reader.GetOutput().GetCellData().GetScalars().GetLookupTable( ) categoricalLut.DeepCopy(originalLut) categoricalLut.IndexedLookupOn() geometryMapper = vtk.vtkDataSetMapper() geometryMapper.SetInputConnection(geometryShrink.GetOutputPort()) geometryMapper.SetScalarModeToUseCellData() geometryMapper.SetScalarRange(0, 11) geometryActor = vtk.vtkActor() geometryActor.SetMapper(geometryMapper) geometryActor.GetProperty().SetLineWidth(3) geometryActor.GetProperty().EdgeVisibilityOn() geometryActor.GetProperty().SetEdgeColor(0, 0, 0) # Legend for v in range(0, legendValues.GetNumberOfTuples()): categoricalLut.SetAnnotation(legendValues.GetValue(v), legendValues.GetValue(v).ToString()) legend = vtk.vtkCategoryLegend() legend.SetScalarsToColors(categoricalLut) legend.SetValues(legendValues) legend.SetTitle('Cell Type') legend.GetBrush().SetColor(colors.GetColor4ub('Silver')) placeLegend = vtk.vtkContextTransform() placeLegend.AddItem(legend) placeLegend.Translate(640 - 20, 480 - 12 * 16) contextView = vtk.vtkContextView() contextView.GetScene().AddItem(placeLegend) renderer = contextView.GetRenderer() renderWindow = contextView.GetRenderWindow() renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(geometryActor) renderer.AddActor(labelActor) renderer.AddActor(edgeActor) renderer.AddActor(pointActor) renderer.SetBackground(colors.GetColor3d('SlateGray')) aCamera = vtk.vtkCamera() aCamera.Azimuth(-40.0) aCamera.Elevation(50.0) renderer.SetActiveCamera(aCamera) renderer.ResetCamera() renderWindow.SetSize(640, 480) renderWindow.SetWindowName('ReadLegacyUnstructuredGrid') renderWindow.Render() renderWindowInteractor.Start()
def CreateVtkMapperActor(self): self.surfMapper = vtk.vtkPolyDataMapper() self.surfMapper.SetInputData(self.vtkSurfPolyData) self.surfActor = vtk.vtkActor() self.surfActor.SetMapper(self.surfMapper) self.surfActor.GetProperty().SetLineWidth(2.0) self.surfActor.GetProperty().SetPointSize(8.0) self.contMapper = vtk.vtkPolyDataMapper() scalarRange = self.vtkContPolyData.GetScalarRange() if scalarRange[0] > scalarRange[1]: scalarRange = (0, 1) self.contMapper.SetScalarRange(scalarRange) lut = MakeLUT() # lut.SetNumberOfTableValues(20) numberOfBands = lut.GetNumberOfTableValues() bands = MakeBands(scalarRange, numberOfBands, False) lut.SetTableRange(scalarRange) # We will use the midpoint of the band as the label. labels = [] for i in range(numberOfBands): labels.append('{:4.2f}'.format(bands[i][1])) # Annotate values = vtk.vtkVariantArray() for i in range(len(labels)): values.InsertNextValue(vtk.vtkVariant(labels[i])) for i in range(values.GetNumberOfTuples()): lut.SetAnnotation(i, values.GetValue(i).ToString()) # Create the contour bands. bcf = vtk.vtkBandedPolyDataContourFilter() bcf.SetInputData(self.vtkContPolyData) # Use either the minimum or maximum value for each band. for i in range(0, numberOfBands): bcf.SetValue(i, bands[i][2]) # We will use an indexed lookup table. bcf.SetScalarModeToIndex() bcf.GenerateContourEdgesOn() self.contMapper.SetInputConnection(bcf.GetOutputPort()) self.contMapper.SetScalarRange(scalarRange) self.contMapper.SetLookupTable(lut) self.contMapper.SetScalarModeToUseCellData() self.contActor = vtk.vtkActor() self.contActor.SetMapper(self.contMapper) self.contActor.VisibilityOff() self.edgeMapper = vtk.vtkPolyDataMapper() self.edgeMapper.SetInputData(self.vtkEdgePolyData) self.edgeActor = vtk.vtkActor() self.edgeActor.SetMapper(self.edgeMapper) self.edgeActor.GetProperty().SetRepresentationToWireframe() self.edgeActor.GetProperty().SetColor([0, 0, 0]) self.edgeActor.GetProperty().SetLineWidth(2.0) self.edgeActor.VisibilityOff() # Source for the glyph filter self.CreateArrowsGlyphs() self.glyphMapper = vtk.vtkPolyDataMapper() self.glyphMapper.SetInputConnection(self.glyph.GetOutputPort()) self.glyphMapper.SetScalarModeToUsePointFieldData() # self.glyphMapper.SetColorModeToMapScalars() self.glyphMapper.ScalarVisibilityOn() # self.glyphMapper.SelectColorArray('vecMag') # Colour by scalars. # scalarRange = polydata.GetScalerRange() # glyphMapper.SetScalarRange(scalarRange) self.glyphActor = vtk.vtkActor() self.glyphActor.GetProperty().SetColor(0.3, 0.3, 0.0) self.glyphActor.SetMapper(self.glyphMapper)
def TestLookupTables(lutMode): ''' Test various combinations of lookup tables. :param: lutMode - if True the tables are ordinal, categorical otherwise. :return: True if all tests passed. ''' lutUtilities = LUTUtilities() lut1 = vtk.vtkLookupTable() lut2 = vtk.vtkLookupTable() colorSeries = vtk.vtkColorSeries() colorSeriesEnum = colorSeries.SPECTRUM colorSeries.SetColorScheme(colorSeriesEnum) colorSeries.BuildLookupTable(lut1) colorSeries.BuildLookupTable(lut2) if lutMode: lut1.IndexedLookupOff() lut2.IndexedLookupOff() lut1.SetNanColor(1, 0, 0, 1) lut2.SetNanColor(1, 0, 0, 1) if not lutMode: # For the annotation just use a letter of the alphabet. values1 = vtk.vtkVariantArray() values2 = vtk.vtkVariantArray() str = "abcdefghijklmnopqrstuvwxyz" for i in range(lut1.GetNumberOfTableValues()): values1.InsertNextValue(vtk.vtkVariant(str[i])) for i in range(lut2.GetNumberOfTableValues()): values2.InsertNextValue(vtk.vtkVariant(str[i])) for i in range(values1.GetNumberOfTuples()): lut1.SetAnnotation(i, values1.GetValue(i).ToString()) for i in range(values2.GetNumberOfTuples()): lut2.SetAnnotation(i, values2.GetValue(i).ToString()) # Are they the same? res = True res &= TestTables(lut1, lut2) # Different size lut2.SetNumberOfTableValues(5) res &= TestTables(lut1, lut2, False) lut2.SetNumberOfTableValues(lut1.GetNumberOfTableValues()) res &= TestTables(lut1, lut2) if lutMode: # Different range lut2.SetTableRange(1, 2) res &= TestTables(lut1, lut2, False) tr = lut1.GetTableRange() lut2.SetTableRange(tr) res &= TestTables(lut1, lut2) # Different color colorSeriesEnum = colorSeries.COOL colorSeries.SetColorScheme(colorSeriesEnum) lut3 = vtk.vtkLookupTable() colorSeries.BuildLookupTable(lut3) lut3.IndexedLookupOff() res &= TestTables(lut1, lut3, False) # One indexed, the other ordinal. lut1.IndexedLookupOn() res &= TestTables(lut1, lut2, False) else: # Different color colorSeriesEnum = colorSeries.COOL colorSeries.SetColorScheme(colorSeriesEnum) lut3 = vtk.vtkLookupTable() colorSeries.BuildLookupTable(lut3) values = vtk.vtkVariantArray() str = "abcdefghijklmnopqrstuvwxyz" for i in range(lut3.GetNumberOfTableValues()): values.InsertNextValue(vtk.vtkVariant(str[i])) for i in range(values.GetNumberOfTuples()): lut3.SetAnnotation(i, values.GetValue(i).ToString()) colorSeries.BuildLookupTable(lut3) res &= TestTables(lut1, lut3, False) # Different annotations. lut2.ResetAnnotations() for i in range(values.GetNumberOfTuples()): if i % 3 == 0: continue lut2.SetAnnotation(i, values.GetValue(i).ToString()) res &= TestTables(lut1, lut2, False) # No annotations lut1.ResetAnnotations() lut2.ResetAnnotations() res &= TestTables(lut1, lut2) # One indexed, the other ordinal. lut1.IndexedLookupOff() res &= TestTables(lut1, lut2, False) return res
def DisplaySurface(st): ''' Make and display the surface. :param: st - the surface to display. :return The vtkRenderWindowInteractor. ''' surface = st.upper() if (not (surface in SURFACE_TYPE)): print st, "is not a surface." iren = vtk.vtkRenderWindowInteractor() return iren # ------------------------------------------------------------ # Create the surface, lookup tables, contour filter etc. # ------------------------------------------------------------ src = vtk.vtkPolyData() if (surface == "PLANE"): src = MakePlane() elif (surface == "SPHERE"): src = MakeSphere() elif (surface == "PARAMETRIC_SURFACE"): src = MakeParametricSource() # The scalars are named "Scalars"by default # in the parametric surfaces, so change the name. src.GetPointData().GetScalars().SetName("Elevation") scalarRange = src.GetScalarRange() lut = MakeLUT() lut.SetTableRange(scalarRange) numberOfBands = lut.GetNumberOfTableValues() # bands = MakeIntegralBands(scalarRange) bands = MakeBands(scalarRange, numberOfBands, False) # Let's do a frequency table. # The number of scalars in each band. #print Frequencies(bands, src) # We will use the midpoint of the band as the label. labels = [] for i in range(len(bands)): labels.append('{:4.2f}'.format(bands[i][1])) # Annotate values = vtk.vtkVariantArray() for i in range(len(labels)): values.InsertNextValue(vtk.vtkVariant(labels[i])) for i in range(values.GetNumberOfTuples()): lut.SetAnnotation(i, values.GetValue(i).ToString()) # Create a lookup table with the colors reversed. lutr = ReverseLUT(lut) # Create the contour bands. bcf = vtk.vtkBandedPolyDataContourFilter() bcf.SetInputData(src) # Use either the minimum or maximum value for each band. for i in range(0, numberOfBands): bcf.SetValue(i, bands[i][2]) # We will use an indexed lookup table. bcf.SetScalarModeToIndex() bcf.GenerateContourEdgesOn() # Generate the glyphs on the original surface. glyph = MakeGlyphs(src, False) # ------------------------------------------------------------ # Create the mappers and actors # ------------------------------------------------------------ srcMapper = vtk.vtkPolyDataMapper() srcMapper.SetInputConnection(bcf.GetOutputPort()) srcMapper.SetScalarRange(scalarRange) srcMapper.SetLookupTable(lut) srcMapper.SetScalarModeToUseCellData() srcActor = vtk.vtkActor() srcActor.SetMapper(srcMapper) srcActor.RotateX(-45) srcActor.RotateZ(45) # Create contour edges edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputData(bcf.GetContourEdgesOutput()) edgeMapper.SetResolveCoincidentTopologyToPolygonOffset() edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.GetProperty().SetColor(0, 0, 0) edgeActor.RotateX(-45) edgeActor.RotateZ(45) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection(glyph.GetOutputPort()) glyphMapper.SetScalarModeToUsePointFieldData() glyphMapper.SetColorModeToMapScalars() glyphMapper.ScalarVisibilityOn() glyphMapper.SelectColorArray('Elevation') # Colour by scalars. glyphMapper.SetScalarRange(scalarRange) glyphActor = vtk.vtkActor() glyphActor.SetMapper(glyphMapper) glyphActor.RotateX(-45) glyphActor.RotateZ(45) # Add a scalar bar. scalarBar = vtk.vtkScalarBarActor() # scalarBar.SetLookupTable(lut) # Use this LUT if you want the highest value at the top. scalarBar.SetLookupTable(lutr) scalarBar.SetTitle('Elevation (m)') # ------------------------------------------------------------ # Create the RenderWindow, Renderer and Interactor # ------------------------------------------------------------ ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() renWin.AddRenderer(ren) iren.SetRenderWindow(renWin) # add actors ren.AddViewProp(srcActor) ren.AddViewProp(edgeActor) ren.AddViewProp(glyphActor) ren.AddActor2D(scalarBar) ren.SetBackground(0.7, 0.8, 1.0) renWin.SetSize(800, 800) renWin.Render() ren.GetActiveCamera().Zoom(1.5) return iren
def DisplaySurface(st): """ Make and display the surface. :param: st - the surface to display. :return The vtkRenderWindowInteractor. """ surface = st.upper() if not (surface in SURFACE_TYPE): print(st, 'is not a surface.') iren = vtk.vtkRenderWindowInteractor() return iren colors = vtk.vtkNamedColors() # Set the background color. colors.SetColor('BkgColor', [179, 204, 255, 255]) # ------------------------------------------------------------ # Create the surface, lookup tables, contour filter etc. # ------------------------------------------------------------ src = vtk.vtkPolyData() if surface == 'TORUS': src = MakeTorus() elif surface == 'PARAMETRIC_TORUS': src = MakeParametricTorus() elif surface == 'PARAMETRIC_HILLS': src = Clipper(MakeParametricHills(), 0.5, 0.5, 0.0) # Here we are assuming that the active scalars are the curvatures. curvatureName = src.GetPointData().GetScalars().GetName() # Use this range to color the glyphs for the normals by elevation. src.GetPointData().SetActiveScalars('Elevation') scalarRangeElevation = src.GetScalarRange() src.GetPointData().SetActiveScalars(curvatureName) scalarRangeCurvatures = src.GetScalarRange() scalarRange = scalarRangeCurvatures lut = MakeLUT() numberOfBands = lut.GetNumberOfTableValues() bands = MakeBands(scalarRange, numberOfBands, False) if surface == 'PARAMETRIC_HILLS': # Comment this out if you want to see how allocating # equally spaced bands works. bands = MakeCustomBands(scalarRange, numberOfBands) # Adjust the number of table values numberOfBands = len(bands) lut.SetNumberOfTableValues(numberOfBands) lut.SetTableRange(scalarRange) # We will use the midpoint of the band as the label. labels = [] for i in range(numberOfBands): labels.append('{:4.2f}'.format(bands[i][1])) # Annotate values = vtk.vtkVariantArray() for i in range(len(labels)): values.InsertNextValue(vtk.vtkVariant(labels[i])) for i in range(values.GetNumberOfTuples()): lut.SetAnnotation(i, values.GetValue(i).ToString()) # Create a lookup table with the colors reversed. lutr = ReverseLUT(lut) # Create the contour bands. bcf = vtk.vtkBandedPolyDataContourFilter() bcf.SetInputData(src) # Use either the minimum or maximum value for each band. for i in range(0, numberOfBands): bcf.SetValue(i, bands[i][2]) # We will use an indexed lookup table. bcf.SetScalarModeToIndex() bcf.GenerateContourEdgesOn() # Generate the glyphs on the original surface. glyph = MakeGlyphs(src, False) # ------------------------------------------------------------ # Create the mappers and actors # ------------------------------------------------------------ srcMapper = vtk.vtkPolyDataMapper() srcMapper.SetInputConnection(bcf.GetOutputPort()) srcMapper.SetScalarRange(scalarRange) srcMapper.SetLookupTable(lut) srcMapper.SetScalarModeToUseCellData() srcActor = vtk.vtkActor() srcActor.SetMapper(srcMapper) srcActor.RotateX(-45) srcActor.RotateZ(45) # Create contour edges edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputData(bcf.GetContourEdgesOutput()) edgeMapper.SetResolveCoincidentTopologyToPolygonOffset() edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.GetProperty().SetColor(colors.GetColor3d('Black')) edgeActor.RotateX(-45) edgeActor.RotateZ(45) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection(glyph.GetOutputPort()) glyphMapper.SetScalarModeToUsePointFieldData() glyphMapper.SetColorModeToMapScalars() glyphMapper.ScalarVisibilityOn() glyphMapper.SelectColorArray('Elevation') # Colour by scalars. glyphMapper.SetScalarRange(scalarRangeElevation) glyphActor = vtk.vtkActor() glyphActor.SetMapper(glyphMapper) glyphActor.RotateX(-45) glyphActor.RotateZ(45) # Add a scalar bar. scalarBar = vtk.vtkScalarBarActor() # This LUT puts the lowest value at the top of the scalar bar. # scalarBar->SetLookupTable(lut); # Use this LUT if you want the highest value at the top. scalarBar.SetLookupTable(lutr) scalarBar.SetTitle('Gaussian\nCurvature') # ------------------------------------------------------------ # Create the RenderWindow, Renderer and Interactor # ------------------------------------------------------------ ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() renWin.AddRenderer(ren) iren.SetRenderWindow(renWin) # add actors ren.AddViewProp(srcActor) ren.AddViewProp(edgeActor) ren.AddViewProp(glyphActor) ren.AddActor2D(scalarBar) ren.SetBackground(colors.GetColor3d('BkgColor')) renWin.SetSize(800, 800) renWin.SetWindowName('CurvatureBandsWithGlyphs') renWin.Render() ren.GetActiveCamera().Zoom(1.5) return iren
def update(self, **kwargs): """ Update the line object because of data of settings changed. """ super(Line, self).update(**kwargs) # Extract x,y data if not self.getOption('append'): self._vtktable.SetNumberOfRows(0) # Get the x,y data and reset to None so that data doesn't append over and over x = self.getOption('x') y = self.getOption('y') if (x and y) and (len(x) == len(y)): for i in range(len(x)): #pylint: disable=consider-using-enumerate array = vtk.vtkVariantArray() array.SetNumberOfTuples(2) array.SetValue(0, x[i]) array.SetValue(1, y[i]) self._vtktable.InsertNextRow(array) self._vtktable.Modified() elif (x and y) and (len(x) != len(y)): mooseutils.MooseException("Supplied x and y data must be same length.") # Apply the line/point settings if self.isOptionValid('color'): self._vtkplot.SetColor(*self.getOption('color')) if self.isOptionValid('width'): self._vtkplot.SetWidth(self.getOption('width')) if self.isOptionValid('label'): self._vtkplot.SetLabel(self.getOption('label')) vtk_marker = getattr(vtk.vtkPlotLine, self.getOption('marker').upper()) self._vtkplot.SetMarkerStyle(vtk_marker) # Label if not self.isOptionValid('label'): self._vtkplot.LegendVisibilityOff() else: self._vtkplot.LegendVisibilityOn() # Handle single point data if self._vtktable.GetNumberOfRows() == 1: self._vtktable.InsertNextRow(self._vtktable.GetRow(0)) # Tracers if self._xtracer: ax = self._vtkplot.GetYAxis() rmin = ax.GetMinimum() rmax = ax.GetMaximum() value = self._vtktable.GetValue(self._vtktable.GetNumberOfRows()-1, 0) self._xtracer.update(x=[value, value], y=[rmin, rmax]) if self._ytracer: ax = self._vtkplot.GetXAxis() rmin = ax.GetMinimum() rmax = ax.GetMaximum() value = self._vtktable.GetValue(self._vtktable.GetNumberOfRows()-1, 1) self._ytracer.update(x=[rmin, rmax], y=[value, value])