def read_vtk(self, to_polydata=False): # Read the source file. reader = vtk.vtkDataReader() reader.SetFileName('.'.join([self.filename, self.input_type])) reader.Update() print('Case ID : {}, input type: {}'.format(self.filename, self.input_type)) if reader.IsFileUnstructuredGrid(): print('Reading Unstructured Grid...') reader = vtk.vtkUnstructuredGridReader() elif reader.IsFilePolyData(): print('Reading Polygonal Mesh...') reader = vtk.vtkPolyDataReader() elif reader.IsFileStructuredGrid(): print('Reading Structured Grid...') reader = vtk.vtkStructuredGridReader() elif reader.IsFileStructuredPoints(): print('Reading Structured Points...') reader = vtk.vtkStructuredPointsReader() elif reader.IsFileRectilinearGrid(): print('Reading Rectilinear Grid...') reader = vtk.vtkRectilinearGridReader() else: print('Data format unknown...') reader.SetFileName(self.filename + '.' + self.input_type) reader.Update() # Needed because of GetScalarRange scalar_range = reader.GetOutput().GetScalarRange() if to_polydata and not reader.IsFilePolyData(): print('Transform to Polygonal Mesh') reader = self.unstructured_grid_to_poly_data(reader) print('Scalar range: \n{}'.format(scalar_range)) return reader, scalar_range
def main(): filename = get_program_parameters() # Read the file reader = vtk.vtkStructuredGridReader() reader.SetFileName(filename) reader.Update() geometry_filter = vtk.vtkStructuredGridGeometryFilter() geometry_filter.SetInputConnection(reader.GetOutputPort()) geometry_filter.Update() # Visualize mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(geometry_filter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window_interactor = vtk.vtkRenderWindowInteractor() render_window_interactor.SetRenderWindow(render_window) renderer.AddActor(actor) named_colors = vtk.vtkNamedColors() renderer.SetBackground(named_colors.GetColor3d("Green")) render_window.Render() render_window_interactor.Start()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkStructuredGridReader(), 'Reading vtkStructuredGrid.', (), ('vtkStructuredGrid',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def loadStructuredGrid(filename): # not tested '''Load a vtkStructuredGrid object from file and return a vtkActor.''' reader = vtk.vtkStructuredGridReader() reader.SetFileName(filename) reader.Update() gf = vtk.vtkStructuredGridGeometryFilter() gf.SetInputConnection(reader.GetOutputPort()) gf.Update() return Actor(gf.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkStructuredGridReader(), 'Reading vtkStructuredGrid.', (), ('vtkStructuredGrid', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def chooseReader(self, file_format, vtk_dataset_type=None): """ Return a reader based on file_format and possibly vtk_dataset_type. @param vtk_dataset_type, None or one of the VTK_DATASET_TYPES """ # Handle .ply files. if file_format == 'ply': return vtk.vtkPLYReader() # Handle .vtk files. if vtk_dataset_type == 'STRUCTURED_GRID': return vtk.vtkStructuredGridReader() elif vtk_dataset_type == 'POLYDATA': return vtk.vtkPolyDataReader() elif vtk_dataset_type == 'UNSTRUCTURED_GRID': return vtk.vtkUnstructuredGridReader()
def extract_data(self): """ Extract the data from the VTK file using the python-vtk library The data is passed to numpy arrays for better manipulation """ # Check the type of file to load it according to its grid structure # which was specified when calling the class These dictionary entries # return the corresponding VTK Reader functions, so they can be easily # called according to the class argument reader_type = { 'XMLUnstructuredGrid': lambda: vtk.vtkXMLUnstructuredGridReader(), 'XMLStructuredGrid': lambda: vtk.vtkXMLStructuredGridReader(), 'UnstructuredGrid': lambda: vtk.vtkUnstructuredGridReader(), 'StructuredGrid': lambda: vtk.vtkStructuredGridReader(), } if self.vtkfiletype.startswith('XML'): # Load the vtk file from the input file self.reader = reader_type[self.vtkfiletype]() self.reader.SetFileName(self.vtk_file) else: # Load the vtk file from the input file self.reader = reader_type[self.vtkfiletype]() self.reader.SetFileName(self.vtk_file) # For Non XML vtk files: self.reader.ReadAllVectorsOn() self.reader.ReadAllScalarsOn() self.reader.Update() # Get the coordinates of the nodes in the mesh nodes_vtk_array = self.reader.GetOutput().GetPoints().GetData() # Get The vector field (data of every node) vf_vtk_array = self.reader.GetOutput().GetPointData().GetArray(0) # Transform the coordinates of the nodes to a Numpy array and # save them to the corresponding class objects nodes_numpy_array = vtk_to_numpy(nodes_vtk_array) self.x, self.y, self.z = (nodes_numpy_array[:, 0], nodes_numpy_array[:, 1], nodes_numpy_array[:, 2] ) # Transform the magnetisation data to a Numpy array and save vf_numpy_array = vtk_to_numpy(vf_vtk_array) self.vf = vf_numpy_array
def create_reader (self): "Create the corresponding reader." debug ("In VtkDataReader::create_reader ()") # set up the reader if self.file_name == "": raise IOError, "No filename specifed for the data handler!" self.grid_type = find_data_type (self.file_name) if self.grid_type == "STRUCTURED_GRID": self.reader = vtk.vtkStructuredGridReader () elif self.grid_type == "STRUCTURED_POINTS": self.reader = vtk.vtkStructuredPointsReader () elif self.grid_type == "RECTILINEAR_GRID": self.reader = vtk.vtkRectilinearGridReader () elif self.grid_type == "POLYDATA": self.reader = vtk.vtkPolyDataReader () elif self.grid_type == "UNSTRUCTURED_GRID": self.reader = vtk.vtkUnstructuredGridReader ()
def load_object_3d(self, path, viewer_3d): generic_reader = vtkDataReader() generic_reader.SetFileName(path) if generic_reader.OpenVTKFile() and generic_reader.ReadHeader(): if generic_reader.IsFileStructuredPoints(): raise Exception("Cannot read VTK structured points") elif generic_reader.IsFilePolyData(): reader = vtkPolyDataReader() reader.SetFileName(path) object_3d = Object3D(reader.GetOutput(), path) elif generic_reader.IsFileStructuredGrid(): reader = vtkStructuredGridReader() reader.SetFileName(path) object_3d = Object3D(reader.GetOutput(), path) elif generic_reader.IsFileUnstructuredGrid(): reader = vtkUnstructuredGridReader() reader.SetFileName(path) object_3d = Object3D(reader.GetOutput(), path) elif generic_reader.IsFileRectilinearGrid(): reader = vtkRectilinearGridReader() reader.SetFileName(path) object_3d = Object3D(reader.GetOutput(), path) else: raise Exception("Cannot read VTK file containing type %i" % generic_reader.GetFileType()) viewer_3d.objects_3d.append(object_3d) else: importer = vtkVRMLImporter() importer.SetFileName(path) importer.Update() actors = importer.GetRenderer().GetActors() number_of_actors = actors.GetNumberOfItems() actors.InitTraversal() for i in range(number_of_actors): actor = actors.GetNextItem() object_3d = Object3D(path + ", %i" % i) object_3d.actor.SetProperty(actor.GetProperty()) object_3d.actor.SetMapper(actor.GetMapper()) viewer_3d.objects_3d.append(object_3d)
def solve(): print(diffusion.solve(0.0, 0.25, 0.5, 1.0)) reader = vtkStructuredGridReader() reader.SetFileName('../sol/solution0.vtk') reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() dim = data.GetDimensions() vec = list(dim) vec = [i-1 for i in dim] vec.append(3) x = np.zeros(data.GetNumberOfPoints()) y = np.zeros(data.GetNumberOfPoints()) z = np.zeros(data.GetNumberOfPoints()) c = data.GetPointData().GetArray('Val') for i in range(data.GetNumberOfPoints()): x[i], y[i], z[i] = data.GetPoint(i) x = x.reshape(dim[0:2], order='F') y = y.reshape(dim[0:2], order='F') z = z.reshape(dim[0:2], order='F') c = VN.vtk_to_numpy(data.GetPointData().GetArray('Val')) c = c.reshape(dim[0:2], order='F') fig = Figure() axis = fig.add_subplot(111) # TODO: Set equal aspect ratio axes # axis.set_aspect('equal') axis.contourf(x, y, c) canvas = FigureCanvas(fig) output = io.BytesIO() canvas.print_png(output) fig.savefig('./static/img/img.png') return output
def _load_file(self, filename): """ Load a structured grid from a file. The file extension will select the type of reader to use. A .vtk extension will use the legacy reader, while .vts will select the VTK XML reader. Parameters ---------- filename : str Filename of grid to be loaded. """ filename = os.path.abspath(os.path.expanduser(filename)) # check file exists if not os.path.isfile(filename): raise Exception('{} does not exist'.format(filename)) # Check file extention if '.vts' in filename: legacy_writer = False elif '.vtk' in filename: legacy_writer = True else: raise Exception( 'Extension should be either ".vts" (xml) or ".vtk" (legacy)') # Create reader if legacy_writer: reader = vtk.vtkStructuredGridReader() else: reader = vtk.vtkXMLStructuredGridReader() # load file to self reader.SetFileName(filename) reader.Update() grid = reader.GetOutput() self.ShallowCopy(grid)
def readSGrid( filename, verbose=0): mypy.my_print(verbose, "*** readSGrid: "+filename+" ***") assert (os.path.isfile(filename)), "Wrong filename (\""+filename+"\"). Aborting." if (filename.endswith("vtk")): sgrid_reader = vtk.vtkStructuredGridReader() elif (filename.endswith("vts")): sgrid_reader = vtk.vtkXMLStructuredGridReader() else: assert 0, "File must be .vtk or .vts. Aborting." sgrid_reader.SetFileName(filename) sgrid_reader.Update() sgrid = sgrid_reader.GetOutput() mypy.my_print(verbose-1, "n_points = "+str(sgrid.GetNumberOfPoints())) mypy.my_print(verbose-1, "n_cells = "+str(sgrid.GetNumberOfCells())) return sgrid
def furniture(): # generate a whole bunch of planes which correspond to # the geometry in the analysis; tables, bookshelves and so on. from vedo import datadir reader = vtk.vtkStructuredGridReader() reader.SetFileName(datadir + "office.binary.vtk") reader.Update() sgrid = reader.GetOutput() table1 = vtk.vtkStructuredGridGeometryFilter() table1.SetInputData(sgrid) table1.SetExtent(11, 15, 7, 9, 8, 8) mapTable1 = vtk.vtkPolyDataMapper() mapTable1.SetInputConnection(table1.GetOutputPort()) mapTable1.ScalarVisibilityOff() table1Actor = vtk.vtkActor() table1Actor.SetMapper(mapTable1) table1Actor.GetProperty().SetColor(.59, .427, .392) table2 = vtk.vtkStructuredGridGeometryFilter() table2.SetInputData(sgrid) table2.SetExtent(11, 15, 10, 12, 8, 8) mapTable2 = vtk.vtkPolyDataMapper() mapTable2.SetInputConnection(table2.GetOutputPort()) mapTable2.ScalarVisibilityOff() table2Actor = vtk.vtkActor() table2Actor.SetMapper(mapTable2) table2Actor.GetProperty().SetColor(.59, .427, .392) FilingCabinet1 = vtk.vtkStructuredGridGeometryFilter() FilingCabinet1.SetInputData(sgrid) FilingCabinet1.SetExtent(15, 15, 7, 9, 0, 8) mapFilingCabinet1 = vtk.vtkPolyDataMapper() mapFilingCabinet1.SetInputConnection(FilingCabinet1.GetOutputPort()) mapFilingCabinet1.ScalarVisibilityOff() FilingCabinet1Actor = vtk.vtkActor() FilingCabinet1Actor.SetMapper(mapFilingCabinet1) FilingCabinet1Actor.GetProperty().SetColor(.8, .8, .6) FilingCabinet2 = vtk.vtkStructuredGridGeometryFilter() FilingCabinet2.SetInputData(sgrid) FilingCabinet2.SetExtent(15, 15, 10, 12, 0, 8) mapFilingCabinet2 = vtk.vtkPolyDataMapper() mapFilingCabinet2.SetInputConnection(FilingCabinet2.GetOutputPort()) mapFilingCabinet2.ScalarVisibilityOff() FilingCabinet2Actor = vtk.vtkActor() FilingCabinet2Actor.SetMapper(mapFilingCabinet2) FilingCabinet2Actor.GetProperty().SetColor(.8, .8, .6) bookshelf1Top = vtk.vtkStructuredGridGeometryFilter() bookshelf1Top.SetInputData(sgrid) bookshelf1Top.SetExtent(13, 13, 0, 4, 0, 11) mapBookshelf1Top = vtk.vtkPolyDataMapper() mapBookshelf1Top.SetInputConnection(bookshelf1Top.GetOutputPort()) mapBookshelf1Top.ScalarVisibilityOff() bookshelf1TopActor = vtk.vtkActor() bookshelf1TopActor.SetMapper(mapBookshelf1Top) bookshelf1TopActor.GetProperty().SetColor(.8, .8, .6) bookshelf1Bottom = vtk.vtkStructuredGridGeometryFilter() bookshelf1Bottom.SetInputData(sgrid) bookshelf1Bottom.SetExtent(20, 20, 0, 4, 0, 11) mapBookshelf1Bottom = vtk.vtkPolyDataMapper() mapBookshelf1Bottom.SetInputConnection(bookshelf1Bottom.GetOutputPort()) mapBookshelf1Bottom.ScalarVisibilityOff() bookshelf1BottomActor = vtk.vtkActor() bookshelf1BottomActor.SetMapper(mapBookshelf1Bottom) bookshelf1BottomActor.GetProperty().SetColor(.8, .8, .6) bookshelf1Front = vtk.vtkStructuredGridGeometryFilter() bookshelf1Front.SetInputData(sgrid) bookshelf1Front.SetExtent(13, 20, 0, 0, 0, 11) mapBookshelf1Front = vtk.vtkPolyDataMapper() mapBookshelf1Front.SetInputConnection(bookshelf1Front.GetOutputPort()) mapBookshelf1Front.ScalarVisibilityOff() bookshelf1FrontActor = vtk.vtkActor() bookshelf1FrontActor.SetMapper(mapBookshelf1Front) bookshelf1FrontActor.GetProperty().SetColor(.8, .8, .6) bookshelf1Back = vtk.vtkStructuredGridGeometryFilter() bookshelf1Back.SetInputData(sgrid) bookshelf1Back.SetExtent(13, 20, 4, 4, 0, 11) mapBookshelf1Back = vtk.vtkPolyDataMapper() mapBookshelf1Back.SetInputConnection(bookshelf1Back.GetOutputPort()) mapBookshelf1Back.ScalarVisibilityOff() bookshelf1BackActor = vtk.vtkActor() bookshelf1BackActor.SetMapper(mapBookshelf1Back) bookshelf1BackActor.GetProperty().SetColor(.8, .8, .6) bookshelf1LHS = vtk.vtkStructuredGridGeometryFilter() bookshelf1LHS.SetInputData(sgrid) bookshelf1LHS.SetExtent(13, 20, 0, 4, 0, 0) mapBookshelf1LHS = vtk.vtkPolyDataMapper() mapBookshelf1LHS.SetInputConnection(bookshelf1LHS.GetOutputPort()) mapBookshelf1LHS.ScalarVisibilityOff() bookshelf1LHSActor = vtk.vtkActor() bookshelf1LHSActor.SetMapper(mapBookshelf1LHS) bookshelf1LHSActor.GetProperty().SetColor(.8, .8, .6) bookshelf1RHS = vtk.vtkStructuredGridGeometryFilter() bookshelf1RHS.SetInputData(sgrid) bookshelf1RHS.SetExtent(13, 20, 0, 4, 11, 11) mapBookshelf1RHS = vtk.vtkPolyDataMapper() mapBookshelf1RHS.SetInputConnection(bookshelf1RHS.GetOutputPort()) mapBookshelf1RHS.ScalarVisibilityOff() bookshelf1RHSActor = vtk.vtkActor() bookshelf1RHSActor.SetMapper(mapBookshelf1RHS) bookshelf1RHSActor.GetProperty().SetColor(.8, .8, .6) bookshelf2Top = vtk.vtkStructuredGridGeometryFilter() bookshelf2Top.SetInputData(sgrid) bookshelf2Top.SetExtent(13, 13, 15, 19, 0, 11) mapBookshelf2Top = vtk.vtkPolyDataMapper() mapBookshelf2Top.SetInputConnection(bookshelf2Top.GetOutputPort()) mapBookshelf2Top.ScalarVisibilityOff() bookshelf2TopActor = vtk.vtkActor() bookshelf2TopActor.SetMapper(mapBookshelf2Top) bookshelf2TopActor.GetProperty().SetColor(.8, .8, .6) bookshelf2Bottom = vtk.vtkStructuredGridGeometryFilter() bookshelf2Bottom.SetInputData(sgrid) bookshelf2Bottom.SetExtent(20, 20, 15, 19, 0, 11) mapBookshelf2Bottom = vtk.vtkPolyDataMapper() mapBookshelf2Bottom.SetInputConnection(bookshelf2Bottom.GetOutputPort()) mapBookshelf2Bottom.ScalarVisibilityOff() bookshelf2BottomActor = vtk.vtkActor() bookshelf2BottomActor.SetMapper(mapBookshelf2Bottom) bookshelf2BottomActor.GetProperty().SetColor(.8, .8, .6) bookshelf2Front = vtk.vtkStructuredGridGeometryFilter() bookshelf2Front.SetInputData(sgrid) bookshelf2Front.SetExtent(13, 20, 15, 15, 0, 11) mapBookshelf2Front = vtk.vtkPolyDataMapper() mapBookshelf2Front.SetInputConnection(bookshelf2Front.GetOutputPort()) mapBookshelf2Front.ScalarVisibilityOff() bookshelf2FrontActor = vtk.vtkActor() bookshelf2FrontActor.SetMapper(mapBookshelf2Front) bookshelf2FrontActor.GetProperty().SetColor(.8, .8, .6) bookshelf2Back = vtk.vtkStructuredGridGeometryFilter() bookshelf2Back.SetInputData(sgrid) bookshelf2Back.SetExtent(13, 20, 19, 19, 0, 11) mapBookshelf2Back = vtk.vtkPolyDataMapper() mapBookshelf2Back.SetInputConnection(bookshelf2Back.GetOutputPort()) mapBookshelf2Back.ScalarVisibilityOff() bookshelf2BackActor = vtk.vtkActor() bookshelf2BackActor.SetMapper(mapBookshelf2Back) bookshelf2BackActor.GetProperty().SetColor(.8, .8, .6) bookshelf2LHS = vtk.vtkStructuredGridGeometryFilter() bookshelf2LHS.SetInputData(sgrid) bookshelf2LHS.SetExtent(13, 20, 15, 19, 0, 0) mapBookshelf2LHS = vtk.vtkPolyDataMapper() mapBookshelf2LHS.SetInputConnection(bookshelf2LHS.GetOutputPort()) mapBookshelf2LHS.ScalarVisibilityOff() bookshelf2LHSActor = vtk.vtkActor() bookshelf2LHSActor.SetMapper(mapBookshelf2LHS) bookshelf2LHSActor.GetProperty().SetColor(.8, .8, .6) bookshelf2RHS = vtk.vtkStructuredGridGeometryFilter() bookshelf2RHS.SetInputData(sgrid) bookshelf2RHS.SetExtent(13, 20, 15, 19, 11, 11) mapBookshelf2RHS = vtk.vtkPolyDataMapper() mapBookshelf2RHS.SetInputConnection(bookshelf2RHS.GetOutputPort()) mapBookshelf2RHS.ScalarVisibilityOff() bookshelf2RHSActor = vtk.vtkActor() bookshelf2RHSActor.SetMapper(mapBookshelf2RHS) bookshelf2RHSActor.GetProperty().SetColor(.8, .8, .6) window = vtk.vtkStructuredGridGeometryFilter() window.SetInputData(sgrid) window.SetExtent(20, 20, 6, 13, 10, 13) mapWindow = vtk.vtkPolyDataMapper() mapWindow.SetInputConnection(window.GetOutputPort()) mapWindow.ScalarVisibilityOff() windowActor = vtk.vtkActor() windowActor.SetMapper(mapWindow) windowActor.GetProperty().SetColor(.3, .3, .5) outlet = vtk.vtkStructuredGridGeometryFilter() outlet.SetInputData(sgrid) outlet.SetExtent(0, 0, 9, 10, 14, 16) mapOutlet = vtk.vtkPolyDataMapper() mapOutlet.SetInputConnection(outlet.GetOutputPort()) mapOutlet.ScalarVisibilityOff() outletActor = vtk.vtkActor() outletActor.SetMapper(mapOutlet) outletActor.GetProperty().SetColor(1, 1, 1) inlet = vtk.vtkStructuredGridGeometryFilter() inlet.SetInputData(sgrid) inlet.SetExtent(0, 0, 9, 10, 0, 6) mapInlet = vtk.vtkPolyDataMapper() mapInlet.SetInputConnection(inlet.GetOutputPort()) mapInlet.ScalarVisibilityOff() inletActor = vtk.vtkActor() inletActor.SetMapper(mapInlet) inletActor.GetProperty().SetColor(1, 1, 1) outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputData(sgrid) mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(mapOutline) outlineActor.GetProperty().SetColor(1, 1, 1) acts = [] acts.append(table1Actor) acts.append(table2Actor) acts.append(FilingCabinet1Actor) acts.append(FilingCabinet2Actor) acts.append(bookshelf1TopActor) acts.append(bookshelf1BottomActor) acts.append(bookshelf1FrontActor) acts.append(bookshelf1BackActor) acts.append(bookshelf1LHSActor) acts.append(bookshelf1RHSActor) acts.append(bookshelf2TopActor) acts.append(bookshelf2BottomActor) acts.append(bookshelf2FrontActor) acts.append(bookshelf2BackActor) acts.append(bookshelf2LHSActor) acts.append(bookshelf2RHSActor) acts.append(windowActor) acts.append(outletActor) acts.append(inletActor) acts.append(outlineActor) return acts
import vtk objectPath = r"./assets/density.vtk" reader = vtk.vtkStructuredGridReader() reader.SetFileName(objectPath) reader.Update() plane = vtk.vtkPlane() plane.SetOrigin(reader.GetOutput().GetCenter()) plane.SetNormal(0.5, 0.5, 0.5) planeCut = vtk.vtkCutter() planeCut.SetInputConnection(reader.GetOutputPort()) planeCut.SetCutFunction(plane) cutMapper = vtk.vtkPolyDataMapper() cutMapper.SetInputConnection(planeCut.GetOutputPort()) cutMapper.SetScalarRange(reader.GetOutput().GetScalarRange()) actor = vtk.vtkActor() actor.SetMapper(cutMapper) # Create a rendering window and renderer renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) # Create a renderwindowinteractor
def loadStructuredGrid(filename): """Load a ``vtkStructuredGrid`` object from file.""" reader = vtk.vtkStructuredGridReader() reader.SetFileName(filename) reader.Update() return reader.GetOutput()
# Create a reader and write out the field comb = vtk.vtkMultiBlockPLOT3DReader() comb.SetXYZFileName(VTK_DATA_ROOT + "/Data/combxyz.bin") comb.SetQFileName(VTK_DATA_ROOT + "/Data/combq.bin") comb.SetScalarFunctionNumber(100) comb.Update() output = comb.GetOutput().GetBlock(0) wsg = vtk.vtkStructuredGridWriter() wsg.SetInputData(output) wsg.SetFileTypeToBinary() wsg.SetFileName("combsg.vtk") wsg.Write() pl3d = vtk.vtkStructuredGridReader() pl3d.SetFileName("combsg.vtk") ds2do = vtk.vtkDataSetToDataObjectFilter() ds2do.SetInputConnection(pl3d.GetOutputPort()) writer = vtk.vtkDataObjectWriter() writer.SetInputConnection(ds2do.GetOutputPort()) writer.SetFileName("SGridField.vtk") writer.Write() # read the field dor = vtk.vtkDataObjectReader() dor.SetFileName("SGridField.vtk") do2ds = vtk.vtkDataObjectToDataSetFilter()
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # read data # reader = vtk.vtkStructuredGridReader() reader.SetFileName(VTK_DATA_ROOT + "/Data/office.binary.vtk") reader.Update() # force a read to occur # to add coverage for vtkOnePieceExtentTranslator translator = vtk.vtkOnePieceExtentTranslator() reader.GetExecutive().SetExtentTranslator(0, translator) length = reader.GetOutput().GetLength() maxVelocity = reader.GetOutput().GetPointData().GetVectors().GetMaxNorm() maxTime = 35.0 * length / maxVelocity table1 = vtk.vtkStructuredGridGeometryFilter() table1.SetInputConnection(reader.GetOutputPort()) table1.SetExtent(11, 15, 7, 9, 8, 8) mapTable1 = vtk.vtkPolyDataMapper()
def getOutputVTKwithPointDataFromFile(fileName): """ Uses the correct VTK reader to obtain a VTK output object so that one can work with the data in *fileName*. NOTE : the cell data are transfered to the nodes. Parameters ---------- fileName : string The .vt* file to open Returns ------- data_outVTK : VTK output object from a VTK reader VTK output object associated to the file type of *fileName* """ # function display print '\n---- DAEPy::getOutputVTKwithPointDataFromFile ----' # test if the file exists print '\n--> Reading', fileName if not os.path.isfile(fileName): raise ValueError("Error : file does not exists") extension = os.path.splitext(fileName)[-1] if extension == '.vtu': reader = vtk.vtkXMLUnstructuredGridReader() elif extension == '.vtk': reader = vtk.vtkStructuredGridReader() elif extension == '.pvtu': reader = vtk.vtkXMLPUnstructuredGridReader() elif extension == '.vtp': reader = vtk.vtkXMLPolyDataReader() elif extension == '.vtm': # TODO : To check reader = vtk.vtkXMLMultiBlockDataReader() reader = vtk.MergeBlocks(reader) else: raise ValueError("Error: unknown extension of file " + fileName) reader.SetFileName(fileName) reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.Update() data_outVTK = reader.GetOutput() # # All the data are transfered to the nodes # c2p = vtk.vtkCellDataToPointData() # c2p.SetInputData(data_outVTK) # c2p.Update() # data_outVTK = c2p.GetOutput() # list the fields available n_fields = data_outVTK.GetPointData().GetNumberOfArrays() print '\n--> Available:', n_fields, 'fields\n' for i in range(n_fields): print ' -', data_outVTK.GetPointData().GetArrayName(i) print '' return data_outVTK
def extract_data(self, rotate=None): """ Extract the data from the VTK file using the python-vtk library The data is passed to numpy arrays for better manipulation """ # Check the type of file to load it according to its grid structure # which was specified when calling the class These dictionary entries # return the corresponding VTK Reader functions, so they can be easily # called according to the class argument # # Rotate argument is a rotation in the x-y plane. To use, set rotate # equal to an angle in radians. reader_type = { 'XMLUnstructuredGrid': lambda: vtk.vtkXMLUnstructuredGridReader(), 'XMLStructuredGrid': lambda: vtk.vtkXMLStructuredGridReader(), 'UnstructuredGrid': lambda: vtk.vtkUnstructuredGridReader(), 'StructuredGrid': lambda: vtk.vtkStructuredGridReader(), } if self.vtkfiletype.startswith('XML'): # Load the vtk file from the input file self.reader = reader_type[self.vtkfiletype]() self.reader.SetFileName(self.vtk_file) else: # Load the vtk file from the input file self.reader = reader_type[self.vtkfiletype]() self.reader.SetFileName(self.vtk_file) # For Non XML vtk files: self.reader.ReadAllVectorsOn() self.reader.ReadAllScalarsOn() self.reader.Update() # Get the coordinates of the nodes in the mesh nodes_vtk_array = self.reader.GetOutput().GetPoints().GetData() # Get The vector field (data of every node) vf_vtk_array = self.reader.GetOutput().GetPointData().GetArray(0) # Transform the coordinates of the nodes to a Numpy array and # save them to the corresponding class objects nodes = vtk_to_numpy(nodes_vtk_array) if rotate: self.x = nodes[:, 0]*np.cos(rotate) - nodes[:, 1]*np.sin(rotate) self.y = nodes[:, 0]*np.sin(rotate) + nodes[:, 1]*np.cos(rotate) self.z = nodes[:, 2] else: self.x, self.y, self.z = (nodes[:, 0], nodes[:, 1], nodes[:, 2] ) # Transform the magnetisation data to a Numpy array and save if rotate: vf = vtk_to_numpy(vf_vtk_array) vfx = vf[:, 0]*np.cos(rotate) - vf[:, 1]*np.sin(rotate) vfy = vf[:, 0]*np.sin(rotate) + vf[:, 1]*np.cos(rotate) vfz = vf[:, 2] self.vf = np.zeros_like(vf) self.vf[:, 0] = vfx self.vf[:, 1] = vfy self.vf[:, 2] = vfz else: self.vf = vtk_to_numpy(vf_vtk_array)
def read_polydata(filename, datatype=None): """ Load the given file, and return a vtkPolyData object for it. Args: filename (str): Path to input file. datatype (str): Additional parameter for vtkIdList objects. Returns: polyData (vtkSTL/vtkPolyData/vtkXMLStructured/ vtkXMLRectilinear/vtkXMLPolydata/vtkXMLUnstructured/ vtkXMLImage/Tecplot): Output data. """ # Check if file exists if not path.exists(filename): raise RuntimeError("Could not find file: %s" % filename) # Check filename format fileType = filename.split(".")[-1] if fileType == '': raise RuntimeError('The file does not have an extension') # Get reader if fileType == 'stl': reader = vtk.vtkSTLReader() reader.MergingOn() elif fileType == 'vtk': # Read header with open(filename, "rb") as f: head = list(islice(f, 10)) head = "".join([l.decode('utf-8', 'backslashreplace') for l in head]).lower() # Set reader based on header if "unstructured_grid" in head: reader = vtk.vtkUnstructuredGridReader() elif "structured_grid" in head: reader = vtk.vtkStructuredGridReader() elif "rectilinear_grid" in head: reader = vtk.vtkRectilinearGridReader() elif "structured_points" in head: reader = vtk.vtkStructuredPointsReader() elif "polydata" in head: reader = vtk.vtkPolyDataReader() elif fileType == 'vtp': reader = vtk.vtkXMLPolyDataReader() elif fileType == 'vts': reader = vtk.vtkXMLStructuredGridReader() elif fileType == 'vtr': reader = vtk.vtkXMLRectilinearGridReader() elif fileType == 'vtu': reader = vtk.vtkXMLUnstructuredGridReader() elif fileType == "vti": reader = vtk.vtkXMLImageDataReader() elif fileType == "np" and datatype == "vtkIdList": result = np.load(filename).astype(np.int) id_list = vtk.vtkIdList() id_list.SetNumberOfIds(result.shape[0]) for i in range(result.shape[0]): id_list.SetId(i, result[i]) return id_list else: raise RuntimeError('Unknown file type %s' % fileType) # Read reader.SetFileName(filename) reader.Update() polydata = reader.GetOutput() return polydata
def __init__(self, dataDir='data', fileName='save.vtk'): """ Reads the parameters. call signature: readParams(dataDir = 'data', fileName = 'save.vtk') Keyword arguments: *dataDir*: Data directory. *fileName*: Name of the dump file. """ reader = vtkStructuredGridReader() if (dataDir[-1] == '/'): dataDir = dataDir[:-1] try: reader.SetFileName(dataDir + '/' + fileName) except IOError: return -1 reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() output = reader.GetOutput() data = output.GetPointData() field = output.GetFieldData() nArrays = field.GetNumberOfArrays() for i in range(nArrays): arrayName = field.GetArrayName(i) tmp = VN.vtk_to_numpy(field.GetArray(arrayName)) if (arrayName == 'nx_ny_nz'): setattr(self, 'nx', tmp[0]) setattr(self, 'ny', tmp[1]) setattr(self, 'nz', tmp[2]) elif (arrayName == 'Lx_Ly_Lz'): setattr(self, 'Lx', tmp[0]) setattr(self, 'Ly', tmp[1]) setattr(self, 'Lz', tmp[2]) elif (arrayName == 'Ox_Oy_Oz'): setattr(self, 'Ox', tmp[0]) setattr(self, 'Oy', tmp[1]) setattr(self, 'Oz', tmp[2]) elif (arrayName == 'dx_dy_dz'): setattr(self, 'dx', tmp[0]) setattr(self, 'dy', tmp[1]) setattr(self, 'dz', tmp[2]) elif (arrayName == 'rxhalf_ryhalf'): setattr(self, 'rxhalf', tmp[0]) setattr(self, 'ryhalf', tmp[1]) elif (arrayName == 'phi1_phi2'): setattr(self, 'phi1', tmp[0]) setattr(self, 'phi2', tmp[1]) else: setattr(self, arrayName, tmp[0]) reader.CloseVTKFile()
def __init__(self, dataDir='data', fileName='save.vtk'): """ Reads the dump file. call signature: readDump(dataDir = 'data', fileName = 'save.vtk') Keyword arguments: *dataDir*: Data directory. *fileName*: Name of the dump file. """ reader = vtkStructuredGridReader() if (dataDir[-1] == '/'): dataDir = dataDir[:-1] try: reader.SetFileName(dataDir + '/' + fileName) except IOError: return -1 reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() output = reader.GetOutput() dim = output.GetDimensions() data = output.GetPointData() nArrays = data.GetNumberOfArrays() for i in range(nArrays): arrayName = data.GetArrayName(i) tmp = VN.vtk_to_numpy(data.GetArray(arrayName)) if (tmp.ndim == 2): tmp = tmp.reshape(dim[2], dim[1], dim[0], 3) tmp = np.swapaxes(tmp, 0, 3) tmp = np.swapaxes(tmp, 1, 2) else: tmp = tmp.reshape(dim[2], dim[1], dim[0]) tmp = np.swapaxes(tmp, 0, 2) setattr(self, arrayName, tmp) del (tmp) # read the grid coordinates points = output.GetPoints() grid = VN.vtk_to_numpy(points.GetData()) grid = grid.reshape(dim[2], dim[1], dim[0], 3) grid = np.swapaxes(grid, 0, 3) grid = np.swapaxes(grid, 1, 2) setattr(self, 'grid', grid) del (grid) # read the parameters p = readParams(dataDir=dataDir, fileName=fileName) setattr(self, 'p', p) reader.CloseVTKFile()
def main(): fileName = get_program_parameters() colors = vtk.vtkNamedColors() # Set the furniture colors. colors.SetColor("Furniture", [204, 204, 153, 255]) scalarRange = [0.0, 0.0] maxTime = 0 aren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(aren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # # Read the data. # reader = vtk.vtkStructuredGridReader() reader.SetFileName(fileName) reader.Update() # Force a read to occur. reader.GetOutput().GetLength() if reader.GetOutput().GetPointData().GetScalars(): reader.GetOutput().GetPointData().GetScalars().GetRange(scalarRange) if reader.GetOutput().GetPointData().GetVectors(): maxVelocity = reader.GetOutput().GetPointData().GetVectors( ).GetMaxNorm() maxTime = 4.0 * reader.GetOutput().GetLength() / maxVelocity # # Outline around the data. # outlineF = vtk.vtkStructuredGridOutlineFilter() outlineF.SetInputConnection(reader.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outlineF.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(outlineMapper) outline.GetProperty().SetColor(colors.GetColor3d("LampBlack")) # # Set up shaded surfaces (i.e., supporting geometry). # doorGeom = vtk.vtkStructuredGridGeometryFilter() doorGeom.SetInputConnection(reader.GetOutputPort()) doorGeom.SetExtent(27, 27, 14, 18, 0, 11) mapDoor = vtk.vtkPolyDataMapper() mapDoor.SetInputConnection(doorGeom.GetOutputPort()) mapDoor.ScalarVisibilityOff() door = vtk.vtkActor() door.SetMapper(mapDoor) door.GetProperty().SetColor(colors.GetColor3d("Burlywood")) window1Geom = vtk.vtkStructuredGridGeometryFilter() window1Geom.SetInputConnection(reader.GetOutputPort()) window1Geom.SetExtent(0, 0, 9, 18, 6, 12) mapWindow1 = vtk.vtkPolyDataMapper() mapWindow1.SetInputConnection(window1Geom.GetOutputPort()) mapWindow1.ScalarVisibilityOff() window1 = vtk.vtkActor() window1.SetMapper(mapWindow1) window1.GetProperty().SetColor(colors.GetColor3d("SkyBlue")) window1.GetProperty().SetOpacity(.6) window2Geom = vtk.vtkStructuredGridGeometryFilter() window2Geom.SetInputConnection(reader.GetOutputPort()) window2Geom.SetExtent(5, 12, 23, 23, 6, 12) mapWindow2 = vtk.vtkPolyDataMapper() mapWindow2.SetInputConnection(window2Geom.GetOutputPort()) mapWindow2.ScalarVisibilityOff() window2 = vtk.vtkActor() window2.SetMapper(mapWindow2) window2.GetProperty().SetColor(colors.GetColor3d("SkyBlue")) window2.GetProperty().SetOpacity(.6) klower1Geom = vtk.vtkStructuredGridGeometryFilter() klower1Geom.SetInputConnection(reader.GetOutputPort()) klower1Geom.SetExtent(17, 17, 0, 11, 0, 6) mapKlower1 = vtk.vtkPolyDataMapper() mapKlower1.SetInputConnection(klower1Geom.GetOutputPort()) mapKlower1.ScalarVisibilityOff() klower1 = vtk.vtkActor() klower1.SetMapper(mapKlower1) klower1.GetProperty().SetColor(colors.GetColor3d("EggShell")) klower2Geom = vtk.vtkStructuredGridGeometryFilter() klower2Geom.SetInputConnection(reader.GetOutputPort()) klower2Geom.SetExtent(19, 19, 0, 11, 0, 6) mapKlower2 = vtk.vtkPolyDataMapper() mapKlower2.SetInputConnection(klower2Geom.GetOutputPort()) mapKlower2.ScalarVisibilityOff() klower2 = vtk.vtkActor() klower2.SetMapper(mapKlower2) klower2.GetProperty().SetColor(colors.GetColor3d("EggShell")) klower3Geom = vtk.vtkStructuredGridGeometryFilter() klower3Geom.SetInputConnection(reader.GetOutputPort()) klower3Geom.SetExtent(17, 19, 0, 0, 0, 6) mapKlower3 = vtk.vtkPolyDataMapper() mapKlower3.SetInputConnection(klower3Geom.GetOutputPort()) mapKlower3.ScalarVisibilityOff() klower3 = vtk.vtkActor() klower3.SetMapper(mapKlower3) klower3.GetProperty().SetColor(colors.GetColor3d("EggShell")) klower4Geom = vtk.vtkStructuredGridGeometryFilter() klower4Geom.SetInputConnection(reader.GetOutputPort()) klower4Geom.SetExtent(17, 19, 11, 11, 0, 6) mapKlower4 = vtk.vtkPolyDataMapper() mapKlower4.SetInputConnection(klower4Geom.GetOutputPort()) mapKlower4.ScalarVisibilityOff() klower4 = vtk.vtkActor() klower4.SetMapper(mapKlower4) klower4.GetProperty().SetColor(colors.GetColor3d("EggShell")) klower5Geom = vtk.vtkStructuredGridGeometryFilter() klower5Geom.SetInputConnection(reader.GetOutputPort()) klower5Geom.SetExtent(17, 19, 0, 11, 0, 0) mapKlower5 = vtk.vtkPolyDataMapper() mapKlower5.SetInputConnection(klower5Geom.GetOutputPort()) mapKlower5.ScalarVisibilityOff() klower5 = vtk.vtkActor() klower5.SetMapper(mapKlower5) klower5.GetProperty().SetColor(colors.GetColor3d("EggShell")) klower6Geom = vtk.vtkStructuredGridGeometryFilter() klower6Geom.SetInputConnection(reader.GetOutputPort()) klower6Geom.SetExtent(17, 19, 0, 7, 6, 6) mapKlower6 = vtk.vtkPolyDataMapper() mapKlower6.SetInputConnection(klower6Geom.GetOutputPort()) mapKlower6.ScalarVisibilityOff() klower6 = vtk.vtkActor() klower6.SetMapper(mapKlower6) klower6.GetProperty().SetColor(colors.GetColor3d("EggShell")) klower7Geom = vtk.vtkStructuredGridGeometryFilter() klower7Geom.SetInputConnection(reader.GetOutputPort()) klower7Geom.SetExtent(17, 19, 9, 11, 6, 6) mapKlower7 = vtk.vtkPolyDataMapper() mapKlower7.SetInputConnection(klower7Geom.GetOutputPort()) mapKlower7.ScalarVisibilityOff() klower7 = vtk.vtkActor() klower7.SetMapper(mapKlower7) klower7.GetProperty().SetColor(colors.GetColor3d("EggShell")) hood1Geom = vtk.vtkStructuredGridGeometryFilter() hood1Geom.SetInputConnection(reader.GetOutputPort()) hood1Geom.SetExtent(17, 17, 0, 11, 11, 16) mapHood1 = vtk.vtkPolyDataMapper() mapHood1.SetInputConnection(hood1Geom.GetOutputPort()) mapHood1.ScalarVisibilityOff() hood1 = vtk.vtkActor() hood1.SetMapper(mapHood1) hood1.GetProperty().SetColor(colors.GetColor3d("Silver")) hood2Geom = vtk.vtkStructuredGridGeometryFilter() hood2Geom.SetInputConnection(reader.GetOutputPort()) hood2Geom.SetExtent(19, 19, 0, 11, 11, 16) mapHood2 = vtk.vtkPolyDataMapper() mapHood2.SetInputConnection(hood2Geom.GetOutputPort()) mapHood2.ScalarVisibilityOff() hood2 = vtk.vtkActor() hood2.SetMapper(mapHood2) hood2.GetProperty().SetColor(colors.GetColor3d("Furniture")) hood3Geom = vtk.vtkStructuredGridGeometryFilter() hood3Geom.SetInputConnection(reader.GetOutputPort()) hood3Geom.SetExtent(17, 19, 0, 0, 11, 16) mapHood3 = vtk.vtkPolyDataMapper() mapHood3.SetInputConnection(hood3Geom.GetOutputPort()) mapHood3.ScalarVisibilityOff() hood3 = vtk.vtkActor() hood3.SetMapper(mapHood3) hood3.GetProperty().SetColor(colors.GetColor3d("Furniture")) hood4Geom = vtk.vtkStructuredGridGeometryFilter() hood4Geom.SetInputConnection(reader.GetOutputPort()) hood4Geom.SetExtent(17, 19, 11, 11, 11, 16) mapHood4 = vtk.vtkPolyDataMapper() mapHood4.SetInputConnection(hood4Geom.GetOutputPort()) mapHood4.ScalarVisibilityOff() hood4 = vtk.vtkActor() hood4.SetMapper(mapHood4) hood4.GetProperty().SetColor(colors.GetColor3d("Furniture")) hood6Geom = vtk.vtkStructuredGridGeometryFilter() hood6Geom.SetInputConnection(reader.GetOutputPort()) hood6Geom.SetExtent(17, 19, 0, 11, 16, 16) mapHood6 = vtk.vtkPolyDataMapper() mapHood6.SetInputConnection(hood6Geom.GetOutputPort()) mapHood6.ScalarVisibilityOff() hood6 = vtk.vtkActor() hood6.SetMapper(mapHood6) hood6.GetProperty().SetColor(colors.GetColor3d("Furniture")) cookingPlateGeom = vtk.vtkStructuredGridGeometryFilter() cookingPlateGeom.SetInputConnection(reader.GetOutputPort()) cookingPlateGeom.SetExtent(17, 19, 7, 9, 6, 6) mapCookingPlate = vtk.vtkPolyDataMapper() mapCookingPlate.SetInputConnection(cookingPlateGeom.GetOutputPort()) mapCookingPlate.ScalarVisibilityOff() cookingPlate = vtk.vtkActor() cookingPlate.SetMapper(mapCookingPlate) cookingPlate.GetProperty().SetColor(colors.GetColor3d("Tomato")) filterGeom = vtk.vtkStructuredGridGeometryFilter() filterGeom.SetInputConnection(reader.GetOutputPort()) filterGeom.SetExtent(17, 19, 7, 9, 11, 11) mapFilter = vtk.vtkPolyDataMapper() mapFilter.SetInputConnection(filterGeom.GetOutputPort()) mapFilter.ScalarVisibilityOff() sgfilter = vtk.vtkActor() sgfilter.SetMapper(mapFilter) sgfilter.GetProperty().SetColor(colors.GetColor3d("Furniture")) # # regular streamlines # line = vtk.vtkLineSource() line.SetResolution(39) line.SetPoint1(0.08, 2.50, 0.71) line.SetPoint2(0.08, 4.50, 0.71) rakeMapper = vtk.vtkPolyDataMapper() rakeMapper.SetInputConnection(line.GetOutputPort()) rake = vtk.vtkActor() rake.SetMapper(rakeMapper) streamers = vtk.vtkStreamTracer() # streamers.DebugOn() streamers.SetInputConnection(reader.GetOutputPort()) streamers.SetSourceConnection(line.GetOutputPort()) streamers.SetMaximumPropagation(maxTime) streamers.SetInitialIntegrationStep(.5) streamers.SetMinimumIntegrationStep(.1) streamers.SetIntegratorType(2) streamers.Update() streamersMapper = vtk.vtkPolyDataMapper() streamersMapper.SetInputConnection(streamers.GetOutputPort()) streamersMapper.SetScalarRange(scalarRange) lines = vtk.vtkActor() lines.SetMapper(streamersMapper) lines.GetProperty().SetColor(colors.GetColor3d("Black")) aren.TwoSidedLightingOn() aren.AddActor(outline) aren.AddActor(door) aren.AddActor(window1) aren.AddActor(window2) aren.AddActor(klower1) aren.AddActor(klower2) aren.AddActor(klower3) aren.AddActor(klower4) aren.AddActor(klower5) aren.AddActor(klower6) aren.AddActor(klower7) aren.AddActor(hood1) aren.AddActor(hood2) aren.AddActor(hood3) aren.AddActor(hood4) aren.AddActor(hood6) aren.AddActor(cookingPlate) aren.AddActor(sgfilter) aren.AddActor(lines) aren.AddActor(rake) aren.SetBackground(colors.GetColor3d("SlateGray")) aCamera = vtk.vtkCamera() aren.SetActiveCamera(aCamera) aren.ResetCamera() aCamera.SetFocalPoint(3.505, 2.505, 1.255) aCamera.SetPosition(3.505, 24.6196, 1.255) aCamera.SetViewUp(0, 0, 1) aCamera.Azimuth(60) aCamera.Elevation(30) aCamera.Dolly(1.5) aren.ResetCameraClippingRange() renWin.SetSize(640, 512) renWin.Render() # interact with data iren.Start()