def save_vtk(self, modei, scale): path = str( QFileDialog.getExistingDirectory(self, "Select Directory")) + '/' print path U = self.MODOS.coord.copy() nnos = self.MODOS.nnos ngl = self.MODOS.ngl nodesr = self.MODOS.nodesr nodesl = list(set(range(nnos)) - set(nodesr)) scale = float(scale) modei = int(modei) - 1 g = self.MODOS.g U_i = zeros((nnos, g), float) U_i[nodesl] = self.MODOS.modo[:, modei].reshape( self.MODOS.modo[:, modei].size / g, g) Ux, Uy, Uz = U_i[:, 0].copy(), U_i[:, 1].copy(), U_i[:, 2].copy() U_i = U_i * scale U = U + U_i[:, :3] connec_face = self.MODOS.connec_face vtk = pyvtk.VtkData( pyvtk.UnstructuredGrid(U, triangle=connec_face), pyvtk.PointData(pyvtk.Scalars(Ux, name='Ux'), pyvtk.Scalars(Uy, name='Uy'), pyvtk.Scalars(Uz, name='Uz'))) vtk.tofile(path + 'MODAL_' + str(modei + 1))
def test_ReadField(self): THIS_FOLDER = os.path.dirname(os.path.abspath(__file__)) my_file = os.path.join(THIS_FOLDER, 'testVtkReader2.vtk') my_file = open(THIS_FOLDER + '/testVtkReader2.vtk', 'rb') Data = pyvtk.VtkData(my_file) dim = [] dim = Data.structure.dimensions #Number of nodes in each direction nx = dim[0] ny = dim[1] nz = dim[2] #coordinates of the points coords = [] coords = Data.structure.get_points() #numNodes = Data.point_data.length numNodes = len(coords) mesh = VtkReader2.readMesh(numNodes, nx, ny, nz, coords) fc = VtkReader2.readField( mesh, Data, FieldID.FID_Concentration, Physics.PhysicalQuantities.getDimensionlessUnit(), "s", "conc", my_file, 1) self.assertTrue(fc.fieldID == FieldID.FID_Concentration) self.assertTrue(fc.fieldType == Field.FieldType.FT_vertexBased)
def getField(self, fieldID, time): Data = pyvtk.VtkData('micress/sim.vtk') log.debug(Data.header) dim = [] dim = Data.structure.dimensions log.debug(dim) #Number of nodes in each direction nx = dim[0] ny = dim[1] nz = dim[2] #coordinates of the points coords = [] coords = Data.structure.get_points() numNodes = Data.point_data.length log.debug(numNodes) if (self.mesh == None): self.mesh = VtkReader2.readMesh(numNodes, nx, ny, nz, coords) f = VtkReader2.readField(self.mesh, Data, FieldID.FID_Concentration, PQ.getDimensionlessUnit(), timeUnits, "conc1", "micress/sim.vtk", 1) return f
def exportVtk(self, filename): """Method for exporting fem calculation output to VTK-compatible format""" print("Exporting results to '%s'..." % filename) # --- Create points and polygon definitions from our node network points = self.outputData.coords.tolist() # --- Make sure topology is VTK-compatible; i.e.: 0-based #polygons = (self.outputData.edof-1).tolist() topo = np.zeros([self.outputData.edof.shape[0], 3], dtype=int) for i in range(self.outputData.edof.shape[0]): topo[i, 0] = self.outputData.edof[i, 1] / 2 - 1 topo[i, 1] = self.outputData.edof[i, 3] / 2 - 1 topo[i, 2] = self.outputData.edof[i, 5] / 2 - 1 polygons = (topo).tolist() # --- Specify both vector and scalar data for each element #pointData = vtk.PointData(vtk.Scalars(self.outputData.a.tolist(), name="Displacement")) #cellData = vtk.CellData(vtk.Scalars(max(self.outputData.stress), name="maxvmstress"),\ # vtk.Vectors(self.outputData.stress, "stress")) cellData = vtk.CellData( vtk.Scalars(self.outputData.stress, name="Von Mises")) # --- Create the structure of the element network structure = vtk.PolyData(points=points, polygons=polygons) # --- Store everything in a vtk instance #vtkData = vtk.VtkData(structure, pointData, cellData) vtkData = vtk.VtkData(structure, cellData) # --- Save the data to the specified file vtkData.tofile(filename, "ascii")
def tovtk(self, N, filename): """Dump probes to VTK file.""" is_root = comm.Get_rank() == 0 z = self.array(N=N) if is_root: d = self.dims d = (d[0], d[1], d[2]) if len(d) > 2 else (d[0], d[1], 1) grid = pyvtk.StructuredGrid(d, self.create_dense_grid()) v = pyvtk.VtkData(grid, "Probe data. Evaluations = {}".format(self.probes.number_of_evaluations())) if self.probes.value_size() == 1: v.point_data.append(pyvtk.Scalars(z, name="Scalar", lookup_table='default')) elif self.probes.value_size() == 3: v.point_data.append(pyvtk.Vectors(z, name="Vector")) elif self.probes.value_size() == 9: # StatisticsProbes if N == 0: num_evals = self.probes.number_of_evaluations() v.point_data.append(pyvtk.Vectors(z[:, :3]/num_evals, name="UMEAN")) rs = ["uu", "vv", "ww", "uv", "uw", "vw"] for i in range(3, 9): v.point_data.append(pyvtk.Scalars(z[:, i]/num_evals, name=rs[i-3], lookup_table='default')) else: # Just dump latest snapshot v.point_data.append(pyvtk.Vectors(z[:, :3], name="U")) else: raise TypeError("Only vector or scalar data supported for VTK") v.tofile(filename)
def omf2vtk(input_omf_file, output_vtk_file, output_format='ascii' ): """ Convert a given input_omf_file into a VTK file in ascii or binary format Magnetisation (direction and magnitude) values are stored as cell values """ data = MagnetisationData(input_omf_file) data.generate_field() data.generate_coordinates() grid = (np.linspace(data.xmin * 1e9, data.xmax * 1e9, data.nx + 1), np.linspace(data.ymin * 1e9, data.ymax * 1e9, data.ny + 1), np.linspace(data.zmin * 1e9, data.zmax * 1e9, data.nz + 1)) structure = pyvtk.RectilinearGrid(* grid) vtk_data = pyvtk.VtkData(structure, "") # Save the magnetisation vtk_data.cell_data.append(pyvtk.Vectors(np.column_stack((data.field_x, data.field_y, data.field_z)), "m")) # Save Ms as scalar field vtk_data.cell_data.append(pyvtk.Scalars(data.field_norm, "Ms")) # Save to VTK file with specified output filename vtk_data.tofile(output_vtk_file, output_format)
def set_data_from_vtk(self, filename): p = pyvtk.VtkData(filename) vtkdata = p.point_data.data ids = self.probes.get_probe_ids() nn = len(ids) # Count the number of fields i = 0 for d in vtkdata: if hasattr(d, 'vectors'): i += 3 else: i += 1 # Put all field in data data = zeros((array(self.dims).prod(), i)) i = 0 for d in vtkdata: if hasattr(d, 'vectors'): data[:, i:(i+3)] = array(d.vectors) i += 3 else: data[:, i] = array(d.scalars) i += 1 self.probes.restart_probes(data.flatten(), self._num_eval)
def export_paraview(self): if self.export_paraview == 0: self.vtk_points = [_v.coord for _v in self.vertices[1:]] self.vtk_triangle = [[_e.vertices[0].tag-1, _e.vertices[1].tag-1, _e.vertices[2].tag-1] for _e in self.elements[1:] if _e.typ==2] pressure = [np.abs(_v.sol[3]) for _v in self.vertices[1:]] # Bidouille pour que la tour et les lettres clignotent dans IAGS 20201 pressure_max = max(pressure) light_on = self.export_paraview%4 if light_on<2: tower_on = 0 else: tower_on = 1 for _ent in self.fem_entities: if _ent.dim ==2: if _ent.mat.MEDIUM_TYPE == "eqf": if _ent.mat.name == "tower": for _elem in _ent.elements: for _v in _elem.vertices: _v.sol[3] = (1+(-1)**tower_on)*(pressure_max/2.) if _ent.mat.name == "letter": for _elem in _ent.elements: for _v in _elem.vertices: _v.sol[3] = (1+(-1)**(tower_on+1))*(pressure_max/2.) pressure = [np.abs(_v.sol[3]) for _v in self.vertices[1:]] vtk = pyvtk.VtkData(pyvtk.UnstructuredGrid(self.vtk_points,triangle=self.vtk_triangle), pyvtk.PointData(pyvtk.Scalars(pressure,name='Pressure'))) vtk.tofile("vtk/"+self.name_project + "-{}".format(self.export_paraview)) self.export_paraview +=1
def dump_vtk_grid(self, path: str): self.set_sigma() point_coords = np.zeros([self.n_nodes, 3]) point_coords += self.a.reshape([self.n_nodes, 3]) point_coords[:, 0] += self.x_0 point_coords[:, 1] += self.y_0 point_velocities = self.a_t.reshape([self.n_nodes, 3]) pd = pvtk.PointData(pvtk.Vectors(point_velocities, name='Velocity')) pd.append(pvtk.Scalars(point_coords[:, 2], name='z')) triangles = [] sigmas = [] for elem in self.elements: triangles.append(list(elem.node_ind)) sigmas.append(elem.sigma) cd = [] names = [ 'sigma_xx', 'sigma_yy', 'sigma_zz', 'tau_xy', 'tau_yz', 'tau_xz' ] sigmas = np.array(sigmas) for i in range(6): cd.append(pvtk.Scalars(sigmas[:, i], name=names[i])) usg = pvtk.UnstructuredGrid(point_coords, triangle=triangles) vtk = pvtk.VtkData(usg, pd) for e in cd: vtk.cell_data.append(e) vtk.tofile(path, 'binary')
def write_vtk(self, filename): import pyvtk if self.mesh_type is "cube": vtkelements = pyvtk.VtkData( pyvtk.UnstructuredGrid(self.points, hexahedron=self.elements), "Mesh") vtkelements.tofile(filename)
def numpy2vtkgrid_file(outfilename, xmin, xmax, ymin, ymax, numpy_matrix, zlevel=0.0, vtk_format='ascii', vtkfilecomment="Created with numpy2vtkgrid", vtkdatacomment="Scalar field"): assert len(numpy_matrix.shape) == 2,\ "data needs to be 2d, but shape is '%s'" % numpy_matrix.shape nx, ny = numpy_matrix.shape xpos = numpy.linspace(xmin, xmax, nx) ypos = numpy.linspace(ymin, ymax, ny) print "point set = %d*%d=%d" % (nx, ny, nx * ny) vtk = pyvtk.VtkData( pyvtk.RectilinearGrid(\ xpos.tolist(),ypos.tolist(),[zlevel] ), vtkfilecomment, pyvtk.PointData( pyvtk.Scalars( numpy_matrix.flatten().tolist(), vtkdatacomment ) ), format=vtk_format ) vtk.tofile(outfilename, format=vtk_format)
def test_tet_mesh(visualize=False): pytest.importorskip("meshpy") from math import pi, cos, sin from meshpy.tet import MeshInfo, build from meshpy.geometry import \ GeometryBuilder, generate_surface_of_revolution, EXT_CLOSED_IN_RZ pytest.importorskip("meshpy") big_r = 3 little_r = 1.5 points = 50 dphi = 2 * pi / points rz = np.array( [[big_r + little_r * cos(i * dphi), little_r * sin(i * dphi)] for i in range(points)]) geo = GeometryBuilder() geo.add_geometry(*generate_surface_of_revolution( rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=20)) mesh_info = MeshInfo() geo.set(mesh_info) mesh = build(mesh_info) def tet_face_vertices(vertices): return [ (vertices[0], vertices[1], vertices[2]), (vertices[0], vertices[1], vertices[3]), (vertices[0], vertices[2], vertices[3]), (vertices[1], vertices[2], vertices[3]), ] face_map = {} for el_id, el in enumerate(mesh.elements): for fid, face_vertices in enumerate(tet_face_vertices(el)): face_map.setdefault(frozenset(face_vertices), []).append( (el_id, fid)) adjacency = {} for face_vertices, els_faces in face_map.items(): if len(els_faces) == 2: (e1, f1), (e2, f2) = els_faces adjacency.setdefault(e1, []).append(e2) adjacency.setdefault(e2, []).append(e1) cuts, part_vert = pymetis.part_graph(17, adjacency) if visualize: import pyvtk vtkelements = pyvtk.VtkData( pyvtk.UnstructuredGrid(mesh.points, tetra=mesh.elements), "Mesh", pyvtk.CellData(pyvtk.Scalars(part_vert, name="partition"))) vtkelements.tofile('split.vtk')
def write_vtk(self, filename): import pyvtk vtkelements = pyvtk.VtkData( pyvtk.UnstructuredGrid( self.points, tetra=self.elements), "Mesh") vtkelements.tofile(filename)
def inp2vtk(self, inp_file=''): """ :rtype : object """ if self._inp_file: inp_file = self._inp_file else: self._inp_file = inp_file if inp_file == '': sys.exit('ERROR: Please provide inp filename!') if self._vtk_file: vtk_file = self._vtk_file else: vtk_file = inp_file[:-4] self._vtk_file = vtk_file + '.vtk' print("--> Reading inp data") with open(inp_file, 'r') as f: line = f.readline() num_nodes = int(line.strip(' ').split()[0]) num_elems = int(line.strip(' ').split()[1]) coord = np.zeros((num_nodes, 3), 'float') elem_list_tri = [] elem_list_tetra = [] for i in range(num_nodes): line = f.readline() coord[i, 0] = float(line.strip(' ').split()[1]) coord[i, 1] = float(line.strip(' ').split()[2]) coord[i, 2] = float(line.strip(' ').split()[3]) for i in range(num_elems): line = f.readline().strip(' ').split() line.pop(0) line.pop(0) elem_type = line.pop(0) if elem_type == 'tri': elem_list_tri.append([int(i) - 1 for i in line]) if elem_type == 'tet': elem_list_tetra.append([int(i) - 1 for i in line]) print('--> Writing inp data to vtk format') vtk = pv.VtkData( pv.UnstructuredGrid(coord, tetra=elem_list_tetra, triangle=elem_list_tri), 'Unstructured pflotran grid') vtk.tofile(vtk_file)
def write_species_vtk(self, species=None, iteration=0, format='binary', scalars=['ux', 'uy', 'uz', 'w'], select=None, zmin_fixed=None): """ Convert the given list of species from the openPMD format to a VTK container, and write it to the disk. Parameters ---------- species: list or None List of species names to be converted. If None, it converts all available species provided by OpenPMDTimeSeries scalars: list of strings list of values associated with each paricle to be included. ex. : 'charge', 'id', 'mass', 'x', 'y', 'z', 'ux', 'uy', 'uz', 'w' iteration: int iteration number to treat (default 0) select: dict dictonary to impoer selection on the particles, as it is defined in opnePMD_viewer format: str format for the VTK file, either 'ascii' or 'binary' zmin_fixed: float or None When treating the simulation data for the animation, in some cases (e.g. with moving window) it is useful to fix the origin of the visualization domain. If float number is given it will be use as z-origin of the visualization domain """ # Check available fields if comps is not defined if species is None: species = self.ts.avail_species # register constants self.iteration = iteration self.zmin_fixed = zmin_fixed self.select = select self.scalars = scalars # Make a numer string for the file to write istr = str(self.iteration) while len(istr)<7 : istr='0'+istr name_base = self.path+'vtk_specie_{:}_{:}' # Convert and save all the species for specie in species: pts_vtk, scalars_vtk = self._convert_species(specie) vtk.VtkData(pts_vtk, vtk.PointData(*scalars_vtk) )\ .tofile(name_base.format(specie,istr), format=format)
def writeVTK(self, filename): import pyvtk origin = N.array([self.x_axis[0], self.y_axis[0], self.z_axis[0]]) spacing = N.array([self.x_axis[1], self.y_axis[1], self.z_axis[1]]) \ - origin values = pyvtk.Scalars(N.ravel(N.transpose(self.data)), 'electron density') data = pyvtk.VtkData( pyvtk.StructuredPoints(self.data.shape, origin, spacing), 'Density map', pyvtk.PointData(values)) data.tofile(filename, format='binary')
def inp2vtk_python(self, inp_file=''): import pyvtk as pv """ Using Python VTK library, convert inp file to VTK file. then change name of CELL_DATA to POINT_DATA. """ print("--> Using Python to convert inp files to VTK files") if self._inp_file: inp_file = self._inp_file else: self._inp_file = inp_file if inp_file == '': sys.exit('ERROR: Please provide inp filename!') if self._vtk_file: vtk_file = self._vtk_file else: vtk_file = inp_file[:-4] self._vtk_file = vtk_file + '.vtk' print("--> Reading inp data") with open(inp_file, 'r') as f: line = f.readline() num_nodes = int(line.strip(' ').split()[0]) num_elems = int(line.strip(' ').split()[1]) coord = np.zeros((num_nodes, 3), 'float') elem_list_tri = [] elem_list_tetra = [] for i in range(num_nodes): line = f.readline() coord[i, 0] = float(line.strip(' ').split()[1]) coord[i, 1] = float(line.strip(' ').split()[2]) coord[i, 2] = float(line.strip(' ').split()[3]) for i in range(num_elems): line = f.readline().strip(' ').split() line.pop(0) line.pop(0) elem_type = line.pop(0) if elem_type == 'tri': elem_list_tri.append([int(i) - 1 for i in line]) if elem_type == 'tet': elem_list_tetra.append([int(i) - 1 for i in line]) print('--> Writing inp data to vtk format') vtk = pv.VtkData( pv.UnstructuredGrid(coord, tetra=elem_list_tetra, triangle=elem_list_tri), 'Unstructured pflotran grid') vtk.tofile(vtk_file)
def test_vtk_writer_speed(): """ Comparison of C backend with the old pyvtk interface For this we use a 200 x 200 x 1 mesh and convert the OMF file into a VTK file using both the C library and the PyVTK library. We run the same conversion for each method during 20 times and print a mean. """ # C backend --------------------------------------------------------------- _file = glob.glob('./vtk_writer_omfs/isolated_sk_Cnv_n_200-Oxs*.omf')[0] data = op.MagnetisationData(_file) data.generate_field() data.generate_coordinates() output_vtk_file = 'vtk_writer_omfs/isolated_sk_Cnv_n_200.vtk' C_timings = [] for i in range(20): start = timeit.default_timer() ot.clib.WriteVTK_RectilinearGrid_C(data.grid[0], data.grid[1], data.grid[2], data.field.reshape(-1), data.field_norm, data.nx, data.ny, data.nz, output_vtk_file) end = timeit.default_timer() C_timings.append(end - start) print('C writer (best of 20): ', np.mean(np.array(C_timings))) # PyVTK ------------------------------------------------------------------- output_vtk_file = 'vtk_writer_omfs/isolated_sk_Cnv_n_200_pyvtk.vtk' pyvtk_timings = [] for i in range(20): start = timeit.default_timer() structure = pyvtk.RectilinearGrid(*data.grid) vtk_data = pyvtk.VtkData(structure, "") # Save the magnetisation vtk_data.cell_data.append(pyvtk.Vectors(data.field, "m")) # Save Ms as scalar field vtk_data.cell_data.append(pyvtk.Scalars(data.field_norm, "Ms")) # Save to VTK file with specified output filename vtk_data.tofile(output_vtk_file, 'binary') end = timeit.default_timer() pyvtk_timings.append(end - start) print('PyVTK writer (best of 20): ', np.mean(np.array(pyvtk_timings)))
def visitPrint(self, k): """ Uses PyVTK to write out data in a VisIt Visualization Tool capable format. """ import pyvtk uVel = pyvtk.Scalars(self.fluid.u().flatten(), name='u') vVel = pyvtk.Scalars(self.fluid.v().flatten(), name='v') totp = pyvtk.Scalars(self.fluid.p().flatten(), name='p') celldat = pyvtk.PointData(uVel, vVel, totp) grid = pyvtk.RectilinearGrid(self.domain.x, self.domain.y, self.domain.z) vtk = pyvtk.VtkData(grid, celldat) vtk.tofile('data%i' % k)
def make_vtk(**kwargs): args = [] if 'grid' in kwargs: args.append(kwargs.get('grid')) if 'point_data' in kwargs: data = kwargs['point_data'] args.append(pyvtk.PointData(*data)) if 'cell_data' in kwargs: data = kwargs['cell_data'] args.append(pyvtk.CellData(*data)) if 'header' in kwargs: args.append(kwargs.get('header')) return pyvtk.VtkData(*args)
def savevtk(v, fn='', lons=[], lats=[], levels=[]): """save tracer field into vtk format, """ import pyvtk def norm(c): return (c - c[0]) / (c[-1] - c[0]) z = levels / abs(levels).max() * (lons.max() - lons.min()) * 0.7 point_data = pyvtk.PointData(pyvtk.Scalars(v.T.flatten())) vtk_object = pyvtk.VtkData(pyvtk.RectilinearGrid(x=lons, y=lats, z=z), point_data) vtk_object.tofile(fn) return
def read_memb(filename): """Reads a vtk file, returns the vertices, triangles, and the name. The CELL_TYPES information is discarded since it is not goanna use. :name: path of the vtk file to read :returns: a numpy array of the shape (N, 3) containing the vertices of the facets, and the name of the object as given in the vtk file. """ vtk_data = pyvtk.VtkData(filename) vertices = vtk_data.structure.points triangles = vtk_data.structure.triangle name = basename(filename)[:-8] # drop the 0005.vtk extension if vertices is None: raise ValueError('not a valid VTK file.') return vertices, triangles, name
def write_fields_vtk(self, comps=None, iteration=0, format='binary', fixed_zmin=None): """ Convert the given list of scalar and vector fields from the openPMD format to a VTK container, and write it to the disk. Parameters ---------- comps: list or None List of scalar and vector fields to be converted. If None, it converts all available components provided by OpenPMDTimeSeries iteration: int iteration number to treat (default 0) format: str format for the VTK file, either 'ascii' or 'binary' fixed_zmin: float or None When treating the simulation data for the animation, in some cases (e.g. with moving window) it is useful to fix the origin of the visualization domain. If float number is given it will be use as z-origin of the visualization domain """ # Check available fields if comps is not defined if comps is None: comps = self.ts.avail_fields # Register z-origin of the visualization domain self.fixed_zmin = fixed_zmin # Convert the fields one by one and store them to the list vtk_container = [] for comp in comps: vtk_container.append(self._convert_field(comp, iteration=iteration)) # Make a numer string for the file to write istr = str(iteration) while len(istr) < 7: istr = '0' + istr # Create the VTK data container and write it to the disk vtk.VtkData(self.grid, vtk.PointData(*vtk_container))\ .tofile(self.path+'vtk_fields_'+istr, format=format)
def plot_vtk(A, V, partition) : V = numpy.append( V, numpy.zeros((A.shape[0],1)), axis=1 ) triples = [] A = scipy.sparse.triu(A,k=1).tocsr() for i in range(A.shape[0]-1): row = A.indices[A.indptr[i]:A.indptr[i+1]].tolist() for t1,t2 in itertools.combinations(row, 2) : if A[t1,t2] : triples.append((i,t1,t2)) vtkelements = pyvtk.VtkData( pyvtk.UnstructuredGrid(V, triangle=triples), "Mesh", pyvtk.PointData(pyvtk.Scalars(partition, name="partition"))) vtkelements.tofile('{0}_{1}.vtk'.format(graph_name,num_parts))
def exportVtk(self, filename): """Export results to VTK""" print("Exporting results to %s." % filename) # --- Skapa punkter och polygon definitioner från vårt nät points = self.outputData.coords.tolist() # --- Tänk på att topologin i VTK är 0-baserad varför vi måste minskar **edof** med 1. #polygons = (self.outputData.edof-1).tolist() # --- För spänningsproblemet användas, se också nästa stycke: polygons = (self.outputData.topo - 1).tolist() # --- Resultat från beräkningen skapas i separata objekt. Punkter i vtk.PointData och # --- elementdata i vtk.CellData. Nedan anger vi både vektor data och skalärvärden för elementen. # --- Tänk på att vektorerna måste ha 3 komponenter, så lägg till detta i beräkningsdelen. #pointData = vtk.PointData(vtk.Scalars(self.outputData.a.tolist(), name="Nodal Properties")) #ellData = vtk.CellData(vtk.Scalars(self.outputData.vonMises, name="Von Mises"), vtk.Vectors(self.outputData.flow, "flow")) # --- För spänningsproblemet blir det istället (ingen pointData) #HÄR BLIR DET KNAS# cellData = vtk.CellData( vtk.Scalars(self.outputData.vonMises, name="mises"), vtk.Vectors(self.outputData.stresses1, "principal stress 1"), vtk.Vectors(self.outputData.stresses2, "principal stress 2")) # --- Skapa strukturen för elementnätet. structure = vtk.PolyData(points=points, polygons=polygons) # --- Lagra allting i en vtk.VtkData instans # vtkData = vtk.VtkData(structure, pointData, cellData) # --- För spänningsfallet vtkData = vtk.VtkData(structure, cellData) # --- Spara allt till filen vtkData.tofile(filename, "ascii")
def _writevtk(self, filename): grid = [ pmini + np.linspace(0, li, ni + 1) for pmini, li, ni in zip(self.mesh.pmin, self.mesh.l, self.mesh.n) ] structure = pyvtk.RectilinearGrid(*grid) vtkdata = pyvtk.VtkData(structure) vectors = [self.__call__(i) for i in self.mesh.coordinates] vtkdata.cell_data.append(pyvtk.Vectors(vectors, self.name)) for i, component in enumerate(dfu.axesdict.keys()): name = "{}_{}".format(self.name, component) vtkdata.cell_data.append( pyvtk.Scalars(list(zip(*vectors))[i], name)) vtkdata.tofile(filename)
def makeFromVTK2(fileName,unit,time=0,skip=['coolwarm']): ''' Return fields stored in *fileName* in the VTK2 (``.vtk``) format. :param str fileName: filename to load from :param unit PhysicalUnit: physical unit of filed values :param float time: time value for created fields (time is not saved in VTK2, thus cannot be recovered) :param [string,] skip: file names to be skipped when reading the input file; the default value skips the default coolwarm colormap. :returns: one field from VTK :rtype: Field ''' import pyvtk from . import fieldID if not fileName.endswith('.vtk'): log.warn('Field.makeFromVTK2: fileName should end with .vtk, you may get in trouble (proceeding).') ret=[] try: data=pyvtk.VtkData(fileName) # this is where reading the file happens (inside pyvtk) except NotImplementedError: log.info('pyvtk fails to open (binary?) file "%s", trying through vtk.vtkGenericDataReader.'%fileName) return Field.makeFromVTK3(fileName,time=time,units=unit,forceVersion2=True) ugr=data.structure if not isinstance(ugr,pyvtk.UnstructuredGrid): raise NotImplementedError("grid type %s is not handled by mupif (only UnstructuredGrid is)."%ugr.__class__.__name__) mesh=Mesh.UnstructuredMesh.makeFromPyvtkUnstructuredGrid(ugr) # get cell and point data pd,cd=data.point_data.data,data.cell_data.data for dd,fieldType in (pd,FieldType.FT_vertexBased),(cd,FieldType.FT_cellBased): for d in dd: # will raise KeyError if fieldID with that name is not defined if d.name in skip: continue fid=fieldID.FieldID[d.name] # determine the number of components using the expected number of values from the mesh expectedNumVal=(mesh.getNumberOfVertices() if fieldType==FieldType.FT_vertexBased else mesh.getNumberOfCells()) nc=len(d.scalars)//expectedNumVal valueType=ValueType.fromNumberOfComponents(nc) values=[d.scalars[i*nc:i*nc+nc] for i in range(len(d.scalars))] ret.append(Field( mesh=mesh, fieldID=fid, units=unit, # not stored at all time=time, # not stored either, set by caller valueType=valueType, values=values, fieldType=fieldType )) return ret
def solnToVTK(self): done = False lcv = 0 coords = self.loadVec('coords.dat', 3) dims = list(coords.shape[:-1]) try: dx = coords[1, 1, 1] - coords[0, 0, 0] except IndexError: try: dx = coords[0, 1, 1] - coords[0, 0, 0] except IndexError: try: dx = coords[1, 0, 1] - coords[0, 0, 0] except IndexError: dx = coords[1, 1, 0] - coords[0, 0, 0] dx = np.where(dx == 0., 0.1, dx) if dims[2] == 1: dims[2] = 2 dims = tuple(dims) print dims dx = tuple(dx) vtkgrid = pyvtk.StructuredPoints(dims, coords[0, 0, 0], dx) while not done: try: if not os.path.exists(self._file_prefix + 'prs%03d.dat' % lcv): raise IOError('Nonexistent file') except IOError: done = True print 'Read %d timesteps' % lcv else: prs_data = self.loadVecToVTK('prs%03d.dat' % lcv, 1) vel_data = self.loadVecToVTK('u%03d.dat' % lcv, 3) wall_data = self.loadVecToVTK('walls%03d.dat' % lcv, 1) pointdata = pyvtk.PointData(prs_data, vel_data, wall_data) data = pyvtk.VtkData( vtkgrid, self._prefix.strip('_') + ' step %d' % lcv, pointdata) data.tofile(self._file_prefix + 'soln_%03d.vtk' % lcv) lcv += 1 return
def write2vtk(self, G): # import sys # sys.path = ['..'] + sys.path import pyvtk points = [list(node) for node, data in G.nodes(data=True)] line = [] for edge in G.edges(): for i, node in enumerate(G.nodes()): if node == edge[0]: n1 = i for i, node in enumerate(G.nodes()): if node == edge[1]: n2 = i line.append([n1, n2]) vtk = pyvtk.VtkData(pyvtk.UnstructuredGrid(points, line=line)) vtk.tofile('example1', 'ascii')
def write2vtk(self, G, filename): """ Exports a graph to a vtk file to be visualized with paraview """ # import sys # sys.path = ['..'] + sys.path import pyvtk points = [list(node) for node, data in G.nodes(data=True)] line = [] for edge in G.edges(): for i, node in enumerate(G.nodes()): if node == edge[0]: n1 = i for i, node in enumerate(G.nodes()): if node == edge[1]: n2 = i line.append([n1, n2]) vtk = pyvtk.VtkData(pyvtk.UnstructuredGrid(points, line=line)) vtk.tofile(filename, 'ascii')