def pushConcentration(self, ecoSlimFile): if os.path.exists(ecoSlimFile): if self.vtkReader: self.vtkReader.SetFileName(ecoSlimFile) else: self.vtkReader = vtk.vtkDataSetReader() self.vtkReader.SetFileName(ecoSlimFile) self.vtkReader.Update() imageData = self.vtkReader.GetOutput() if imageData: array = imageData.GetCellData().GetArray('Concentration') dataRange = array.GetRange(0) print('push concentration: %s' % ecoSlimFile) self.publish( 'parflow.sandtank.concentration', { 'time': self.lastEcoSLIMTimestep, 'range': dataRange, 'array': self.addAttachment( memoryview(array).tobytes()) }) elif self.lastEcoSLIMTimestep > -1: self.lastEcoSLIMTimestep -= 1
def show_vtk_file(path): # open vtk file from arglist reader = vtk.vtkDataSetReader() reader.SetFileName(path) reader.Update() # read out data and scalarrange output = reader.GetOutput() scalarrange = output.GetScalarRange() # generate Mapper and set DataSource mapper = vtk.vtkDataSetMapper() mapper.SetInput(output) mapper.SetScalarRange(scalarrange) # create actor actor = vtk.vtkActor() actor.SetMapper(mapper) # build renderer renderer = vtk.vtkRenderer() window = vtk.vtkRenderWindow() window.AddRenderer(renderer) # create interaction interaction = vtk.vtkRenderWindowInteractor() interaction.SetRenderWindow(window) # add actor renderer.AddActor(actor) # show window and start inteaction and renderer interaction.Initialize() window.Render() interaction.Start()
def vtkDatasetFromHdf5(g): """ extract a vtkDataset Object from a text file representation stored in a hdf5 character array dataset g. The concrete returned type depends on the content of the file. """ gridtype2vtureader = { 'vtkImageData': vtk.vtkXMLImageDataReader, 'vtkPolyData': vtk.vtkXMLPolyDataReader, 'vtkUnstructuredGrid': vtk.vtkXMLUnstructuredGridReader, } filetype = g.attrs["TYPE"] if filetype == 'VTK_FILE': # shit! i used vtu files at first before i noticed that the legacy vtk format is much easier to deal with ... reader = vtk.vtkDataSetReader() reader.ReadFromInputStringOn() reader.SetInputString(np.asarray(g).tostring()) reader.Update() else: probable_vtk_dataset_type = g.attrs.get('VTK_DATASET_TYPE', 'vtkUnstructuredGrid') import mkstemp # my stuff tf = mkstemp.File(suffix=".vtx") f = open(tf.filename, 'wb') f.write(np.asarray(g).tostring()) f.close() reader = gridtype2vtureader[probable_vtk_dataset_type]() reader.SetFileName(tf.filename) reader.Update() tf.remove() return reader.GetOutput()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkDataSetReader(), 'Reading vtkDataSet.', (), ('vtkDataSet',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def load_vtk(t, case="free"): f = "rvat-log-" + case + "/velocity/"+str(t)+".vtk" reader = vtk.vtkDataSetReader() reader.SetFileName(f) reader.Update() data = reader.GetOutput() npoints = data.GetNumberOfPoints() point = data.GetPoint(0) d = data.GetPointData() array = d.GetArray("Velocity") u = np.zeros(npoints) v = np.zeros(npoints) w = np.zeros(npoints) x = np.zeros(npoints) y = np.zeros(npoints) z = np.zeros(npoints) for n in range(npoints): x[n], y[n], z[n] = data.GetPoint(n) u[n], v[n], w[n] = array.GetTuple(n) u = u[np.where(x==1.0)[0]] v = v[np.where(x==1.0)[0]] w = w[np.where(x==1.0)[0]] y = y[np.where(x==1.0)[0]] z = z[np.where(x==1.0)[0]] yarray, zarray, [uarray, varray, warray] = ts.build_plane_arrays(y, z, [u, v, w]) return yarray, zarray, uarray, varray, warray
def _read_polydata(self): """ This private method reads the given `filename` and return a vtkPolyData object containing all informations about file; to avoid useless IO operation on the same file, it stores polydata of the last file parsed and if user ask for this file, the polydata previously stored is returned. :return: polydata containing information about file. :rtype: vtkPolyData """ # Polydata from `filename` is allready loaded; return it if self._cached_data is not None: return self._cached_data if not os.path.isfile(self._filename): raise RuntimeError("{0!s} doesn't exist".format( os.path.abspath(self._filename))) reader = vtk.vtkDataSetReader() reader.SetFileName(self._filename) reader.Update() data = reader.GetOutput() self._cached_data = data return data
def get_tensor_array(filename): """Returns vtk tensor array object which can have 'GetTuple9(i)' called on it.""" print "Reading " + filename reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() print 'npoints:', output.GetNumberOfPoints() print 'ncells:', output.GetNumberOfCells() print 'nscalars:', reader.GetNumberOfScalarsInFile() print 'ntensors:', reader.GetNumberOfTensorsInFile() print 'ScalarName:', reader.GetScalarsNameInFile(0) print 'TensorName:', reader.GetTensorsNameInFile(0) output = reader.GetOutput() pointdata = output.GetPointData() #scalar_array = pointdata.GetArray('scalar') tensor_array = pointdata.GetTensors() if not tensor_array: tensor_array = pointdata.GetArray('tensor') if not tensor_array: tensor_array = pointdata.GetArray('tensors') if not tensor_array: tensor_array = pointdata.GetArray('Tensors_') if not tensor_array: tensor_array = pointdata.GetArray('tensor1') if not tensor_array: print "Cannot find tensors in %s" % filename sys.exit(1) return tensor_array
def write(self, mesh_points, filename): """ Writes a vtk file, called filename, copying all the structures from self.filename but the coordinates. `mesh_points` is a matrix that contains the new coordinates to write in the vtk file. :param numpy.ndarray mesh_points: it is a `n_points`-by-3 matrix containing the coordinates of the points of the mesh :param string filename: name of the output file. """ self._check_filename_type(filename) self._check_extension(filename) self._check_infile_instantiation() self.outfile = filename reader = vtk.vtkDataSetReader() reader.SetFileName(self.infile) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() points = vtk.vtkPoints() for i in range(data.GetNumberOfPoints()): points.InsertNextPoint(mesh_points[i, :]) data.SetPoints(points) writer = vtk.vtkDataSetWriter() writer.SetFileName(self.outfile) writer.SetInputData(data) writer.Write()
def get_tensor_array(filename): """Returns vtk tensor array object which can have 'GetTuple9(i)' called on it.""" print("Reading " + filename) reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() print('npoints:', output.GetNumberOfPoints()) print('ncells:', output.GetNumberOfCells()) print('nscalars:', reader.GetNumberOfScalarsInFile()) print('ntensors:', reader.GetNumberOfTensorsInFile()) print('ScalarName:', reader.GetScalarsNameInFile(0)) print('TensorName:', reader.GetTensorsNameInFile(0)) output = reader.GetOutput() pointdata = output.GetPointData() #scalar_array = pointdata.GetArray('scalar') tensor_array = pointdata.GetTensors() if not tensor_array: tensor_array = pointdata.GetArray('tensor') if not tensor_array: tensor_array = pointdata.GetArray('tensors') if not tensor_array: tensor_array = pointdata.GetArray('Tensors_') if not tensor_array: tensor_array = pointdata.GetArray('tensor1') if not tensor_array: print("Cannot find tensors in %s" % filename) sys.exit(1) return tensor_array
def parse(self, filename): """ Method to parse the file `filename`. It returns a matrix with all the coordinates. :param string filename: name of the input file. :return: mesh_points: it is a `n_points`-by-3 matrix containing the coordinates of the points of the mesh :rtype: numpy.ndarray .. todo:: - specify when it works """ self._check_filename_type(filename) self._check_extension(filename) self.infile = filename reader = vtk.vtkDataSetReader() reader.SetFileName(self.infile) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() n_points = data.GetNumberOfPoints() mesh_points = np.zeros([n_points, 3]) for i in range(n_points): mesh_points[i][0], mesh_points[i][1], mesh_points[i][2] = data.GetPoint(i) return mesh_points
def getReaderWriter(file_name, out_dir=None): r = vtk.vtkDataSetReader() r.SetFileName(file_name) f_base = os.path.splitext(file_name)[0] r.Update() reader = None writer = None xmlsuffix = '.xml' map = {'StructuredPoints': '.vti', 'StructuredGrid': '.vts', 'RectilinearGrid': '.vtr', 'UnstructuredGrid': '.vtu', 'PolyData': '.vtp'} for i in ['StructuredPoints', 'StructuredGrid', 'RectilinearGrid', 'UnstructuredGrid', 'PolyData']: if eval('r.IsFile%s()'%i): reader = eval('vtk.vtk%sReader()'%i) if i == 'StructuredPoints': writer = eval('vtk.vtkXMLImageDataWriter()') else: writer = eval('vtk.vtkXML%sWriter()'%i) xmlsuffix = map[i] break if not reader: return None, None reader.SetFileName(file_name) reader.Update() out_file = f_base + xmlsuffix if out_dir: out_file = os.path.join(out_dir, os.path.basename(f_base) + xmlsuffix) writer.SetFileName(out_file) return reader, writer
def vtk_bin_to_ascii(fin, fout, origin, spacing): """Convert VTK file to ascii format. Intended for VTK files with 3D voxel data. Also adjusts origin and spacing. Args: fin (str): input filename fout (str): output filename origin (list): origin of coordinate system spacing (list): distance between the nodes in structured mesh """ reader = vtk.vtkDataSetReader() reader.SetFileName(fin) reader.Update() data = vtk.vtkImageData() data.ShallowCopy(reader.GetOutput()) data.SetOrigin(origin) data.SetSpacing(spacing) writer = vtk.vtkStructuredPointsWriter() if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInputConnection(data.GetProducerPort()) else: writer.SetInputData(data) writer.SetFileName(fout) writer.Write()
def parse(self, filename): """ Method to parse the file `filename`. It returns a matrix with all the coordinates. :param string filename: name of the input file. :return: mesh_points: it is a `n_points`-by-3 matrix containing the coordinates of the points of the mesh :rtype: numpy.ndarray .. todo:: - specify when it works """ self._check_filename_type(filename) self._check_extension(filename) self.infile = filename reader = vtk.vtkDataSetReader() reader.SetFileName(self.infile) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() n_points = data.GetNumberOfPoints() mesh_points = np.zeros([n_points, 3]) for i in range(n_points): mesh_points[i][0], mesh_points[i][1], mesh_points[i][ 2] = data.GetPoint(i) return mesh_points
def read_points(filename): """ Load points of a VTK surface file. Parameters ---------- filename : string path/filename of a VTK format file Returns ------- points : list of lists of floats each element is a list of 3-D coordinates of a surface mesh vertex """ import vtk Reader = vtk.vtkDataSetReader() Reader.SetFileName(filename) Reader.ReadAllScalarsOn() # Activate the reading of all scalars Reader.Update() Data = Reader.GetOutput() points = [list(Data.GetPoint(point_id)) for point_id in range(Data.GetNumberOfPoints())] return points
def readCellsFromFile(cells, path, iteration, rank): import vtk import os.path filename = path.replace('__ITERATION__', str(iteration)).replace('__RANK__', str(rank)) if os.path.exists(filename): reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.SetReadAllScalars(True) reader.Update() grid = reader.GetOutput() numberOfCells = grid.GetNumberOfCells() cellData = grid.GetCellData() qs = cellData.GetScalars("q0") for cellId in xrange(numberOfCells): vtkCell = grid.GetCell(cellId) q = qs.GetTuple(cellId)[0] cells.append(Cell(vtkCell, vtkCell.GetBounds()[:], q)) return numberOfCells else: return 0
def ConvertVTKMatlab(input_filename, output_filename): import vtk.util.numpy_support as vtkNumPy import numpy import scipy.io as scipyio extension = input_filename.split('.').pop() vtkReader = None if extension == 'vtk': vtkReader = vtk.vtkDataSetReader() elif extension == 'vti': vtkReader = vtk.vtkXMLImageDataReader() else: raise RuntimeError('unknown file type %s ' % input_filename) vtkReader.SetFileName("%s" % (input_filename)) vtkReader.Update() imageDataVTK = vtkReader.GetOutput() dimensions = imageDataVTK.GetDimensions() spacing = imageDataVTK.GetSpacing() origin = imageDataVTK.GetOrigin() print spacing, origin, dimensions #fem.SetImagingDimensions( dimensions ,origin,spacing) image_point_data = imageDataVTK.GetPointData() image_data = vtkNumPy.vtk_to_numpy(image_point_data.GetArray(0)) # write numpy to disk in matlab # indexing is painful.... reshape to dimensions and transpose 2d dimensions only scipyio.savemat( output_filename, { 'spacing': spacing, 'origin': origin, 'image': image_data.reshape(dimensions, order='F').transpose( 1, 0, 2) })
def load_vtk(filepath): file_extension = osp.splitext(filepath)[1] if file_extension == '.vtu': reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(filepath) reader.Update() grid = reader.GetOutput() return grid elif file_extension == '.vtk': reader = vtk.vtkDataSetReader() reader.SetFileName(filepath) reader.Update() if reader.GetUnstructuredGridOutput() is not None: return reader.GetUnstructuredGridOutput() elif reader.GetPolyDataOutput() is not None: return reader.GetPolyDataOutput() elif reader.GetStructuredPointsOutput() is not None: raise RuntimeError('StructuredPoints not supported (yet?)') elif reader.GetStructuredGridOutput() is not None: filtered = append_filter(reader.GetStructuredGridOutput()) return filtered elif reader.GetRectilinearGridOutput() is not None: raise RuntimeError('RectilinearGrid not supported (yet?)') else: raise RuntimeError('Unrecognized data type') else: raise RuntimeError('Unknown file type {}'.format(file_extension))
def read_vtk_vector(filename): """ Summary: Much of this code was taken from Matthew Priddy's example file. Inputs: Outputs: """ # Initialize the reading of the VTK microstructure created by Dream3D reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.ReadAllTensorsOn() reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() dim = data.GetDimensions() vec = list(dim) vec = [i - 1 for i in dim] el = vec[0] Euler = data.GetCellData().GetArray(reader.GetVectorsNameInFile(0)) euler_py = np.zeros([3, el**3]) for ii in xrange(el**3): euler_py[0, ii] = Euler.GetValue(ii * 3 + 0) euler_py[1, ii] = Euler.GetValue(ii * 3 + 1) euler_py[2, ii] = Euler.GetValue(ii * 3 + 2) return euler_py
def read_vertices(Filename): """ Load VERTICES segment from a VTK file (actually contains indices to vertices) Parameters ---------- Filename : string The path/filename of a VTK format file. Returns ------- indices : a list of integers Each element is an integer defined in VERTICES segment of the VTK file. The integer is an index referring to a point defined in POINTS segment of the VTK file. Notes :: We assume that VERTICES segment is organized as one line, the first column of which is the number of vertices. Vertices here are as vertices in VTK terminology. It may not be the vertices in your 3-D surface. """ import vtk Reader = vtk.vtkDataSetReader() Reader.SetFileName(Filename) Reader.Update() Data = Reader.GetOutput() Vrts = Data.GetVerts() indices = [Vrts.GetData().GetValue(i) for i in range(1, Vrts.GetSize())] return indices
def read_vtk_scalar(filename): """ Summary: Much of this code was taken from Matthew Priddy's example file. Inputs: Outputs: """ # Initialize the reading of the VTK microstructure created by Dream3D reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.ReadAllTensorsOn() reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() dim = data.GetDimensions() vec = list(dim) vec = [i-1 for i in dim] el = vec[0] # Calculate the total number of elements el_total = el**3 Scalar = data.GetCellData().GetArray(reader.GetScalarsNameInFile(0)) scalar_py = zeros([el_total]) for ii in xrange(el_total): scalar_py[ii] = Scalar.GetValue(ii) return scalar_py
def Test3(datadir): reader = vtk.vtkDataSetReader() reader.SetFileName(datadir + "/Data/blow.vtk") reader.UpdateInformation(); reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() dssf = vtk.vtkDataSetSurfaceFilter() dssf.SetInputConnection(reader.GetOutputPort()) stripper = vtk.vtkStripper() stripper.SetInputConnection(dssf.GetOutputPort()) f = vtk.vtkIntegrateAttributes() f.SetInputConnection(stripper.GetOutputPort()) f.Update() result = f.GetOutputDataObject(0) val = result.GetPointData().GetArray("displacement1").GetValue(0) assert (val > 463.64 and val < 463.642) val = result.GetPointData().GetArray("thickness3").GetValue(0) assert (val > 874.61 and val < 874.618) val = result.GetCellData().GetArray("Area").GetValue(0) assert (val > 1145.405 and val < 1145.415)
def _ReadFile(self,**kw): """Read in a VTK data structure from a vtk data file """ fd = open( self.filepath, 'r' ) # Instantiate the field object field = objects.field.Field() reader = vtk.vtkDataSetReader() reader.SetFileName(self.filepath) #field.vtkdata = reader.GetStructuredPointsOutput() data = reader.GetOutput() # Need to update so that the data gets pulled through. data.Update() if not data: raise Exception,"VTK_IO no data found while reading file: %s" % self.filepath if not data.GetClassName() == 'vtkStructuredPoints': raise Exception,"VTK_IO someone needs to tell me how to read something other than Structured Points!" field.dim = data.GetDimensions() #print data.GetDataDimension() origin = data.GetOrigin() field.origin = objects.vector.Vector( origin ) field.vtkdata = data field.title = self.name field.name = self.name self.fields.append(field)
def get_tensor_array(filename): """Returns vtk tensor array object which can have 'GetTuple9(i)' called on it.""" reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() npoints = output.GetNumberOfPoints() print 'npoints:', npoints ncells = output.GetNumberOfCells() print 'ncells:', ncells nscalars = reader.GetNumberOfScalarsInFile() print 'nscalars:', nscalars print reader.GetScalarsNameInFile(0) ntensors = reader.GetNumberOfTensorsInFile() print 'ntensors:', ntensors print reader.GetTensorsNameInFile(0) output = reader.GetOutput() point_data = output.GetPointData() scalar_array = point_data.GetArray('scalar') tensor_array = point_data.GetArray('tensor') if not tensor_array: tensor_array = point_data.GetArray('tensors') return tensor_array
def ConvertVTKMatlab(input_filename,output_filename): import vtk.util.numpy_support as vtkNumPy import numpy import scipy.io as scipyio extension = input_filename.split('.').pop() vtkReader = None if extension == 'vtk': vtkReader = vtk.vtkDataSetReader() elif extension == 'vti': vtkReader = vtk.vtkXMLImageDataReader() else: raise RuntimeError('unknown file type %s ' % input_filename) vtkReader.SetFileName( "%s" % (input_filename) ) vtkReader.Update() imageDataVTK = vtkReader.GetOutput() dimensions = imageDataVTK.GetDimensions() spacing = imageDataVTK.GetSpacing() origin = imageDataVTK.GetOrigin() print spacing, origin, dimensions #fem.SetImagingDimensions( dimensions ,origin,spacing) image_point_data = imageDataVTK.GetPointData() image_data = vtkNumPy.vtk_to_numpy( image_point_data.GetArray(0) ) # write numpy to disk in matlab # indexing is painful.... reshape to dimensions and transpose 2d dimensions only scipyio.savemat( output_filename, {'spacing':spacing, 'origin':origin,'image':image_data.reshape(dimensions,order='F').transpose(1,0,2)})
def plot(self, plot_file=None, save_fig=False): """ Method to plot a vtk file. If `plot_file` is not given it plots `self.infile`. :param string plot_file: the vtk filename you want to plot. :param bool save_fig: a flag to save the figure in png or not. If True the plot is not shown. :return: figure: matlplotlib structure for the figure of the chosen geometry :rtype: matplotlib.pyplot.figure """ if plot_file is None: plot_file = self.infile else: self._check_filename_type(plot_file) # Read the source file. reader = vtk.vtkDataSetReader() reader.SetFileName(plot_file) reader.Update() data = reader.GetOutput() points = data.GetPoints() ncells = data.GetNumberOfCells() # for each cell it contains the indeces of the points that define the cell figure = plt.figure() axes = a3.Axes3D(figure) vtx = np.zeros((ncells, 3, 3)) for i in range(0, ncells): for j in range(0, 3): cell = data.GetCell(i).GetPointId(j) vtx[i][j][0], vtx[i][j][1], vtx[i][j][2] = points.GetPoint(int(cell)) tri = a3.art3d.Poly3DCollection([vtx[i]]) tri.set_color('b') tri.set_edgecolor('k') axes.add_collection3d(tri) ## Get the limits of the axis and center the geometry max_dim = np.array([np.max(vtx[:,:,0]), \ np.max(vtx[:,:,1]), \ np.max(vtx[:,:,2])]) min_dim = np.array([np.min(vtx[:,:,0]), \ np.min(vtx[:,:,1]), \ np.min(vtx[:,:,2])]) max_lenght = np.max(max_dim - min_dim) axes.set_xlim(-.6*max_lenght + (max_dim[0]+min_dim[0])/2, .6*max_lenght + (max_dim[0]+min_dim[0])/2) axes.set_ylim(-.6*max_lenght + (max_dim[1]+min_dim[1])/2, .6*max_lenght + (max_dim[1]+min_dim[1])/2) axes.set_zlim(-.6*max_lenght + (max_dim[2]+min_dim[2])/2, .6*max_lenght + (max_dim[2]+min_dim[2])/2) # Show the plot to the screen if not save_fig: plt.show() else: figure.savefig(plot_file.split('.')[0] + '.png') return figure
def testGlyphs(self): '''Test if the glyphs are created nicely.''' reader = vtk.vtkDataSetReader() data_file = os.path.join(Testing.VTK_DATA_ROOT, "Data", "tensors.vtk") reader.SetFileName(data_file) g1 = SimpleGlyph(reader) g1.glyph.ColorGlyphsOff() g1.Update() g2 = SimpleGlyph(reader) g2.glyph.ExtractEigenvaluesOff() g2.Update() g2.SetPosition((2.0, 0.0, 0.0)) g3 = SimpleGlyph(reader) g3.glyph.SetColorModeToEigenvalues() g3.glyph.ThreeGlyphsOn() g3.Update() g3.SetPosition((0.0, 2.0, 0.0)) g4 = SimpleGlyph(reader) g4.glyph.SetColorModeToEigenvalues() g4.glyph.ThreeGlyphsOn() g4.glyph.SymmetricOn() g4.Update() g4.SetPosition((2.0, 2.0, 0.0)) # 6Components symetric tensor g5 = SimpleGlyph(reader) g5.glyph.SetInputArrayToProcess(0, 0, 0, 0, "symTensors1") g5.SetPosition((4.0, 2.0, 0.0)) g5.Update() ren = vtk.vtkRenderer() for i in (g1, g2, g3, g4, g5): for j in i.GetActors(): ren.AddActor(j) ren.ResetCamera(); cam = ren.GetActiveCamera() cam.Azimuth(-20) cam.Elevation(20) cam.Zoom(1.1) ren.SetBackground(0.5, 0.5, 0.5) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.Render() img_file = "TestTensorGlyph.png" Testing.compareImage(renWin, Testing.getAbsImagePath(img_file)) Testing.interact()
def unpickle_vtk_2(filename): with open(filename, 'rb') as handle: to_deserialize = pickle.load(handle) reader = vtk.vtkDataSetReader() reader.ReadFromInputStringOn() reader.SetInputString(to_deserialize) reader.Update() return pv.wrap(reader.GetOutput())
def testGlyphs(self): '''Test if the glyphs are created nicely.''' reader = vtk.vtkDataSetReader() data_file = os.path.join(Testing.VTK_DATA_ROOT, "Data", "tensors.vtk") reader.SetFileName(data_file) g1 = SimpleGlyph(reader) g1.glyph.ColorGlyphsOff() g1.Update() g2 = SimpleGlyph(reader) g2.glyph.ExtractEigenvaluesOff() g2.Update() g2.SetPosition((2.0, 0.0, 0.0)) g3 = SimpleGlyph(reader) g3.glyph.SetColorModeToEigenvalues() g3.glyph.ThreeGlyphsOn() g3.Update() g3.SetPosition((0.0, 2.0, 0.0)) g4 = SimpleGlyph(reader) g4.glyph.SetColorModeToEigenvalues() g4.glyph.ThreeGlyphsOn() g4.glyph.SymmetricOn() g4.Update() g4.SetPosition((2.0, 2.0, 0.0)) # 6Components symetric tensor g5 = SimpleGlyph(reader) g5.glyph.SetInputArrayToProcess(0, 0, 0, 0, "symTensors1") g5.SetPosition((4.0, 2.0, 0.0)) g5.Update() ren = vtk.vtkRenderer() for i in (g1, g2, g3, g4, g5): for j in i.GetActors(): ren.AddActor(j) ren.ResetCamera() cam = ren.GetActiveCamera() cam.Azimuth(-20) cam.Elevation(20) cam.Zoom(1.1) ren.SetBackground(0.5, 0.5, 0.5) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.Render() img_file = "TestTensorGlyph.png" Testing.compareImage(renWin, Testing.getAbsImagePath(img_file)) Testing.interact()
def readDataSet(fileName, **kwargs): """Read the dataset from a file. The reader type used is determined from the file extension. Returns: +------------+----------------------+ | File ext. | Return type | +============+======================+ | .vtp | vtkPolyData | +------------+----------------------+ | .vtu | vtkUnstructuredGrid | +------------+----------------------+ | .vti | vtkImageData | +------------+----------------------+ | .stl | vtkPolyData | +------------+----------------------+ | .case | vtkMultiBlockDataSet | +------------+----------------------+ """ if not os.path.isfile(fileName): raise RuntimeError('The file', fileName, 'did not exist') filePrefix, fileExtension = os.path.splitext(fileName) if fileExtension == '.vtp': reader = vtk.vtkXMLPolyDataReader() elif fileExtension == '.vtu': reader = vtk.vtkXMLUnstructuredGridReader() elif fileExtension == '.vti': reader = vtk.vtkXMLImageDataReader() elif fileExtension == '.vtm': reader = vtk.vtkXMLMultiBlockDataReader() elif fileExtension == '.stl': reader = vtk.vtkSTLReader() elif fileExtension == '.vtk': #reader = _createVTKReader(fileName) reader = vtk.vtkDataSetReader() elif fileExtension == '.case': reader = vtk.vtkEnSightGoldBinaryReader() for k, v in kwargs.items(): if k == 'disableCellArrays': for arrName in v: reader.GetCellDataArraySelection().DisableArray(arrName) elif k == 'disablePointArrays': for arrName in v: reader.GetPointDataArraySelection().DisableArray(arrName) else: raise RuntimeError('Unknown keyword argument' + str(k)) else: raise RuntimeError('Unknown file extension', fileExtension) if fileExtension == '.case': reader.SetCaseFileName(fileName) else: reader.SetFileName(fileName) reader.Update() return reader.GetOutput()
def read_vtk_tensor(filename, tensor_id, comp): """ Summary: Much of this code was taken from Matthew Priddy's example file. Inputs: Outputs: """ # Initialize the reading of the VTK microstructure created by Dream3D reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.ReadAllTensorsOn() reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() dim = data.GetDimensions() vec = list(dim) vec = [i - 1 for i in dim] el = vec[0] # Calculate the total number of elements el_total = el**3 meas = data.GetCellData().GetArray(reader.GetTensorsNameInFile(tensor_id)) # if tensor_id == 0, we read the stress tensor # if tensor_id == 1, we read the strain tensor # if tensor_id == 2, we read the plastic strain tensor meas_py = np.zeros([el_total]) for ii in xrange(el_total): meas_py[ii] = meas.GetValue(ii * 9 + comp) return meas_py
def get_num_fibers(filename): reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() #import pudb #pudb.set_trace() nlines = reader.GetOutput().GetNumberOfLines() return nlines
def read(filename): reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() header = reader.GetHeader() no_nodes = data.GetNumberOfPoints() no_connections = data.GetNumberOfCells() return (data, header, no_nodes, no_connections)
def _create_vtk_reader(self,url,type): if type==1: self.reader=vtk.vtkDataSetReader() self.reader.SetFileName(url) self.reader.Update() print "zrobilem vtk readera" if type==0: print "convert_dat_file_to_vtk_reader(url)" self.reader=self.convert_dat_file_to_vtk_reader(url)
def read_vtk_struct(filename): reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.ReadAllFieldsOn() reader.Update() polydata = reader.GetOutput() points = vtk_to_numpy(polydata.GetPoints().GetData()) cells = vtk_to_numpy(polydata.GetCells().GetData()) cells = reshape_cells(cells) return cells, points
def load_vtk_cloud(vtk_cloud_file): reader = vtk.vtkDataSetReader() reader.SetFileName(vtk_cloud_file) reader.Update() actor = vtk.vtkActor() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(reader.GetOutputPort()) actor.SetMapper(mapper) return actor
def write(self, output_values, filename, output_name=None, write_bin=False): """ Writes a mat file, called filename. output_values is a matrix that contains the new values of the output to write in the mat file. :param numpy.ndarray output_values: it is a `n_points`-by-1 matrix containing the values of the chosen output. :param string filename: name of the output file. :param string output_name: name of the output of interest inside the mat file. If it is not passed, it is equal to self.output_name. :param bool write_bin: flag to write in the binary format. Default is False. """ self._check_filename_type(filename) self._check_extension(filename) self._check_infile_instantiation(self.infile) if output_name is None: output_name = self.output_name else: self._check_filename_type(output_name) reader = vtk.vtkDataSetReader() reader.SetFileName(self.infile) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() output_array = ns.numpy_to_vtk(num_array=output_values, array_type=vtk.VTK_DOUBLE) output_array.SetName(output_name) if self.cell_data is True: data.GetCellData().AddArray(output_array) else: data.GetPointData().AddArray(output_array) writer = vtk.vtkDataSetWriter() if write_bin: writer.SetFileTypeToBinary() writer.SetFileName(filename) if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(data) else: writer.SetInputData(data) writer.Write()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkDataSetReader(), "Reading vtkDataSet.", (), ("vtkDataSet",), replaceDoc=True, inputFunctions=None, outputFunctions=None, )
def vtk_points(offset, filenameout='data'): filename = ''.join([filenameout, repr(offset), '.vtk']) datareader = v.vtkDataSetReader() datareader.SetFileName(filename) datareader.Update() data = datareader.GetOutput() vtk_points = data.GetPoints().GetData() points = ah.vtk2array(vtk_points) return points
def vtk_points(offset,filenameout='data'): filename=''.join([filenameout,repr(offset),'.vtk']) datareader = v.vtkDataSetReader() datareader.SetFileName(filename) datareader.Update() data = datareader.GetOutput() vtk_points=data.GetPoints().GetData() points=ah.vtk2array(vtk_points) return points
def vtk2stl(fn_in, fn_out): reader = vtk.vtkDataSetReader() reader.SetFileName(fn_in) reader.Update() gfilter = vtk.vtkGeometryFilter() gfilter.SetInput(reader.GetOutput()) writer = vtk.vtkSTLWriter() writer.SetFileName(fn_out) writer.SetInput(gfilter.GetOutput()) writer.Write()
def main(filenameIn, filenameOut, origin, spacing): r = vtk.vtkDataSetReader() r.SetFileName(filenameIn) r.Update() data = vtk.vtkImageData() data.ShallowCopy(r.GetOutput()) data.SetOrigin(origin) data.SetSpacing(spacing) data.Update() w = vtk.vtkStructuredPointsWriter() w.SetInput(data) w.SetFileName(filenameOut) w.Write()
def main(filenameIn,filenameOut,origin,spacing): r = vtk.vtkDataSetReader() r.SetFileName(filenameIn) r.Update() data = vtk.vtkImageData() data.ShallowCopy(r.GetOutput()) data.SetOrigin(origin) data.SetSpacing(spacing) data.Update() w = vtk.vtkStructuredPointsWriter() w.SetInput(data) w.SetFileName(filenameOut) w.Write()
def __setstate__(self, state): """Support unpickle.""" vtk_serialized = state.pop('vtk_serialized') self.__dict__.update(state) reader = vtk.vtkDataSetReader() reader.ReadFromInputStringOn() reader.SetInputString(vtk_serialized) reader.Update() mesh = pyvista.wrap(reader.GetOutput()) # copy data self.copy_structure(mesh) self.copy_attributes(mesh)
def write(self, output_values, filename, output_name=None, write_bin=False): """ Writes a mat file, called filename. output_values is a matrix that contains the new values of the output to write in the mat file. :param numpy.ndarray output_values: it is a `n_points`-by-1 matrix containing the values of the chosen output. :param string filename: name of the output file. :param string output_name: name of the output of interest inside the mat file. If it is not passed, it is equal to self.output_name. :param bool write_bin: flag to write in the binary format. Default is False. """ self._check_filename_type(filename) self._check_extension(filename) self._check_infile_instantiation(self.infile) if output_name is None: output_name = self.output_name else: self._check_filename_type(output_name) reader = vtk.vtkDataSetReader() reader.SetFileName(self.infile) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() output_array = ns.numpy_to_vtk(num_array=output_values,array_type=vtk.VTK_DOUBLE) output_array.SetName(output_name) if self.cell_data is True: data.GetCellData().AddArray(output_array) else: data.GetPointData().AddArray(output_array) writer = vtk.vtkDataSetWriter() if write_bin: writer.SetFileTypeToBinary() writer.SetFileName(filename) if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(data) else: writer.SetInputData(data) writer.Write()
def read_legacy(filename): """Use VTK's legacy reader to read a file.""" reader = vtk.vtkDataSetReader() reader.SetFileName(filename) # Ensure all data is fetched with poorly formatted legacy files reader.ReadAllScalarsOn() reader.ReadAllColorScalarsOn() reader.ReadAllNormalsOn() reader.ReadAllTCoordsOn() reader.ReadAllVectorsOn() # Perform the read output = standard_reader_routine(reader, None) if output is None: raise RuntimeError('No output when using VTKs legacy reader') return output
def unpickle_vtk(data): unpickled_data = pickle.loads( data) # data is a result of writer.GetOutputString() reader = vtk.vtkDataSetReader() # Which one to use? # reader.SetReadFromInputString(True) reader.ReadFromInputStringOn() reader.SetInputString(unpickled_data) # reader.ReadAllVectorsOn() # reader.ReadAllScalarsOn() reader.Update() data = pv.wrap(reader.GetOutput()) return data # this is a vtk object being returned
def main(filenameIn,filenameOut,dx,dy,dz,vx,vy,vz): r = vtk.vtkDataSetReader() r.SetFileName(filenameIn) r.Update() data = vtk.vtkImageData() data.ShallowCopy(r.GetOutput()) data.SetOrigin(dx,dy,dz) data.SetSpacing(dx/vx,dy/vy,dz/vz) data.Update() #w = vtk.vtkDataSetWriter() w = vtk.vtkStructuredPointsWriter() # w.SetInputConnection(data.GetProducerPort()) w.SetInput(data) w.SetFileName(filenameOut) w.Write()
def parse(self, filename, output_name=None): """ Method to parse the `filename`. It returns a vector (matrix with one column) with all the values of the chosen output. If `output_name` is not given it is set to the default value. :param string filename: name of the input file. :param string output_name: name of the output of interest inside the mat file. If it is not passed, it is equal to self.output_name. :return: output_values: it is a `n_points`-by-1 matrix containing the values of the chosen output :rtype: numpy.ndarray """ if output_name is None: output_name = self.output_name else: self._check_filename_type(output_name) self._check_filename_type(filename) self._check_extension(filename) self.infile = filename reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() extracted_data_cell = data.GetCellData().GetArray(output_name) extracted_data_point = data.GetPointData().GetArray(output_name) if extracted_data_cell is None: extracted_data = extracted_data_point self.cell_data = False else: extracted_data = extracted_data_cell self.cell_data = True # TODO: check if the output is a scalar or vector data_dim = extracted_data.GetSize() output_values = np.zeros([data_dim,1]) for i in range (0,data_dim): output_values[i] = extracted_data.GetValue(i) return output_values
def parse(self, filename, output_name=None): """ Method to parse the `filename`. It returns a vector (matrix with one column) with all the values of the chosen output. If `output_name` is not given it is set to the default value. :param string filename: name of the input file. :param string output_name: name of the output of interest inside the mat file. If it is not passed, it is equal to self.output_name. :return: output_values: it is a `n_points`-by-1 matrix containing the values of the chosen output :rtype: numpy.ndarray """ if output_name is None: output_name = self.output_name else: self._check_filename_type(output_name) self._check_filename_type(filename) self._check_extension(filename) self.infile = filename reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.ReadAllVectorsOn() reader.ReadAllScalarsOn() reader.Update() data = reader.GetOutput() extracted_data_cell = data.GetCellData().GetArray(output_name) extracted_data_point = data.GetPointData().GetArray(output_name) if extracted_data_cell is None: extracted_data = extracted_data_point self.cell_data = False else: extracted_data = extracted_data_cell self.cell_data = True # TODO: check if the output is a scalar or vector data_dim = extracted_data.GetSize() output_values = np.zeros([data_dim, 1]) for i in range(0, data_dim): output_values[i] = extracted_data.GetValue(i) return output_values
def read_faces_points(filename): """ Load points and faces of a VTK surface file. Parameters ---------- filename : string path/filename of a VTK format file Returns ------- faces : list of lists of integers each element is list of 3 indices of vertices that form a face on a surface mesh points : list of lists of floats each element is a list of 3-D coordinates of a surface mesh vertex npoints : integer number of points Examples -------- >>> import os >>> from mindboggle.utils.io_vtk import read_faces_points >>> path = os.environ['MINDBOGGLE_DATA'] >>> folds_file = os.path.join(path, 'arno', 'features', 'folds.vtk') >>> faces, points, npoints = read_faces_points(folds_file) """ import vtk Reader = vtk.vtkDataSetReader() Reader.SetFileName(filename) Reader.ReadAllScalarsOn() # Activate the reading of all scalars Reader.Update() Data = Reader.GetOutput() points = [list(Data.GetPoint(point_id)) for point_id in range(Data.GetNumberOfPoints())] npoints = len(points) if Data.GetNumberOfPolys() > 0: faces = [[int(Data.GetPolys().GetData().GetValue(j)) for j in range(i*4 + 1, i*4 + 4)] for i in range(Data.GetPolys().GetNumberOfCells())] else: faces = [] return faces, points, npoints
def read_vtk(filename): reader = vtk.vtkDataSetReader() reader.SetFileName(filename) reader.Update() out = reader.GetOutput() verts = np.zeros((out.GetNumberOfPoints(), 3)) for i in xrange(out.GetNumberOfPoints()): verts[i] = np.array(out.GetPoint(i)) faces = np.zeros((out.GetPolys().GetNumberOfCells(), 3)) for i in xrange(out.GetPolys().GetNumberOfCells()): faces[i] = np.array([int(out.GetPolys().GetData().GetValue(j)) for j in range(4 * i + 1, 4 * i + 4)]) return verts, faces
def ReadLegacyVTK(file_name): reader = vtk.vtkDataSetReader() reader.SetFileName(file_name) reader.Update() if None != reader.GetPolyDataOutput(): polyData = vtk.vtkPolyData() polyData.ShallowCopy(reader.GetPolyDataOutput()) return polyData if None != reader.GetUnstructuredGridOutput(): return VTKViewer.ConvertDataSetToSurface(reader.GetOutputPort()) if None != reader.GetStructuredPointsOutput(): return VTKViewer.ConvertDataSetToSurface(reader.GetOutputPort()) if None != reader.GetStructuredGridOutput(): return VTKViewer.ConvertDataSetToSurface(reader.GetOutputPort()) if None != reader.GetRectilinearGridOutput(): return VTKViewer.ConvertDataSetToSurface(reader.GetOutputPort()) else: raise Exception("unsupported: ????????\n")