def _ajouter_omega_aux_noeuds(self): """ajoute omega aux noeuds du maillage- necessaire aux calculs de grandeurs (a transformer en FieldData quand le pipe vtk le passera correctement) cette fonction est appelee en meme temps que lire_solution de maniere a ce que omega soit disponible aux noeuds """ if self.get('omega_par_blocs') is None: raise IOError, 'omega_par_blocs doit etre defini avant' if self.get_maillage_vtkDataObject() is None: print 'Maillage._vtkDataObject doit etre defini avant' elif isinstance(self.get_maillage_vtkDataObject(), vtk.vtkMultiBlockDataSet): for numero_bloc_mai in get_numeros_blocs_non_vides( self.get_maillage_vtkDataObject()): bloc = self.get_maillage_vtkDataObject().GetBlock(numero_bloc_mai) narray = numpy.ones(bloc.GetNumberOfPoints(), dtype = float) \ * self.omega_par_blocs[numero_bloc_mai - 1] varray = numpy_support.numpy_to_vtk(narray, deep = 1) varray.SetName('omega') bloc.GetPointData().AddArray(varray) else: bloc = self.get_maillage_vtkDataObject() narray = numpy.ones(bloc.GetNumberOfPoints(), dtype = float) * self.omega_par_blocs varray = numpy_support.numpy_to_vtk(narray, deep = 1) varray.SetName('omega') bloc.GetPointData().AddArray(varray) #partie qui ajoute omega aux noeuds du vtkDataObject #utile quand on lit directement un vtm pour charger la solution #mais ne fonctionne pas lorsque la lecture est instationnaire ! et qu'on lit pour la deuxieme fois #if self.get_vtkDataObject() is None: #pass #elif isinstance(self.get_vtkDataObject(), vtk.vtkMultiBlockDataSet): #for numero_bloc_mai in get_numeros_blocs_non_vides( #self.get_vtkDataObject()): #bloc = self.get_vtkDataObject().GetBlock(numero_bloc_mai) #narray = numpy.ones(bloc.GetNumberOfPoints(), dtype = float) \ #* self.omega_par_blocs[numero_bloc_mai - 1] #varray = numpy_support.numpy_to_vtk(narray, deep = 1) #varray.SetName('omega') #bloc.GetPointData().AddArray(varray) #else: #bloc = self.get_vtkDataObject() #narray = numpy.ones(bloc.GetNumberOfPoints(), dtype = float) * self.omega_par_blocs #varray = numpy_support.numpy_to_vtk(narray, deep = 1) #varray.SetName('omega') #bloc.GetPointData().AddArray(varray) return 0
def lire_interface_file(input, acces_fichier, type_fichier = "v3d", \ fmt_fichier= "fmt", endian= "big" , \ precision = 'i4r8', nom_array_interface = "interface_index"): """ fonction de lecture des interface file la surface doit etre indique en entree 1 est attribue aux cellules indiquee dans le fichier interface file, 0 aux autres le fichier interface_file doit etre donne a format v3d """ output = vtk_new_shallowcopy(input) if type_fichier == 'v3d': data = lire_v3d(acces_fichier = acces_fichier, fmt_fichier = fmt_fichier, endian = endian, precision = precision) elif type_fichier == 'tp': data = lire_fichier_tecplot(acces_fichier = acces_fichier) else: raise IOError, 'format de fichier non implemente' cell_interf = numpy.zeros(output.GetNumberOfCells()) cell_interf[numpy.asarray(data['data'][nom_array_interface], dtype = int) - 1] = 1 cell_interf = numpy_support.numpy_to_vtk(cell_interf, deep = 1) cell_interf.SetName(nom_array_interface) output.GetCellData().AddArray(cell_interf) return output
def rgbreader(self, fname): """opens a color image file and returns it as a color buffer""" if "VTK" in self.backends: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height * width, 3) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height - 1, 0, width - 1, 0, 0) id.GetPointData().SetScalars(vtkarray) writer = self._make_writer(fname) writer.SetInputData(id) writer.SetFileName(fname) writer.Write() elif "PIL" in self.backends: try: im = PIL.Image.open(fname) #print ("read", fname) return numpy.array(im, numpy.uint8).reshape( im.size[1], im.size[0], 3) except: #print ("no such file", fname) return None else: print("Warning: need PIL or VTK to read from " + fname)
def coprocess(time, timeStep, grid, attributes): global coProcessor import vtk import vtkPVCatalystPython as catalyst import paraview from paraview import numpy_support dataDescription = catalyst.vtkCPDataDescription() dataDescription.SetTimeData(time, timeStep) dataDescription.AddInput("input") if coProcessor.RequestDataDescription(dataDescription): import fedatastructures imageData = vtk.vtkImageData() imageData.SetExtent(grid.XStartPoint, grid.XEndPoint, 0, grid.NumberOfYPoints - 1, 0, grid.NumberOfZPoints - 1) imageData.SetSpacing(grid.Spacing) velocity = paraview.numpy_support.numpy_to_vtk(attributes.Velocity) velocity.SetName("velocity") imageData.GetPointData().AddArray(velocity) pressure = numpy_support.numpy_to_vtk(attributes.Pressure) pressure.SetName("pressure") imageData.GetCellData().AddArray(pressure) dataDescription.GetInputDescriptionByName("input").SetGrid(imageData) dataDescription.GetInputDescriptionByName("input").SetWholeExtent( 0, grid.NumberOfGlobalXPoints - 1, 0, grid.NumberOfYPoints - 1, 0, grid.NumberOfZPoints - 1) coProcessor.CoProcess(dataDescription)
def coprocess(time, timeStep, grid, attributes): global coProcessor import vtk import vtkPVCatalystPython as catalyst import paraview from paraview import numpy_support dataDescription = catalyst.vtkCPDataDescription() dataDescription.SetTimeData(time, timeStep) dataDescription.AddInput("input") if coProcessor.RequestDataDescription(dataDescription): import fedatastructures imageData = vtk.vtkImageData() imageData.SetExtent(grid.XStartPoint, grid.XEndPoint, 0, grid.NumberOfYPoints-1, 0, grid.NumberOfZPoints-1) imageData.SetSpacing(grid.Spacing) velocity = paraview.numpy_support.numpy_to_vtk(attributes.Velocity) velocity.SetName("velocity") imageData.GetPointData().AddArray(velocity) pressure = numpy_support.numpy_to_vtk(attributes.Pressure) pressure.SetName("pressure") imageData.GetCellData().AddArray(pressure) dataDescription.GetInputDescriptionByName("input").SetGrid(imageData) dataDescription.GetInputDescriptionByName("input").SetWholeExtent(0, grid.NumberOfGlobalXPoints-1, 0, grid.NumberOfYPoints-1, 0, grid.NumberOfZPoints-1) coProcessor.CoProcess(dataDescription)
def rgbwriter(self, imageslice, fname): """takes in a color buffer and writes it as an image file""" if "VTK" in self.backends: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height*width, 3) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height-1, 0, width-1, 0, 0) id.GetPointData().SetScalars(vtkarray) if self.threadedwriter is not None: self.threadedwriter.EncodeAndWrite(id, fname) else: writer = self._make_writer(fname) writer.SetInputData(id) writer.SetFileName(fname) writer.Write() elif "PIL" in self.backends: imageslice = numpy.flipud(imageslice) pimg = PIL.Image.fromarray(imageslice) pimg.save(fname) else: print("Warning: need PIL or VTK to write to " + fname)
def rgbwriter(self, imageslice, fname): """takes in a color buffer and writes it as an image file""" if "VTK" in self.backends: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height * width, 3) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height - 1, 0, width - 1, 0, 0) id.GetPointData().SetScalars(vtkarray) if self.threadedwriter is not None: self.threadedwriter.EncodeAndWrite(id, fname) else: writer = self._make_writer(fname) writer.SetInputData(id) writer.SetFileName(fname) writer.Write() return fname elif "PIL" in self.backends: imageslice = numpy.flipud(imageslice) pimg = PIL.Image.fromarray(imageslice) pimg.save(fname) return fname else: raise ValueError("Warning: need PIL or VTK to write to " + fname)
def rgbreader(self, fname): """opens a color image file and returns it as a color buffer""" if "VTK" in self.backends: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height*width,3) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height-1, 0, width-1, 0, 0) id.GetPointData().SetScalars(vtkarray) writer = self._make_writer(fname) writer.SetInputData(id) writer.SetFileName(fname) writer.Write() elif "PIL" in self.backends: try: im = PIL.Image.open(fname) #print ("read", fname) return numpy.array(im, numpy.uint8).reshape(im.size[1],im.size[0],3) except: #print ("no such file", fname) return None else: print ("Warning: need PIL or VTK to read from " + fname)
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 numpyTovtkDataArray(array, name="numpy_array"): """Given a numpy array or a VTKArray and a name, returns a vtkDataArray. The resulting vtkDataArray will store a reference to the numpy array through a DeleteEvent observer: the numpy array is released only when the vtkDataArray is destroyed.""" if not array.flags.contiguous: array = array.copy() vtkarray = numpy_support.numpy_to_vtk(array) vtkarray.SetName(name) # This makes the VTK array carry a reference to the numpy array. vtkarray.AddObserver('DeleteEvent', MakeObserver(array)) return vtkarray
def zwriter(self, imageslice, fname): """takes in a depth buffer and writes it as a depth file""" if "OpenEXR" in self.backends: imageslice = numpy.flipud(imageslice) exr.save_depth(imageslice, fname) return fname # if self.dontCompressFloatVals: # if "VTK" in self.backends: # height = imageslice.shape[1] # width = imageslice.shape[0] # # file = open(fname, mode='w') # file.write("Image type: L 32F image\r\n") # file.write("Name: A cinema depth image\r\n") # file.write( # "Image size (x*y): "+str(height) + # "*" + str(width) + "\r\n") # file.write("File size (no of images): 1\r\n") # file.write(chr(26)) # imageslice.tofile(file) # file.close() # return # # imageslice = numpy.flipud(imageslice) # pimg = PIL.Image.fromarray(imageslice) # # TODO: # # don't let ImImagePlugin.py insert the Name: filename in # line two. why? because ImImagePlugin.py reader has a 100 # character limit # pimg.save(fname) imageslice = numpy.flipud(imageslice) # Adjust the filename, replace .im with .npz baseName, ext = os.path.splitext(fname) adjustedName = baseName + ".Z" if self.threadedwriter is not None: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height * width) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height - 1, 0, width - 1, 0, 0) id.GetPointData().SetScalars(vtkarray) self.threadedwriter.EncodeAndWrite(id, adjustedName) else: with open(adjustedName, mode='wb') as file: file.write(zlib.compress(numpy.array(imageslice))) return adjustedName
def genericwriter(self, imageslice, fname): """write generic binary data dump""" if self.threadedwriter is not None: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height * width) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height - 1, 0, width - 1, 0, 0) id.GetPointData().SetScalars(vtkarray) self.threadedwriter.EncodeAndWrite(id, fname) else: with open(fname, "w") as file: file.write(imageslice)
def zwriter(self, imageslice, fname): """takes in a depth buffer and writes it as a depth file""" if "OpenEXR" in self.backends: imageslice = numpy.flipud(imageslice) exr.save_depth(imageslice, fname) return # if self.dontCompressFloatVals: # if "VTK" in self.backends: # height = imageslice.shape[1] # width = imageslice.shape[0] # # file = open(fname, mode='w') # file.write("Image type: L 32F image\r\n") # file.write("Name: A cinema depth image\r\n") # file.write( # "Image size (x*y): "+str(height) + # "*" + str(width) + "\r\n") # file.write("File size (no of images): 1\r\n") # file.write(chr(26)) # imageslice.tofile(file) # file.close() # return # # imageslice = numpy.flipud(imageslice) # pimg = PIL.Image.fromarray(imageslice) # # TODO: # # don't let ImImagePlugin.py insert the Name: filename in # line two. why? because ImImagePlugin.py reader has a 100 # character limit # pimg.save(fname) imageslice = numpy.flipud(imageslice) # Adjust the filename, replace .im with .npz baseName, ext = os.path.splitext(fname) adjustedName = baseName + ".Z" if self.threadedwriter is not None: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height*width) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height-1, 0, width-1, 0, 0) id.GetPointData().SetScalars(vtkarray) self.threadedwriter.EncodeAndWrite(id, adjustedName) else: with open(adjustedName, mode='wb') as file: file.write(zlib.compress(numpy.array(imageslice)))
def genericwriter(self, imageslice, fname): """write generic binary data dump""" if self.threadedwriter is not None: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height*width) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height-1, 0, width-1, 0, 0) id.GetPointData().SetScalars(vtkarray) self.threadedwriter.EncodeAndWrite(id, fname) else: with open(fname, "w") as file: file.write(imageslice)
def moyenne_sur_epaisseur(paroi, data, liste_ep): """Fonction qui realise la moyenne des donnees presentes aux points sur plusieurs nappes decalees par rapport a la premiere le long du vecteur 'Normals' utilise fonctions_basiques.VTKProbe pour prober mono/multi-blocs si paroi est un vtkStructuredGrid, alors il est transforme en vtkPolyData en utilisant le filtre vtkGeometryFilter, avant d'entrer dans le vtkProbleFilter """ paroi.GetPointData().SetActiveVectors('Normals') for nom_array in get_noms_arrays_presents(paroi, 'points'): if nom_array != 'Normals': paroi.GetPointData().RemoveArray(nom_array) for nom_array in get_noms_arrays_presents(paroi, 'cellules'): paroi.GetCellData().RemoveArray(nom_array) liste_noms_arrays = get_noms_arrays_presents(data, loc = 'points') dict_data = dict.fromkeys(liste_noms_arrays) f = vtk.vtkGeometryFilter() f.SetInput(paroi) f.Update() paroi = f.GetOutput() for ep in liste_ep: print "epaisseur ", ep warp = vtk.vtkWarpVector() warp.SetInput(paroi) warp.SetScaleFactor(ep) warp.Update() warp = warp.GetOutput() warp = VTKProbe(input = warp, source = data) for array in liste_noms_arrays: if dict_data[array] is None: dict_data[array] = get_vtk_array_as_numpy_array(warp, array, True).reshape( warp.GetPointData().GetArray(array).GetNumberOfTuples(), warp.GetPointData().GetArray(array).GetNumberOfComponents()) else: dict_data[array] += get_vtk_array_as_numpy_array(warp, array, True).reshape( warp.GetPointData().GetArray(array).GetNumberOfTuples(), warp.GetPointData().GetArray(array).GetNumberOfComponents()) for array in dict_data: dict_data[array] /= len(liste_ep) varray = numpy_support.numpy_to_vtk(dict_data[array], deep = 1) varray.SetName(array) paroi.GetPointData().AddArray(varray) return paroi
def _cell_derivatives(narray, dataset, attribute_type, filter): # basic error checking if not dataset: raise RuntimeError, 'Need a dataset to compute gradients' if len(narray.shape) == 1: narray = narray.reshape((narray.shape[0], 1)) if narray.shape[0] != dataset.GetNumberOfPoints(): raise RuntimeError, 'The number of points does not match the number of tuples in the array' ncomp = narray.shape[1] if attribute_type == 'scalars' and ncomp != 1: raise RuntimeError, 'This function expects scalars.' if attribute_type == 'vectors' and ncomp != 3: raise RuntimeError, 'This function expects vectors.' # create a dataset with only our array but the same geometry/topology ds = dataset.NewInstance() ds.CopyStructure(dataset.VTKObject) # numpy_to_vtk converts only contiguous arrays if not narray.flags.contiguous: narray = narray.copy() varray = numpy_support.numpy_to_vtk(narray) if attribute_type == 'scalars': varray.SetName('scalars') ds.GetPointData().SetScalars(varray) else: varray.SetName('vectors') ds.GetPointData().SetVectors(varray) # setup and execute the pipeline # filter (vtkCellDerivatives) must have all of its properties # set filter.SetInput(ds) ds.UnRegister(None) c2p = vtk.vtkCellDataToPointData() c2p.SetInputConnection(filter.GetOutputPort()) c2p.Update() return c2p.GetOutput().GetPointData()
def rgbwriter(self, imageslice, fname): if "VTK" in self.backends: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height*width,3) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height-1, 0, width-1, 0, 0) id.GetPointData().SetScalars(vtkarray) writer = self._make_writer(fname) writer.SetInputData(id) writer.SetFileName(fname) writer.Write() elif "PIL" in self.backends: imageslice = numpy.flipud(imageslice) pimg = PIL.Image.fromarray(imageslice) pimg.save(fname) else: print "Warning: need PIL or VTK to write to " + fname
def gradient(narray, dataset=None): "Computes the gradient of a point-centered scalar array over a given dataset." if not dataset: dataset = narray.DataSet if not dataset: raise RuntimeError, 'Need a dataset to compute gradients' if len(narray.shape) == 1: narray = narray.reshape((narray.shape[0], 1)) if narray.shape[0] != narray.GetNumberOfTuples(): raise RuntimeError, 'The number of points does not match the number of tuples in the array' if narray.shape[1] > 1: raise RuntimeError, 'Gradient only works with 1 component arrays' ds = dataset.NewInstance() ds.CopyStructure(dataset.VTKObject) # numpy_to_vtk converts only contiguous arrays if not narray.flags.contiguous: narray = narray.copy() varray = numpy_support.numpy_to_vtk(narray) varray.SetName('scalars') ds.GetPointData().SetScalars(varray) cd = vtk.vtkCellDerivatives() cd.SetInput(ds) ds.UnRegister(None) c2p = vtk.vtkCellDataToPointData() c2p.SetInputConnection(cd.GetOutputPort()) c2p.Update() retVal = c2p.GetOutput().GetPointData().GetVectors() try: if narray.GetName(): retVal.SetName("gradient of " + narray.GetName()) else: retVal.SetName("gradient") except AttributeError: retVal.SetName("gradient") return dataset_adapter.vtkDataArrayToVTKArray(retVal, dataset)
def rgbwriter(imageslice, fname): if pilEnabled: imageslice = numpy.flipud(imageslice) pimg = PIL.Image.fromarray(imageslice) pimg.save(fname) return if vtkEnabled: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height*width,3) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height-1, 0, width-1, 0, 0) id.GetPointData().SetScalars(vtkarray) writer = _make_writer(fname) writer.SetInputData(id) writer.SetFileName(fname) writer.Write() return print "Warning: need PIL or VTK to write to " + fname
def rgbwriter(imageslice, fname): if pilEnabled: imageslice = numpy.flipud(imageslice) pimg = PIL.Image.fromarray(imageslice) pimg.save(fname) return if vtkEnabled: height = imageslice.shape[1] width = imageslice.shape[0] contig = imageslice.reshape(height * width, 3) vtkarray = n2v.numpy_to_vtk(contig) id = vtkImageData() id.SetExtent(0, height - 1, 0, width - 1, 0, 0) id.GetPointData().SetScalars(vtkarray) writer = _make_writer(fname) writer.SetInputData(id) writer.SetFileName(fname) writer.Write() return print "Warning: need PIL or VTK to write to " + fname
def _cell_derivatives (narray, dataset, attribute_type, filter): if not dataset : raise RuntimeError, 'Need a dataset to compute _cell_derivatives.' # Reshape n dimensional vector to n by 1 matrix if len(narray.shape) == 1 : narray = narray.reshape((narray.shape[0], 1)) ncomp = narray.shape[1] if attribute_type == 'scalars' and ncomp != 1 : raise RuntimeError, 'This function expects scalars.'\ 'Input shape ' + narray.shape if attribute_type == 'vectors' and ncomp != 3 : raise RuntimeError, 'This function expects vectors.'\ 'Input shape ' + narray.shape # numpy_to_vtk converts only contiguous arrays if not narray.flags.contiguous : narray = narray.copy() varray = numpy_support.numpy_to_vtk(narray) if attribute_type == 'scalars': varray.SetName('scalars') else : varray.SetName('vectors') # create a dataset with only our array but the same geometry/topology ds = dataset.NewInstance() ds.UnRegister(None) ds.CopyStructure(dataset.VTKObject) if dataset_adapter.ArrayAssociation.FIELD == narray.Association : raise RuntimeError, 'Unknown data association. Data should be associated with points or cells.' if dataset_adapter.ArrayAssociation.POINT == narray.Association : # Work on point data if narray.shape[0] != dataset.GetNumberOfPoints() : raise RuntimeError, 'The number of points does not match the number of tuples in the array' if attribute_type == 'scalars': ds.GetPointData().SetScalars(varray) else : ds.GetPointData().SetVectors(varray) elif dataset_adapter.ArrayAssociation.CELL == narray.Association : # Work on cell data if narray.shape[0] != dataset.GetNumberOfCells() : raise RuntimeError, 'The number of does not match the number of tuples in the array' # Since vtkCellDerivatives only works with point data, we need to convert # the cell data to point data first. ds2 = dataset.NewInstance() ds2.UnRegister(None) ds2.CopyStructure(dataset.VTKObject) if attribute_type == 'scalars' : ds2.GetCellData().SetScalars(varray) else : ds2.GetCellData().SetVectors(varray) c2p = vtkCellDataToPointData() c2p.SetInputData(ds2) c2p.Update() # Set the output to the ds dataset if attribute_type == 'scalars': ds.GetPointData().SetScalars(c2p.GetOutput().GetPointData().GetScalars()) else: ds.GetPointData().SetVectors(c2p.GetOutput().GetPointData().GetVectors()) filter.SetInputData(ds) if dataset_adapter.ArrayAssociation.POINT == narray.Association : # Since the data is associated with cell and the query is on points # we have to convert to point data before returning c2p = vtkCellDataToPointData() c2p.SetInputConnection(filter.GetOutputPort()) c2p.Update() return c2p.GetOutput().GetPointData() elif dataset_adapter.ArrayAssociation.CELL == narray.Association : filter.Update() return filter.GetOutput().GetCellData() else : # We shall never reach here raise RuntimeError, 'Unknown data association. Data should be associated with points or cells.'
def trouver_col(volume, bloc_aubage, nb_aubes, coupe="coordx=65", formule_extraction_surface_aubage="j=jmin"): """POUR DIFFUSEUR RADIAL SEULEMENT - extension a programmer fonction qui retourne un plan correspondant au col nb_aubes est le nombre d'aubes correspondant a la grille consideree. Ce nombre est utilise pour determiner la position de l'aube voisine. coupe est la coupe a effectuer pour obtenir un profil 2d a partir du 3d et determiner la ligne du col, support du plan au col """ surface = Extraction(input = bloc_aubage, formule_extraction = formule_extraction_surface_aubage, calculer_vecteur_normal = 1).get_output() ligne = Extraction(input = surface, formule_extraction = coupe).get_output() coords = get_vtk_array_as_numpy_array(input = ligne, nom_array = 'coords') coordr = numpy.sqrt(coords[:, 1] ** 2 + coords[:, 2] ** 2) coords_ba = coords[numpy.argmin(coordr), :] angle_rotation = 2 * numpy.pi / nb_aubes coords_ba = [ coords_ba[0], coords_ba[1] * numpy.cos(angle_rotation) - coords_ba[2] * numpy.sin(angle_rotation), coords_ba[2] * numpy.cos(angle_rotation) + coords_ba[1] * numpy.sin(angle_rotation) ] dist_ba = numpy.sqrt(numpy.sum((coords - coords_ba) ** 2, axis = 1)) coords_col = coords[dist_ba.argmin(), :] vect_col = coords_ba - coords_col normal = numpy.cross([1, 0, 0], vect_col) / numpy.linalg.norm(vect_col) plan = vtk.vtkPlane() plan.SetOrigin(coords_ba) plan.SetNormal(normal) coupe = vtk.vtkCutter() coupe.SetCutFunction(plan) volume_duplique = dupliquer_canal(volume, angle_rotation * 180. / numpy.pi) plan = appliquer_sur_multibloc(coupe, volume_duplique) plan = merge_multibloc(plan) coords = get_vtk_array_as_numpy_array(plan, 'coords') #calcul pour exclure les exterieurs du plan, et ne garder que le col data = numpy.dot(coords[:, 1:] - coords_col[1:], vect_col[1:]) / numpy.linalg.norm(vect_col) ** 2 data = numpy_support.numpy_to_vtk(data, deep = 1) data.SetName("dist") plan.GetPointData().AddArray(data) plan = set_scalaires_actifs(plan, "dist") select = vtk.vtkThreshold() select.SetInput(plan) select.ThresholdBetween(1e-6, 1 - 1e-6) select.Update() col = select.GetOutput() return col
def resample_to_2d_1d(pdi, pdi_frac, pdo, geom): # geom_types=ns.vtk_to_numpy(geom.GetCellTypesArray()) geom_locations=ns.vtk_to_numpy(geom.GetCellLocationsArray()) geom_2d_id=np.where(geom_types==VTK_TRIANGLE)[0] n_2d_cells=geom_2d_id.size #print geom_2d_id #geom_2d_locations=geom_locations[geom_2d_id] geom_1d_id=np.where(geom_types==VTK_LINE)[0] n_1d_cells=geom_1d_id.size #print geom_1d_id geom_1d_locations=geom_locations[geom_1d_id] # should check that there are both 2d and 1d elements other # similarly we should check that there are only triangles in the pdi # create a sampling dataset aux_dataset=vtk.vtkUnstructuredGrid() # compute centroids input_copy = geom.NewInstance() input_copy.UnRegister(None) input_copy.ShallowCopy(geom) geom_centers=vtk.vtkCellCenters() geom_centers.SetInputData(geom) geom_centers.Update() output=geom_centers.GetOutput() barycenters=ns.vtk_to_numpy(output.GetPoints().GetData()).reshape(-1,3) barycenters_2d=barycenters[geom_2d_id] #print barycenters_2d # shift right half of points barycenters_2d[:,0]=np.where(barycenters_2d[:,0]<0, barycenters_2d[:,0]-X_SHIFT_LEFT, barycenters_2d[:,0]+X_SHIFT_RIGHT) # compute 1d avarage points cell_data=ns.vtk_to_numpy(geom.GetCells().GetData()) grid = np.meshgrid( [0,1,2], geom_1d_locations ) grid = map(np.ravel, grid) cell_data_selection=grid[0]+grid[1] array_of_1d_cells=(cell_data[cell_data_selection]) assert(len(array_of_1d_cells)>0) geom_points_y=ns.vtk_to_numpy(geom.GetPoints().GetData())[:,1] x_points=np.array((0)) y_points=np.array((0)) # trapezoid rule """ def weights(N): return np.array([0.5] + (N-2)*[1.0] + [0.5]) average_weights=np.outer( weights(AVERAGE_POINTS_X), weights(AVERAGE_POINTS_Y)).flatten() # reference grid x=np.linspace(-X_SHIFT_LEFT, X_SHIFT_RIGHT, AVERAGE_POINTS_X) y=np.linspace(0,1,AVERAGE_POINTS_Y) """ def weights(N): # trapezoidal weights return np.array([0.5] + (N-2)*[1.0] + [0.5]) # midpoint rule in both directions (avoid problems at boundary) average_weights=np.outer( np.ones(AVERAGE_POINTS_Y), np.ones(AVERAGE_POINTS_X) ).flatten() # reference grid N=float(AVERAGE_POINTS_X) dx=(X_SHIFT_RIGHT + X_SHIFT_LEFT)/N x=np.linspace(-X_SHIFT_LEFT+dx/2, X_SHIFT_RIGHT-dx/2,N) N=float(AVERAGE_POINTS_Y) y=np.linspace(1/(2*N),1-1/(2*N),N) #print "weights: ", average_weights #print "y: ", y ref_x, ref_y=map(np.ravel, np.meshgrid(x,y)) #print "y: ", ref_y #print "x: ", ref_x assert( np.all(array_of_1d_cells[0::3]==2) ) p0=geom_points_y[array_of_1d_cells[1::3]] p1=geom_points_y[array_of_1d_cells[2::3]] x_points=np.tile(ref_x, geom_1d_id.size) yy,y0=np.meshgrid(ref_y,p0) yy,y1=np.meshgrid(ref_y,p1) y_points=(y0*yy+y1*(1-yy)).ravel() #print average_weights.size, x_points.size, y_points.size assert(x_points.size==y_points.size) assert(AVERAGE_POINTS_X*AVERAGE_POINTS_Y==average_weights.size) z_points=np.zeros(len(x_points)) points_1d=np.hstack(( x_points.reshape((-1,1)), y_points.reshape((-1,1)), z_points.reshape((-1,1)) )) #print points_1d barycenters_2d.shape=(-1,3) points_1d.shape=(-1,3) #all_points=append(barycenters_2d, points_1d) #all_points.shape=(-1,3) # make a dataset # probe on fracture dataset points_f=vtk.vtkPoints() points_f.SetData(ns.numpy_to_vtk(points_1d, deep=1)) point_set_f=vtk.vtkUnstructuredGrid() point_set_f.SetPoints(points_f) probe_f=vtk.vtkProbeFilter() probe_f.SetSourceData(pdi_frac) probe_f.SetInputData(point_set_f) probe_f.Update() out_f=probe_f.GetOutput() probe_data_f=out_f.GetPointData() # probe on continuum dataset points=vtk.vtkPoints() points.SetData(ns.numpy_to_vtk(barycenters_2d, deep=1)) point_set=vtk.vtkUnstructuredGrid() point_set.SetPoints(points) probe=vtk.vtkProbeFilter() probe.SetSourceData(pdi) probe.SetInputData(point_set) probe.Update() out=probe.GetOutput() probe_data=out.GetPointData() # reconstruct element arrays pdo.DeepCopy(geometry) cell_data=pdo.GetCellData() for i_array in range(cell_data.GetNumberOfArrays()): cell_data.RemoveArray(i_array) point_data=pdo.GetPointData() for i_array in range(point_data.GetNumberOfArrays()): point_data.RemoveArray(i_array) assert(probe_data.GetNumberOfArrays() == probe_data_f.GetNumberOfArrays() ) for i_array in range(probe_data.GetNumberOfArrays()): vtk_array=probe_data.GetArray(i_array) array=ns.vtk_to_numpy(vtk_array) n_components=vtk_array.GetNumberOfComponents() n_tuples=vtk_array.GetNumberOfTuples() assert(n_tuples == n_2d_cells) array.shape=(n_tuples,n_components) vtk_array_f=probe_data_f.GetArray(i_array) array_f=ns.vtk_to_numpy(vtk_array_f) n_components_f=vtk_array_f.GetNumberOfComponents() n_tuples_f=vtk_array_f.GetNumberOfTuples() assert(n_components == n_components_f) assert( n_1d_cells*len(average_weights) == n_tuples_f) assert( array.dtype == array_f.dtype) array_f.shape=(n_1d_cells, len(average_weights), n_components) #print vtk_array.GetName() #print array_f.shape #print array_f new_array=np.zeros((pdo.GetNumberOfCells(),n_components), dtype=array.dtype) new_array[geom_2d_id,:]=array new_array[geom_1d_id,:]=np.average(array_f, weights=average_weights, axis=1) new_vtk_array=ns.numpy_to_vtk(new_array, deep=1) new_vtk_array.SetName(vtk_array.GetName()) cell_data.AddArray(new_vtk_array) #ids=ns.numpy_to_vtk(np.arange(n_2d_cells+n_1d_cells), deep=1) #ids.SetName('ids') #cell_data.AddArray(ids) '''
def _matrix_math_filter (narray, operation) : if operation not in ['Determinant', 'Inverse', 'Eigenvalue', 'Eigenvector'] : raise RuntimeError, 'Unknown quality measure ['+operation+']'+\ 'Supported are [Determinant, Inverse, Eigenvalue, Eigenvector]' dataset = narray.DataSet() if not dataset : raise RuntimeError, 'narray is not associated with a dataset.' if dataset_adapter.ArrayAssociation.FIELD == narray.Association : raise RuntimeError, 'Unknown data association. Data should be associated with points or cells.' if narray.ndim != 3 : raise RuntimeError, operation+' only works for an array of matrices(3D array).'\ 'Input shape ' + narray.shape elif narray.shape[1] != narray.shape[2] : raise RuntimeError, operation+' requires an array of 2D square matrices.'\ 'Input shape ' + narray.shape # numpy_to_vtk converts only contiguous arrays if not narray.flags.contiguous : narray = narray.copy() # Reshape is necessary because numpy_support.numpy_to_vtk only works with 2D or # less arrays. nrows = narray.shape[0] ncols = narray.shape[1] * narray.shape[2] narray = narray.reshape(nrows, ncols) ds = dataset.NewInstance() ds.UnRegister(None) ds.ShallowCopy(dataset.VTKObject) varray = numpy_support.numpy_to_vtk(narray) varray.SetName('tensors') filter = vtkMatrixMathFilter() if operation == 'Determinant' : filter.SetOperationToDeterminant() elif operation == 'Inverse' : filter.SetOperationToInverse() elif operation == 'Eigenvalue' : filter.SetOperationToEigenvalue() elif operation == 'Eigenvector' : filter.SetOperationToEigenvector() if dataset_adapter.ArrayAssociation.POINT == narray.Association : ds.GetPointData().SetTensors(varray) # filter.SetQualityTypeToPointQuality() elif dataset_adapter.ArrayAssociation.CELL == narray.Association : ds.GetCellData().SetTensors(varray) # filter.SetQualityTypeToCellQuality() filter.SetInputData(ds) filter.Update() if dataset_adapter.ArrayAssociation.POINT == narray.Association : varray = filter.GetOutput().GetPointData().GetArray(operation) elif dataset_adapter.ArrayAssociation.CELL == narray.Association : varray = filter.GetOutput().GetCellData().GetArray(operation) ans = dataset_adapter.vtkDataArrayToVTKArray(varray, dataset) # The association information has been lost over the vtk filter # we must reconstruct it otherwise lower pipeline will be broken. ans.Association = narray.Association return ans
def make_vtk_array(numpy_array, name): vtk_array=ns.numpy_to_vtk(numpy_array, deep=1) vtk_array.SetName(name) return vtk_array
def resample_to_2d_1d(pdi, pdo, geom): # geom_types=ns.vtk_to_numpy(geom.GetCellTypesArray()) geom_locations=ns.vtk_to_numpy(geom.GetCellLocationsArray()) geom_2d_id=np.where(geom_types==VTK_TRIANGLE)[0] n_2d_cells=geom_2d_id.size #print geom_2d_id geom_2d_locations=geom_locations[geom_2d_id] geom_1d_id=np.where(geom_types==VTK_LINE)[0] n_1d_cells=geom_1d_id.size #print geom_1d_id geom_1d_locations=geom_locations[geom_1d_id] # should check that there are both 2d and 1d elements other # similarly we should check that there are only triangles in the pdi # create a sampling dataset aux_dataset=vtk.vtkUnstructuredGrid() # compute centroids input_copy = geom.NewInstance() input_copy.UnRegister(None) input_copy.ShallowCopy(geom) geom_centers=vtk.vtkCellCenters() geom_centers.SetInputData(geom) geom_centers.Update() output=geom_centers.GetOutput() barycenters=ns.vtk_to_numpy(output.GetPoints().GetData()).reshape(-1,3) barycenters_2d=barycenters[geom_2d_id] #print barycenters_2d # shift right half of points barycenters_2d[:,0]=np.where(barycenters_2d[:,0]<0, barycenters_2d[:,0]+LEFT_SHIFT, barycenters_2d[:,0]+RIGHT_SHIFT) # compute 1d avarage points cell_data=ns.vtk_to_numpy(geom.GetCells().GetData()) grid = np.meshgrid( [0,1,2], geom_1d_locations ) grid = map(np.ravel, grid) cell_data_selection=grid[0]+grid[1] array_of_1d_cells=(cell_data[cell_data_selection]) assert(len(array_of_1d_cells)>0) geom_points_y=ns.vtk_to_numpy(geom.GetPoints().GetData())[:,1] x_points=np.array((0)) y_points=np.array((0)) # reference grid x=np.linspace(LEFT_SHIFT,RIGHT_SHIFT,AVERAGE_POINTS) y=np.linspace(0,1,AVERAGE_POINTS) ref_x, ref_y=map(np.ravel, np.meshgrid(x,y)) assert( np.all(array_of_1d_cells[0::3]==2) ) p0=geom_points_y[array_of_1d_cells[1::3]] p1=geom_points_y[array_of_1d_cells[2::3]] x_points=np.tile(ref_x, geom_1d_id.size) yy,y0=np.meshgrid(ref_y,p0) yy,y1=np.meshgrid(ref_y,p1) y_points=(y0*yy+y1*(1-yy)).ravel() assert(x_points.size==y_points.size) z_points=np.zeros(len(x_points)) points_1d=np.hstack(( x_points.reshape((-1,1)), y_points.reshape((-1,1)), z_points.reshape((-1,1)) )) #print points_1d all_points=append(barycenters_2d, points_1d) all_points.shape=(-1,3) # make a probe dataset points=vtk.vtkPoints() points.SetData(make_vtk_array(all_points, "points")) point_set=vtk.vtkUnstructuredGrid() point_set.SetPoints(points) probe=vtk.vtkProbeFilter() probe.SetSourceData(pdi) probe.SetInputData(point_set) probe.Update() out=probe.GetOutput() probe_data=out.GetPointData() # reconstruct element arrays pdo.DeepCopy(geometry) cell_data=pdo.GetCellData() for i_array in range(probe_data.GetNumberOfArrays()): # make interpolation array vtk_array=probe_data.GetArray(i_array) array_name=vtk_array.GetName() n_components=vtk_array.GetNumberOfComponents() n_tuples=vtk_array.GetNumberOfTuples() array=ns.vtk_to_numpy(vtk_array) array.shape=(n_tuples,n_components) new_array=np.zeros((pdo.GetNumberOfCells(),n_components), dtype=array.dtype) new_array[geom_2d_id,:]=array[0:n_2d_cells,:] array_1d=array[n_2d_cells:,:].reshape(n_1d_cells, AVERAGE_POINTS*AVERAGE_POINTS, n_components) new_array[geom_1d_id,:]=np.average(array_1d, axis=1) new_vtk_array=ns.numpy_to_vtk(new_array, deep=1) cell_data.AddArray( make_vtk_array(new_array, "interpol_"+vtk_array.GetName()) ) # compute difference array vtk_geometry_array=pdo.GetCellData().GetArray(array_name) if vtk_geometry_array: assert_eq(vtk_geometry_array.GetNumberOfComponents(), new_array.shape[1]) assert_eq(vtk_geometry_array.GetNumberOfTuples(), new_array.shape[0]) geometry_array=ns.vtk_to_numpy(vtk_geometry_array) geometry_array.shape=new_array.shape difference=geometry_array - new_array cell_data.AddArray( make_vtk_array(difference, "diff_"+vtk_array.GetName()) )
VTK_data = numpy_support.numpy_to_vtk(num_array=NumPy_data.ravel(), deep=True, array_type=vtk.VTK_FLOAT) # You can get it back with NumPy_data_from_VTK = numpy_support.vtk_to_numpy(VTK_data) NumPy_data_from_VTK = NumPy_data_from_VTK.reshape(NumPy_data_shape) # start the VTK magic dataImporter = vtk.vtkImageImport() dataImporter.CopyImportVoidPointer(NumPy_data, NumPy_data.nbytes) dataImporter.SetNumberOfScalarComponents(1) dataImporter.SetDataExtent(0, 11, 0, 7, 0, 0) dataImporter.SetWholeExtent(0, 11, 0, 7, 0, 0) ''' from paraview import numpy_support ParaView_numpy_data = numpy_support.numpy_to_vtk(NumPy_data.copy()) import paraview import paraview.simple import paraview.numpy_support import paraview.servermanager import paraview.vtk """renderView1=paraview.simple.GetActiveViewOrCreate("RenderView") #cone=paraview.simple.Cone() psrc=paraview.servermanager.sources.ProgrammableSource() psrc.Script='''import numpy import paraview.numpy_suppor print "foo" tmp=paraview.numpy_support.numpy_to_vtk(numpy.random.random(100,101)) output.PointData.append(tmp,"scalar") '''
def resample_to_2d_1d(pdi, pdo, geom): # geom_types = ns.vtk_to_numpy(geom.GetCellTypesArray()) geom_locations = ns.vtk_to_numpy(geom.GetCellLocationsArray()) geom_2d_id = np.where(geom_types == VTK_TRIANGLE)[0] n_2d_cells = geom_2d_id.size #print geom_2d_id geom_2d_locations = geom_locations[geom_2d_id] geom_1d_id = np.where(geom_types == VTK_LINE)[0] n_1d_cells = geom_1d_id.size #print geom_1d_id geom_1d_locations = geom_locations[geom_1d_id] # should check that there are both 2d and 1d elements other # similarly we should check that there are only triangles in the pdi # create a sampling dataset aux_dataset = vtk.vtkUnstructuredGrid() # compute centroids input_copy = geom.NewInstance() input_copy.UnRegister(None) input_copy.ShallowCopy(geom) geom_centers = vtk.vtkCellCenters() geom_centers.SetInputData(geom) geom_centers.Update() output = geom_centers.GetOutput() barycenters = ns.vtk_to_numpy(output.GetPoints().GetData()).reshape(-1, 3) barycenters_2d = barycenters[geom_2d_id] #print barycenters_2d # shift right half of points barycenters_2d[:, 0] = np.where(barycenters_2d[:, 0] < 0, barycenters_2d[:, 0] + LEFT_SHIFT, barycenters_2d[:, 0] + RIGHT_SHIFT) # compute 1d avarage points cell_data = ns.vtk_to_numpy(geom.GetCells().GetData()) grid = np.meshgrid([0, 1, 2], geom_1d_locations) grid = map(np.ravel, grid) cell_data_selection = grid[0] + grid[1] array_of_1d_cells = (cell_data[cell_data_selection]) assert (len(array_of_1d_cells) > 0) geom_points_y = ns.vtk_to_numpy(geom.GetPoints().GetData())[:, 1] x_points = np.array((0)) y_points = np.array((0)) # reference grid x = np.linspace(LEFT_SHIFT, RIGHT_SHIFT, AVERAGE_POINTS) y = np.linspace(0, 1, AVERAGE_POINTS) ref_x, ref_y = map(np.ravel, np.meshgrid(x, y)) assert (np.all(array_of_1d_cells[0::3] == 2)) p0 = geom_points_y[array_of_1d_cells[1::3]] p1 = geom_points_y[array_of_1d_cells[2::3]] x_points = np.tile(ref_x, geom_1d_id.size) yy, y0 = np.meshgrid(ref_y, p0) yy, y1 = np.meshgrid(ref_y, p1) y_points = (y0 * yy + y1 * (1 - yy)).ravel() assert (x_points.size == y_points.size) z_points = np.zeros(len(x_points)) points_1d = np.hstack((x_points.reshape((-1, 1)), y_points.reshape( (-1, 1)), z_points.reshape((-1, 1)))) #print points_1d all_points = append(barycenters_2d, points_1d) all_points.shape = (-1, 3) # make a probe dataset points = vtk.vtkPoints() points.SetData(make_vtk_array(all_points, "points")) point_set = vtk.vtkUnstructuredGrid() point_set.SetPoints(points) probe = vtk.vtkProbeFilter() probe.SetSourceData(pdi) probe.SetInputData(point_set) probe.Update() out = probe.GetOutput() probe_data = out.GetPointData() # reconstruct element arrays pdo.DeepCopy(geometry) cell_data = pdo.GetCellData() for i_array in range(probe_data.GetNumberOfArrays()): # make interpolation array vtk_array = probe_data.GetArray(i_array) array_name = vtk_array.GetName() n_components = vtk_array.GetNumberOfComponents() n_tuples = vtk_array.GetNumberOfTuples() array = ns.vtk_to_numpy(vtk_array) array.shape = (n_tuples, n_components) new_array = np.zeros((pdo.GetNumberOfCells(), n_components), dtype=array.dtype) new_array[geom_2d_id, :] = array[0:n_2d_cells, :] array_1d = array[n_2d_cells:, :].reshape( n_1d_cells, AVERAGE_POINTS * AVERAGE_POINTS, n_components) new_array[geom_1d_id, :] = np.average(array_1d, axis=1) new_vtk_array = ns.numpy_to_vtk(new_array, deep=1) cell_data.AddArray( make_vtk_array(new_array, "interpol_" + vtk_array.GetName())) # compute difference array vtk_geometry_array = pdo.GetCellData().GetArray(array_name) if vtk_geometry_array: assert_eq(vtk_geometry_array.GetNumberOfComponents(), new_array.shape[1]) assert_eq(vtk_geometry_array.GetNumberOfTuples(), new_array.shape[0]) geometry_array = ns.vtk_to_numpy(vtk_geometry_array) geometry_array.shape = new_array.shape difference = geometry_array - new_array cell_data.AddArray( make_vtk_array(difference, "diff_" + vtk_array.GetName()))
def make_vtk_array(numpy_array, name): vtk_array = ns.numpy_to_vtk(numpy_array, deep=1) vtk_array.SetName(name) return vtk_array
def load_map(output=None, ncmap_fn=None, tidx=None): output = output or vtk.vtkUnstructuredGrid() if ncmap_fn is None: ncmap_fn = "/home/rusty/models/delft/nms/nms_00_project.dsproj_data/nms_hydro_00_output/DFM_OUTPUT_nms_hydro_00/nms_hydro_00_map.nc" ncmap, g = load_data(ncmap_fn) if tidx is None: tidx = len(ncmap.time) - 1 # force to last time step # Still have about 1.6s in all of this stuff Nk = len(ncmap.dimensions['laydim']) # 3-D locations of nodes Zbed = ncmap.NetNode_z[:] Zsurf_cells = ncmap.s1[ tidx, :] # unfortunately this is at cell centers, not nodes. Zsurf = g.interp_cell_to_node(Zsurf_cells) Znode = np.zeros((g.Nnodes(), Nk + 1), 'f8') Zbed = np.minimum(Zsurf - 0.2, Zbed) alpha = np.linspace(0, 1, Nk + 1)[None, :] # this is where the positive up stuff is assumed Znode[:, :] = (1 - alpha) * Zbed[:, None] + alpha * Zsurf[:, None] # map nodes to linear index node_idx = np.arange(Znode.size).reshape(Znode.shape) # assemble the 3-d points array and write to a vtk file: all_z = Znode.ravel() all_x = np.repeat(g.nodes['x'][:, 0], Nk + 1) all_y = np.repeat(g.nodes['x'][:, 1], Nk + 1) max_Ncells_3d = g.Ncells() * Nk # upper bound pts = vtk.vtkPoints() xyz = np.ascontiguousarray(np.array([all_x, all_y, all_z]).T) arr = pnp.numpy_to_vtk(xyz, deep=1) pts.SetData(arr) # do we have to specify 'Points' here? output.SetPoints(pts) output.Allocate(max_Ncells_3d, 1000) t = time.time() # this is always the most expensive part. # but it could be cached, and just update the points with # different timesteps, or not even worry about changing geometry. for c in range(g.Ncells()): nodes = g.cell_to_nodes(c) if len(nodes) == 3: for k in range(Nk): # assuming that nodes is CCW, then we start with the top layer connectivity = [ node_idx[nodes[0], k], node_idx[nodes[1], k], node_idx[nodes[2], k], node_idx[nodes[0], k + 1], node_idx[nodes[1], k + 1], node_idx[nodes[2], k + 1] ] cell_type = wedge_type pointIds = vtk.vtkIdList() for pointId, conn in enumerate(connectivity): pointIds.InsertId(pointId, conn) output.InsertNextCell(cell_type, pointIds) elif len(nodes) == 4: # arrays are small, actually slower to construct connectivity via # ndarray for k in range(Nk): # 5.29s for cell building connectivity = [ node_idx[nodes[0], k + 1], node_idx[nodes[1], k + 1], node_idx[nodes[2], k + 1], node_idx[nodes[3], k + 1], node_idx[nodes[0], k], node_idx[nodes[1], k], node_idx[nodes[2], k], node_idx[nodes[3], k] ] cell_type = hexahedron_type pointIds = vtk.vtkIdList() for pointId, conn in enumerate(connectivity): pointIds.InsertId(pointId, conn) output.InsertNextCell(cell_type, pointIds) else: raise Exception("Only know how to translate 3,4 sided cells") print("Elapsed for building cells: %.2f" % (time.time() - t)) t = time.time() ncells3d = output.GetNumberOfCells() # add cell velocity: cellData = output.GetCellData() # dataSetAttributes u = ncmap.variables['ucx'][tidx, :, :].ravel() v = ncmap.variables['ucy'][tidx, :, :].ravel() w = ncmap.variables['ucz'][tidx, :, :].ravel() # 0.01 print("Reading data: %.2f" % (time.time() - t)) U = np.ascontiguousarray(np.array([u, v, w]).T) arr = pnp.numpy_to_vtk(U, deep=1) arr.SetName("cell_velocity") cellData.AddArray(arr) # scalars for nc_name, pv_name in [('sa1', 'salinity'), ('rho', 'rho')]: scal = ncmap.variables[nc_name][tidx, :, :] scal = scal[:, :Nk] # in case it's rho and has an extra layer. scal = scal.ravel() arr = pnp.numpy_to_vtk(np.ascontiguousarray(scal), deep=1) arr.SetName(pv_name) cellData.AddArray(arr) # 0.33 print("Elapsed total for cell data: %.2f" % (time.time() - t))
assert (n_tuples == n_elements) array = ns.vtk_to_numpy(vtk_array) array.shape = (n_tuples, n_components) #print array new_array = np.empty((n_nodes, n_components), dtype=array.dtype) for i_comp in range(n_components): print vtk_array.GetName(), i_comp # solution guess node_sum = np.zeros((n_nodes)) node_counts = np.zeros((n_nodes)) to_add = np.repeat(array[:, i_comp], nodes_per_cell) for i in range(len(cell_node_ids)): node_sum[cell_node_ids[i]] += to_add[i] node_counts[cell_node_ids[i]] += 1 #node_sum[cell_node_ids]=np.repeat(array[:,i_comp], nodes_per_cell) #node_counts[cell_node_ids]=np.ones((len(cell_node_ids))) node_vals_0 = node_sum / node_counts #print array[:,i_comp] #print node_vals_0 # solve overdetermined system by least squares #new_array[:,i_comp]=node_vals_0 new_array[:, i_comp] = lsq(interpolation_matrix, array[:, i_comp], node_vals_0) new_vtk_array = ns.numpy_to_vtk(new_array, deep=1) new_vtk_array.SetName(vtk_array.GetName()) pdo.GetPointData().AddArray(new_vtk_array)
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)
array=ns.vtk_to_numpy(vtk_array) array.shape=(n_tuples,n_components) #print array new_array=np.empty((n_nodes,n_components), dtype=array.dtype) for i_comp in range(n_components): print vtk_array.GetName(), i_comp # solution guess node_sum=np.zeros((n_nodes)) node_counts=np.zeros((n_nodes)) to_add=np.repeat(array[:,i_comp], nodes_per_cell) for i in range(len(cell_node_ids)): node_sum[cell_node_ids[i]]+=to_add[i] node_counts[cell_node_ids[i]]+=1 #node_sum[cell_node_ids]=np.repeat(array[:,i_comp], nodes_per_cell) #node_counts[cell_node_ids]=np.ones((len(cell_node_ids))) node_vals_0=node_sum/node_counts #print array[:,i_comp] #print node_vals_0 # solve overdetermined system by least squares #new_array[:,i_comp]=node_vals_0 new_array[:,i_comp]=lsq(interpolation_matrix, array[:,i_comp], node_vals_0) new_vtk_array=ns.numpy_to_vtk(new_array, deep=1) new_vtk_array.SetName(vtk_array.GetName()) pdo.GetPointData().AddArray(new_vtk_array)
from numpy_interface import dataset_adapter as dsa xmin, xmax, Nx, ymin, ymax, Ny, zmin, zmax, Nz = -1, 1, 10, -1, 2, 20, -1, 3, 30 loci = numpy.mgrid[xmin:xmax:1j * Nx, ymin:ymax:1j * Ny, zmin:zmax:1j * Nz] values = numpy.random.random(loci[0].shape) exts = [xmin, xmax, ymin, ymax, zmin, zmax] sg0 = output # paraview.vtk.vtkStructuredGrid() sg0.SetExtent(exts) Xc, Yc, Zc = loci coordinates = algs.make_vector(Xc.ravel(), Yc.ravel(), Zc.ravel()) pts = paraview.vtk.vtkPoints() pts.SetData(dsa.numpyTovtkDataArray(coordinates, "Points")) from paraview import numpy_support data = numpy_support.numpy_to_vtk(num_array=values.ravel(), deep=True, array_type=vtk.VTK_FLOAT) sg0.PointData.append(data, "mydata") # sg0.SetPoints(pts) # use vtkImageData # gets just 60 points and still no output import numpy import paraview import paraview.vtk from numpy_interface import algorithms as algs from numpy_interface import dataset_adapter as dsa xmin, xmax, Nx, ymin, ymax, Ny, zmin, zmax, Nz = -1, 1, 10, -1, 2, 20, -1, 3, 30 loci = numpy.mgrid[xmin:xmax:1j * Nx, ymin:ymax:1j * Ny, zmin:zmax:1j * Nz] values = numpy.random.random(loci.reshape(3, -1)[0].shape)
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