def gt_to_vtk(din): """ From the graph-tool property value type creates an equivalent vtkDataArray object. Args: din (str): graph-tool property value type Returns: vtkDataArray object """ # Check that a string object is passed if not isinstance(din, str): error_msg = 'str object required as input.' raise pexceptions.PySegInputError(expr='gt_to_vtk (TypesConverter)', msg=error_msg) if (din == 'bool') or (din == 'vector<bool>'): return vtk.vtkIntArray() # was vtk.vtkBitArray() elif (din == 'int16_t') or (din == 'vector<int16_t>'): return vtk.vtkTypeInt16Array() elif (din == 'int32_t') or (din == 'vector<int32_t>'): return vtk.vtkIntArray() elif (din == 'int64_t') or (din == 'vector<int64_t>'): return vtk.vtkTypeInt64Array() elif (din == 'double') or (din == 'vector<double>'): return vtk.vtkFloatArray() else: error_msg = 'Graph-tool alias not identified.' raise pexceptions.PySegInputError(expr='gt_to_vtk (TypesConverter)', msg=error_msg)
def __init__(self, args): self.Surface = None self.InputFile = args.surface self.OutputFile = args.file_out self.FeatureAngle = 50.0 #args.feature_angle self.NumberOfRegions = 0 self.RegionIdsArrayName = "RegionsId" self.boundaries = vtk.vtkFeatureEdges() self.NewScalars = vtk.vtkIntArray() self.RegionAreas = vtk.vtkDoubleArray() self.mesh = vtk.vtkPolyData() self.BoundaryLines = vtk.vtkPolyData() self.BoundaryPointArray = vtk.vtkIntArray() self.BoundaryCellArray = vtk.vtkIntArray() self.CheckCells = vtk.vtkIdList() self.CheckCells2 = vtk.vtkIdList() self.CheckCellsCareful = vtk.vtkIdList() self.CheckCellsCareful2 = vtk.vtkIdList() # dynamic alloated arrays self.checked = None self.checkedcarefully = None self.pointMapper = None #Feature edges options self.BoundaryEdges = 0 self.ManifoldEdges = 0 self.NonManifoldEdges = 0 self.FeatureEdges = 1 self.ExtractLargestregion = 0
def __init__(self, data): super(ModelDataHelper, self).__init__() self.data = data self.points = vtk.vtkPoints() self.data.SetPoints(self.points) self.global_ids1 = vtk.vtkIdTypeArray() #self.global_ids1.SetName("global_ids") self.global_ids2 = vtk.vtkIntArray() self.global_ids2.SetName("global_ids") self.visible = vtk.vtkIntArray() self.visible.SetName("visible") self.original_ids = vtk.vtkIntArray() self.original_ids.SetName("original_ids") self.basic_types = vtk.vtkIntArray() self.basic_types.SetName("basic_types") self.basic_shapes = vtk.vtkIntArray() self.basic_shapes.SetName("basic_shapes") self.data.GetCellData().SetGlobalIds(self.global_ids1) self.data.GetCellData().AddArray(self.visible) self.data.GetCellData().AddArray(self.original_ids) self.data.GetCellData().AddArray(self.global_ids2) self.data.GetCellData().AddArray(self.basic_types) self.data.GetCellData().AddArray(self.basic_shapes)
def __init__(self): super(ModelBaseData, self).__init__() self.data = vtk.vtkUnstructuredGrid() self.points = None self.global_ids = vtk.vtkIdTypeArray() self.global_ids.SetName("global_ids") self.visible = vtk.vtkIntArray() self.visible.SetName("visible") self.original_ids = vtk.vtkIntArray() self.original_ids.SetName("original_ids") self.basic_types = vtk.vtkIntArray() self.basic_types.SetName("basic_types") self.basic_shapes = vtk.vtkIntArray() self.basic_shapes.SetName("basic_shapes") self.data.GetCellData().SetGlobalIds(self.global_ids) self.data.GetCellData().AddArray(self.visible) self.data.GetCellData().AddArray(self.original_ids) self.data.GetCellData().AddArray(self.global_ids) self.data.GetCellData().AddArray(self.basic_types) self.data.GetCellData().AddArray(self.basic_shapes)
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 testBarGraph(self): "Test if bar graphs can be built with python" # Set up a 2D scene, add an XY chart to it view = vtk.vtkContextView() view.GetRenderer().SetBackground(1.0, 1.0, 1.0) view.GetRenderWindow().SetSize(400, 300) chart = vtk.vtkChartXY() view.GetScene().AddItem(chart) # Create a table with some points in it table = vtk.vtkTable() arrMonth = vtk.vtkIntArray() arrMonth.SetName("Month") arr2008 = vtk.vtkIntArray() arr2008.SetName("2008") arr2009 = vtk.vtkIntArray() arr2009.SetName("2009") arr2010 = vtk.vtkIntArray() arr2010.SetName("2010") numMonths = 12 for i in range(0, numMonths): arrMonth.InsertNextValue(i + 1) arr2008.InsertNextValue(data_2008[i]) arr2009.InsertNextValue(data_2009[i]) arr2010.InsertNextValue(data_2010[i]) table.AddColumn(arrMonth) table.AddColumn(arr2008) table.AddColumn(arr2009) table.AddColumn(arr2010) # Now add the line plots with appropriate colors line = chart.AddPlot(2) line.SetInputData(table, 0, 1) line.SetColor(0, 255, 0, 255) line = chart.AddPlot(2) line.SetInputData(table, 0, 2) line.SetColor(255, 0, 0, 255) line = chart.AddPlot(2) line.SetInputData(table, 0, 3) line.SetColor(0, 0, 255, 255) view.GetRenderWindow().SetMultiSamples(0) view.GetRenderWindow().Render() img_file = "TestBarGraph.png" vtk.test.Testing.compareImage( view.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def testBarGraph(self): "Test if bar graphs can be built with python" # Set up a 2D scene, add an XY chart to it view = vtk.vtkContextView() view.GetRenderer().SetBackground(1.0,1.0,1.0) view.GetRenderWindow().SetSize(400,300) chart = vtk.vtkChartXY() view.GetScene().AddItem(chart) # Create a table with some points in it table = vtk.vtkTable() arrMonth = vtk.vtkIntArray() arrMonth.SetName("Month") arr2008 = vtk.vtkIntArray() arr2008.SetName("2008") arr2009 = vtk.vtkIntArray() arr2009.SetName("2009") arr2010 = vtk.vtkIntArray() arr2010.SetName("2010") numMonths = 12 for i in range(0,numMonths): arrMonth.InsertNextValue(i + 1) arr2008.InsertNextValue(data_2008[i]) arr2009.InsertNextValue(data_2009[i]) arr2010.InsertNextValue(data_2010[i]) table.AddColumn(arrMonth) table.AddColumn(arr2008) table.AddColumn(arr2009) table.AddColumn(arr2010) # Now add the line plots with appropriate colors line = chart.AddPlot(2) line.SetInput(table,0,1) line.SetColor(0,255,0,255) line = chart.AddPlot(2) line.SetInput(table,0,2) line.SetColor(255,0,0,255); line = chart.AddPlot(2) line.SetInput(table,0,3) line.SetColor(0,0,255,255); view.GetRenderWindow().SetMultiSamples(0) view.GetRenderWindow().Render() img_file = "TestBarGraph.png" vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25) vtk.test.Testing.interact()
def TestDataType(dataType, reader, writer, ext, numTris, useSubdir=False): s = GetSource(dataType) filename = VTK_TEMP_DIR + "/%s.p%s" % (dataType, ext) writer.SetInputConnection(s.GetOutputPort()) npieces = 16 writer.SetNumberOfPieces(npieces) pperrank = npieces // nranks start = pperrank * rank end = start + pperrank - 1 writer.SetStartPiece(start) writer.SetEndPiece(end) writer.SetFileName(filename) if useSubdir: writer.SetUseSubdirectory(True) #writer.SetDataModeToAscii() writer.Write() if contr: contr.Barrier() reader.SetFileName(filename) cf = vtk.vtkContourFilter() cf.SetValue(0, 130) cf.SetComputeNormals(0) cf.SetComputeGradients(0) cf.SetInputConnection(reader.GetOutputPort()) cf.UpdateInformation() cf.GetOutputInformation(0).Set( vtk.vtkStreamingDemandDrivenPipeline.UPDATE_NUMBER_OF_PIECES(), nranks) cf.GetOutputInformation(0).Set( vtk.vtkStreamingDemandDrivenPipeline.UPDATE_PIECE_NUMBER(), rank) cf.Update() ntris = cf.GetOutput().GetNumberOfCells() da = vtk.vtkIntArray() da.InsertNextValue(ntris) da2 = vtk.vtkIntArray() da2.SetNumberOfTuples(1) contr.AllReduce(da, da2, vtk.vtkCommunicator.SUM_OP) if rank == 0: print(da2.GetValue(0)) import os os.remove(filename) for i in range(npieces): if not useSubdir: os.remove(VTK_TEMP_DIR + "/%s_%d.%s" % (dataType, i, ext)) else: os.remove(VTK_TEMP_DIR + "/%s/%s_%d.%s" % (dataType, dataType, i, ext)) assert da2.GetValue(0) == numTris
def tetgen2vtk(name="mesh", arrayName="doubledNode"): """ read tetgen output files into memory (ugrid) """ ugrid = vtk.vtkUnstructuredGrid() points = vtk.vtkPoints() inFile = open(name + ".1.node", 'r') line = inFile.readline().split() nbnod = int(line[0]) vtkArray = vtk.vtkIntArray() if arrayName: vtkArray.SetName(arrayName) vtkArray.SetNumberOfValues(nbnod) for i in range(nbnod): line = inFile.readline().split() points.InsertPoint(i, float(line[1]), float(line[2]), float(line[3])) try: vtkArray.SetValue(i, int(line[4]) - 1) #car on renumerote a nouveau a partir de 1 except: vtkArray.SetValue(i, -1) ugrid.GetPointData().AddArray(vtkArray) inFile.close() ugrid.SetPoints(points) inFile = open(name + ".1.ele", 'r') line = inFile.readline().split() nbelm = int(line[0]) materArray = vtk.vtkIntArray() materArray.SetName("material label") materArray.SetNumberOfValues(nbelm) for i in range(0, nbelm): line = inFile.readline().split() n1 = int(line[1]) - 1 n2 = int(line[2]) - 1 n3 = int(line[3]) - 1 n4 = int(line[4]) - 1 tetra = vtk.vtkTetra() tetra.GetPointIds().SetId(0, n1) tetra.GetPointIds().SetId(1, n2) tetra.GetPointIds().SetId(2, n3) tetra.GetPointIds().SetId(3, n4) ugrid.InsertNextCell(tetra.GetCellType(), tetra.GetPointIds()) try: materArray.SetValue(i, int(line[5])) except: # no material label materArray.SetValue(i, 1) ugrid.GetCellData().AddArray(materArray) inFile.close() return ugrid
def TestDataType(dataType, reader, writer, ext, numTris, useSubdir=False): s = GetSource(dataType) filename = VTK_TEMP_DIR + "/%s.p%s" % (dataType, ext) writer.SetInputConnection(s.GetOutputPort()) npieces = 16 writer.SetNumberOfPieces(npieces) pperrank = npieces // nranks start = pperrank * rank end = start + pperrank - 1 writer.SetStartPiece(start) writer.SetEndPiece(end) writer.SetFileName(filename) if useSubdir: writer.SetUseSubdirectory(True) #writer.SetDataModeToAscii() writer.Write() if contr: contr.Barrier() reader.SetFileName(filename) cf = vtk.vtkContourFilter() cf.SetValue(0, 130) cf.SetComputeNormals(0) cf.SetComputeGradients(0) cf.SetInputConnection(reader.GetOutputPort()) cf.UpdateInformation() cf.GetOutputInformation(0).Set(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_NUMBER_OF_PIECES(), nranks) cf.GetOutputInformation(0).Set(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_PIECE_NUMBER(), rank) cf.Update() ntris = cf.GetOutput().GetNumberOfCells() da = vtk.vtkIntArray() da.InsertNextValue(ntris) da2 = vtk.vtkIntArray() da2.SetNumberOfTuples(1) contr.AllReduce(da, da2, vtk.vtkCommunicator.SUM_OP) if rank == 0: print(da2.GetValue(0)) import os os.remove(filename) for i in range(npieces): if not useSubdir: os.remove(VTK_TEMP_DIR + "/%s_%d.%s" % (dataType, i, ext)) else: os.remove(VTK_TEMP_DIR + "/%s/%s_%d.%s" %(dataType, dataType, i, ext)) assert da2.GetValue(0) == numTris
def main(): view = vtk.vtkContextView() table = vtk.vtkTable() arrMonth = vtk.vtkIntArray() arrMonth.SetName("Month") arr2008 = vtk.vtkIntArray() arr2008.SetName("2008") arr2009 = vtk.vtkIntArray() arr2009.SetName("2009") arr2010 = vtk.vtkIntArray() arr2010.SetName("2010") table.AddColumn(arrMonth) table.AddColumn(arr2008) table.AddColumn(arr2009) table.AddColumn(arr2010) table.SetNumberOfRows(12) for i in range(12): table.SetValue(i, 0, i + 1) table.SetValue(i, 1, data_2008[i]) table.SetValue(i, 2, data_2009[i]) table.SetValue(i, 3, data_2010[i]) chart = vtk.vtkChartXY() line = chart.AddPlot(vtk.vtkChart.BAR) line.SetInputData(table, 0, 1) line.SetColor(0.0, 1.0, 0.0) line = chart.AddPlot(vtk.vtkChart.BAR) line.SetInputData(table, 0, 2) line.SetColor(1.0, 0.0, 0.0) line = chart.AddPlot(vtk.vtkChart.BAR) line.SetInputData(table, 0, 3) line.SetColor(0.0, 0.0, 1.0) view.GetScene().AddItem(chart) view.GetRenderer().SetBackground(1.0, 1.0, 1.0) view.GetRenderWindow().SetSize(1200, 1000) view.GetRenderWindow().Render() winToImageFilter = vtk.vtkWindowToImageFilter() winToImageFilter.SetInput(view.GetRenderWindow()) winToImageFilter.Update() writer = vtk.vtkPNGWriter() writer.SetFileName("./test.png") writer.SetInputData(winToImageFilter.GetOutput()) writer.Write()
def loadActorsFromFile(self): global show_height, show_width file1 = open(self.bouttons_src) for line_i in file1: list_i = line_i.strip().split(' ') line_index = int(list_i[0]) slice_index = int(list_i[1]) x1, y1, z1 = self.lines[line_index][slice_index][2:5] x0 = int(x1 * 10 / 3 - show_width / 2) y0 = int(y1 * 10 / 3 - show_height / 2) x = float(list_i[2]) y = float(list_i[3]) z = float(list_i[4]) index_array = vtk.vtkIntArray() index_array.SetNumberOfComponents(1) index_array.InsertNextValue(line_index) index_array.InsertNextValue(slice_index) location_array = vtk.vtkFloatArray() location_array.SetNumberOfComponents(3) location_array.InsertNextTupleValue((x, y, z)) isNewArray = vtk.vtkIntArray() isNewArray.SetNumberOfComponents(1) isNewArray.InsertNextValue(0) index_array.SetName('Indices') location_array.SetName('Locations') isNewArray.SetName('IsNew') actor1 = MyActor() actor1.maFieldData.AddArray(index_array) actor1.maFieldData.AddArray(location_array) actor1.maFieldData.AddArray(isNewArray) actor1.GetProperty().SetColor(255.0, 0, 255.0) sphere1 = vtk.vtkSphereSource() sphere1.SetCenter(x - x0, y - y0, 0) sphere1.SetRadius(self.sphere_radius_ren1) mapper1 = vtk.vtkPolyDataMapper() mapper1.SetInputConnection(sphere1.GetOutputPort()) actor1.SetMapper(mapper1) self.ren1_sphere_actors.AddItem(actor1) matrix1 = vtk.vtkMatrix4x4() actor1.SetVisibility(False) if self.ren1AssemblyList[line_index] is None: self.ren1AssemblyList[line_index] = [None] * len( self.lines[line_index]) if self.ren1AssemblyList[line_index][slice_index] is None: assembly1 = vtk.vtkAssemblyPath() self.ren1AssemblyList[line_index][slice_index] = assembly1 self.ren1AssemblyList[line_index][slice_index].AddNode( actor1, matrix1) self.ren1.AddActor(actor1) file1.close()
def loadActorsFromFile(self): global show_height, show_width file1 = open(self.bouttons_src) for line_i in file1: list_i = line_i.strip().split('\t') line_index = int(list_i[0]) slice_index = int(list_i[1]) x1, y1, z1 = self.lines[line_index][slice_index][2 : 5] x0 = int(x1 * 10 / 3 - show_width / 2) y0 = int(y1 * 10 / 3 - show_height / 2) x = float(list_i[2]) y = float(list_i[3]) z = float(list_i[4]) index_array = vtk.vtkIntArray() index_array.SetNumberOfComponents(1) index_array.InsertNextValue(line_index) index_array.InsertNextValue(slice_index) location_array = vtk.vtkFloatArray() location_array.SetNumberOfComponents(3) location_array.InsertNextTupleValue((x, y, z)) isNewArray = vtk.vtkIntArray() isNewArray.SetNumberOfComponents(1) isNewArray.InsertNextValue(0) index_array.SetName('Indices') location_array.SetName('Locations') isNewArray.SetName('IsNew') actor1 = MyActor() actor1.maFieldData.AddArray(index_array) actor1.maFieldData.AddArray(location_array) actor1.maFieldData.AddArray(isNewArray) actor1.GetProperty().SetColor(255.0, 0, 255.0) sphere1 = vtk.vtkSphereSource() sphere1.SetCenter(x - x0, y - y0, 0) sphere1.SetRadius(self.sphere_radius_ren1) mapper1 = vtk.vtkPolyDataMapper() mapper1.SetInputConnection(sphere1.GetOutputPort()) actor1.SetMapper(mapper1) self.ren1_sphere_actors.AddItem(actor1) matrix1 = vtk.vtkMatrix4x4() actor1.SetVisibility(False) if self.ren1AssemblyList[line_index] is None: self.ren1AssemblyList[line_index] = [None] * len(self.lines[line_index]) if self.ren1AssemblyList[line_index][slice_index] is None: assembly1 = vtk.vtkAssemblyPath() self.ren1AssemblyList[line_index][slice_index] = assembly1 self.ren1AssemblyList[line_index][slice_index].AddNode(actor1, matrix1) self.ren1.AddActor(actor1) file1.close()
def write_vtk(self, DX=2.0, DY=2.0, DZ=0.05): """Reads cell data from vals array and writes into a VTK file called 'Stratal_Arch.vti' and is a structure grid object. Spacing defaults are 2.0/2.0/0.05""" vtk_obj = vtkImageData() vtk_obj.SetSpacing(DX, DY, DZ) vtk_obj.SetDimensions(self.dims[0]+1, self.dims[1]+1, self.dims[2]+1) # Start writing from the top of the object to match output from Eclipse vtk_obj.SetOrigin(0, 0, self.dims[2]+1) array = vtkIntArray() array.SetName("Stratal Architecture") array.SetNumberOfComponents(1) for z in range(0, self.dims[2]): for y in range(0, self.dims[1]): for x in range(0, self.dims[0]): val = self.vals[x][y][z] array.InsertNextTuple1(val) vtk_obj.GetCellData().AddArray(array) vtk_f = vtkXMLImageDataWriter() vtk_f.SetFileName("Stratal_Arch.vti") vtk_f.SetInputData(vtk_obj) vtk_f.Write()
def AssignLabelToRoots(root_canal, surf, label_name): label_array = surf.GetPointData().GetArray(label_name) RC_BoundingBox = root_canal.GetPoints().GetBounds() x = (RC_BoundingBox[0] + RC_BoundingBox[1]) / 2 y = (RC_BoundingBox[2] + RC_BoundingBox[3]) / 2 z = (RC_BoundingBox[4] + RC_BoundingBox[5]) / 2 surfID = vtk.vtkOctreePointLocator() surfID.SetDataSet(surf) surfID.BuildLocator() labelID = vtk.vtkIntArray() labelID.SetNumberOfComponents(1) labelID.SetNumberOfTuples(root_canal.GetNumberOfPoints()) labelID.SetName(label_name) labelID.Fill(-1) for pid in range(labelID.GetNumberOfTuples()): ID = surfID.FindClosestPoint(x, y, z, vtk.reference(20)) labelID.SetTuple(pid, (int(label_array.GetTuple(ID)[0]), )) root_canal.GetPointData().AddArray(labelID) return root_canal
def write_boundary_edge_cells(self, edge_cell_ids): '''Write a PolyData surface containing the cells incident to boundary edges. This is for debugging. ''' cell_mask = vtk.vtkIntArray() cell_mask.SetNumberOfValues(num_cells) cell_mask.SetName("CellMask") for i in range(num_cells): cell_mask.SetValue(i, 0) surface.GetCellData().AddArray(cell_mask) for cell_id in edge_cell_ids: cell_mask.SetValue(cell_id, 1) thresh = vtk.vtkThreshold() thresh.SetInputData(surface) thresh.ThresholdBetween(1, 1) thresh.SetInputArrayToProcess( 0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_CELLS", "CellMask") thresh.Update() surfacefilter = vtk.vtkDataSetSurfaceFilter() surfacefilter.SetInputData(thresh.GetOutput()) surfacefilter.Update() edge_cells = surfacefilter.GetOutput() writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName("boundary_edge_cells.vtp") writer.SetInputData(edge_cells) writer.Write()
def _NcubeDataFrameToVTKArrays(df): from vtk import vtkStringArray, vtkIntArray, vtkFloatArray, vtkBitArray arrays = [] # Create columns for colname in df.columns: dtype = df[colname].dtype #print (colname, dtype) if dtype in ['O', 'str', 'datetime64']: vtk_arr = vtkStringArray() elif dtype in ['int64']: vtk_arr = vtkIntArray() elif dtype in ['float64']: vtk_arr = vtkFloatArray() elif dtype in ['bool']: vtk_arr = vtkBitArray() else: print('Unknown Pandas column type', dtype) vtk_arr = vtkStringArray() vtk_arr.SetNumberOfComponents(1) vtk_arr.SetName(colname) for val in df[colname]: # some different datatypes could be saved as strings if isinstance(vtk_arr, vtkStringArray): val = str(val) vtk_arr.InsertNextValue(val) arrays.append(vtk_arr) return arrays
def write_vtk(self, DX=2.0, DY=2.0, DZ=0.05): """Reads cell data from vals array and writes into a VTK file called 'Stratal_Arch.vti' and is a structure grid object. Spacing defaults are 2.0/2.0/0.05""" vtk_obj = vtkImageData() vtk_obj.SetSpacing(DX, DY, DZ) vtk_obj.SetDimensions(self.dims[0] + 1, self.dims[1] + 1, self.dims[2] + 1) # Start writing from the top of the object to match output from Eclipse vtk_obj.SetOrigin(0, 0, self.dims[2] + 1) array = vtkIntArray() array.SetName("Stratal Architecture") array.SetNumberOfComponents(1) for z in range(0, self.dims[2]): for y in range(0, self.dims[1]): for x in range(0, self.dims[0]): val = self.vals[x][y][z] array.InsertNextTuple1(val) vtk_obj.GetCellData().AddArray(array) vtk_f = vtkXMLImageDataWriter() vtk_f.SetFileName("Stratal_Arch.vti") vtk_f.SetInputData(vtk_obj) vtk_f.Write()
def _NCubeGeoDataFrameRowToVTKArrays(items): #vtkPolyData, vtkAppendPolyData, vtkPoints, vtkCellArray, from vtk import vtkStringArray, vtkIntArray, vtkFloatArray, vtkBitArray from shapely.geometry.base import BaseGeometry, BaseMultipartGeometry vtk_row = [] for (key, value) in items.items(): #print (key,value) # define attribute as array if isinstance(value, (BaseMultipartGeometry)): #print ('BaseMultipartGeometry') continue elif isinstance(value, (BaseGeometry)): #print ('BaseGeometry') continue elif isinstance(value, (int)): vtk_arr = vtkIntArray() elif isinstance(value, (float)): vtk_arr = vtkFloatArray() elif isinstance(value, (bool)): vtk_arr = vtkBitArray() else: # some different datatypes could be saved as strings value = _str(value) vtk_arr = vtkStringArray() vtk_arr.SetNumberOfComponents(1) vtk_arr.SetName(key) vtk_row.append((vtk_arr, value)) return vtk_row
def ndarray_to_vtkarray(colors, radius, nbat): # define the colors color_scalars = vtk.vtkFloatArray() for c in colors: color_scalars.InsertNextValue(c) color_scalars.SetName("colors") # some radii radius_scalars = vtk.vtkFloatArray() for r in radius: radius_scalars.InsertNextValue(r) radius_scalars.SetName("radius") # the original index index_scalars = vtk.vtkIntArray() for i in range(nbat): index_scalars.InsertNextValue(i) radius_scalars.SetName("index") scalars = vtk.vtkFloatArray() scalars.SetNumberOfComponents(3) scalars.SetNumberOfTuples(radius_scalars.GetNumberOfTuples()) scalars.CopyComponent(0, radius_scalars ,0 ) scalars.CopyComponent(1, color_scalars ,0 ) scalars.CopyComponent(2, index_scalars ,0 ) scalars.SetName("scalars") return scalars
def get_sgrid_map(): """ Create the structured grid of the map """ map_grid = vtk.vtkStructuredGrid() points = vtk.vtkPoints() coordinate_texture = vtk.vtkFloatArray() coordinate_texture.SetNumberOfComponents(2) scalars = vtk.vtkIntArray() left = max(TOP_LEFT[1], BOTTOM_LEFT[1]) top = min(TOP_LEFT[0], TOP_RIGHT[0]) data_map = filter_data_map() for i, row in enumerate(data_map): for j, altitude in enumerate(row): latitude = top - i * delta_degree longitude = left + j * delta_degree points.InsertNextPoint( coordinate_earth(latitude, longitude, altitude)) l, m = get_texture_coord(latitude, longitude) coordinate_texture.InsertNextTuple((l, m)) scalars.InsertNextValue(altitude) map_grid.SetPoints(points) dim_y, dim_x = data_map.shape map_grid.SetDimensions(dim_x, dim_y, 1) map_grid.GetPointData().SetTCoords(coordinate_texture) map_grid.GetPointData().SetScalars(scalars) return map_grid
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 createTrail(ts): Points = vtk.vtkPoints() id_array = vtk.vtkIntArray() #id_array.SetNumberofComponents(1) id_array.SetName("haloid") phi_array = vtk.vtkDoubleArray() phi_array.SetName("phi") for i in range(0,ts+1): px,py,pz,phid,pphi = readParticle(i) for j in range(0,len(px)): Points.InsertNextPoint(px[j],py[j],pz[j]) id_array.InsertNextTuple1(phid[j]) phi_array.InsertNextTuple1(pphi[j]) polydata = vtk.vtkPolyData() polydata.SetPoints(Points) polydata.GetPointData().AddArray(id_array) polydata.GetPointData().AddArray(phi_array) if vtk.VTK_MAJOR_VERSION <= 5: polydata.Update() outputFile = "/home/subhashis/VisData/merger_trees/particleTrail/time" + str(ts) + ".vtp" writer = vtk.vtkXMLPolyDataWriter(); writer.SetFileName(outputFile); if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(polydata) else: writer.SetInputData(polydata) writer.Write() print "Done generating output for time %d" %ts
def create_labels(graph, label_nodes, labels=[], priorities=[]): label_points = vtk.vtkPoints() label_str = vtk.vtkStringArray() label_str.SetName('Labels') for ii, n in enumerate(label_nodes): label_points.InsertNextPoint( (graph.node[n]['x'], graph.node[n]['y'], graph.node[n]['z'])) if len(labels) == len(label_nodes): label = str(labels[ii]) else: label = str(n) label_str.InsertNextValue(label) label_polydata = vtk.vtkPolyData() label_polydata.SetPoints(label_points) label_polydata.GetPointData().AddArray(label_str) hierarchy = vtk.vtkPointSetToLabelHierarchy() hierarchy.SetLabelArrayName(label_str.GetName()) if (len(priorities) > 0) and (len(priorities) == len(label_nodes)): parray = vtk.vtkIntArray() parray.SetName('Priorities') for priority in priorities: parray.InsertNextValue(priority) hierarchy.SetPriorityArrayName(parray.GetName()) label_mapper = vtk.vtkLabelPlacementMapper() label_mapper.SetInputConnection(hierarchy.GetOutputPort()) if vtk.VTK_MAJOR_VERSION <= 5: hierarchy.SetInput(label_polydata) else: hierarchy.SetInputData(label_polydata) label_actor = vtk.vtkActor2D() label_actor.SetMapper(label_mapper) return label_actor
def beginReplay(self, sequenceBrowserNode, endFrameIndex, tumorModelNode, leftViewNode, rightViewNode, tableNode): self.endFrameIndex = endFrameIndex self.sequenceBrowserNode = sequenceBrowserNode self.sequenceBrowserNode.SetPlaybackRateFps(9.5) self.sequenceBrowserNode.SetPlaybackActive(True) self.leftViewNode = leftViewNode self.rightViewNode = rightViewNode self.tumorModelNode = tumorModelNode self.tableNode = tableNode self.tableColumnIndices = vtk.vtkIntArray() self.tableColumnIndices.SetName("Index") self.tableColumnTime = vtk.vtkDoubleArray() self.tableColumnTime.SetName("Time (s)") self.tableColumnLeftMinimumX = vtk.vtkDoubleArray() self.tableColumnLeftMinimumX.SetName("Left View Minimum X Extent") self.tableColumnLeftMaximumX = vtk.vtkDoubleArray() self.tableColumnLeftMaximumX.SetName("Left View Maximum X Extent") self.tableColumnLeftMinimumY = vtk.vtkDoubleArray() self.tableColumnLeftMinimumY.SetName("Left View Minimum Y Extent") self.tableColumnLeftMaximumY = vtk.vtkDoubleArray() self.tableColumnLeftMaximumY.SetName("Left View Maximum Y Extent") self.tableColumnRightMinimumX = vtk.vtkDoubleArray() self.tableColumnRightMinimumX.SetName("Right View Minimum X Extent") self.tableColumnRightMaximumX = vtk.vtkDoubleArray() self.tableColumnRightMaximumX.SetName("Right View Maximum X Extent") self.tableColumnRightMinimumY = vtk.vtkDoubleArray() self.tableColumnRightMinimumY.SetName("Right View Minimum Y Extent") self.tableColumnRightMaximumY = vtk.vtkDoubleArray() self.tableColumnRightMaximumY.SetName("Right View Maximum Y Extent") self.timer = qt.QTimer() self.timer.setSingleShot(False) self.timer.setInterval(100) # Once every 10th of a second self.timer.connect('timeout()', self.onTimeout) self.timer.start()
def extract_cell_field_data(self, cell_shell_optimization=False): """ Extracts basic information about cell field :return: """ cell_type_array = vtk.vtkIntArray() cell_type_array.SetName("celltype") cell_type_array_int_addr = extract_address_int_from_vtk_object( cell_type_array) # Also get the CellId cell_id = vtk.vtkLongArray() cell_id.SetName("cellid") cell_id_int_addr = extract_address_int_from_vtk_object(cell_id) used_cell_types_list = self.field_extractor.fillCellFieldData3D( cell_type_array_int_addr, cell_id_int_addr, cell_shell_optimization) ret_val = { 'cell_type_array': cell_type_array, 'cell_id_array': cell_id, 'used_cell_types': used_cell_types_list } return ret_val
def get_vtk_data(self,geo): """Returns dictionary of VTK data arrays from rock types. The geometry object geo must be passed in.""" from vtk import vtkIntArray,vtkFloatArray,vtkCharArray arrays={'Block':{'Rock type index':vtkIntArray(),'Porosity':vtkFloatArray(), 'Permeability':vtkFloatArray(),'Name':vtkCharArray()},'Node':{}} vector_properties=['Permeability'] string_properties=['Name'] string_length=5 nele=geo.num_underground_blocks array_length={'Block':nele,'Node':0} for array_type,array_dict in arrays.items(): for name,array in array_dict.items(): array.SetName(name) if name in vector_properties: array.SetNumberOfComponents(3) array.SetNumberOfTuples(array_length[array_type]) elif name in string_properties: array.SetNumberOfComponents(string_length) array.SetNumberOfTuples(array_length[array_type]) else: array.SetNumberOfComponents(1) array.SetNumberOfValues(array_length[array_type]) natm=geo.num_atmosphere_blocks rindex=self.rocktype_indices[natm:] for i,ri in enumerate(rindex): arrays['Block']['Rock type index'].SetValue(i,ri) rt=self.rocktypelist[ri] arrays['Block']['Porosity'].SetValue(i,rt.porosity) k=rt.permeability arrays['Block']['Permeability'].SetTuple3(i,k[0],k[1],k[2]) for i,blk in enumerate(self.blocklist[natm:]): arrays['Block']['Name'].SetTupleValue(i,blk.name) return arrays
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 get_sphere_data(data, core_num, step): step_arr = vtk.vtkIntArray().NewInstance() step_arr.SetName("NumSends") step_arr.SetNumberOfComponents(1) step_arr.InsertValue(0, data[core_num][step]) return step_arr
def create_vtk_polydata(pos, attrs=[]): point_ids = vtk.vtkIdList() point_ids.SetNumberOfIds(len(pos)) for i in range(len(pos)): point_ids.InsertNextId(i) points = vtk.vtkPoints() for x in pos: points.InsertNextPoint(*x) polydata = vtk.vtkPolyData() polydata.SetPoints(points) for attr in attrs: attr_name, attr_type, attr_comp, attr_data = attr if attr_type == 'int': vtk_attr = vtk.vtkIntArray() elif attr_type == 'float': vtk_attr = vtk.vtkDoubleArray() else: raise Exception('attribute data type %s not supported' % attr_type) vtk_attr.SetNumberOfComponents(attr_comp) vtk_attr.SetName(attr_name) for x in attr_data: vtk_attr.InsertNextValue(x) polydata.GetPointData().AddArray(vtk_attr) return polydata
def execute_module(self): # get the vtkDICOMVolumeReader to try and execute self._reader.Update() # now get some metadata out and insert it in our output stream # first determine axis labels based on IOP #################### iop = self._reader.GetImageOrientationPatient() row = iop[0:3] col = iop[3:6] # the cross product (plane normal) based on the row and col will # also be in the LPH coordinate system norm = [0, 0, 0] vtk.vtkMath.Cross(row, col, norm) xl = misc_utils.major_axis_from_iop_cosine(row) yl = misc_utils.major_axis_from_iop_cosine(col) zl = misc_utils.major_axis_from_iop_cosine(norm) lut = {'L': 0, 'R': 1, 'P': 2, 'A': 3, 'F': 4, 'H': 5} if xl and yl and zl: # add this data as a vtkFieldData fd = self._reader.GetOutput().GetFieldData() axis_labels_array = vtk.vtkIntArray() axis_labels_array.SetName('axis_labels_array') for l in xl + yl + zl: axis_labels_array.InsertNextValue(lut[l]) fd.AddArray(axis_labels_array)
def _resolve_array_type(data): if isinstance(data, float): return vtk.vtkFloatArray() elif isinstance(data, int): return vtk.vtkIntArray() else: raise ValueError(f'Unsupported input data type: {type(data)}')
def __init__(self): VTKPythonAlgorithmBase.__init__(self, nInputPorts=1, inputType='vtkUnstructuredGrid', nOutputPorts=1, outputType='vtkUnstructuredGrid') self.selection_list = vtk.vtkIntArray() self.selection_node = vtk.vtkSelectionNode() self.selection = vtk.vtkSelection() self.ex = vtk.vtkExtractSelection() self.active_groups = set() self.active_types = set() self.visible_ids = set() self.visible_on = True self.selection_list.SetName('visible') self.selection_list.SetNumberOfValues(2) self.selection_list.SetValue(0, 1) self.selection_list.SetValue(1, 1) self.selection_node.SetContentType(vtk.vtkSelectionNode.THRESHOLDS) self.selection_node.SetSelectionList(self.selection_list) self.selection.AddNode(self.selection_node) self.ex.ReleaseDataFlagOn() self.ex.SetInputDataObject(1, self.selection)
def export2vts(self, filename): import vtk grid = self.info['grid'] # Set grid points points = vtk.vtkPoints() for z in range (grid[2]): for y in range (grid[1]): for x in range (grid[0]): points.InsertNextPoint( [x , y , z ] ) struGrid = vtk.vtkStructuredGrid() struGrid.SetDimensions( grid ) struGrid.SetPoints( points ) struGrid.Update() # Set point data grid_pt_num = struGrid.GetNumberOfPoints() array = vtk.vtkIntArray() array.SetNumberOfComponents(1) # this is 3 for a vector array.SetNumberOfTuples(grid_pt_num) array.SetName('MicrostructureID') matPoint = self.microstructure.reshape( [grid_pt_num] ) for i in range(grid_pt_num): array.SetValue(i, matPoint[i]) struGrid.GetPointData().AddArray(array) struGrid.Update() # Write output file outWriter = vtk.vtkXMLStructuredGridWriter() outWriter.SetDataModeToBinary() outWriter.SetCompressorTypeToZLib() outWriter.SetFileName( filename + '.vts' ) outWriter.SetInput(struGrid) outWriter.Update() outWriter.Write()
def vtkIntArray(it): """Makes a vtkIntArray from a Python iterable""" via = vtk.vtkIntArray() via.SetNumberOfTuples(len(it)) for idx,val in enumerate(it): via.SetValue(idx, int(val)) return via
def ExtractCylindricInterpolationVoronoiDiagram(cellId, pointId, cylinderRadius, voronoi, centerlines): isInside = 0 if (cellId == 0): cylinderTop = centerlines.GetPoint(pointId) cylinderCenter = centerlines.GetPoint(pointId - interpolationHalfSize) cylinderBottom = centerlines.GetPoint(pointId - interpolationHalfSize * 2) else: cylinderTop = centerlines.GetPoint(pointId) cylinderCenter = centerlines.GetPoint(pointId + interpolationHalfSize) cylinderBottom = centerlines.GetPoint(pointId + interpolationHalfSize * 2) interpolationDataset = vtk.vtkPolyData() interpolationDatasetPoints = vtk.vtkPoints() interpolationDatasetCellArray = vtk.vtkCellArray() maskArray = vtk.vtkIntArray() maskArray.SetNumberOfComponents(1) maskArray.SetNumberOfTuples(voronoi.GetNumberOfPoints()) maskArray.FillComponent(0, 0) for i in range(voronoi.GetNumberOfPoints()): point = voronoi.GetPoint(i) isInside = IsPointInsideInterpolationCylinder(point, cylinderTop, cylinderCenter, cylinderBottom, cylinderRadius) if (isInside == 1): maskArray.SetTuple1(i, 1) numberOfInterpolationPoints = ComputeNumberOfMaskedPoints(maskArray) radiusArray = vtk.vtkDoubleArray() radiusArray.SetNumberOfComponents(1) radiusArray.SetNumberOfTuples(numberOfInterpolationPoints) radiusArray.SetName(radiusArrayName) radiusArray.FillComponent(0, 0.0) count = 0 for i in range(voronoi.GetNumberOfPoints()): value = maskArray.GetTuple1(i) if (value == 1): interpolationDatasetPoints.InsertNextPoint(voronoi.GetPoint(i)) interpolationDatasetCellArray.InsertNextCell(1) interpolationDatasetCellArray.InsertCellPoint(count) radius = voronoi.GetPointData().GetArray( radiusArrayName).GetTuple1(i) radiusArray.SetTuple1(count, radius) count += 1 interpolationDataset.SetPoints(interpolationDatasetPoints) interpolationDataset.SetVerts(interpolationDatasetCellArray) interpolationDataset.GetPointData().AddArray(radiusArray) return interpolationDataset
def execute_module(self): # get the vtkDICOMVolumeReader to try and execute self._reader.Update() # now get some metadata out and insert it in our output stream # first determine axis labels based on IOP #################### iop = self._reader.GetImageOrientationPatient() row = iop[0:3] col = iop[3:6] # the cross product (plane normal) based on the row and col will # also be in the LPH coordinate system norm = [0,0,0] vtk.vtkMath.Cross(row, col, norm) xl = misc_utils.major_axis_from_iop_cosine(row) yl = misc_utils.major_axis_from_iop_cosine(col) zl = misc_utils.major_axis_from_iop_cosine(norm) lut = {'L' : 0, 'R' : 1, 'P' : 2, 'A' : 3, 'F' : 4, 'H' : 5} if xl and yl and zl: # add this data as a vtkFieldData fd = self._reader.GetOutput().GetFieldData() axis_labels_array = vtk.vtkIntArray() axis_labels_array.SetName('axis_labels_array') for l in xl + yl + zl: axis_labels_array.InsertNextValue(lut[l]) fd.AddArray(axis_labels_array)
def hierarchical(input_polydata, number_of_clusters=300, threshold=2, fcluster_threshold=0.4, number_of_jobs=3): """ This is just a test. This is only a test. Stay tuned.""" distance_matrix = \ _pairwise_distance_matrix(input_polydata, threshold, number_of_jobs) # convert to upper triangular [not needed] # (note should compute only this part.) #mask_matrix = numpy.ones(distance_matrix.shape) #mask_matrix = numpy.triu(mask_matrix) #distance_matrix_triu = distance_matrix(numpy.nonzero(mask_matrix)) z_link = scipy.cluster.hierarchy.linkage(distance_matrix) cluster_idx = scipy.cluster.hierarchy.fcluster(z_link, fcluster_threshold) cluster_colors = vtk.vtkIntArray() cluster_colors.SetName('ClusterNumber') output_polydata = input_polydata for lidx in range(0, output_polydata.GetNumberOfLines()): cluster_colors.InsertNextTuple1(cluster_idx[lidx]) output_polydata.GetCellData().AddArray(cluster_colors) output_polydata.GetCellData().SetActiveScalars('ClusterNumber') return output_polydata, cluster_idx
def _format_output_polydata(output_polydata, cluster_idx, color, embed): """ Output polydata with embedding colors, cluster numbers, and embedding coordinates. Cell data array names are: EmbeddingColor ClusterNumber EmbeddingCoordinate """ embed_colors = vtk.vtkUnsignedCharArray() embed_colors.SetNumberOfComponents(3) embed_colors.SetName('EmbeddingColor') cluster_colors = vtk.vtkIntArray() cluster_colors.SetName('ClusterNumber') embed_data = vtk.vtkFloatArray() embed_data.SetNumberOfComponents(embed.shape[1]) embed_data.SetName('EmbeddingCoordinate') for lidx in range(0, output_polydata.GetNumberOfLines()): embed_colors.InsertNextTuple3( color[lidx, 0], color[lidx, 1], color[lidx, 2]) cluster_colors.InsertNextTuple1(int(cluster_idx[lidx])) embed_data.InsertNextTupleValue(embed[lidx, :]) output_polydata.GetCellData().AddArray(embed_data) output_polydata.GetCellData().AddArray(cluster_colors) output_polydata.GetCellData().AddArray(embed_colors) output_polydata.GetCellData().SetActiveScalars('EmbeddingColor') return output_polydata
def _appendData(dataContainer, arrayName, valuesToInsert): values = np.array(valuesToInsert) if not dataContainer.HasArray(arrayName): if values.dtype == 'int64': array = vtk.vtkLongArray() elif values.dtype == 'int32': array = vtk.vtkIntArray() elif values.dtype == 'float64': array = vtk.vtkDoubleArray() elif values.dtype == 'float32': array = vtk.vtkFloatArray() else: raise RuntimeError('Unsupported data type ' + str(values.dtype)) array.SetName(arrayName) # Determine number of components if values.ndim == 1 or values.ndim == 0: array.SetNumberOfComponents(1) elif values.ndim > 1: array.SetNumberOfComponents(values.shape[1]) else: raise ValueError('Invalid value array dimension ' + str(values.shape)) dataContainer.AddArray(array) else: array = dataContainer.GetArray(arrayName) _insertIntoVTKArray(array, values)
def __init__(self): VTKPythonAlgorithmBase.__init__(self) self.SetNumberOfInputPorts(1) self.SetNumberOfOutputPorts(1) self.visible = True self.visible_selection = vtk.vtkIntArray() self.visible_selection.SetName("visible") self.visible_selection.InsertNextValue(1) self.visible_selection.InsertNextValue(1) self.selection_vis_node = vtk.vtkSelectionNode() self.selection_vis_node.SetContentType(vtk.vtkSelectionNode.THRESHOLDS) self.selection_vis_node.SetSelectionList(self.visible_selection) self.selection_vis = vtk.vtkSelection() self.selection_vis.AddNode(self.selection_vis_node) self.ex_vis = vtk.vtkExtractSelection() self.ex_vis.ReleaseDataFlagOn() self.ex_vis.SetInputDataObject(1, self.selection_vis) self._callbacks = []
def ndarray_to_vtkarray(colors, radius, nbat): # define the colours color_scalars = vtk.vtkFloatArray() color_scalars.SetNumberOfValues(colors.shape[0]) for i,c in enumerate(colors): color_scalars.SetValue(i,c) color_scalars.SetName("colors") # some radii radius_scalars = vtk.vtkFloatArray() radius_scalars.SetNumberOfValues(radius.shape[0]) for i,r in enumerate(radius): radius_scalars.SetValue(i,r) radius_scalars.SetName("radius") # the original index index_scalars = vtk.vtkIntArray() index_scalars.SetNumberOfValues(nbat) for i in range(nbat): index_scalars.SetValue(i,i) index_scalars.SetName("index") scalars = vtk.vtkFloatArray() scalars.SetNumberOfComponents(3) scalars.SetNumberOfTuples(radius_scalars.GetNumberOfTuples()) scalars.CopyComponent(0, radius_scalars ,0 ) scalars.CopyComponent(1, color_scalars ,0 ) scalars.CopyComponent(2, index_scalars ,0 ) scalars.SetName("scalars") return scalars
def selection_threshold(self): selection_threshold = vtk.vtkIntArray() selection_threshold.SetName("basic_shapes") selection_threshold.SetNumberOfComponents(1) if self._nodes: selection_threshold.InsertNextValue(vtk_globals.VTK_NODE) selection_threshold.InsertNextValue(vtk_globals.VTK_NODE) if self._points: selection_threshold.InsertNextValue(vtk_globals.VTK_VERTEX) selection_threshold.InsertNextValue(vtk_globals.VTK_VERTEX) if self._bars: selection_threshold.InsertNextValue(vtk_globals.VTK_LINE) selection_threshold.InsertNextValue(vtk_globals.VTK_LINE) if self._tris: selection_threshold.InsertNextValue(vtk_globals.VTK_TRI) selection_threshold.InsertNextValue(vtk_globals.VTK_TRI) if self._quads: selection_threshold.InsertNextValue(vtk_globals.VTK_QUAD) selection_threshold.InsertNextValue(vtk_globals.VTK_QUAD) if self._mpcs: selection_threshold.InsertNextValue(vtk_globals.VTK_POLY_LINE) selection_threshold.InsertNextValue(vtk_globals.VTK_POLY_LINE) return selection_threshold
def testObjectConstructor(self): """Construct from VTK object""" o = vtk.vtkIntArray() v = vtk.vtkVariant(o) self.assertEqual(v.GetType(), vtk.VTK_OBJECT) self.assertEqual(v.GetTypeAsString(), o.GetClassName()) self.assertEqual(v.ToVTKObject(), o)
def draw(self, gfxwindow, device): device.comment("Material Color") if config.dimension() == 2: themesh = self.who().resolve(gfxwindow) polygons = self.polygons(gfxwindow, themesh) # colorcache is a dictionary of colors keyed by Material. It # prevents us from having to call material.fetchProperty for # each element. colorcache = {} for polygon, material in zip(polygons, self.materials(gfxwindow, themesh)): if material is not None: try: # If material has been seen already, retrieve its color. color = colorcache[material] except KeyError: # This material hasn't been seen yet. try: colorprop = material.fetchProperty('Color') color = colorprop.color() except ooferror.ErrNoSuchProperty: color = None colorcache[material] = color if color is not None: device.set_fillColor(color) device.fill_polygon(primitives.Polygon(polygon)) elif config.dimension() == 3: # TODO 3D: clean up this code in general, perhaps the look # up table should be a member of the microstructure... themesh = self.who().resolve(gfxwindow).getObject() grid = themesh.skelgrid numCells = grid.GetNumberOfCells() # TODO 3D: will need to handle the creation and deletion of this array within canvas... materialdata = vtk.vtkIntArray() materialdata.SetNumberOfValues(numCells) grid.GetCellData().SetScalars(materialdata) lut = vtk.vtkLookupTable() colordict = {} for i in xrange(numCells): cat = themesh.elements[i].dominantPixel(themesh.MS) materialdata.SetValue(i,cat) mat = themesh.elements[i].material(themesh) if mat is not None: try: color = colordict[cat] except KeyError: colorprop = mat.fetchProperty('Color') color = colorprop.color() colordict[cat] = color lut.SetNumberOfColors(max(colordict.keys())+1) lut.SetTableRange(min(colordict.keys()), max(colordict.keys())) for i in colordict: color = colordict[i] if color is not None: lut.SetTableValue(i,color.getRed(),color.getGreen(),color.getBlue(),1) else: lut.SetTableValue(i,0,0,0,0) device.draw_unstructuredgrid_with_lookuptable(grid, lut, mode="cell", scalarbar=False)
def getActor(self): data1 = vtk.vtkFieldData() array1 = vtk.vtkIntArray() array1.SetNumberOfComponents(1) array1.InsertNextValue(1) array2 = vtk.vtkIntArray() array2.SetNumberOfComponents(1) array2.InsertNextValue(44) data1.AddArray(array1) data1.AddArray(array2) sphere = vtk.vtkSphereSource() mapper = vtk.vtkPolyDataMapper() actor = vtk.vtkActor() mapper.SetInput(sphere.GetOutput()) sphere.GetOutput().SetFieldData(data1) actor.SetMapper(mapper) return actor
def testVoidPointer(self): a = vtk.vtkIntArray() a.SetNumberOfTuples(1) a.SetValue(0, 1) b = vtk.vtkIntArray() b.SetNumberOfTuples(1) b.SetValue(0, 2) ptr = a.GetVoidPointer(0) # check the format _0123456789abcdef_p_void self.assertEqual(ptr[0:1], "_") self.assertEqual(ptr[-7:], "_p_void") address = int(ptr[1:-7], 16) # check that we can use the pointer b.SetVoidArray(ptr, 1, 1) self.assertEqual(b.GetValue(0), 1) a.SetValue(0, 10) self.assertEqual(b.GetValue(0), 10)
def save_one_file(infilename, outfilename): df1 = read_file( infilename ) if df1.shape[0]==0: return pts = vtk.vtkPoints() x = df1['COORX'] y = df1['COORY'] z = df1['COORZ'] tp = df1['ITYPE'] il = df1['ILAGR'] ex = df1['EXIST'] tt = df1['T'] pts.SetNumberOfPoints(df1.shape[0]) for j in range(df1.shape[0]): pts.SetPoint(j, (x.iloc[j],y.iloc[j],z.iloc[j])) types = vtk.vtkShortArray() types.SetNumberOfComponents(1) types.SetNumberOfTuples(pts.GetNumberOfPoints()) types.SetName('ITYPE') ilagr = vtk.vtkIntArray() ilagr.SetNumberOfComponents(1) ilagr.SetNumberOfTuples(pts.GetNumberOfPoints()) ilagr.SetName('ILAGR') exist = vtk.vtkShortArray() exist.SetNumberOfComponents(1) exist.SetNumberOfTuples(pts.GetNumberOfPoints()) exist.SetName('EXIST') T = vtk.vtkFloatArray() T.SetNumberOfComponents(1) T.SetNumberOfTuples(pts.GetNumberOfPoints()) T.SetName('T') for j in range(df1.shape[0]): types.SetTuple1(j, tp.iloc[j]) ilagr.SetTuple1(j, il.iloc[j]) exist.SetTuple1(j, ex.iloc[j]) T.SetTuple1(j, tt.iloc[j]) pd = vtk.vtkPolyData() pd.SetPoints(pts) pd.GetPointData().AddArray(types) pd.GetPointData().AddArray(ilagr) pd.GetPointData().AddArray(exist) pd.GetPointData().AddArray(T) wr= vtk.vtkXMLPolyDataWriter() wr.SetInputData(pd) wr.SetDataModeToBinary() wr.SetFileName(outfilename) wr.Write()
def testCollectionChild(self): #check that iteration is being inherited correctly dataArray = vtk.vtkIntArray() dataArrayCollection = vtk.vtkDataArrayCollection() dataArrayCollection.AddItem(dataArray) self.assertEqual([obj for obj in dataArrayCollection], [dataArray])
def testDefaultPointer(self): """Test a POD pointer arg with default value of 0.""" a = vtk.vtkIntArray() a.SetNumberOfComponents(3) # pass an int pointer arg, expect something back inc = [0] vtk.vtkImagePointDataIterator.GetVoidPointer(a, 0, inc) self.assertEqual(inc, [3]) # do not pass the pointer arg, default value 0 is passed vtk.vtkImagePointDataIterator.GetVoidPointer(a, 0)
def _Execute(self, *args): assert isinstance(self.Value, int) assert isinstance(self.Iolet, Iolet) input = self.GetPolyDataInput() clipped = self._Clip(input) clipped.BuildLinks(0) newPoints = vtkPoints() newPoints.DeepCopy(clipped.GetPoints()) newPolys = vtkCellArray() newPolys.DeepCopy(clipped.GetPolys()) newData = vtkIntArray() newData.DeepCopy(clipped.GetCellData().GetScalars()) boundaryExtractor = vtkvmtkPolyDataBoundaryExtractor() boundaryExtractor.SetInputData(clipped) boundaryExtractor.Update() boundaries = boundaryExtractor.GetOutput() boundariesPointIdMap = boundaries.GetPointData().GetScalars() for i in xrange(boundaries.GetNumberOfCells()): boundary = vtkPolyLine.SafeDownCast(boundaries.GetCell(i)) barycentre = [0., 0., 0.] vtkvmtkBoundaryReferenceSystems.ComputeBoundaryBarycenter( boundary.GetPoints(), barycentre) barycentreId = newPoints.InsertNextPoint(barycentre) numberOfBoundaryPoints = boundary.GetNumberOfPoints() trianglePoints = vtkIdList() trianglePoints.SetNumberOfIds(3) for j in xrange(numberOfBoundaryPoints): trianglePoints.SetId(0, boundariesPointIdMap.GetValue(boundary.GetPointId(j))) trianglePoints.SetId(1, barycentreId) trianglePoints.SetId(2, boundariesPointIdMap.GetValue(boundary.GetPointId((j + 1) % numberOfBoundaryPoints)) ) newPolys.InsertNextCell(trianglePoints) newData.InsertNextValue(self.Value) continue continue output = self.GetPolyDataOutput() output.SetPoints(newPoints) output.SetPolys(newPolys) output.GetCellData().SetScalars(newData) return
def get_dataset(pa=None,ca=None): sphere = vtk.vtkSphereSource() sphere.Update() data = sphere.GetOutputDataObject(0) data.GetPointData().Initialize() data.GetCellData().Initialize() if pa: array = vtk.vtkIntArray() array.SetName(pa) array.SetNumberOfTuples(data.GetNumberOfPoints()) data.GetPointData().AddArray(array) if ca: array = vtk.vtkIntArray() array.SetName(ca) array.SetNumberOfTuples(data.GetNumberOfCells()) data.GetCellData().AddArray(array) return data
def get_new_vtk_data_array(self, scalar_dtype): if scalar_dtype == np.int32: return vtk.vtkIntArray() if scalar_dtype == np.ushort: return vtk.vtkUnsignedShortArray() if scalar_dtype == np.ubyte: return vtk.vtkUnsignedCharArray() if scalar_dtype == np.float32: return vtk.vtkFloatArray() print >> sys.stderr, '[ERROR] ' + str(scalar_dtype) + ' is not supported ' return None
def testPythonRTTI(self): """Test the python isinstance and issubclass methods """ o = vtkCustomObject() d = vtk.vtkIntArray() self.assertEqual(True, isinstance(o, vtk.vtkObjectBase)) self.assertEqual(True, isinstance(d, vtk.vtkObjectBase)) self.assertEqual(True, isinstance(o, vtkCustomObject)) self.assertEqual(False, isinstance(d, vtkCustomObject)) self.assertEqual(False, isinstance(o, vtk.vtkDataArray)) self.assertEqual(True, issubclass(vtkCustomObject, vtk.vtkObject)) self.assertEqual(False, issubclass(vtk.vtkObject, vtkCustomObject)) self.assertEqual(False, issubclass(vtkCustomObject, vtk.vtkDataArray))
def ExtractCylindricInterpolationVoronoiDiagram(cellId,pointId,cylinderRadius,voronoi,centerlines): isInside = 0 if (cellId == 0): cylinderTop = centerlines.GetPoint(pointId) cylinderCenter = centerlines.GetPoint(pointId-interpolationHalfSize) cylinderBottom = centerlines.GetPoint(pointId-interpolationHalfSize*2) else: cylinderTop = centerlines.GetPoint(pointId) cylinderCenter = centerlines.GetPoint(pointId+interpolationHalfSize) cylinderBottom = centerlines.GetPoint(pointId+interpolationHalfSize*2) interpolationDataset = vtk.vtkPolyData() interpolationDatasetPoints = vtk.vtkPoints() interpolationDatasetCellArray = vtk.vtkCellArray() maskArray = vtk.vtkIntArray() maskArray.SetNumberOfComponents(1) maskArray.SetNumberOfTuples(voronoi.GetNumberOfPoints()) maskArray.FillComponent(0,0) for i in range(voronoi.GetNumberOfPoints()): point = voronoi.GetPoint(i) isInside = IsPointInsideInterpolationCylinder(point,cylinderTop,cylinderCenter,cylinderBottom,cylinderRadius) if (isInside == 1): maskArray.SetTuple1(i,1) numberOfInterpolationPoints = ComputeNumberOfMaskedPoints(maskArray) radiusArray = vtk.vtkDoubleArray() radiusArray.SetNumberOfComponents(1) radiusArray.SetNumberOfTuples(numberOfInterpolationPoints) radiusArray.SetName(radiusArrayName) radiusArray.FillComponent(0,0.0) count = 0 for i in range(voronoi.GetNumberOfPoints()): value = maskArray.GetTuple1(i) if (value == 1): interpolationDatasetPoints.InsertNextPoint(voronoi.GetPoint(i)) interpolationDatasetCellArray.InsertNextCell(1) interpolationDatasetCellArray.InsertCellPoint(count) radius = voronoi.GetPointData().GetArray(radiusArrayName).GetTuple1(i) radiusArray.SetTuple1(count,radius) count +=1 interpolationDataset.SetPoints(interpolationDatasetPoints) interpolationDataset.SetVerts(interpolationDatasetCellArray) interpolationDataset.GetPointData().AddArray(radiusArray) return interpolationDataset
def testCallUnboundMethods(self): """Test calling an unbound method in an overridded method""" o = vtkCustomObject() a = vtk.vtkIntArray() o.SetExtraObject(a) a.Modified() # GetMTime should return a's mtime self.assertEqual(o.GetMTime(), a.GetMTime()) # calling the vtkObject mtime should give a lower MTime self.assertNotEqual(o.GetMTime(), vtk.vtkObject.GetMTime(o)) # another couple quick unbound method check vtk.vtkDataArray.InsertNextTuple1(a, 2) self.assertEqual(a.GetTuple1(0), 2)
def Execute(self): if (self.OutputFileName == ''): self.PrintError('Error: no OutputFileName.') if self.TimeStepsOnly: self.GenerateTimeStepsFile() return if self.Mesh == None: self.PrintError('Error: no Mesh.') self.NormalizationTransform = vtk.vtkTransform() if self.UseCellDefinedEntities == 1: entityIds = [] entityNames = [] if self.NormalizationEntityId != -1: entityIds.append(self.NormalizationEntityId) entityNames.append('NormalizationEntity') self.NormalizationEntity = 'NormalizationEntity' for inletEntityId in self.InletEntityIds: entityIds.append(inletEntityId) entityNames.append('InletEntity'+str(inletEntityId)) self.InletEntities.append('InletEntity'+str(inletEntityId)) for reverseInletEntityId in self.ReverseInlets: self.ReverseInletEntities.append('InletEntity'+str(reverseInletEntityId)) if self.OutletEntityId != -1: entityIds.append(self.OutletEntityId) entityNames.append('OutletEntity') self.OutletEntity = 'OutletEntity' if self.WallEntityId != -1: entityIds.append(self.WallEntityId) entityNames.append('WallEntity') self.WallEntity = 'WallEntity' if self.HistoryEntityId != -1: entityIds.append(self.HistoryEntityId) entityNames.append('HistoryEntity') self.HistoryEntity = 'HistoryEntity' for i in range(len(entityIds)): entityId = entityIds[i] entityName = entityNames[i] pointEntityArray = vtk.vtkIntArray() pointEntityArray.SetName(entityName) self.BuildPointEntityArray(entityId,pointEntityArray) self.Mesh.GetPointData().AddArray(pointEntityArray) self.GenerateTetrInFile()
def addSphereActor(self, x1, y1, z1): x0, y0, z0 = self.roi_list[self.image_slice] index_array = vtk.vtkIntArray() index_array.SetNumberOfComponents(1) index_array.InsertNextValue(self.line_index) index_array.InsertNextValue(self.image_slice) index_array.SetName('Indices') location_array = vtk.vtkDoubleArray() location_array.SetName('Locations') location_array.SetNumberOfComponents(3) location_array.InsertNextTupleValue((x0 + x1, y0 + y1, z0 + z1)) isNewArray = vtk.vtkIntArray() isNewArray.SetName('IsNew') isNewArray.SetNumberOfComponents(1) isNewArray.InsertNextValue(1) new_sphere = vtk.vtkSphereSource() new_sphere.SetRadius(self.sphere_radius_ren1) new_sphere.SetCenter(x1, y1, 0) new_mapper = vtk.vtkPolyDataMapper() new_mapper.SetInputConnection(new_sphere.GetOutputPort()) new_sphere_actor = MyActor() matrix1 = vtk.vtkMatrix4x4() new_sphere_actor.maFieldData.AddArray(index_array) new_sphere_actor.maFieldData.AddArray(location_array) new_sphere_actor.maFieldData.AddArray(isNewArray) self.bouttons_spheres.append(new_sphere_actor) new_sphere_actor.SetMapper(new_mapper) new_sphere_actor.GetProperty().SetColor(255.0, 0, 255.0) self.ren1_sphere_actors.AddItem(new_sphere_actor) self.slice_assembly.AddNode(new_sphere_actor, matrix1) if self.last_added_sphere_ren1 is None: self.toolBarAction4.setEnabled(True) else: self.newed_spheres.AddItem(self.last_added_sphere_ren1) self.last_added_sphere_ren1 = new_sphere_actor self.ren1.AddActor(new_sphere_actor) self.slice_assembly.Modified() self.ren1.GetRenderWindow().Render()
def testHash(self): """Use a variant as a dict key""" d = {} # doubles, ints, srings, all hash as strings d[vtk.vtkVariant(1.0)] = 'double' d[vtk.vtkVariant(1)] = 'int' self.assertEqual(d[vtk.vtkVariant('1')], 'int') # strings and unicode have the same hash d[vtk.vtkVariant(u's')] = 'unicode' d[vtk.vtkVariant('s')] = 'string' self.assertEqual(d[vtk.vtkVariant(u's')], 'string') # every vtkObject is hashed by memory address o1 = vtk.vtkIntArray() o2 = vtk.vtkIntArray() d[vtk.vtkVariant(o1)] = 'vtkIntArray1' d[vtk.vtkVariant(o2)] = 'vtkIntArray2' self.assertEqual(d[vtk.vtkVariant(o1)], 'vtkIntArray1') self.assertEqual(d[vtk.vtkVariant(o2)], 'vtkIntArray2') # invalid variants all hash the same d[vtk.vtkVariant()] = 'invalid' self.assertEqual(d[vtk.vtkVariant()], 'invalid')