def Mesh2VTKUGrid(mesh): vtkcelltypes=((),(vtk.VTK_EMPTY_CELL,vtk.VTK_VERTEX,vtk.VTK_LINE),(vtk.VTK_EMPTY_CELL,vtk.VTK_VERTEX,vtk.VTK_LINE,vtk.VTK_TRIANGLE,vtk.VTK_QUAD,vtk.VTK_POLYGON,vtk.VTK_POLYGON),(vtk.VTK_EMPTY_CELL,vtk.VTK_VERTEX,vtk.VTK_LINE,vtk.VTK_TRIANGLE,vtk.VTK_TETRA,vtk.VTK_CONVEX_POINT_SET,vtk.VTK_CONVEX_POINT_SET,vtk.VTK_CONVEX_POINT_SET,vtk.VTK_HEXAHEDRON)) npoints=mesh.num_vertices() geom=mesh.geometry() pts=vtk.vtkPoints() pts.SetNumberOfPoints(npoints) for i in xrange(npoints): p=geom.point(i) pts.SetPoint(i,p.x(),p.y(),p.z()) dim = mesh.topology().dim() ncells=mesh.num_cells() cells=vtk.vtkCellArray() cellTypes=vtk.vtkUnsignedCharArray() cellTypes.SetNumberOfTuples(ncells) cellLocations=vtk.vtkIdTypeArray() cellLocations.SetNumberOfTuples(ncells) loc=0 for (cell,i) in zip(mesh.cells(),xrange(ncells)) : ncellpoints=len(cell) cells.InsertNextCell(ncellpoints) for cpoint in cell: cells.InsertCellPoint(cpoint) cellTypes.SetTuple1(i,vtkcelltypes[dim][ncellpoints]) cellLocations.SetTuple1(i,loc) loc+=1+ncellpoints ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(pts) ugrid.SetCells(cellTypes,cellLocations,cells) return ugrid
def parametrize_dataset(dataset, grid): from paraview.numpy_support import vtk_to_numpy xyz = vtk_to_numpy(dataset.GetPoints().GetData()) from numpy import sqrt from numpy import zeros_like xrt = zeros_like(xyz) xrt[:, 0] = xyz[:, 0] xrt[:, 1] = sqrt(xyz[:, 1] ** 2 + xyz[:, 2] ** 2) from paraview.numpy_support import numpy_to_vtk from paraview.vtk import vtkPoints points = vtkPoints() points.SetData(numpy_to_vtk(xrt, deep=1)) input = vtk.vtkPolyData() input.SetPoints(points) probe = vtk.vtkProbeFilter() probe.SetInput(input) probe.SetSource(grid) probe.Update() outputPointData = probe.GetOutput().GetPointData() pointData = dataset.GetPointData() pointData.AddArray(outputPointData.GetArray('hsH')) pointData.AddArray(outputPointData.GetArray('xm'))
def parametrize(spline, numberOfPoints=101, relativeExtension=0.1): from paraview.vtk import vtkFloatArray arrayU = vtkFloatArray() arrayV = vtkFloatArray() arrayU.SetName('hsH') arrayV.SetName('xm') from paraview.vtk import vtkPoints points = vtkPoints() uvMin = -relativeExtension uvMax = 1.0 + relativeExtension for _v in linspace(uvMin, uvMax, numberOfPoints): for _u in (uvMin, uvMax): arrayU.InsertNextTuple1(_u) arrayV.InsertNextTuple1(_v) pnt = spline(_u, _v) points.InsertNextPoint(pnt[0], pnt[1], 0.0) from paraview.vtk import vtkStructuredGrid grid = vtkStructuredGrid() grid.SetExtent(1, 2, 1, numberOfPoints, 1, 1) grid.SetPoints(points) pointData = grid.GetPointData() pointData.AddArray(arrayU) pointData.AddArray(arrayV) return grid
def RequestData(self, request, inInfo, outInfo): logger.debug("Requesting data...") input = self.GetInputDataObject(0, 0) trajectory_data = dsa.WrapDataObject(input) output = dsa.WrapDataObject(vtkPolyData.GetData(outInfo)) # Retrieve current time time = timesteps_util.get_timestep(self, logger=logger) # Retrieve trajectory data trajectory_times = trajectory_data.PointData["Time"] trajectory_points = trajectory_data.Points # Interpolate along the trajectory to find current position current_position = [ np.interp(time, trajectory_times, trajectory_points[:, i]) for i in range(3) ] # Expose to VTK points_vtk = vtk.vtkPoints() verts_vtk = vtk.vtkCellArray() verts_vtk.InsertNextCell(1) points_vtk.InsertPoint(0, *current_position) verts_vtk.InsertCellPoint(0) output.SetPoints(points_vtk) output.SetVerts(verts_vtk) # Interpolate remaining point data along the trajectory for dataset in trajectory_data.PointData.keys(): if dataset == "Time": continue point_data = trajectory_data.PointData[dataset] data_at_position = np.zeros(point_data.shape[1:]) if len(data_at_position.shape) > 0: for i in itertools.product( *map(range, data_at_position.shape)): point_data_i = point_data[(slice(None), ) + i] if len(trajectory_times) == len(point_data_i): data_at_position[i] = np.interp( time, trajectory_times, point_data_i) else: logger.warning( "Unable to interpolate trajectory dataset" f" {dataset}[{i}]: Length of dataset" f" ({len(point_data_i)}) does not match length of" f" trajectory times ({len(trajectory_times)}).") else: data_at_position = np.interp(time, trajectory_times, point_data) data_vtk = vtknp.numpy_to_vtk(np.array([data_at_position])) data_vtk.SetName(dataset) output.GetPointData().AddArray(data_vtk) return 1
def _lattice2poly_data(cuds): poly_data = vtk.vtkPolyData() points = vtk.vtkPoints() coordinates = cuds.get_coordinate # copy node data point_data = poly_data.GetPointData() data_collector = CUBADataAccumulator(container=point_data) for node in cuds.iter(item_type=CUBA.NODE): points.InsertNextPoint(coordinates(node.index)) data_collector.append(node.data) poly_data.SetPoints(points) return poly_data
def _mesh2unstructured_grid(cuds): point2index = {} unstructured_grid = vtk.vtkUnstructuredGrid() unstructured_grid.Allocate() # copy points points = vtk.vtkPoints() point_data = unstructured_grid.GetPointData() data_collector = CUBADataAccumulator(container=point_data) for index, point in enumerate(cuds.iter(item_type=CUBA.POINT)): point2index[point.uid] = index points.InsertNextPoint(*point.coordinates) data_collector.append(point.data) # prepare to copy elements cell_data = unstructured_grid.GetCellData() data_collector = CUBADataAccumulator(container=cell_data) # copy edges mapping = points2edge() for edge in cuds.iter(item_type=CUBA.EDGE): npoints = len(edge.points) ids = vtk.vtkIdList() for uid in edge.points: ids.InsertNextId(point2index[uid]) unstructured_grid.InsertNextCell(mapping[npoints], ids) data_collector.append(edge.data) # copy faces mapping = points2face() for face in cuds.iter(item_type=CUBA.FACE): npoints = len(face.points) ids = vtk.vtkIdList() for uid in face.points: ids.InsertNextId(point2index[uid]) unstructured_grid.InsertNextCell(mapping[npoints], ids) data_collector.append(face.data) # copy cells mapping = points2cell() for cell in cuds.iter(item_type=CUBA.CELL): npoints = len(cell.points) ids = vtk.vtkIdList() for uid in cell.points: ids.InsertNextId(point2index[uid]) unstructured_grid.InsertNextCell(mapping[npoints], ids) data_collector.append(cell.data) unstructured_grid.SetPoints(points) return unstructured_grid
def RequestData(self, request, inInfo, outInfo): logger.debug("Requesting data...") output = dsa.WrapDataObject(vtkPolyData.GetData(outInfo)) with h5py.File(self._filename, "r") as trajectory_file: subfile = trajectory_file[self._subfile] coords = np.array(subfile[self._coords_dataset]) coords[:, 1:] *= self._radial_scale logger.debug(f"Loaded coordinates with shape {coords.shape}.") # Construct a line of points points_vtk = vtk.vtkPoints() # Each ID is composed of (1) the order of the point in the line and (2) # the index in the `vtkPoints` constructed above line_vtk = vtk.vtkPolyLine() point_ids = line_vtk.GetPointIds() point_ids.SetNumberOfIds(len(coords)) for i, point in enumerate(coords): points_vtk.InsertPoint(i, *point[1:]) point_ids.SetId(i, i) output.SetPoints(points_vtk) # Set the line ordering as "cell data" output.Allocate(1, 1) output.InsertNextCell(line_vtk.GetCellType(), line_vtk.GetPointIds()) # Add time data to the points time = vtknp.numpy_to_vtk(coords[:, 0]) time.SetName("Time") output.GetPointData().AddArray(time) # Add remaining datasets from file to trajectory points with h5py.File(self._filename, "r") as trajectory_file: subfile = trajectory_file[self._subfile] for dataset in subfile: if dataset == self._coords_dataset: continue dataset_vtk = vtknp.numpy_to_vtk(subfile[dataset][:, 1:]) dataset_vtk.SetName(dataset.replace(".dat", "")) output.GetPointData().AddArray(dataset_vtk) return 1
def pvgrid(pvobj, filename): """Generate a ParaView source This function is not meant to be directly run, but is to be run as a ParaView progamable source. In ParaView Sources > Programmable Source in the properties tab set the Output Data Set to 'vtkUnstructuredGrid' and in the script box put from mesh.writers import pvgrid pvgrid(self, "filename.ext") make sure that afepy is on your PYTHONPATH """ from paraview import vtk mesh = parse_xml(filename) output = pvobj.GetOutput() # allocate points pts = vtk.vtkPoints() for point in mesh.coords: if mesh.num_dim == 2: point = np.append(point, 0.) pts.InsertNextPoint(*point) output.SetPoints(pts) num_elem, num_node_per_elem = mesh.connect.shape output.Allocate(num_elem, 1000) for cell in mesh.connect: point_ids = vtk.vtkIdList() for point_id in range(num_node_per_elem): point_ids.InsertId(point_id, int(cell[point_id])) cell_type = VTK.vtk_cell_types(mesh.num_dim, num_node_per_elem) output.InsertNextCell(cell_type, point_ids)
def _particles2poly_data(cuds): particle2index = {} points = vtk.vtkPoints() lines = vtk.vtkCellArray() poly_data = vtk.vtkPolyData() point_data = poly_data.GetPointData() data_collector = CUBADataAccumulator(container=point_data) for index, particle in enumerate(cuds.iter(item_type=CUBA.PARTICLE)): particle2index[particle.uid] = index points.InsertPoint(index, *particle.coordinates) data_collector.append(particle.data) cell_data = poly_data.GetCellData() data_collector = CUBADataAccumulator(container=cell_data) for bond in cuds.iter(item_type=CUBA.BOND): lines.InsertNextCell(len(bond.particles)) for uuid in bond.particles: lines.InsertCellPoint(particle2index[uuid]) data_collector.append(bond.data) poly_data.SetPoints(points) poly_data.SetLines(lines) return poly_data
from paraview import vtk import os # Set your OpenGeoSys .msh file here. filename = os.path.normcase("./examples/daejeon-ogs-final.msh") f = open(filename) output = self.GetOutput() # Read everything with no line break but with space. IMPORTANT contents = f.read().replace('\n', ' ') words = contents.split() # Now read point(node) info numPoints = int(words[words.index('$NODES') + 1]) #print (numPoints) pts = vtk.vtkPoints() pos1 = words.index('$NODES') + 2 for node in range(numPoints): # node_idx = words[pos+node*4] x = float(words[pos1 + node * 4 + 1]) y = float(words[pos1 + node * 4 + 2]) z = float(words[pos1 + node * 4 + 3]) pts.InsertNextPoint(x, y, z) # print x, y, z output.SetPoints(pts) # Now read element(cell) info numCells = int(words[words.index('$ELEMENTS') + 1]) #print (numCells)
""" """ CONVERT COORDINATES AND UNITS Convert the coordinate XYZ from units of m to km and normalize origin to 0, Change the units of the output from units of m/s to km/s I honestly have no idea how I made this work, the documentation for these filters is apalling. Wtf paraview. """ from paraview import vtk pdi = self.GetInput() pdo = self.GetOutput() numPoints = pdi.GetNumberOfPoints() newPoints = vtk.vtkPoints() min_x, _, min_y, _, _, _ = pdi.GetBounds() for i in range(0, numPoints): coords = pdi.GetPoint(i) x, y, z = coords[:3] x -= min_x y -= min_y # Convert to units of km x *= 1E-3 y *= 1E-3 z *= 1E-3 newPoints.InsertPoint(i, x, y, z) # Set the new coordinate system pdo.SetPoints(newPoints)
def lire_monobloc(self, acces_fichier, numbloc=None): """lecture d'un seul bloc si numbloc est indique, alors le bloc est stocke comme numbloc et le numero de bloc lu dans le v3d est ignore """ dictionnaire_lecture = lire_v3d( acces_fichier=acces_fichier, fmt_fichier=self.fmt_fichier, endian=self.endian, precision=self.precision, compter_saut_de_ligne=self.compter_saut_de_ligne, ) if numbloc is None: numbloc = dictionnaire_lecture["numbloc"] + self.decalage_numbloc_lus try: bloc_temp = vtk_new_shallowcopy( self.output if isinstance(self.output, vtk.vtkStructuredGrid) else self.output.GetBlock(numbloc) ) except: bloc_temp = vtk.vtkStructuredGrid() # liste des donnees traitees donnees_traitees = [] # GEOMETRIE # si des coordonnees (x,y,z) sont comprises dans le fichier lu if ( dictionnaire_lecture["data"].has_key("x") and dictionnaire_lecture["data"].has_key("y") and dictionnaire_lecture["data"].has_key("z") ): numpyArrayCoords = numpy.vstack( ( dictionnaire_lecture["data"]["x"], dictionnaire_lecture["data"]["y"], dictionnaire_lecture["data"]["z"], ) ).transpose(1, 0) vtkArray = numpy_support.numpy_to_vtk(numpy.ascontiguousarray(numpyArrayCoords), deep=1) points = vtk.vtkPoints() points.SetData(vtkArray) bloc_temp.SetDimensions( dictionnaire_lecture["dims"][0], dictionnaire_lecture["dims"][1], dictionnaire_lecture["dims"][2] ) bloc_temp.SetPoints(points) donnees_traitees += ["x", "y", "z"] # DONNEES if not bloc_temp is None and bloc_temp.GetNumberOfPoints() != 0: # si il y a rou rov row if ( dictionnaire_lecture["data"].has_key("rou") and dictionnaire_lecture["data"].has_key("rov") and dictionnaire_lecture["data"].has_key("row") and self.assembler_vecteurs is True ): momentum = numpy.vstack( ( dictionnaire_lecture["data"]["rou"], dictionnaire_lecture["data"]["rov"], dictionnaire_lecture["data"]["row"], ) ).transpose(1, 0) vtkArray = numpy_support.numpy_to_vtk(numpy.ascontiguousarray(momentum), deep=1) vtkArray.SetName("momentum") self.ajouter_au_bloc(bloc_temp, vtkArray) donnees_traitees += ["rou", "rov", "row"] # si il y a trois donnees (et seulement trois) du type *_0 *_1 *_2 liste_temp = [nom[:-2] for nom in dictionnaire_lecture["data"].keys()] for key in liste_temp: if ( numpy.all( [ key + "_{0}".format(composante) in dictionnaire_lecture["data"].keys() for composante in range(3) ] ) and numpy.all([key + "_{0}".format(composante) not in donnees_traitees for composante in range(3)]) and self.assembler_vecteurs is True ): vector = numpy.vstack( ( dictionnaire_lecture["data"][key + "_0"], dictionnaire_lecture["data"][key + "_1"], dictionnaire_lecture["data"][key + "_2"], ) ).transpose(1, 0) vtkArray = numpy_support.numpy_to_vtk(numpy.ascontiguousarray(vector), deep=1) vtkArray.SetName(key) self.ajouter_au_bloc(bloc_temp, vtkArray) donnees_traitees += [key + "_%s" % (composante) for composante in range(3)] for key in dictionnaire_lecture["data"]: if key not in donnees_traitees: vtkArray = numpy_support.numpy_to_vtk(dictionnaire_lecture["data"][key], deep=1) vtkArray.SetName(key) self.ajouter_au_bloc(bloc_temp, vtkArray) donnees_traitees += [key] else: print "## IGNORE -- LA GEOMETRIE N'EST PAS CHARGEE" bloc_temp = None if isinstance(self.output, vtk.vtkStructuredGrid): self.output = bloc_temp else: self.output.SetBlock(numbloc, bloc_temp)
def trouver_centres_spheres_inscrites(surface_1, surface_2, precision=1e-6, pas_initial=10): """fonction qui recherche les centrse des spheres inscrites entre les surface_1 et surface_2 le vecteur 'Normals' doit etre present aux noeuds de surface_1 la recherche se fait par trouver_zero_fonction_croissante, pour chacun des points de surface_1 on cherche un point sur la ligne orthogonale a surface_1, equidistant de surface_1 et surface_2 --> centre de la sphere inscrite entre surface_1 et surface_2 passant par le point de surface_1 considere surface_1 et surface_2 doivent etre des vtkPolyData """ # initialisation des outils vtk de calcul des distances calcul_distance_1 = vtk.vtkKdTreePointLocator() calcul_distance_1.SetDataSet(surface_1) calcul_distance_1.BuildLocator() calcul_distance_2 = vtk.vtkKdTreePointLocator() calcul_distance_2.SetDataSet(surface_2) calcul_distance_2.BuildLocator() vtkMath = vtk.vtkMath() # lecture des donnees de la surface liste_normals_surface_1 = numpy_support.vtk_to_numpy(surface_1.GetPointData().GetArray('Normals')) liste_points_surface_1 = numpy_support.vtk_to_numpy(surface_1.GetPoints().GetData()) # ACTION liste_centres = numpy.empty((0,3)) print "progression ", printed = False for numero_point_surface_1 in range(0, surface_1.GetNumberOfPoints()): progress = ((numero_point_surface_1 + 1) * 100) // surface_1.GetNumberOfPoints() if progress % 10 == 0 and printed is False: print "{0}%".format(progress), printed = True elif progress % 10 != 0: printed = False """le vecteur normal et les coordonnees de point definissent une ligne sur laquelle chercher le centre de la sphere""" normal = liste_normals_surface_1[numero_point_surface_1] point = liste_points_surface_1[numero_point_surface_1] def fonction_a_annuler(x): centre = point + x * normal p1 = surface_1.GetPoint(calcul_distance_1.FindClosestPoint(centre)) p2 = surface_2.GetPoint(calcul_distance_2.FindClosestPoint(centre)) dist_1 = vtkMath.Distance2BetweenPoints(p1, centre) dist_2 = vtkMath.Distance2BetweenPoints(p2, centre) nv_ecart = dist_1 ** (1. / 2) - dist_2 ** (1. / 2) return nv_ecart """ recherche du centre de la sphere inscrite par trouver_zero_fonction_croissante""" # il est possible que le pas initial indique soit trop petit pas = pas_initial while fonction_a_annuler(pas) < 0: pas *= 2. # recherche par dichotomie x_solution = trouver_zero_fonction_croissante(0.0, pas, fonction_a_annuler, precision) centre = point + x_solution * normal liste_centres = numpy.r_[liste_centres, centre.reshape((1, 3))] print "termine" # creation d'un object vtkPolyData vtkPoints_mean = vtk.vtkPoints() vtkPoints_mean.SetData(numpy_support.numpy_to_vtk(liste_centres, deep = 1)) surface_moyenne = vtk.vtkPolyData() surface_moyenne.SetPoints(vtkPoints_mean) surface_moyenne.SetPolys(surface_1.GetPolys()) surface_moyenne.Update() return surface_moyenne
def calculer_champ_meridien(vtkDataObject, maillage_regulier=None, retourner_maillage_regulier=False, hubFileName = "/media/FreeAgent GoFlex Drive/DATA_PI4/hub", tipFileName = "/media/FreeAgent GoFlex Drive/DATA_PI4/shroud", stepSize=2.0, relativeExtension=0.1, numberOfPoints_xm = 75, numberOfPoints_h = 10, dtheta = 2 * numpy.pi / (21 * 10) ): """Fonction qui retourne un plan, contenant le champ meridien Le champ est le resultat d'une moyenne azimutale ponderee simple """ #Creation du maillage regulier if maillage_regulier is None: from UVParametrizationFilter import CreateSpline spline, numberOfPoints = CreateSpline(hubFileName, tipFileName, stepSize, relativeExtension=relativeExtension) coords = get_vtk_array_as_numpy_array(vtkDataObject, "coords") coordx = coords[:, 0] coordy = coords[:, 1] coordz = coords[:, 2] coordtheta = numpy.arctan2(coordz, coordy) min_theta = coordtheta.min() max_theta = coordtheta.max() ntheta = int((max_theta - min_theta) // dtheta) print "Dimensions du grid ", numberOfPoints_xm, numberOfPoints_h, ntheta points = vtk.vtkPoints() uvMin = -relativeExtension uvMax = 1.0 + relativeExtension for _v in numpy.linspace(uvMin, uvMax, numberOfPoints_xm): print _v for _u in numpy.linspace(uvMin, uvMax, numberOfPoints_h): for theta in numpy.linspace(min_theta, max_theta, ntheta): pnt = spline(_u, _v) x = pnt[0] y = pnt[1] * numpy.cos(theta) z = pnt[1] * numpy.sin(theta) points.InsertNextPoint(x, y, z) grid = vtk.vtkStructuredGrid() grid.SetDimensions(ntheta, numberOfPoints_h, numberOfPoints_xm) grid.SetPoints(points) #on retourne le maillage_regulier si demande if retourner_maillage_regulier == 1: return grid else: grid = maillage_regulier #Probe et moyenne azimutale, pour finalement retourner le plan grid = VTKProbe(input = grid, source = vtkDataObject) #pour le plan a retourner, on choisit arbitrairement le plan i=0 du maillage regulier plan = Extraction(input = grid, formule_extraction='i=0').get_output() #moyenne de chacune des grandeurs le long des lignes a x, r, constants for nom_grandeur in get_noms_arrays_presents(vtkDataObject): grandeur = get_vtk_array_as_numpy_array(grid, nom_grandeur) if grandeur.size == grid.GetNumberOfPoints(): grandeur = grandeur.reshape(grid.GetDimensions()[::-1]) else: grandeur = grandeur.reshape(grid.GetDimensions()[::-1] + (3,)) grandeur = numpy.ma.masked_less(grandeur, 0.1) grandeur = numpy.mean(grandeur, axis=2) grandeur = grandeur.ravel() plan = ajouter_numpy_array_as_vtk_array(plan, grandeur, nom_grandeur) return plan
output.RowData.append(max(rtdata), 'max') ########################################################################### #5.CSV Reader(Source) #file format: # x,y,z,velocity # 1,0,0,1 # 2,0,1,1 # . . . from paraview import vtk import os filepath="/home/jiabin/python/datafile.txt" filename=os.path.normcase(filepath) pts=vtk.vtkPoints() f=open(filename) pdo=self.GetOutput() firstline=True for line in f: if firstline: firstline=False for pos,word in enumerate(line.split(",")): if pos > 2: newArray = vtk.vtkDoubleArray() newArray.SetName(word) newArray.SetNumberOfComponents(1) pdo.GetPointData().AddArray(newArray) else: for pos,word in enumerate(line.split(",")):