def compare_files_vtu(first_file, second_file, file_type, tolerance=1e-12): import vtk # read files: if file_type == "vtu": reader1 = vtk.vtkXMLUnstructuredGridReader() reader2 = vtk.vtkXMLUnstructuredGridReader() else: reader1 = vtk.vtkXMLPUnstructuredGridReader() reader2 = vtk.vtkXMLPUnstructuredGridReader() reader1.SetFileName(first_file) reader1.Update() output1 = reader1.GetOutput() reader2.SetFileName(second_file) reader2.Update() output2 = reader2.GetOutput() # check fidelity point_data1 = output1.GetPointData() point_data2 = output2.GetPointData() # verify same number of PointData arrays in both files if point_data1.GetNumberOfArrays() != point_data2.GetNumberOfArrays(): print("File 1:", point_data1.GetNumberOfArrays(), "\n", "File 2:", point_data2.GetNumberOfArrays()) raise ValueError("Fidelity test failed: Mismatched data array count") for i in range(point_data1.GetNumberOfArrays()): arr1 = point_data1.GetArray(i) arr2 = point_data2.GetArray(i) # verify both files contain same arrays if point_data1.GetArrayName(i) != point_data2.GetArrayName(i): print("File 1:", point_data1.GetArrayName(i), "\n", "File 2:", point_data2.GetArrayName(i)) raise ValueError( "Fidelity test failed: Mismatched data array names") # verify arrays are same sizes in both files if arr1.GetSize() != arr2.GetSize(): print("File 1, DataArray", i, ":", arr1.GetSize(), "\n", "File 2, DataArray", i, ":", arr2.GetSize()) raise ValueError( "Fidelity test failed: Mismatched data array sizes") # verify individual values w/in given tolerance for j in range(arr1.GetSize()): if abs(arr1.GetValue(j) - arr2.GetValue(j)) > tolerance: print("Tolerance:", tolerance) raise ValueError( "Fidelity test failed: Mismatched data array values with given tolerance" ) print("VTU Fidelity test completed successfully with tolerance", tolerance)
def scalar(self): pass ''' ''' #self.scalar= scalar # define reader for pvtu, set timestape xmlReader = vtk.vtkXMLPUnstructuredGridReader() xmlReader.SetFileName(self.fname) xmlReader.Update() # number of arrays narrays = xmlReader.GetOutput().GetPointData().GetNumberOfArrays() # number of partitions npartition = xmlReader.GetNumberOfPieces() output = xmlReader.GetOutput() xmlReader.Update() self.dict_scalars = {} for i in range(narrays): self.dict_scalars[i] = xmlReader.GetPointArrayName(i) print(self.dict_scalars) return self.dict_scalars def reader(self): pass xmlReader = vtk.vtkXMLPUnstructuredGridReader() xmlReader.SetFileName(self.path_timestep) xmlReader.Update() narrays = xmlReader.GetOutput().GetPointData().GetNumberOfArrays() output = xmlReader.GetOutput() xmlReader.Update() npartition = xmlReader.GetNumberOfPieces() dict_var = {} for i in range(narrays): dict_var[i] = xmlReader.GetPointArrayName(i) self.velocity = vtk_to_numpy( xmlReader.GetOutput().GetPointData().GetArray(19)) print(dict_var) print(narrays) print(npartition)
def __init__(self,offset,get=1,file='data',type='vtu',mirrorPlane=None,silent=0): self.offset=offset self.filenameout = file self.type = type self.isLoaded = False self.mirrorPlane=mirrorPlane self.silent = silent if type == 'vtu': self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.vtu']) self.datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.pvtu']) self.datareader = v.vtkXMLPUnstructuredGridReader() elif type == 'vti': self.filename=''.join([self.filenameout,repr(offset).zfill(4),'.vti']) self.datareader = v.vtkXMLImageDataReader() else: print 'Unknown filetype' if (self.silent == 0): print '========================================' if (self.silent == 0): print 'loading file %s' % (self.filename) if get != None: self.getAll()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkXMLPUnstructuredGridReader(), 'Reading vtkXMLPUnstructuredGrid.', (), ('vtkXMLPUnstructuredGrid',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def read_vertical_heatflux(self, n, verbose=False, **kwargs): if not (hasattr(self, 'snames')): self.get_solution_filenames(verbose=verbose) if self.mesh_file != self.mnames[n]: self.read_mesh(n, verbose=verbose) filename = self.directory + self.snames[n] if verbose: print("Reading vertical heat flux from", filename) if self.format == 'hdf5': f = h5py.File(filename, "r") Fz_data = f['vertical_heat_flux'] Fz = Fz_data[:, 0] if self.format == 'vtu': reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(filename) reader.Update() my_vtk_array = reader.GetOutput().GetPointData().GetArray( "vertical_heat_flux") Fz = vtk_to_numpy(my_vtk_array) # print('loaded shape', np.shape(T)) Fz = Fz[self.indices] Fz.shape = self.array_shape # print('final shape', np.shape(Fz)) return self.x, self.y, self.z, Fz
def ReadPVTUFile(fname): reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(fname) reader.Update() #print reader.GetNumberOfPieces() return reader
def __init__(self, filename=None): """Creates a vtu object by reading the specified file.""" if filename is None: self.ugrid = vtk.vtkUnstructuredGrid() else: self.gridreader = None if filename[-4:] == ".vtu": self.gridreader = vtk.vtkXMLUnstructuredGridReader() elif filename[-5:] == ".pvtu": self.gridreader = vtk.vtkXMLPUnstructuredGridReader() else: raise Exception("ERROR: don't recognise file extension" + filename) self.gridreader.SetFileName(filename) self.gridreader.Update() self.ugrid = self.gridreader.GetOutput() self.points = self.ugrid.GetPoints() self.pointdata = self.ugrid.GetPointData() self.cells = self.ugrid.GetCells() self.celldata = self.ugrid.GetCellData() if self.ugrid.GetNumberOfPoints() + self.ugrid.GetNumberOfCells( ) == 0: raise Exception( "ERROR: No points or cells found after loading vtu " + filename) self._coords = None self.filename = filename self._data_dict = {} self._rawdata_dict = {} self._rawcelldata_dict = {} self._raw_coords = None
def load_vtk_mesh(fileName): """ Loads surface/volume mesh to VTK """ if (fileName == ''): return 0 fn_dir, fn_ext = os.path.splitext(fileName) if (fn_ext == '.vtk'): print('Reading vtk with name: ', fileName) reader = vtk.vtkPolyDataReader() elif (fn_ext == '.vtp'): print('Reading vtp with name: ', fileName) reader = vtk.vtkXMLPolyDataReader() elif (fn_ext == '.stl'): print('Reading stl with name: ', fileName) reader = vtk.vtkSTLReader() elif (fn_ext == '.obj'): print('Reading obj with name: ', fileName) reader = vtk.vtkOBJReader() elif (fn_ext == '.vtu'): print('Reading vtu with name: ', fileName) reader = vtk.vtkXMLUnstructuredGridReader() elif (fn_ext == '.pvtu'): print('Reading pvtu with name: ', fileName) reader = vtk.vtkXMLPUnstructuredGridReader() else: print(fn_ext) raise ValueError('File extension not supported') reader.SetFileName(fileName) reader.Update() return reader.GetOutput()
def get_pointdata(offset,filenameout='data',type='pvtu',attribute_mode='cell'): if type == 'vtu': filename=''.join([filenameout,repr(offset).zfill(4),'.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': filename=''.join([filenameout,repr(offset).zfill(4),'.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() print '=== Reading ',filename,' ===' datareader.SetFileName(filename) datareader.Update() data = datareader.GetOutput() if attribute_mode == 'cell': c2p = v.vtkCellDataToPointData() c2p.SetInput(data) pointdata=c2p.GetOutput() pointdata.Update() else: pointdata = data vtk_points=data.GetPoints().GetData() points=ah.vtk2array(vtk_points) print '=== Done with reading data! ===' return {'pointdata': pointdata, 'points': points}
def ReadVTKXMLPMeshFile(self): if (self.InputFileName == ''): self.PrintError('Error: no InputFileName.') self.PrintLog('Reading VTK XML Parallel format mesh file.') reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(self.InputFileName) reader.Update() self.Mesh = reader.GetOutput()
def read_mesh(self, n, verbose=False): if not (hasattr(self, 'snames')): self.get_solution_filenames(verbose=verbose) # if self.format=='hdf5': # mesh_filename = self.directory+"mesh-00000.h5" # if self.format=='vtu': # mesh_filename = self.directory+"solution-09999.pvtu" mesh_filename = self.directory + self.mnames[n] self.mesh_file = self.mnames[n] if verbose: print("Reading mesh from", mesh_filename) if self.format == 'hdf5': mesh_file = h5py.File(mesh_filename, "r") nodes_data = mesh_file['nodes'] coords = nodes_data[:, :] if self.format == 'vtu': reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(mesh_filename) reader.Update() my_vtk_array = reader.GetOutput().GetPointData().GetArray("T") nodes_vtk_array = reader.GetOutput().GetPoints().GetData() coords = vtk_to_numpy(nodes_vtk_array) # Just collect unique rows (duplication due to parallel files) coords = coords.round(decimals=14) # idx = unique_rows_indices(coords) u, idx = np.unique(coords, axis=0, return_index=True) ind = np.lexsort((coords[idx, 2], coords[idx, 1], coords[idx, 0])) self.indices = idx[ind] self.coords = coords[self.indices, :] xm = self.coords[:, 0] ym = self.coords[:, 1] zm = self.coords[:, 2] xu = np.unique(xm) yu = np.unique(ym) zu = np.unique(zm) self.x, self.y, self.z = xu, yu, zu nx, ny, nz = len(self.x), len(self.y), len(self.z) self.array_shape = (nx, ny, nz) xm.shape = self.array_shape ym.shape = self.array_shape zm.shape = self.array_shape self.xm = xm self.ym = ym self.zm = zm return self.x, self.y, self.z
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkXMLPUnstructuredGridReader(), 'Reading vtkXMLPUnstructuredGrid.', (), ('vtkXMLPUnstructuredGrid', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def get_numpy_arrays(t): # Load modules import vtk as vtk from vtk.util import numpy_support # Get pvtu number pvtu_number = get_pvtu_number(time_steps[t]) # Load vtu data (pvtu directs to vtu files) reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(vtk_directory + 'solution-' + pvtu_number + '.pvtu') reader.Update() # Get the coordinates of nodes in the mesh nodes_vtk_array = reader.GetOutput().GetPoints().GetData() # Convert nodal vtk data to a numpy array nodes_numpy_array = vtk.util.numpy_support.vtk_to_numpy(nodes_vtk_array) # Extract x, y and z coordinates from numpy array x, y, z = nodes_numpy_array[:, 0], nodes_numpy_array[:, 1], nodes_numpy_array[:, 2] # Determine the number of scalar fields contained in the .pvtu file number_of_fields = reader.GetOutput().GetPointData().GetNumberOfArrays() # Determine the name of each field and place it in an array. field_names = [] for i in range(number_of_fields): field_names.append(reader.GetOutput().GetPointData().GetArrayName(i)) # Determine the index of the temperature field idx = field_names.index("T") # Extract values of temperature field_vtk_array = reader.GetOutput().GetPointData().GetArray(idx) temperature = numpy_support.vtk_to_numpy(field_vtk_array) # Determine the index of the pressure field idx = field_names.index("p") # Extract values of pressure field_vtk_array = reader.GetOutput().GetPointData().GetArray(idx) pressure = numpy_support.vtk_to_numpy(field_vtk_array) # Save unfiltered (raw vtk) arrays np.savez(results_directory + '/' + 'unfiltered_' + pvtu_number, x=x, y=y, z=z, temperature=temperature, pressure=pressure) return x, y, z, temperature, pressure
def __init__(self, bodypoints, geoname, AutomaticFile, AutomaticVTU_Number, parallel, U0 = None, p0 = None, rho0 = None): """ Read vtu/pvtu file and geo file, set basic information. """ self.bodypoints = bodypoints self.geoname = geoname self.AutomaticFile = AutomaticFile self.AutomaticVTU_Number = AutomaticVTU_Number self.parallel = parallel self.U0 = U0 self.p0 = p0 self.rho0 = rho0 # Reading *.vtu/*.pvtu file if (len(sys.argv)>1): filename = sys.argv[1] vtu_number = int(sys.argv[2]) else: filename = self.AutomaticFile vtu_number = int(self.AutomaticVTU_Number) if parallel == True: reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(filename+'_'+str(vtu_number)+'.pvtu') elif parallel == False: reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(filename+'_'+str(vtu_number)+'.vtu') self.reader = reader # Read *.geo file info = [] infile = open(self.geoname, "rb") for line in infile: if line.split()[0] != 'Point': break words = line.split('{')[1].split('}')[0].split(', ') nums = [] for i in range(3): num = float(words[i]) nums.append(num) info.append(nums) arrays = np.array(info) self.c0 = arrays[0] r = abs(arrays[1, 0] - self.c0[0]) #r = sum(abs(arrays[1:self.bodypoints + 1, 0] - self.c0[0]))/self.bodypoints self.D = 2 * r geolen = [] for i in range(3): geolen.append(max(arrays[:,i])) self.geolen = np.array(geolen)
def __init__(self, offset, get=1, file='data', type='vtu', mirrorPlane=None, rotateX=0, rotateY=0, rotateZ=0, scaleX=1, scaleY=1, scaleZ=1, silent=0): self.offset = offset self.filenameout = file self.type = type self.isLoaded = False self.mirrorPlane = mirrorPlane self.silent = silent self.rotateX = rotateX self.rotateY = rotateY self.rotateZ = rotateZ self.scaleX = scaleX self.scaleY = scaleY self.scaleZ = scaleZ if type == 'vtu': self.filename = ''.join( [self.filenameout, repr(offset).zfill(4), '.vtu']) self.datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': self.filename = ''.join( [self.filenameout, repr(offset).zfill(4), '.pvtu']) self.datareader = v.vtkXMLPUnstructuredGridReader() elif type == 'vti': self.filename = ''.join( [self.filenameout, repr(offset).zfill(4), '.vti']) self.datareader = v.vtkXMLImageDataReader() else: print('Unknown filetype') if (self.silent == 0): print('========================================') if (self.silent == 0): print('loading file %s' % (self.filename)) if get is not None: self.getAll()
def vtu_values(offset,varname,filenameout='data',attribute_mode='cell',type='vtu'): if type == 'vtu': filename=''.join([filenameout,repr(offset).zfill(4),'.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': filename=''.join([filenameout,repr(offset).zfill(4),'.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() datareader.SetFileName(filename) datareader.Update() data = datareader.GetOutput() return read.extract(data,varname,attribute_mode=attribute_mode)
def read_ugrid(filename): if filename.endswith(".pvtu"): reader = vtk.vtkXMLPUnstructuredGridReader() elif filename.endswith(".vtk"): reader = vtk.vtkUnstructuredGridReader() elif filename.endswith(".vtu"): reader = vtk.vtkUnstructuredGridReader() else: raise BaseException("Illegal filename suffix %s" % filename) reader.SetFileName(filename) reader.Update() return reader.GetOutput()
def _read_single(filename, vtk_type=None): vtk_type = vtk_type or _get_vtk_type(filename) if vtk_type == 'UnstructuredGrid': reader = vtk.vtkXMLUnstructuredGridReader() elif vtk_type == 'PUnstructuredGrid': reader = vtk.vtkXMLPUnstructuredGridReader() else: raise NotImplementedError( f"VTK Files of type {vtk_type} can not yet be processed") reader.SetFileName(filename) reader.Update() geometryFilter = vtk.vtkGeometryFilter() geometryFilter.SetInputData(reader.GetOutput()) geometryFilter.Update() return geometryFilter.GetOutput()
def vtu_points(offset,filenameout='data',type='vtu'): if type == 'vtu': filename=''.join([filenameout,repr(offset).zfill(4),'.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': filename=''.join([filenameout,repr(offset).zfill(4),'.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() datareader.SetFileName(filename) datareader.Update() data = datareader.GetOutput() vtk_points=data.GetPoints().GetData() points=ah.vtk2array(vtk_points) return points
def readData(self): if self.type == 'vtu': filename=''.join([self.filenameout,repr(self.offset).zfill(4),'.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif self.type == 'pvtu': filename=''.join([self.filenameout,repr(self.offset).zfill(4),'.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() print '=== Reading ',filename,' ===' datareader.SetFileName(filename) datareader.Update() self.data = datareader.GetOutput() vtk_points=self.data.GetPoints().GetData() self.points=ah.vtk2array(vtk_points)
def readXMLPUGrid(mesh_file_name, verbose=True): if (verbose): print '*** readXMLPUGrid ***' mesh_reader = vtk.vtkXMLPUnstructuredGridReader() mesh_reader.SetFileName(mesh_file_name) mesh_reader.Update() mesh = mesh_reader.GetOutput() if (verbose): nb_points = mesh.GetNumberOfPoints() print 'nb_points =', nb_points nb_cells = mesh.GetNumberOfCells() print 'nb_cells =', nb_cells return mesh
def vtu_points(offset, filenameout='data', type='vtu'): if type == 'vtu': filename = ''.join([filenameout, repr(offset).zfill(4), '.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': filename = ''.join([filenameout, repr(offset).zfill(4), '.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() datareader.SetFileName(filename) datareader.Update() data = datareader.GetOutput() vtk_points = data.GetPoints().GetData() points = ah.vtk2array(vtk_points) return points
def __init__(self, filename = None): """Creates a vtu object by reading the specified file.""" if filename is None: self.ugrid = vtk.vtkUnstructuredGrid() else: self.gridreader = None if filename[-4:] == ".vtu": self.gridreader=vtk.vtkXMLUnstructuredGridReader() elif filename[-5:] == ".pvtu": self.gridreader=vtk.vtkXMLPUnstructuredGridReader() else: raise Exception("ERROR: don't recognise file extension" + filename) self.gridreader.SetFileName(filename) self.gridreader.Update() self.ugrid=self.gridreader.GetOutput() if self.ugrid.GetNumberOfPoints() + self.ugrid.GetNumberOfCells() == 0: raise Exception("ERROR: No points or cells found after loading vtu " + filename) self.filename=filename
def vtu_values(offset, varname, filenameout='data', attribute_mode='cell', type='vtu'): if type == 'vtu': filename = ''.join([filenameout, repr(offset).zfill(4), '.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': filename = ''.join([filenameout, repr(offset).zfill(4), '.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() datareader.SetFileName(filename) datareader.Update() data = datareader.GetOutput() return read.extract(data, varname, attribute_mode=attribute_mode)
def Contour(self, val): parallel = False if self.vtuname.endswith(".pvtu"): parallel = True # NAME OF THE VARIABLE YOU WANT TO EXTRACT DATA FROM path = self.path data_name_field = self.field # Initial if (parallel == True): reader = vtk.vtkXMLPUnstructuredGridReader() else: reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(self.path + self.vtuname) reader.Update() field = [] coords = [] X = [] Y = [] ugrid = reader.GetOutput() ugrid.GetPointData().SetActiveScalars(data_name_field) Contour = vtk.vtkContourFilter() Contour.SetInputData(ugrid) Contour.SetNumberOfContours(1) Contour.SetValue(0, val) Contour.Update() # Fields=Contour.GetOutputDataObject(0) CContour = Contour.GetOutput() num = CContour.GetNumberOfPoints() print(num) for i in range(num): #field.append(CContour.GetPointData().GetScalars().GetTuple3(i)) coords.append(CContour.GetPoints().GetData().GetTuple3(i)) X.append(float(coords[i][0])) Y.append(float(coords[i][1])) # for i in range(0,4000): # field.append(Contour.GetPointData().GetScalars().GetTuple3(i)) # plt.plot(np.unique(Y), np.poly1d(np.polyfit(Y, X, 25))(np.unique(Y))) # return coords, X, Y
def load(offset, filenameout='data', type='pvtu'): if type == 'vtu': filename = ''.join([filenameout, repr(offset).zfill(4), '.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': filename = ''.join([filenameout, repr(offset).zfill(4), '.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() print '=== loading and converting to pointdata, file:', filename, ' ===' datareader.SetFileName(filename) datareader.Update() c2p = v.vtkCellDataToPointData() c2p.SetInput(datareader.GetOutput()) pointdata = c2p.GetOutput() pointdata.Update() print '=== Done with loading pointdata ===' return pointdata
def load(offset, filenameout="data", type="pvtu"): if type == "vtu": filename = "".join([filenameout, repr(offset).zfill(4), ".vtu"]) datareader = v.vtkXMLUnstructuredGridReader() elif type == "pvtu": filename = "".join([filenameout, repr(offset).zfill(4), ".pvtu"]) datareader = v.vtkXMLPUnstructuredGridReader() print "=== loading and converting to pointdata, file:", filename, " ===" datareader.SetFileName(filename) datareader.Update() c2p = v.vtkCellDataToPointData() c2p.SetInput(datareader.GetOutput()) pointdata = c2p.GetOutput() pointdata.Update() print "=== Done with loading pointdata ===" return pointdata
def __init__(self, bodypoints, geoname, AutomaticFile, AutomaticVTU_Number, parallel, c0, D, geolen, U0=None, p0=None, rho0=None): """ Read vtu/pvtu file and geo file, set basic information. """ self.bodypoints = bodypoints self.geoname = geoname self.AutomaticFile = AutomaticFile self.AutomaticVTU_Number = AutomaticVTU_Number self.parallel = parallel self.U0 = U0 self.p0 = p0 self.rho0 = rho0 self.c0 = c0 self.D = D self.geolen = geolen # Reading *.vtu/*.pvtu file if (len(sys.argv) > 1): filename = sys.argv[1] vtu_number = int(sys.argv[2]) else: filename = self.AutomaticFile vtu_number = int(self.AutomaticVTU_Number) if parallel == True: reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(filename + '_' + str(vtu_number) + '.pvtu') elif parallel == False: reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(filename + '_' + str(vtu_number) + '.vtu') self.reader = reader
def read_velocity(self, n, verbose=False, **kwargs): if not (hasattr(self, 'snames')): self.get_solution_filenames(verbose=verbose) if self.mesh_file != self.mnames[n]: self.read_mesh(n, verbose=verbose) filename = self.directory + self.snames[n] if verbose: print("Reading velocity from", filename) if self.format == 'hdf5': f = h5py.File(filename, "r") vel_data = f['velocity'] u = vel_data[:, 0] v = vel_data[:, 1] w = vel_data[:, 2] if self.format == 'vtu': reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(filename) reader.Update() my_vtk_array = reader.GetOutput().GetPointData().GetArray( "velocity") vel_data = vtk_to_numpy(my_vtk_array) u = vel_data[:, 0] v = vel_data[:, 1] w = vel_data[:, 2] u = u[self.indices] u.shape = self.array_shape v = v[self.indices] v.shape = self.array_shape w = w[self.indices] w.shape = self.array_shape mag = np.sqrt(u**2 + v**2 + w**2) return self.x, self.y, self.z, u, v, w, mag
def MergeVTKWorker(itime, args): appendF = vtk.vtkAppendFilter() for inpts in args.inputs: # g = vtkXMLUnstructuredGridReader() # VTU file g = vtk.vtkXMLPUnstructuredGridReader() # PVTU file g.SetFileName(inpts) g.Update() appendF.AddInputData(g.GetOutput()) # print appendF.GetMergePoints() appendF.MergePointsOn() # print appendF.GetMergePoints() appendF.Update() W = vtk.vtkXMLUnstructuredGridWriter() W.SetFileName(args.output) W.SetInputData(appendF.GetOutput()) W.Update()
def read_dataset(filename): import vtk extension = os.path.splitext(filename)[1] if (extension == ".vtk"): # VTK Legacy format reader = vtk.vtkDataSetReader() elif (extension == ".vtp"): # VTK XML Poly format reader = vtk.vtkXMLPolyDataReader() elif (extension == ".vtu"): # VTK XML Unstructured format reader = vtk.vtkXMLUnstructuredGridReader() elif (extension == ".stl"): # Stereolithography format reader = vtk.vtkSTLReader() elif (extension == ".ply"): # Stanford triangle format reader = vtk.vtkPLYReader() elif (extension == ".obj"): # Wavefront OBJ format reader = vtk.vtkOBJReader() elif (extension == ".pvtu"): reader = vtk.vtkXMLPUnstructuredGridReader() # Parallel XML format else: raise MeshFormatError() reader.SetFileName(filename) reader.Update() return reader.GetOutput()
def get_pointdata(offset,filenameout='data',type='pvtu'): if type == 'vtu': filename=''.join([filenameout,repr(offset).zfill(4),'.vtu']) datareader = v.vtkXMLUnstructuredGridReader() elif type == 'pvtu': filename=''.join([filenameout,repr(offset).zfill(4),'.pvtu']) datareader = v.vtkXMLPUnstructuredGridReader() print '=== Reading ',filename,' ===' datareader.SetFileName(filename) datareader.Update() data = datareader.GetOutput() c2p = v.vtkCellDataToPointData() c2p.SetInput(data) pointdata=c2p.GetOutput() pointdata.Update() vtk_points=data.GetPoints().GetData() points=ah.vtk2array(vtk_points) print '=== Done with reading data! ===' return {'pointdata': pointdata, 'points': points}
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 TestDataType('ImageData', vtk.vtkXMLPImageDataReader(), vtk.vtkXMLPImageDataWriter(), 'vti', 4924) TestDataType('RectilinearGrid', vtk.vtkXMLPRectilinearGridReader(), vtk.vtkXMLPRectilinearGridWriter(), 'vtr', 4924) TestDataType('StructuredGrid', vtk.vtkXMLPStructuredGridReader(), vtk.vtkXMLPStructuredGridWriter(), 'vts', 4924) TestDataType('UnstructuredGrid', vtk.vtkXMLPUnstructuredGridReader(), vtk.vtkXMLPUnstructuredGridWriter(), 'vtu', 11856) # Test writers with UseSubdirectory on TestDataType('ImageData', vtk.vtkXMLPImageDataReader(), vtk.vtkXMLPImageDataWriter(), 'vti', 4924, useSubdir=True) TestDataType('RectilinearGrid', vtk.vtkXMLPRectilinearGridReader(), vtk.vtkXMLPRectilinearGridWriter(), 'vtr', 4924, useSubdir=True)
def _load_file(filename, c, alpha, threshold, spacing, unpack): fl = filename.lower() ################################################################# other formats: if fl.endswith(".xml") or fl.endswith(".xml.gz") or fl.endswith(".xdmf"): # Fenics tetrahedral file actor = loadDolfin(filename) elif fl.endswith(".neutral") or fl.endswith(".neu"): # neutral tetrahedral file actor = loadNeutral(filename) elif fl.endswith(".gmsh"): # gmesh file actor = loadGmesh(filename) elif fl.endswith(".pcd"): # PCL point-cloud format actor = loadPCD(filename) actor.GetProperty().SetPointSize(2) elif fl.endswith(".off"): actor = loadOFF(filename) elif fl.endswith(".3ds"): # 3ds format actor = load3DS(filename) elif fl.endswith(".wrl"): importer = vtk.vtkVRMLImporter() importer.SetFileName(filename) importer.Read() importer.Update() actors = importer.GetRenderer().GetActors() #vtkActorCollection actors.InitTraversal() wacts = [] for i in range(actors.GetNumberOfItems()): act = actors.GetNextActor() wacts.append(act) actor = Assembly(wacts) ################################################################# volumetric: elif fl.endswith(".tif") or fl.endswith(".slc") or fl.endswith(".vti") \ or fl.endswith(".mhd") or fl.endswith(".nrrd") or fl.endswith(".nii") \ or fl.endswith(".dem"): img = loadImageData(filename, spacing) if threshold is False: if c is None and alpha == 1: c = ['b','lb','lg','y','r'] # good for blackboard background alpha = (0.0, 0.0, 0.2, 0.4, 0.8, 1) actor = Volume(img, c, alpha) else: actor = Volume(img).isosurface(threshold=threshold) actor.color(c).alpha(alpha) ################################################################# 2D images: elif fl.endswith(".png") or fl.endswith(".jpg") or fl.endswith(".bmp") or fl.endswith(".jpeg"): if ".png" in fl: picr = vtk.vtkPNGReader() elif ".jpg" in fl or ".jpeg" in fl: picr = vtk.vtkJPEGReader() elif ".bmp" in fl: picr = vtk.vtkBMPReader() picr.SetFileName(filename) picr.Update() actor = Picture() # object derived from vtk.vtkImageActor() actor.SetInputData(picr.GetOutput()) if alpha is None: alpha = 1 actor.SetOpacity(alpha) ################################################################# multiblock: elif fl.endswith(".vtm") or fl.endswith(".vtmb"): read = vtk.vtkXMLMultiBlockDataReader() read.SetFileName(filename) read.Update() mb = read.GetOutput() if unpack: acts = [] for i in range(mb.GetNumberOfBlocks()): b = mb.GetBlock(i) if isinstance(b, (vtk.vtkPolyData, vtk.vtkImageData, vtk.vtkUnstructuredGrid, vtk.vtkStructuredGrid, vtk.vtkRectilinearGrid)): acts.append(b) return acts else: return mb ################################################################# numpy: elif fl.endswith(".npy"): acts = loadNumpy(filename) if unpack == False: return Assembly(acts) return acts elif fl.endswith(".geojson") or fl.endswith(".geojson.gz"): return loadGeoJSON(fl) ################################################################# polygonal mesh: else: if fl.endswith(".vtk"): # read all legacy vtk types #output can be: # PolyData, StructuredGrid, StructuredPoints, UnstructuredGrid, RectilinearGrid reader = vtk.vtkDataSetReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.ReadAllFieldsOn() reader.ReadAllNormalsOn() reader.ReadAllColorScalarsOn() elif fl.endswith(".ply"): reader = vtk.vtkPLYReader() elif fl.endswith(".obj"): reader = vtk.vtkOBJReader() elif fl.endswith(".stl"): reader = vtk.vtkSTLReader() elif fl.endswith(".byu") or fl.endswith(".g"): reader = vtk.vtkBYUReader() elif fl.endswith(".foam"): # OpenFoam reader = vtk.vtkOpenFOAMReader() elif fl.endswith(".pvd"): reader = vtk.vtkXMLGenericDataObjectReader() elif fl.endswith(".vtp"): reader = vtk.vtkXMLPolyDataReader() elif fl.endswith(".vts"): reader = vtk.vtkXMLStructuredGridReader() elif fl.endswith(".vtu"): reader = vtk.vtkXMLUnstructuredGridReader() elif fl.endswith(".vtr"): reader = vtk.vtkXMLRectilinearGridReader() elif fl.endswith(".pvtk"): reader = vtk.vtkPDataSetReader() elif fl.endswith(".pvtr"): reader = vtk.vtkXMLPRectilinearGridReader() elif fl.endswith("pvtu"): reader = vtk.vtkXMLPUnstructuredGridReader() elif fl.endswith(".txt") or fl.endswith(".xyz"): reader = vtk.vtkParticleReader() # (format is x, y, z, scalar) elif fl.endswith(".facet"): reader = vtk.vtkFacetReader() else: return None reader.SetFileName(filename) reader.Update() routput = reader.GetOutput() if not routput: colors.printc("~noentry Unable to load", filename, c=1) return None actor = Actor(routput, c, alpha) if fl.endswith(".txt") or fl.endswith(".xyz"): actor.GetProperty().SetPointSize(4) actor.filename = filename return actor
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): os.remove(VTK_TEMP_DIR + "/%s_%d.%s" % (dataType, i, ext)) assert da2.GetValue(0) == numTris TestDataType('ImageData', vtk.vtkXMLPImageDataReader(), vtk.vtkXMLPImageDataWriter(), 'vti', 4924) TestDataType('RectilinearGrid', vtk.vtkXMLPRectilinearGridReader(), vtk.vtkXMLPRectilinearGridWriter(), 'vtr', 4924) TestDataType('StructuredGrid', vtk.vtkXMLPStructuredGridReader(), vtk.vtkXMLPStructuredGridWriter(), 'vts', 4924) TestDataType('UnstructuredGrid', vtk.vtkXMLPUnstructuredGridReader(), vtk.vtkXMLPUnstructuredGridWriter(), 'vtu', 11856)
def Line(self, X1, X2, Y1, Y2, Z1, Z2, res): parallel = False if self.vtuname.endswith(".pvtu"): parallel = True ############################ Plot from Numerical results #NAME OF THE VARIABLE YOU WANT TO EXTRACT DATA FROM path = self.path data_name_field = self.field ############ initial AutoVTU = 2 AutoNumber = 0 if AutoVTU == 1: for files in os.listdir(path): if files.endswith(".vtu"): pos = files.rfind('_') pos2 = files.rfind('.') AutoFile = files[:pos] AutoNumber = max(AutoNumber, int(files[pos + 1:pos2])) AutomaticFile = AutoFile AutomaticVTU_Number = AutoNumber if (len(sys.argv) > 1): filename = sys.argv[1] vtu_number = int(sys.argv[2]) else: filename = AutomaticFile vtu_number = int(AutomaticVTU_Number) # serial if (parallel == True): reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(filename + '_' + str(vtu_number) + '.pvtu') else: reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(filename + '_' + str(vtu_number) + '.vtu') else: if (parallel == True): reader = vtk.vtkXMLPUnstructuredGridReader() else: reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(self.path + self.vtuname) #reader.Update() ugrid = reader.GetOutputPort() #Initial and last coordinate of the probe x0 = X1 x1 = X2 y0 = Y1 # 1.0/float(NUMBER) y1 = Y2 z0 = Z1 z1 = Z2 #Resolution of the probe resolution = res #ugrid.Update() ###########Create the probe line############# Field = [] detector = [] Dline = [] hx = (x1 - x0) / resolution hy = (y1 - y0) / resolution hz = (z1 - z0) / resolution for i in range(resolution + 1): detector.append([hx * i + x0, hy * i + y0, hz * i + z0]) #print 'using',len(detector),'detectors' points = vtk.vtkPoints() points.SetDataTypeToDouble() for i in range(len(detector)): points.InsertNextPoint(detector[i][0], detector[i][1], detector[i][2]) detectors = vtk.vtkPolyData() detectors.SetPoints(points) ###########Create the probe line end############# probe = vtk.vtkProbeFilter() probe.SetInputConnection(ugrid) probe.SetSourceConnection(ugrid) probe.SetInputData(detectors) probe.Update() valid_ids = probe.GetOutput().GetPointData().GetArray( "vtkValidPointMask") data = probe.GetOutput() for j in range(points.GetNumberOfPoints()): ID = valid_ids.GetTuple(j) if ID[0] > 0: Dline.append(detector[j][:]) Field.append(data.GetPointData().GetScalars( data_name_field).GetTuple(j)) return Dline, Field
def compute_vonMisesStress_for_MV(inputfilename, outputfilename): # ====================================================================== # get system arguments ------------------------------------------------- # Path to input file and name of the output file #inputfilename = sys.argv[1] #outputfilename = sys.argv[2] print " " print "==================================================================================================" print "=== Execute Python script to analyze MV geometry in order for the HiFlow3-based MVR-Simulation ===" print "==================================================================================================" print " " # ====================================================================== # Read file if inputfilename[-4] == 'p': reader = vtk.vtkXMLPUnstructuredGridReader() reader.SetFileName(inputfilename) reader.Update() else: reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(inputfilename) reader.Update() print "Reading input files: DONE." # ====================================================================== # Compute displacement vector calc = vtk.vtkArrayCalculator() calc.SetInput(reader.GetOutput()) calc.SetAttributeModeToUsePointData() calc.AddScalarVariable('x', 'u0', 0) calc.AddScalarVariable('y', 'u1', 0) calc.AddScalarVariable('z', 'u2', 0) calc.SetFunction('x*iHat+y*jHat+z*kHat') calc.SetResultArrayName('DisplacementSolutionVector') calc.Update() # ====================================================================== # Compute strain tensor derivative = vtk.vtkCellDerivatives() derivative.SetInput(calc.GetOutput()) derivative.SetTensorModeToComputeStrain() derivative.Update() # ====================================================================== # Compute von Mises stress calc = vtk.vtkArrayCalculator() calc.SetInput(derivative.GetOutput()) calc.SetAttributeModeToUseCellData() calc.AddScalarVariable('Strain_0', 'Strain', 0) calc.AddScalarVariable('Strain_1', 'Strain', 1) calc.AddScalarVariable('Strain_2', 'Strain', 2) calc.AddScalarVariable('Strain_3', 'Strain', 3) calc.AddScalarVariable('Strain_4', 'Strain', 4) calc.AddScalarVariable('Strain_5', 'Strain', 5) calc.AddScalarVariable('Strain_6', 'Strain', 6) calc.AddScalarVariable('Strain_7', 'Strain', 7) calc.AddScalarVariable('Strain_8', 'Strain', 8) calc.SetFunction('sqrt( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8))^2 - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) + 3 * ((2*700*Strain_3)^2 + (2*700*Strain_6)^2 + (2*700*Strain_7)^2) )') calc.SetResultArrayName('vonMisesStress_forMV_mu700_lambda28466') calc.Update() print "Computation of displacement vectors, Cauchy strain and vom Mises stress: DONE." # ====================================================================== # Define dummy variable; get output of calc filter dummy = calc.GetOutput() # Get point data arrays u0, u1 and u2 pointData_u0 = dummy.GetPointData().GetArray('u0') pointData_u1 = dummy.GetPointData().GetArray('u1') pointData_u2 = dummy.GetPointData().GetArray('u2') # Set scalars dummy.GetPointData().SetScalars(pointData_u0) # ====================================================================== # Warp by scalar u0 warpScalar = vtk.vtkWarpScalar() warpScalar.SetInput(dummy) warpScalar.SetNormal(1.0,0.0,0.0) warpScalar.SetScaleFactor(1.0) warpScalar.SetUseNormal(1) warpScalar.Update() # Get output and set scalars dummy = warpScalar.GetOutput() dummy.GetPointData().SetScalars(pointData_u1) # ====================================================================== # Warp by scalar u1 warpScalar = vtk.vtkWarpScalar() warpScalar.SetInput(dummy) warpScalar.SetNormal(0.0,1.0,0.0) warpScalar.SetScaleFactor(1.0) warpScalar.SetUseNormal(1) warpScalar.Update() # Get output and set scalars dummy = warpScalar.GetOutput() dummy.GetPointData().SetScalars(pointData_u2) # ====================================================================== # Warp by scalar u2 warpScalar = vtk.vtkWarpScalar() warpScalar.SetInput(dummy) warpScalar.SetNormal(0.0,0.0,1.0) warpScalar.SetScaleFactor(1.0) warpScalar.SetUseNormal(1) warpScalar.Update() # Get ouput and add point data arrays that got deleted earlier dummy = warpScalar.GetOutput() dummy.GetPointData().AddArray(pointData_u0) dummy.GetPointData().AddArray(pointData_u1) # ====================================================================== # Write output to vtu writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetDataModeToAscii() writer.SetFileName(outputfilename) writer.SetInput(dummy) writer.Write() # ====================================================================== print "Writing Extended VTU incl. von Mises Stress information: DONE." print "==============================================================" print " "
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 TestDataType('ImageData', vtk.vtkXMLPImageDataReader(), vtk.vtkXMLPImageDataWriter(), 'vti', 4924) TestDataType('RectilinearGrid', vtk.vtkXMLPRectilinearGridReader(), vtk.vtkXMLPRectilinearGridWriter(), 'vtr', 4924) TestDataType('StructuredGrid', vtk.vtkXMLPStructuredGridReader(), vtk.vtkXMLPStructuredGridWriter(), 'vts', 4924) TestDataType('UnstructuredGrid', vtk.vtkXMLPUnstructuredGridReader(), vtk.vtkXMLPUnstructuredGridWriter(), 'vtu', 11856) TestDataType('Table', vtk.vtkXMLPTableReader(), vtk.vtkXMLPTableWriter(), 'vtt', 18522) # Test writers with UseSubdirectory on TestDataType('ImageData', vtk.vtkXMLPImageDataReader(), vtk.vtkXMLPImageDataWriter(), 'vti', 4924, useSubdir=True) TestDataType('RectilinearGrid', vtk.vtkXMLPRectilinearGridReader(), vtk.vtkXMLPRectilinearGridWriter(), 'vtr', 4924, useSubdir=True) TestDataType('StructuredGrid', vtk.vtkXMLPStructuredGridReader(), vtk.vtkXMLPStructuredGridWriter(), 'vts', 4924, useSubdir=True) TestDataType('UnstructuredGrid', vtk.vtkXMLPUnstructuredGridReader(), vtk.vtkXMLPUnstructuredGridWriter(), 'vtu', 11856, useSubdir=True) TestDataType('Table', vtk.vtkXMLPTableReader(), vtk.vtkXMLPTableWriter(), 'vtt', 18522, useSubdir=True)
indexFile = 0 if run == runs[0]: #First data comes from previous Run path = '/home/users/merino4i/MISMIP+/' + caseFirst + '/' + run + '/' filesIce = glob.glob(path + '*.pvtu') filesIce.sort() for fileTest in filesIce: file1 = fileTest else: path = '/home/users/merino4i/MISMIP+/' + case + '/' + run + '/' filesIce = glob.glob(path + '*.pvtu') filesIce.sort() for fileTest in filesIce: file1 = fileTest reader = vtk.vtkXMLPUnstructuredGridReader() print file1 reader.SetFileName(file1) reader.Update() output = reader.GetOutput() Coords = vtk_to_numpy(output.GetPoints().GetData()) PointData = output.GetPointData() numArrays = PointData.GetNumberOfArrays() for i in np.arange(numArrays): if PointData.GetArrayName(i) == 'ssavelocity': VarIndex = i break Vel = vtk_to_numpy(PointData.GetArray(VarIndex)) for i in np.arange(numArrays):