def errdiff(firstfile, secondfile, vector): reader0 = vtkXMLStructuredGridReader() reader0.SetFileName(firstfile) reader0.Update() data0 = reader0.GetOutput() u0 = VN.vtk_to_numpy(data0.GetPointData().GetArray(vector)) errmax = -1 errmax_x = -1 errmax_y = -1 errmax_z = -1 errmax_i = -1 reader1 = vtkXMLStructuredGridReader() reader1.SetFileName(secondfile) reader1.Update() data1 = reader1.GetOutput() u1 = VN.vtk_to_numpy(data1.GetPointData().GetArray(vector)) # print "Points = ", data0.GetNumberOfPoints(), data1.GetNumberOfPoints() for i in range(data1.GetNumberOfPoints()): x, y, z = data0.GetPoint(i) u0x, u0y, u0z = u0[i] u1x, u1y, u1z = u1[i] err = max(abs(u0x - u1x), abs(u0y - u1y), abs(u0z - u1z)) if err > errmax: errmax = err errmax_x = x errmax_y = y errmax_z = z errmax_i = i # print x,y,z,u0x,u0y,u0z,u1x,u1y,u1z,err print os.path.basename(firstfile), errmax_x, errmax_y, errmax_z, u0[ errmax_i], u1[errmax_i], errmax
def test_structured_grid(compression_fixture, format_fixture): f = io.StringIO() N = 5 r = np.linspace(0, 1, N) theta = np.linspace(0, 2 * np.pi, 5 * N) theta, r = np.meshgrid(theta, r, indexing='ij') x = r * np.cos(theta) y = r * np.sin(theta) points = np.vstack([x.ravel(), y.ravel()]).T compress = compression_fixture.param format = format_fixture.param grid = StructuredGrid(f, points, (N, 5 * N), compression=compress) data = np.exp(-4 * r**2) grid.addPointData(DataArray(data, reversed(range(2)), 'data'), vtk_format=format) grid.write() reader = vtkXMLStructuredGridReader() reader.SetReadFromInputString(True) reader.SetInputString(f.getvalue()) reader.Update() output = reader.GetOutput() vtk_data = vtk_to_numpy(output.GetPointData().GetArray('data')) vtk_data = vtk_data.reshape(data.shape, order='C') assert all(vtk_data == data)
def __init__(self, skel_file=None): try: self.reader = vtk.vtkXMLStructuredGridReader() self.reader.SetFileName(skel_file) self.reader.Update() except: print ("Failed to find skeleton file. Please make sure the file specified is a valid .vts XML file") sys.exit(9) ## load as a numpy array self.skel = dsa.WrapDataObject(self.reader.GetOutput()) self.extents = self.reader.GetUpdateExtent() print ("Extents: {}".format(self.reader.GetUpdateExtent())) # self.grid = inc.cm_to_re(np.array(self.skel.Points)) self.grid = np.array(self.skel.Points) self.dims = np.array([0,0,0]) self.dims[2] = self.extents[1]+1 self.dims[1] = self.extents[3]+1 self.dims[0] = self.extents[5]+1 self.npdims = np.array([0,0,0,0]) self.npdims[0] = self.dims[0] self.npdims[1] = self.dims[1] self.npdims[2] = self.dims[2] self.npdims[3] = 3 self.x, self.y, self.z = self.build_grid(self.grid) # assert False self.dipole = dpd.DipoleData()
def convert_vts_file(src, dst): start = time.time() reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(src) reader.Update() output = reader.GetOutput() dims = output.GetDimensions() fd = output.GetFieldData() cd = output.GetCellData() pd = output.GetPointData() var_names = get_variable_names(pd) use_double = False tecio.open_file(dst, src, var_names, use_double) # Not sure how to get solution time from VTS files yet solution_time = 0 strand = 0 tecio.create_ordered_zone(src, dims, solution_time, strand) # Write XYZ values xyz_points = get_points(output) tecio.zone_write_values(xyz_points[0]) tecio.zone_write_values(xyz_points[1]) tecio.zone_write_values(xyz_points[2]) add_point_data(pd, dims) print("Elapsed Time: ", time.time()-start) tecio.close_file()
def extract_files(name): #very long and expensive procedure gridreader = vtk.vtkXMLStructuredGridReader() gridreader.SetFileName(name) gridreader.Update() grid = gridreader.GetOutput() data = grid.GetPointData() points = grid.GetPoints() dims = grid.GetDimensions() velocity = data.GetArray("Velocity") phase = data.GetArray("Phase") vz = numpy.zeros([dims[0], dims[1], dims[2]]) vy = numpy.zeros([dims[0], dims[1], dims[2]]) vx = numpy.zeros([dims[0], dims[1], dims[2]]) phase_numpy = numpy.zeros([dims[0], dims[1], dims[2]]) print vz.shape print vy.shape for counter in range(0, points.GetNumberOfPoints()): coorx, coory, coorz = points.GetPoint(counter) velx, vely, velz = velocity.GetTuple3(counter) vz[int(coorx), int(coory), int(coorz)] = velz vy[int(coorx), int(coory), int(coorz)] = vely vx[int(coorx), int(coory), int(coorz)] = velx phase_numpy[int(coorx), int(coory), int(coorz)] = phase.GetTuple1(counter) numpy.savetxt("vz.txt", vz[0, :, :]) numpy.savetxt("vy.txt", vy[0, :, :]) numpy.savetxt("phase.txt", phase_numpy[0, :, :])
def vtk_write(train_y, ann_data): flow_file_list = sorted(glob.glob('/share/data/Planar_flow/vts/#flow*')) # load a vtk file as input print('reading : ', flow_file_list[0]) reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(flow_file_list[0]) reader.Update() # get the coordinates of nodes in the mesh nodes_vtk_array = reader.GetOutput().GetPoints().GetData() #get the coordinates of the nodes print('change to numpy from vtk') nodes_nummpy_array = vtk_to_numpy(nodes_vtk_array) x, y, z = nodes_nummpy_array[:, 0], nodes_nummpy_array[:, 1], nodes_nummpy_array[:, 2] gridToVTK("./structured", x, y, z, pointData={ "temp": train_y[:, 0], "ann_temp": ann_data[:, 0] })
def read_data(filename): reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() data_arrays = output.GetPointData() numpy_arrays = [ vtk_to_numpy(data_arrays.GetArray(i)) for i in range(data_arrays.GetNumberOfArrays()) ] coords = vtk_to_numpy(output.GetPoints().GetData()) dim = output.GetDataDimension() ncells = reader.GetNumberOfCells() elements = np.zeros((ncells, 2**dim), dtype=np.uint16) for ic in range(ncells): c = output.GetCell(ic) elements[ic] = [ c.GetPointId(ip) for ip in range(c.GetNumberOfPoints()) ] if dim == 2: fieldnames = ['u', 'v', 'lambda', 'rank'] else: fieldnames = ['u', 'v', 'v', 'lambda', 'rank'] return (dim, coords, elements, numpy_arrays, fieldnames)
def read(self, file_name): """Loads the given .vts file """ self.reader = vtk.vtkXMLStructuredGridReader() self.reader.SetFileName(file_name) self.reader.Update()
def convert_vtk_file(vtk_file, plt_file, strand=None, solution_time=None): reader = None if vtk_file.endswith(".vtu"): reader = vtk.vtkXMLUnstructuredGridReader() elif vtk_file.endswith(".vtp"): reader = vtk.vtkXMLPolyDataReader() elif vtk_file.endswith(".vts"): reader = vtk.vtkXMLStructuredGridReader() elif vtk_file.endswith(".vti"): reader = vtk.vtkXMLImageDataReader() reader.SetFileName(vtk_file) reader.Update() vtk_dataset = reader.GetOutput() tp.new_layout() tecplot_dataset = tp.active_frame().dataset add_vtk_dataset(vtk_dataset, tecplot_dataset) if tecplot_dataset.num_zones == 0: print("No zones created.") return for z in tecplot_dataset.zones(): z.name = os.path.basename(vtk_file) if strand and solution_time: z.strand = strand z.solution_time = solution_time tp.data.save_tecplot_plt(plt_file, dataset=tecplot_dataset)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkXMLStructuredGridReader(), 'Reading vtkXMLStructuredGrid.', (), ('vtkXMLStructuredGrid',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def main(): filename = get_program_parameters() colors = vtk.vtkNamedColors() # Read the file reader = vtk.vtkXMLStructuredGridReader() 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) renderer.SetBackground(colors.GetColor3d("Green")) render_window.Render() render_window_interactor.Start()
def draw_streamlines(name): import vtk import numpy from PyNGL import Ngl gridreader = vtk.vtkXMLStructuredGridReader() gridreader.SetFileName(name) #gridreader.SetPointArrayStatus("Density",0) #selection=gridreader.GetPointDataArraySelection() #selection.DisableArray("Density") #selection.DisableArray("Velocity") gridreader.Update() grid = gridreader.GetOutput() data = grid.GetPointData() points = grid.GetPoints() dims = grid.GetDimensions() velocity = data.GetArray("Velocity") phase = data.GetArray("Phase") vz = numpy.zeros([dims[1], dims[2]]) vy = numpy.zeros([dims[1], dims[2]]) phase_numpy = numpy.zeros([dims[1], dims[2]]) print vz.shape print vy.shape for counter in range(0, points.GetNumberOfPoints()): coorx, coory, coorz = points.GetPoint(counter) #print coorx,coory,coorz if coorx == 1: vz[int(coory), int(coorz)] = velocity.GetTuple3(counter)[2] vy[int(coory), int(coorz)] = velocity.GetTuple3(counter)[1] phase_numpy[int(coory), int(coorz)] = phase.GetTuple1(counter) #data.SetActiveScalars("Phase"); #data.SetActiveVectors("Velocity") numpy.savetxt("vz.txt", vz) numpy.savetxt("vy.txt", vy) numpy.savetxt("phase.txt", phase_numpy) wks_type = "ps" wks = Ngl.open_wks(wks_type, "test") resources = Ngl.Resources() #uvar = file.variables["U_GRD_6_ISBL"] #vvar = file.variables["V_GRD_6_ISBL"] #if hasattr(uvar,"units"): # resources.tiMainString = "GRD_6_ISBL (u,v " + uvar.units + ")" #else: #resources.tiMainString = "GRD_6_ISBL" #if hasattr(uvar,"_FillValue"): # resources.vfMissingUValueV = uvar._FillValue # if hasattr(vvar,"_FillValue"): # resources.vfMissingVValueV = vvar._FillValue resources.tiMainFont = "Times-Roman" resources.tiXAxisString = "streamlines" resources.vpHeightF = 0.25 # Define height, width, and location of plot. resources.vpWidthF = 7.5 * 0.25 #plot = Ngl.streamline(wks,uvar[0,::2,::2],vvar[0,::2,::2],resources) plot = Ngl.streamline(wks, vz[:, ::10], vy[:, ::10], resources)
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkXMLStructuredGridReader(), 'Reading vtkXMLStructuredGrid.', (), ('vtkXMLStructuredGrid', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def vtk_xml_reader(self): """ Generates and returns the vtk reader object for the file associated with the data object :return: vtkObject for the reader """ reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(self.file) reader.Update() assert isinstance(reader, vtk.vtkObject) return reader
def loadPolyData(filename): '''Load a file and return a vtkPolyData object (not a vtkActor).''' if not os.path.exists(filename): colors.printc('Error in loadPolyData: Cannot find', filename, c=1) return None fl = filename.lower() if fl.endswith('.vtk') or fl.endswith('.vtp'): reader = vtk.vtkPolyDataReader() 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('.vtp'): reader = vtk.vtkXMLPolyDataReader() elif fl.endswith('.vts'): reader = vtk.vtkXMLStructuredGridReader() elif fl.endswith('.vtu'): reader = vtk.vtkXMLUnstructuredGridReader() elif fl.endswith('.txt'): reader = vtk.vtkParticleReader() # (x y z scalar) elif fl.endswith('.xyz'): reader = vtk.vtkParticleReader() else: reader = vtk.vtkDataReader() reader.SetFileName(filename) if fl.endswith('.vts'): # structured grid reader.Update() gf = vtk.vtkStructuredGridGeometryFilter() gf.SetInputConnection(reader.GetOutputPort()) gf.Update() poly = gf.GetOutput() elif fl.endswith('.vtu'): # unstructured grid reader.Update() gf = vtk.vtkGeometryFilter() gf.SetInputConnection(reader.GetOutputPort()) gf.Update() poly = gf.GetOutput() else: try: reader.Update() poly = reader.GetOutput() except: poly = None if not poly: return None cleanpd = vtk.vtkCleanPolyData() cleanpd.SetInputData(poly) cleanpd.Update() return cleanpd.GetOutput()
def read_coarse_vec(filename): reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() data_arrays = output.GetPointData() numpy_arrays = [ vtk_to_numpy(data_arrays.GetArray(i)) for i in range(data_arrays.GetNumberOfArrays()) ] return numpy_arrays
def read_vtkxml_data(filepath): if filepath.endswith('.vtu'): reader = vtk.vtkXMLUnstructuredGridReader() elif filepath.endswith('.vts'): reader = vtk.vtkXMLStructuredGridReader() elif filepath.endswith('.vti'): reader = vtk.vtkXMLImageDataReader() elif filepath.endswith('.vtp'): reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filepath) reader.Update() return reader.GetOutput()
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 load_structured_grid(input_file: str): """Load vtkStructuredGrid from file :param input_file: Path to vtk structured grid file :type input_file: str :raises TypeError: :return: Loaded grid :rtype: vtk.vtkStructuredGrid """ if input_file[-4:].lower() != ".vts": raise TypeError("Input file should be .vts type") reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(input_file) reader.Update() grid = reader.GetOutput() return grid
def extract_array_from_grid_file(input_grid_file: str, array_name: str) -> np.ndarray: """ Read an array from vtkStructuredGrid file :param input_grid_file: Input file, should be a vtkStructuredGrid file :type input_grid_file: str :param array_name: Array to extract from grid :type array_name: str :return: Extracted array :rtype: np.ndarray """ reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(input_grid_file) reader.Update() input_grid = reader.GetOutput() return extract_array_from_grid(input_grid, array_name)
def __init__(self, filename = None, sg=None): """Creates a vtu object by reading the specified file.""" if filename is None and ugrid is None: self.ugrid = vtk.vtkStructuredGrid() elif filename is None and ugrid is not None: self.ugrid = ugrid else: self.gridreader = None if filename[-4:] == ".vtu": self.gridreader=vtk.vtkXMLStructuredGridReader() elif filename[-5:] == ".pvtu": self.gridreader=vtk.vtkXMLPStructuredGridReader() 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 load_vtk_structured(self, file_name): self.fname = file_name #reader = vtk.vtkUnstructuredGridReader() reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(file_name) reader.Update() self.output = reader.GetOutput() self.vtk_n_pts = self.output.GetNumberOfPoints() self.vtk_pts_dim = self.output.GetDataDimension() self.vtk_pts = self.output.GetPointData() self.vtk_n_props = self.vtk_pts.GetNumberOfArrays() self.reader = reader #get_range = self.output.GetScalarRange() #print get_range print " [Vtk_structured_reader]:", for i in range(self.vtk_n_props): print "\'%s\'" % (self.vtk_pts.GetArrayName(i)), print
def loadPoly(filename): '''Return a vtkPolyData object, NOT a vtkActor''' if not os.path.exists(filename): vc.printc(('Error in loadPoly: Cannot find', filename), c=1) return None fl = filename.lower() if '.vtk' in fl: reader = vtk.vtkPolyDataReader() elif '.ply' in fl: reader = vtk.vtkPLYReader() elif '.obj' in fl: reader = vtk.vtkOBJReader() elif '.stl' in fl: reader = vtk.vtkSTLReader() elif '.byu' in fl or '.g' in fl: reader = vtk.vtkBYUReader() elif '.vtp' in fl: reader = vtk.vtkXMLPolyDataReader() elif '.vts' in fl: reader = vtk.vtkXMLStructuredGridReader() elif '.vtu' in fl: reader = vtk.vtkXMLUnstructuredGridReader() elif '.txt' in fl: reader = vtk.vtkParticleReader() # (x y z scalar) elif '.xyz' in fl: reader = vtk.vtkParticleReader() else: reader = vtk.vtkDataReader() reader.SetFileName(filename) reader.Update() if '.vts' in fl: # structured grid gf = vtk.vtkStructuredGridGeometryFilter() gf.SetInputConnection(reader.GetOutputPort()) gf.Update() poly = gf.GetOutput() elif '.vtu' in fl: # unstructured grid gf = vtk.vtkGeometryFilter() gf.SetInputConnection(reader.GetOutputPort()) gf.Update() poly = gf.GetOutput() else: poly = reader.GetOutput() if not poly: vc.printc(('Unable to load', filename), c=1) return False cleanpd = vtk.vtkCleanPolyData() vu.setInput(cleanpd, poly) cleanpd.Update() return cleanpd.GetOutput()
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 create_dataset(filename): reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() dims = output.GetDimensions() fd = output.GetFieldData() cd = output.GetCellData() pd = output.GetPointData() tp.new_layout() ds = tp.active_frame().create_dataset(name=os.path.basename(filename)) # Add the XYZ variables - a dataset needs one variable before you can add a zone ds.add_variable('x', dtypes = [FieldDataType.Float]) ds.add_variable('y', dtypes = [FieldDataType.Float]) ds.add_variable('z', dtypes = [FieldDataType.Float]) zone_name = os.path.basename(filename) zone = ds.add_ordered_zone(zone_name, dims) # Not sure how to get solution time from VTS files yet #solution_time = float(filename.split('_')[-1].split('.')[0]) #strand = 1 #zone.solution_time = solution_time #zone.strand = strand # Write XYZ values xyz_points = get_points(output) zone.values(0)[:] = xyz_points[0] zone.values(1)[:] = xyz_points[1] zone.values(2)[:] = xyz_points[2] add_point_data(pd, zone) return ds
def _import(filename): if len(filename) == 0: raise ValueError("The input filename string is empty") reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(filename) reader.Update() mesh = reader.GetOutput() dimensions = mesh.GetDimensions() imported_block = Block(self.params, dimensions, mesh) if all(np.equal(dimensions, self.dimensions)): self.block.merge(imported_block) else: final_dimensions = [ self.block.dimensions, imported_block.dimensions ] final_dimensions = np.max(final_dimensions, axis=0) if all(np.equal(self.dimensions, final_dimensions)): self.block.merge(imported_block) else: self.remove_elements() old_block = self.block self.set_dimensions(final_dimensions) self.load_elements() self.add_elements() # restore edge visibility self.block.toggle_edges(old_block.show_edges) # restore block mode self.set_block_mode() self.block.merge(old_block) self.block.merge(imported_block) self.selector.hide() self.update_camera() self.render_scene()
gridWriter.SetDataModeToAscii() gridWriter.Write() gridWriter.SetInputData(output) gridWriter.SetFileName(file1) gridWriter.SetDataModeToAppended() gridWriter.SetNumberOfPieces(2) gridWriter.Write() gridWriter.SetFileName(file2) gridWriter.SetDataModeToBinary() gridWriter.SetWriteExtent(8, 56, 4, 16, 1, 24) gridWriter.Write() # read the extracted grid reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(file0) reader.WholeSlicesOff() reader.Update() sg = vtk.vtkStructuredGrid() sg.DeepCopy(reader.GetOutput()) cF0 = vtk.vtkContourFilter() cF0.SetInputData(sg) cF0.SetValue(0, 0.38) mapper0 = vtk.vtkPolyDataMapper() mapper0.SetInputConnection(cF0.GetOutputPort()) mapper0.ScalarVisibilityOff() actor0 = vtk.vtkActor()
def extract_profiles(name): gridreader = vtk.vtkXMLStructuredGridReader() gridreader.SetFileName(name) gridreader.Update() grid = gridreader.GetOutput() data = grid.GetPointData() points=grid.GetPoints() dims =grid.GetDimensions() velocity=data.GetArray("Velocity") phase=data.GetArray("Phase") vz=numpy.zeros([dims[1],dims[2]]) vy=numpy.zeros([dims[1],dims[2]]) vx=numpy.zeros([dims[1],dims[2]]) phase_numpy=numpy.zeros([dims[1],dims[2]]) print vz.shape print vy.shape for coory in range(0,dims[1]): for coorz in range(0,dims[2]): counter=coorz*dims[0]*dims[1]+coory*dims[0] velx,vely,velz=velocity.GetTuple3(counter) vz[coory,coorz]=velz vy[coory,coorz]=vely vx[coory,coorz]=velx phase_numpy[coory,coorz]=phase.GetTuple1(counter) #numpy.savetxt("vz.txt",vz) #numpy.savetxt("vy.txt",vy) #numpy.savetxt("phase.txt",phase_numpy) #parameters of the binary liquid model k=0.04 a=0.04 center=phase_numpy[0,:] z1 = numpy.min(numpy.where(center < 0.0)) z2 = numpy.max(numpy.where(center < 0.0)) if z1==0: z2=numpy.min(numpy.where(center>0.0))+dims[2] z1=numpy.max(numpy.where(center>0.0)) print z1,z2 mid =((z1+z2)/2)%dims[2] print mid phase_mid=numpy.zeros([dims[0],dims[1]]) #for counter in range(0,points.GetNumberOfPoints()): # coorx,coory,coorz=points.GetPoint(counter) # if coorz==mid: # phase_mid[int(coorx),int(coory)]=phase.GetTuple1(counter) for coorx in range(0,dims[0]): for coory in range(0,dims[1]): counter=mid*dims[0]*dims[1]+coory*dims[0]+coorx phase_mid[coorx,coory]= phase.GetTuple1(counter) #pylab.figure() #pylab.imshow(phase_mid[1:,1:],cmap="gray",extent=[0.0,1.0,0.0,1.0],origin="lower") #Calculation of the capillary number capillary=vz[0,z2%dims[2]]*(2.0/3.0)/math.sqrt(8.0*k*a/9.0) number=str(capillary*100)[:3] if number[2]==".": number=number[:3] pylab.savefig("phase_crossection_ca"+number+".eps") #pylab.imshow(array['phi'],cmap="gray",extent=[0.0,15.0,0.0,1.0]) #pylab.yticks([0.0,0.5,1.0]) print "Reynolds=",vz[0,z2%dims[2]]*2.0*(dims[0]-2)/(2.0/3.0) prof_axis=phase_mid[0,1:] prof_diag=numpy.diag(phase_mid[1:,1:]) print Get_Zero(prof_axis) print Get_Zero(prof_diag) axis_zero=Get_Zero(prof_axis)/(dims[0]-2.0) diag_zero=math.sqrt(2.0)*Get_Zero(prof_diag)/(dims[0]-2.0) print axis_zero,diag_zero print "Capillary=",capillary pylab.figure() pylab.plot(phase_mid[1,1:]) #pylab.plot(numpy.diag(phase_mid[1:,1:])) return axis_zero,diag_zero,capillary
def read_vtk_2d(name): gridreader = vtk.vtkXMLStructuredGridReader() gridreader.SetFileName(name) #gridreader.SetPointArrayStatus("Density",0) selection=gridreader.GetPointDataArraySelection() selection.DisableArray("Density") #selection.DisableArray("Velocity") #selection.DisableArray("Phase") gridreader.Update() grid = gridreader.GetOutput() data = grid.GetPointData() points=grid.GetPoints() dims =grid.GetDimensions() data.SetActiveScalars("Phase"); data.SetActiveVectors("Velocity") velocity=data.GetArray("Velocity") phase = data.GetArray("Phase") image=vtk.vtkImageData() image.SetSpacing(1.0,1.0,1.0) image.SetOrigin(0.0,0.0,0.0) image.SetDimensions(dims[0],dims[1],dims[2]) image.GetPointData().SetScalars(phase) image.GetPointData().SetVectors(velocity) image.Update() print "image=",image extract=vtk.vtkExtractVOI() extract.SetInput(image) extract.SetVOI(0,0,0,dims[1]-1,0,dims[2]-1) extract.Update() contour=vtk.vtkContourFilter() contour.SetInputConnection(extract.GetOutputPort()) contour.SetValue(0,0.0) contour.Update() probe=vtk.vtkProbeFilter() probe.SetInputConnection(contour.GetOutputPort()) probe.SetSource(image) #probe.SpatialMatchOn() probe.Update() print "Probe=",probe.GetOutput() cont=probe.GetOutput() vel=cont.GetPointData().GetArray("Velocity") phi=cont.GetPointData().GetArray("Phase") cont_points=cont.GetPoints() x_numpy=numpy.zeros(cont_points.GetNumberOfPoints()) y_numpy=numpy.zeros(cont_points.GetNumberOfPoints()) z_numpy=numpy.zeros(cont_points.GetNumberOfPoints()) velx_numpy=numpy.zeros(cont_points.GetNumberOfPoints()) vely_numpy=numpy.zeros(cont_points.GetNumberOfPoints()) velz_numpy=numpy.zeros(cont_points.GetNumberOfPoints()) phi_numpy=numpy.zeros(cont_points.GetNumberOfPoints()) for counter in range(0,cont.GetPoints().GetNumberOfPoints()): x,y,z=cont_points.GetPoint(counter) x_numpy[counter]=x y_numpy[counter]=y z_numpy[counter]=z velx_numpy[counter]=vel.GetTuple3(counter)[0] vely_numpy[counter]=vel.GetTuple3(counter)[1] velz_numpy[counter]=vel.GetTuple3(counter)[2] phi_numpy[counter]=phi.GetTuple1(counter) #Velocity of the interface vz=numpy.zeros([dims[1],dims[2]]) vy=numpy.zeros([dims[1],dims[2]]) vx=numpy.zeros([dims[1],dims[2]]) phase_numpy=numpy.zeros([dims[1],dims[2]]) print vz.shape print vy.shape for coory in range(0,dims[1]): for coorz in range(0,dims[2]): counter=coorz*dims[0]*dims[1]+coory*dims[0] velx,vely,velz=velocity.GetTuple3(counter) vz[coory,coorz]=velz vy[coory,coorz]=vely vx[coory,coorz]=velx phase_numpy[coory,coorz]=phase.GetTuple1(counter) center=phase_numpy[0,:] z1 = numpy.min(numpy.where(center < 0.0)) z2 = numpy.max(numpy.where(center < 0.0)) if z1==0: z2=numpy.min(numpy.where(center>0.0))+dims[2] z1=numpy.max(numpy.where(center>0.0)) print z1,z2 mid =((z1+z2)/2)%dims[2] print vz[0,z2%dims[2]] print vz[0,((z1+z2)/2)%dims[2]] y_numpy=y_numpy/50.0 z_numpy=z_numpy/50.0 fig=pylab.figure(figsize=(10,3)) pylab.plot(z_numpy,y_numpy,"o",markersize=5,color="black") pylab.ylim(ymax=1.0) #pylab.xlim(xmin=0.1,xmax=5) #pylab.ylim(ymin=0.01) #numpy.savetxt("capillary.dat",zip(capillaries,widths)) pylab.xticks(fontsize=16) pylab.yticks(fontsize=16) pylab.ylabel(r'''$y$''',fontsize=30) pylab.xlabel(r'''$z$''',fontsize=30) fig.subplots_adjust(bottom=0.25) pylab.savefig("velocity_interface_contour.eps",dpi=300) #labels=[r'''$H_{eff}='''+str(value-2)+r'''$''' for value in ny] #leg=pylab.legend(["CPU results","Refined grid","Large body force","Heil","GPU results"],fancybox=True) #legtext = leg.get_texts() # all the text.Text instance in the legend #for text in legtext: # text.set_fontsize(20) #pylab.figure() #pylab.plot(z_numpy,phi_numpy,"g+") #pylab.figure() #pylab.plot(z_numpy,velx_numpy,"+") #pylab.figure() #pylab.plot(z_numpy,vely_numpy,"+") fig=pylab.figure(figsize=(10,3)) pylab.plot(z_numpy,velz_numpy,"o",markersize=5,color="black") #pylab.plot(z_numpy,y_numpy,"o",markersize=5,color="black") #pylab.xlim(xmin=0.1,xmax=5) #pylab.ylim(ymin=0.01) #numpy.savetxt("capillary.dat",zip(capillaries,widths)) pylab.xticks(fontsize=16) pylab.yticks(fontsize=16) pylab.ylabel(r'''$U$''',fontsize=30) pylab.xlabel(r'''$z$''',fontsize=30) fig.subplots_adjust(bottom=0.25) pylab.savefig("velocity_interface_values.eps",dpi=300)
def pyngl_streamline(name): from PyNGL import Ngl gridreader = vtk.vtkXMLStructuredGridReader() gridreader.SetFileName(name) gridreader.Update() grid = gridreader.GetOutput() data = grid.GetPointData() points=grid.GetPoints() dims =grid.GetDimensions() velocity=data.GetArray("Velocity") phase=data.GetArray("Phase") vz=numpy.zeros([dims[1],dims[2]]) vy=numpy.zeros([dims[1],dims[2]]) vx=numpy.zeros([dims[1],dims[2]]) phase_numpy=numpy.zeros([dims[1],dims[2]]) print vz.shape print vy.shape for coory in range(0,dims[1]): for coorz in range(0,dims[2]): counter=coorz*dims[0]*dims[1]+coory*dims[0] velx,vely,velz=velocity.GetTuple3(counter) vz[coory,coorz]=velz vy[coory,coorz]=vely vx[coory,coorz]=velx phase_numpy[coory,coorz]=phase.GetTuple1(counter) #parameters of the binary liquid model k=0.04 a=0.04 center=phase_numpy[0,:] z1 = numpy.min(numpy.where(center < 0.0)) z2 = numpy.max(numpy.where(center < 0.0)) if z1==0: z2=numpy.min(numpy.where(center>0.0))+dims[2] z1=numpy.max(numpy.where(center>0.0)) print z1,z2 mid =((z1+z2)/2)%dims[2] print mid #pylab.figure() #pylab.imshow(phase_mid[1:,1:],cmap="gray",extent=[0.0,1.0,0.0,1.0],origin="lower") #Calculation of the capillary number capillary=vz[0,z2%dims[2]]*(2.0/3.0)/math.sqrt(8.0*k*a/9.0) print "Capillary=",capillary ux=vz-vz[0,z2%dims[2]] uy=vy #ux_mask=ux[::5,::100] #uy_mask=uy[::5,::100] #x_mask=x[::5,::100] #y_mask=y[::5,::100] wks_type = "eps" wks = Ngl.open_wks(wks_type,"stream_ca"+str(100*capillary)[0:2]) resources = Ngl.Resources() resources.tiMainFont = "Times-Roman" resources.tiMainOn=True resources.tiMainString="Ca="+str(capillary)[0:4] #resources.tiXAxisString = "streamlines" resources.vpHeightF = 0.25 # Define height, width, and location of plot. resources.vpWidthF = 3*0.25 resources.wkPaperSize="A5" resources.nglFrame = False resources.vfXArray=numpy.linspace(0.0,30.0,len(ux[1,::10])) resources.vfYArray=numpy.linspace(0.0,1.0,len(ux[::2,1])) resources2=Ngl.Resources() resources2.tiMainFont = "Times-Roman" ##resources2.tiXAxisString = "streamlines" resources2.tiMainOn=True resources2.tiMainString="Ca="+str(capillary)[0:4] resources2.wkPaperSize="A5" resources2.vpHeightF = 0.25 # Define height, width, and location of plot. resources2.vpWidthF = 3*0.25 #resources2.nglFrame = False resources2.cnLineLabelsOn = False # Turn off contour line labels. resources2.cnLinesOn = True # Turn off contour lines. resources2.cnFillOn = False # Turn on contour fill. resources2.cnInfoLabelOn = False resources2.cnLevelSelectionMode = "ExplicitLevels" # Select contour levels. ##resources2.cnMinLevelValF = 0.0 ##resources2.cnMaxLevelValF = 0.001 ##resources2.cnLevelSpacingF = 0.0 resources2.cnLevelCount=1 resources2.cnLevels=[0.0] ##resources2.cnLineThicknesses=[3] resources2.cnMonoLineThickness=True resources2.cnLineThicknessF=3.0 resources2.lbLabelBarOn=False resources2.lbLabelsOn=False resources2.sfXArray=numpy.linspace(0.0,30.0,len(ux[1,:])) resources2.sfYArray=numpy.linspace(0.0,1.0,len(ux[:,1])) #plot = Ngl.streamline(wks,uvar[0,::2,::2],vvar[0,::2,::2],resources) #print vz_diff.shape #print vy.shape #x,y=numpy.mgrid[0:dims[1],0:dims[2]] #vx=numpy.sin(x)*numpy.sin(y) #vy=numpy.cos(x)*numpy.cos(y) #plot=Ngl.streamline(wks,ux[::5,::50],uy[::5,::50],resources) plot=Ngl.streamline(wks,ux[::2,::10],uy[::2,::10],resources) #Ngl.contour(wks,phase[::5,::50],resources2) Ngl.contour(wks,phase_numpy[:,:],resources2) #plot=Ngl.streamline(wks,vx,vy,resources) Ngl.end()
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)
#line1.SetColor(150, 100, 0, 255) if __name__ == "__main__": dirname, filename = os.path.split(sys.argv[1]) _, _, k = filename.partition("-") l,_,_ = k.partition(".") view = vtk.vtkContextView() view.GetRenderer().SetBackground(1.0, 1.0, 1.0) view.GetRenderWindow().SetSize(800, 600) chart = vtk.vtkChartXY() view.GetScene().AddItem(chart) chart.SetTitle("time = {}".format(int(l))) chart.GetAxis(0).SetTitle("Pressure") chart.GetAxis(1).SetTitle("Coordinate") reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(sys.argv[1]) reader.Update() addPlot(chart, reader, "time = {}".format(int(l))) #chart.SetShowLegend(True) view.GetRenderWindow().SetMultiSamples(0) view.GetRenderWindow().Render() captureImage(view.GetRenderWindow(), l)
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
def readVTSFile(fileName): '''Function to read vtk structured grid (vts) and return a grid object.''' Reader = vtk.vtkXMLStructuredGridReader() Reader.SetFileName(fileName) Reader.Update() return Reader.GetOutput()