def HDF5toVTKLumen(): cellType = "ec" # Both ATP and WSS maps use EC mesh input_meshes = [] # Read input EC meshes. for in_file in input_mesh_files[cellType]: reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(in_file) reader.Update() input_meshes += [reader.GetOutput()] # Only add parent mesh for a tube (non-bifurcation) if branches == 1: break append_filter = vtk.vtkAppendFilter() for branch in range(branches): species_array = [] mesh = vtk.vtkPolyData() mesh.DeepCopy(input_meshes[branch]) # The base input h5 filename given the branch and from which writer it came on said branch. h5_file_base = base_names[output] + '_b_' + str(branch + 1) + '_' + 'x' + '.h5' print "Processing file", h5_file_base for writer in range(writers): h5_file_name = h5_file_base[:-4] + str(writer) + h5_file_base[-3:] fid = h5py.h5f.open(h5_file_name) dset = h5py.h5d.open(fid, "data") shape = dset.shape rdata = numpy.zeros(shape[0], dtype=numpy.float64) dset.read(h5py.h5s.ALL, h5py.h5s.ALL, rdata) species_array += list(rdata.ravel())[:] reordered_array = vtk.vtkDoubleArray() reordered_array.SetName(output) reordered_array.SetNumberOfValues(numCells[cellType][0] * numCells[cellType][1] * circQuads * axialQuads) reorder_species(species_array, reordered_array, cellType) mesh.GetCellData().AddArray(reordered_array) append_filter.AddInputData(mesh) append_filter.Update() # Write the result. vtu_file = base_names[output] + '.vtu' print 'Writing file', os.path.abspath(vtu_file) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(vtu_file) writer.SetInputData(append_filter.GetOutput()) writer.Update()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkXMLPolyDataReader(), 'Reading vtkXMLPolyData.', (), ('vtkXMLPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def load_polydata(file_name): # get file extension (type) file_extension = file_name.split(".")[-1].lower() # todo better generic load if file_extension == "vtk": reader = vtk.vtkPolyDataReader() elif file_extension == "vtp": reader = vtk.vtkPolyDataReader() elif file_extension == "fib": reader = vtk.vtkPolyDataReader() elif file_extension == "ply": reader = vtk.vtkPLYReader() elif file_extension == "stl": reader = vtk.vtkSTLReader() elif file_extension == "xml": reader = vtk.vtkXMLPolyDataReader() elif file_extension == "obj": reader = vtk.vtkOBJReader() #try: # try to read as a normal obj # reader = vtk.vtkOBJReader() #except: # than try load a MNI obj format # reader = vtk.vtkMNIObjectReader() else: raise "polydata " + file_extension + " is not suported" reader.SetFileName(file_name) reader.Update() print file_name, " Mesh ", file_extension, "Loaded" return reader.GetOutput()
def readPData( filename, verbose=1): myVTK.myPrint(verbose, "*** readPData: "+filename+" ***") assert (os.path.isfile(filename)), "Wrong filename (\""+filename+"\"). Aborting." if ('vtk' in filename): pdata_reader = vtk.vtkPolyDataReader() elif ('vtp' in filename): pdata_reader = vtk.vtkXMLPolyDataReader() else: assert 0, "File must be .vtk or .vtp. Aborting." pdata_reader.SetFileName(filename) pdata_reader.Update() pdata = pdata_reader.GetOutput() myVTK.myPrint(verbose-1, "n_points = "+str(pdata.GetNumberOfPoints())) myVTK.myPrint(verbose-1, "n_verts = "+str(pdata.GetNumberOfVerts())) myVTK.myPrint(verbose-1, "n_lines = "+str(pdata.GetNumberOfLines())) myVTK.myPrint(verbose-1, "n_polys = "+str(pdata.GetNumberOfPolys())) myVTK.myPrint(verbose-1, "n_strips = "+str(pdata.GetNumberOfStrips())) return pdata
def pointToCellData(): print "Using angle: " + str(angle) atpFiles = glob.glob(str(angle) + '/*.vtp') if not atpFiles: exit("No atp files found") if not os.path.exists(str(angle) + '_new'): os.makedirs(str(angle) + '_new') for inputFile in atpFiles: print 'Reading', inputFile atpReader = vtk.vtkXMLPolyDataReader() atpReader.SetFileName(inputFile) atpReader.Update() atpDataset = atpReader.GetOutput() pointToCell = vtk.vtkPointDataToCellData() pointToCell.SetInputData(atpDataset) pointToCell.PassPointDataOn() pointToCell.Update() newArray = pointToCell.GetOutput() # Remove the point data arrays, they exist as cell data newArray.GetPointData().RemoveArray('ATP') newArray.GetPointData().RemoveArray('tau') newArray.GetCellData().RemoveArray('p') atpWriter = vtk.vtkXMLPolyDataWriter() atpWriter.SetInputData(newArray) atpWriter.SetFileName(str(angle) + '_new/' + inputFile[3:]) atpWriter.Update()
def trim_vtp(fn = "c.vtp", fnout = "t.vtk", s = (1.0,1.0,1.0)): if not os.path.exists(fn): print "%s does not exists, skip" % (fn,) return # Read vtp rd = vtk.vtkXMLPolyDataReader() rd.SetFileName(fn) rd.Update() # the poly data pd = vtk.vtkPolyData() pd = rd.GetOutput() # times by 10.0 (CM -> MM) MM = [10.0 for each in range(0,len(s))] pd = scale_vtkPolyData(pd, MM) # then divides the spacing ss = [1/each for each in s] pd = scale_vtkPolyData(pd, ss) # Write vtk wt = vtk.vtkPolyDataWriter() wt.SetInputData(pd) wt.SetFileName(fnout) wt.Write()
def loadVtk(filename): if 'vtp' in filename: vreader = vtk.vtkXMLPolyDataReader() else: vreader = vtk.vtkPolyDataReader() vreader.SetFileName(filename) vreader.Update() polydata = vreader.GetOutput() polydata.ReleaseDataFlagOn() streamlines = [] verts = vtk_to_numpy(polydata.GetPoints().GetData()) scalars = {} pointdata = polydata.GetPointData() for si in range(pointdata.GetNumberOfArrays()): sname = pointdata.GetArrayName(si) scalars[sname] = vtk_to_numpy(pointdata.GetArray(si)) for i in range(polydata.GetNumberOfCells()): pids = polydata.GetCell(i).GetPointIds() ids = [ pids.GetId(p) for p in range(pids.GetNumberOfIds())] streamlines.append(ids) res = {'points':verts, 'values':scalars, 'streamlines':streamlines} return res
def read_vtk_file(filename): rd = vtk.vtkXMLPolyDataReader() rd.SetFileName(filename) rd.Update() data = rd.GetOutput() N = data.GetNumberOfPoints() x = []; y = []; z = []; itype = []; ilagr = []; exist = []; T = []; for i in range(N): pt = data.GetPoint(i) x.append(pt[0]) y.append(pt[1]) z.append(pt[2]) itype.append( data.GetPointData().GetArray('ITYPE').GetTuple1(i) ) ilagr.append( data.GetPointData().GetArray('ILAGR').GetTuple1(i) ) exist.append( data.GetPointData().GetArray('EXIST').GetTuple1(i) ) T.append( data.GetPointData().GetArray('T').GetTuple1(i) ) df = pd.DataFrame({'COORX':x, 'COORY':y, 'COORZ':z, 'ITYPE':itype, 'ILAGR':ilagr, 'EXIST':exist, 'T':T }) return df
def Read(self, m_forceRead=False): """ Initial step, should be performed before everything else starts, considering to add this into the class constructor so that it is read automatically. :return: """ # Skip redundant read if it is already done if self._IS_READ_FLAG and not m_forceRead: return if self.filename.split(".")[-1] == "vtp" or self.filename.split(".")[-1] == "vtk": m_reader = vtk.vtkXMLPolyDataReader() elif self.filename.split(".")[-1] == "stl": m_reader = vtk.vtkSTLReader() else: raise IOError("Input file for arm surface is of incorrect format") m_reader.SetFileName(self.filename) m_reader.Update() m_mapper = vtk.vtkPolyDataMapper() m_mapper.SetInputConnection(m_reader.GetOutputPort()) m_actor = vtk.vtkActor() m_actor.SetMapper(m_mapper) self._reader = m_reader self._renderer.AddActor(m_actor) self._data = m_reader.GetOutput() self._IS_READ_FLAG = True pass
def _read_vtp(file_name): '''Internal function to read vtp mesh files ''' reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(file_name) reader.Update() mesh_data = PanelMesh(file_name) mesh_data.orig_type = 'VTK Polydata (.vtp)' readerOut = reader.GetOutput() mesh_data.num_faces = int(readerOut.GetNumberOfCells()) mesh_data.num_points = int(readerOut.GetNumberOfPoints()) for i in xrange(mesh_data.num_points): mesh_data.points.append(readerOut.GetPoint(i)) mesh_data.points = np.array(mesh_data.points) for i in xrange(mesh_data.num_faces): c = readerOut.GetCell(i) numCellPoints = int(c.GetNumberOfPoints()) idsTemp = [] for i in xrange(numCellPoints): idsTemp.append(int(c.GetPointId(i))) mesh_data.faces.append(np.array(idsTemp)) mesh_data.faces = np.array(mesh_data.faces) return mesh_data
def CreateSurfaceFromFile(self, filename): scalar = False if filename.lower().endswith('.stl'): reader = vtk.vtkSTLReader() elif filename.lower().endswith('.ply'): reader = vtk.vtkPLYReader() elif filename.lower().endswith('.obj'): reader = vtk.vtkOBJReader() elif filename.lower().endswith('.vtp'): reader = vtk.vtkXMLPolyDataReader() scalar = True else: wx.MessageBox(_("File format not reconized by InVesalius"), _("Import surface error")) return if _has_win32api: reader.SetFileName(win32api.GetShortPathName(filename).encode(const.FS_ENCODE)) else: reader.SetFileName(filename.encode(const.FS_ENCODE)) reader.Update() polydata = reader.GetOutput() if polydata.GetNumberOfPoints() == 0: wx.MessageBox(_("InVesalius was not able to import this surface"), _("Import surface error")) else: name = os.path.splitext(os.path.split(filename)[-1])[0] self.CreateSurfaceFromPolydata(polydata, name=name, scalar=scalar)
def read_vtkPolyData(filename): r''' Reads a VTKPolyData file and outputs a tracts/tracts_data pair Parameters ---------- filename : str VTKPolyData filename Returns ------- tracts : list of float array N_ix3 Each element of the list is a tract represented as point array, the length of the i-th tract is N_i tract_data : dict of <data name>= list of float array of N_ixM Each element in the list corresponds to a tract, N_i is the length of the i-th tract and M is the number of components of that data type. ''' if filename.endswith('xml') or filename.endswith('vtp'): polydata_reader = vtk.vtkXMLPolyDataReader() else: polydata_reader = vtk.vtkPolyDataReader() polydata_reader.SetFileName(filename) polydata_reader.Update() polydata = polydata_reader.GetOutput() return vtkPolyData_to_tracts(polydata)
def filter_step(self, unfiltered_file, include_file, exclude_file): import shutil fiber_basename = self.get_unique_name() filtered_temp_file = '%s_filtered.vtp' % fiber_basename shutil.copy2(unfiltered_file, filtered_temp_file) if include_file: cmd='slicerFilterFibers.sh --pass 1 %s %s %s' % (include_file, filtered_temp_file, filtered_temp_file) exec_cmd(cmd) if exclude_file: cmd='slicerFilterFibers.sh --nopass 1 %s %s %s' % (exclude_file, filtered_temp_file, filtered_temp_file) exec_cmd(cmd) vreader = vtkXMLPolyDataReader() vreader.SetFileName(filtered_temp_file) vreader.Update() polydata = vreader.GetOutput() vwriter = vtkPolyDataWriter() output_file = '%s_filtered.vtk' % fiber_basename vwriter.SetFileName(output_file) vwriter.SetInput(polydata) vwriter.Write() return output_file
def read_polydata(filename): """Read whole-brain tractography as vtkPolyData format.""" if VERBOSE: print "Reading in data from", filename, "..." basename, extension = os.path.splitext(filename) if (extension == '.vtk'): reader = vtk.vtkPolyDataReader() elif (extension == '.vtp'): reader = vtk.vtkXMLPolyDataReader() else: print 'Cannot recognize model file format' return None reader.SetFileName(filename) reader.Update() outpd = reader.GetOutput() del reader if VERBOSE: print "Done reading in data from", filename print "Number of lines found:", outpd.GetNumberOfLines() return outpd
def Import(filename): reader = vtk.vtkXMLPolyDataReader() try: reader.SetFileName(filename.encode(wx.GetDefaultPyEncoding())) except AttributeError: reader.SetFileName(filename) reader.Update() return reader.GetOutput()
def rescaleATPToRange(): # This is where the data is for testing purposes. print "Current working directory:", os.getcwd() print 'Reading', inputFile atpReader = vtk.vtkXMLPolyDataReader() atpReader.SetFileName(inputFile) atpReader.Update() atpDataset = atpReader.GetOutput() atp = atpDataset.GetPointData().GetArray('ATP') inMin, inMax = atp.GetRange() atpR = vtk.vtkFloatArray() atpR.SetName('initialATP') for i in range(atp.GetNumberOfTuples()): val = atp.GetTuple(i)[0] atpR.InsertNextValue(rescale(val, inMin, inMax)) atpDataset.GetCellData().AddArray(atpR) atpDataset.GetPointData().RemoveArray('ATP') atpDataset.GetPointData().RemoveArray('tau_w') atpDataset.GetCellData().RemoveArray('initialJPLC') print 'Writing', outputFile atpWriter = vtk.vtkXMLPolyDataWriter() atpWriter.SetInput(atpDataset) atpWriter.SetFileName(outputFile) atpWriter.Update() print 'Reading', inputSurfaceFile surfaceReader = vtk.vtkXMLPolyDataReader() surfaceReader.SetFileName(inputSurfaceFile) surfaceReader.Update() surface = surfaceReader.GetOutput() surface.GetCellData().AddArray(atpR) print 'Writing', outputSurfaceFile surfaceWriter = vtk.vtkXMLPolyDataWriter() surfaceWriter.SetInput(surface) surfaceWriter.SetFileName(outputSurfaceFile) surfaceWriter.Update()
def ReadVTKXMLSurfaceFile(self): if (self.InputFileName == ''): self.PrintError('Error: no InputFileName.') self.PrintLog('Reading VTK XML surface file.') reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(self.InputFileName) reader.Update() self.Surface = reader.GetOutput()
def Import(filename): reader = vtk.vtkXMLPolyDataReader() if isinstance(filename, unicode): reader.SetFileName(filename.encode(wx.GetDefaultPyEncoding())) else: reader.SetFileName(filename) reader.Update() return reader.GetOutput()
def CentreLinePolyData(self): """Compute centrelines based on the profile, reusing our memoed copy or reading from the cache file if possible. """ if (os.path.exists(self.CentreLineFile ) and os.path.getmtime(self.CentreLineFile ) > os.path.getmtime(self.StlFile) and os.path.getmtime(self.CentreLineFile ) > os.path.getmtime(self.FileName)): # Cached! reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(self.CentreLineFile) reader.Update() return reader.GetOutput() # Have to compute it # Read the STL file reader = vtk.vtkSTLReader() reader.SetFileName(profile.StlFile) # Find the seed points for centreline calculation # Use points one iolet radius back along the normal. outletPts = [] def scale(iolet): pt = (iolet.Centre - iolet.Radius * iolet.Normal) pt = pt / self.LengthUnit return pt.magnitude for iolet in self.Iolets: if isinstance(iolet._iolet, Inlet): inletPt = scale(iolet) else: outletPts.append(scale(iolet)) pass continue srcPts, tgtPts = FindSeeds(reader, inletPt, outletPts) # Lazy import since it's so slow! from vmtk import vtkvmtk centreliner = vtkvmtk.vtkvmtkPolyDataCenterlines() centreliner.SetInputConnection(reader.GetOutputPort()) centreliner.SetSourceSeedIds(srcPts) centreliner.SetTargetSeedIds(tgtPts) centreliner.SetRadiusArrayName("radius") centreliner.SetCostFunction("1/R") cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(centreliner.GetOutputPort()) writer = vtk.vtkXMLPolyDataWriter() writer.SetInputConnection(cleaner.GetOutputPort()) writer.SetFileName(self.CentreLineFile) writer.Write() return cleaner.GetOutput()
def vtp_reader(filename): reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filename) reader.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(reader.GetOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper)
def __read_vtk_mesh(self): """ Import vtk mesh """ reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(self.__vtk_mesh) reader.Update() self.__vtk_model = reader.GetOutput() self.__nb_vtk_cells = self.__vtk_model.GetNumberOfCells() self.__nb_vtk_points = self.__vtk_model.GetNumberOfPoints()
def HDF5toVTKCells(): input_meshes = [] # Read input meshes. for in_file in input_mesh_files[output]: reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(in_file) reader.Update() input_meshes += [reader.GetOutput()] # Only add parent mesh for a tube (non-bifurcation) if branches == 1: break for time_step in range(args.start, args.end + 1): print("Time:", time_step) append_filter = vtk.vtkAppendFilter() for branch in range(branches): mesh = vtk.vtkPolyData() mesh.DeepCopy(input_meshes[branch]) # The base input h5 filename given the branch and from which writer it came on said branch. h5_file_base = base_names[output] + str(time_step) + '_b_' + str(branch + 1) + '_' + 'x' + '.h5' print("Processing file", h5_file_base) # Group all datasets of a branch at a specific time point given # the number of writers the data was split into. species_array = append_datasets(writers, h5_file_base, "data") # Loop through all attirbutes and append them to a new array in the # correct order given the quad to task ratio. for attribute in attributes[output]: reordered_array = vtk.vtkDoubleArray() reordered_array.SetName(attribute) reordered_array.SetNumberOfValues(numCells[output][0] * numCells[output][1] * circQuads * axialQuads) reorder_species(species_array[attribute], reordered_array, output) mesh.GetCellData().AddArray(reordered_array) append_filter.AddInputData(mesh) append_filter.Update() # Write the result. vtu_file = base_names[output] + str(time_step) + '.vtu' print("Writing file", os.path.abspath(vtu_file)) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(vtu_file) writer.SetInputData(append_filter.GetOutput()) writer.Update()
def addVTPFile(self,fname): reader=vtk.vtkXMLPolyDataReader() reader.SetFileName(fname) mapper = vtk.vtkPolyDataMapper(); mapper.InterpolateScalarsBeforeMappingOn() mapper.SetInputConnection(reader.GetOutputPort()) mapper.SetScalarModeToUsePointData() mapper.ScalarVisibilityOn(); surfaceActor = vtk.vtkActor(); surfaceActor.SetMapper(mapper); self.ren.AddActor(surfaceActor);
def getParticleCount(hid,ts): f_path = "/home/subhashis/VisData/merger_trees/particleList/time" + str(ts) + ".vtp" # Read the source file. reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(f_path) reader.Update() hid_array = vtk_to_numpy(reader.GetOutput().GetPointData().GetArray('haloid')) totalNum = len(hid_array) count = 0 for i in range(0,totalNum): if hid == hid_array[i]: count += 1 return count
def copyATPFromRef(angle): print "Processing angle", angle, "..." # Read reference file. # Get Jplc double array from point data. referenceReader = vtk.vtkXMLPolyDataReader() referenceReader.SetFileName("quadMeshFullATPc4080_reference.vtp") referenceReader.Update() Jplc = referenceReader.GetOutput().GetCellData().GetArray("initialATP") # Read EC mesh. # Get centroids. ecMeshReader = vtk.vtkXMLPolyDataReader() ecMeshReader.SetFileName(os.path.join(str(angle), "quadMeshFullECc4080.vtp")) ecMeshReader.Update() ecSurface = ecMeshReader.GetOutput() ecCentroidFilter = vtk.vtkCellCenters() ecCentroidFilter.VertexCellsOn() ecCentroidFilter.SetInput(ecSurface) ecCentroidFilter.Update() ecCentroids = ecCentroidFilter.GetOutput() # Write EC mesh with Jplc as cell data. ecSurface.GetCellData().AddArray(Jplc) atpSurfaceWriter = vtk.vtkXMLPolyDataWriter() atpSurfaceWriter.SetInput(ecSurface) atpSurfaceWriter.SetFileName(os.path.join(str(angle), "quadMeshFullATPc4080_.vtp")) atpSurfaceWriter.Update() # Write EC centroids with Jpls as cell data. ecCentroids.GetCellData().AddArray(Jplc) atpPointsWriter = vtk.vtkXMLPolyDataWriter() atpPointsWriter.SetInput(ecCentroids) atpPointsWriter.SetFileName(os.path.join(str(angle), "quadMeshFullATPc4080.vtp")) print atpPointsWriter.GetFileName() atpPointsWriter.Update()
def loadMesh(shape_filename): """ loads a vtk .vtp file and returns a Bullet concave shape WARNING triangles cells assumed! """ reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(shape_filename) reader.Update() polydata = reader.GetOutput() points = polydata.GetPoints().GetData() num_points = points.GetNumberOfTuples() num_triangles = polydata.GetNumberOfCells() keep = None shape = None if polydata.GetCellType(0) == 5: apoints = np.empty((num_points, 3)) for i in range(0, points.GetNumberOfTuples()): p = points.GetTuple(i) apoints[i, 0] = p[0] apoints[i, 1] = p[1] apoints[i, 2] = p[2] aindices = np.empty((num_triangles, 3), dtype=np.int32) for i in range(0, num_triangles): c = polydata.GetCell(i) aindices[i, 0] = c.GetPointIds().GetId(0) aindices[i, 1] = c.GetPointIds().GetId(1) aindices[i, 2] = c.GetPointIds().GetId(2) tri = btTriangleIndexVertexArray(apoints, aindices) shape = btGImpactMeshShape(tri) shape.updateBound() keep = tri, apoints, aindices else: # assume convex shape coors = dict() for i in range(0, points.GetNumberOfTuples()): coors[points.GetTuple(i)] = 1 shape = btConvexHullShape() for p in coors: shape.addPoint(btVector3(*p)) return keep, shape
def readvtp(filename, dataarrays=True): """Read polydata in vtp format.""" reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filename) reader.Update() if dataarrays == False: for i in range(reader.GetNumberOfPointArrays()): arrayname = reader.GetPointArrayName(i) reader.SetPointArrayStatus(arrayname, 0) for i in range(reader.GetNumberOfCellArrays()): arrayname = reader.GetCellArrayName(i) reader.SetPointArrayStatus(arrayname, 0) reader.Update() return reader.GetOutput()
def main(): # Read reference file. # Get Jplc double array from point data. referenceReader = vtk.vtkXMLPolyDataReader() referenceReader.SetFileName("quadMeshFullATPc4080_reference.vtp") referenceReader.Update() Jplc = referenceReader.GetOutput().GetCellData().GetArray("initialATP") # Read EC mesh. # Get centroids. ecMeshReader = vtk.vtkXMLPolyDataReader() ecMeshReader.SetFileName("quadMeshFullECc4080.vtp") ecMeshReader.Update() ecSurface = ecMeshReader.GetOutput() ecCentroidFilter = vtk.vtkCellCenters() ecCentroidFilter.VertexCellsOn() ecCentroidFilter.SetInput(ecSurface) ecCentroidFilter.Update() ecCentroids = ecCentroidFilter.GetOutput() # Write EC mesh with Jplc as cell data. # Write EC centroids with Jpls as cell data. ecSurface.GetCellData().AddArray(Jplc) atpSurfaceWriter = vtk.vtkXMLPolyDataWriter() atpSurfaceWriter.SetInput(ecSurface) atpSurfaceWriter.SetFileName("quadMeshFullATPc4080_.vtp") atpSurfaceWriter.Update() ecCentroids.GetCellData().AddArray(Jplc) atpPointsWriter = vtk.vtkXMLPolyDataWriter() atpPointsWriter.SetInput(ecCentroids) atpPointsWriter.SetFileName("quadMeshFullATPc4080.vtp") atpPointsWriter.Update()
def QVTKRenderWidgetConeExample(): """A simple example that uses the QVTKRenderWindowInteractor class.""" # every QT app needs an app app = QtGui.QApplication(['QVTKRenderWindowInteractor']) vreader = vtk.vtkXMLPolyDataReader() vreader.SetFileName('lh.vtk') vreader reader1 = VTKFileReader() reader1.initialize(vtkFile_l) # create the widget widget = QVTKRenderWindowInteractor() widget.setMouseInteractionSchemeTo3D() widget.Initialize() widget.Start() # if you dont want the 'q' key to exit comment this. widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit()) ren = vtk.vtkRenderer() widget.GetRenderWindow().AddRenderer(ren) cone = vtk.vtkConeSource() cone.SetResolution(8) coneMapper = vtk.vtkPolyDataMapper() VTK_MAJOR_VERSION=vtk.vtkVersion.GetVTKMajorVersion() if VTK_MAJOR_VERSION>=6: coneMapper.SetInputData(cone.GetOutput()) else: coneMapper.SetInput(cone.GetOutput()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) ren.AddActor(coneActor) # show the widget widget.show() # start event processing app.exec_()
def testAll(self): reader = vtk.vtkXMLPolyDataReader() reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/disk_out_ref_surface.vtp") reader.SetPointArrayStatus("Temp", 1); reader.SetPointArrayStatus("Pres", 1); reader.Update(); input = reader.GetOutput() cf = vtk.vtkContourFilter() cf.SetInputData(input) cf.SetValue(0,400) cf.SetInputArrayToProcess(0, 0, 0, 0, "Temp"); cf.GenerateTrianglesOff() cf.Update() self.assertEqual(cf.GetOutput().GetNumberOfPoints(), 36) self.assertEqual(cf.GetOutput().GetNumberOfCells(), 36) cf.GenerateTrianglesOn() cf.Update() self.assertEqual(cf.GetOutput().GetNumberOfPoints(), 36) self.assertEqual(cf.GetOutput().GetNumberOfCells(), 36) # Check that expected arrays are in the output # The active scalars in the input shouldn't effect the # scalars in the output availableScalars = ["Temp", "Pres"] for scalar in availableScalars: input.GetPointData().SetActiveScalars(scalar) cf.ComputeScalarsOn() cf.Update() pd = cf.GetOutput().GetPointData() self.assertNotEqual(pd.GetArray("Temp"), None) self.assertNotEqual(pd.GetArray("Pres"), None) cf.ComputeScalarsOff() # "Temp" array should not be in output cf.Update() pd = cf.GetOutput().GetPointData() self.assertEqual(pd.GetArray("Temp"), None) self.assertNotEqual(pd.GetArray("Pres"), None)
trial_folder = 'trial_' + str(i_trial) command_string = 'cd ' + trial_folder print(command_string) os.chdir(trial_folder) command_string = SVPOST_PATH + ' -sn 50 -vtu all_results.vtu -vtp all_results.vtp ' \ + '-vtkcombo -all' print(command_string) os.system(command_string) # Now that we have the all_results file, we can process it to find out # output quantities of interest. We want to find quantities on the outlet # face, so let's first isolate this part of the model by finding the # nodes that belong on this face: all_results_reader = vtk.vtkXMLPolyDataReader() all_results_reader.SetFileName('all_results.vtp') all_results_reader.Update() all_results_model = vtk.vtkPolyData() all_results_model = all_results_reader.GetOutput() all_results_numPts = all_results_model.GetNumberOfPoints() all_results_nodeID = all_results_model.GetPointData().GetArray( "GlobalNodeID") # Get the velocity and pressure arrays from the all_results pressure_result = vtk.vtkDoubleArray() pressure_result = all_results_model.GetPointData().GetArray( 'pressure_00050') velocity_result = vtk.vtkDoubleArray() velocity_result = all_results_model.GetPointData().GetArray( 'velocity_00050')
def AddNewActor(self, slice_, mask, surface_parameters): """ Create surface actor, save into project and send it to viewer. """ t_init = time.time() matrix = slice_.matrix filename_img = slice_.matrix_filename spacing = slice_.spacing algorithm = surface_parameters['method']['algorithm'] options = surface_parameters['method']['options'] surface_name = surface_parameters['options']['name'] quality = surface_parameters['options']['quality'] fill_holes = surface_parameters['options']['fill'] keep_largest = surface_parameters['options']['keep_largest'] mode = 'CONTOUR' # 'GRAYSCALE' min_value, max_value = mask.threshold_range colour = mask.colour[:3] try: overwrite = surface_parameters['options']['overwrite'] except KeyError: overwrite = False mask.matrix.flush() if quality in const.SURFACE_QUALITY.keys(): imagedata_resolution = const.SURFACE_QUALITY[quality][0] smooth_iterations = const.SURFACE_QUALITY[quality][1] smooth_relaxation_factor = const.SURFACE_QUALITY[quality][2] decimate_reduction = const.SURFACE_QUALITY[quality][3] pipeline_size = 4 if decimate_reduction: pipeline_size += 1 if (smooth_iterations and smooth_relaxation_factor): pipeline_size += 1 if fill_holes: pipeline_size += 1 if keep_largest: pipeline_size += 1 language = ses.Session().language if (prj.Project().original_orientation == const.CORONAL): flip_image = False else: flip_image = True n_processors = multiprocessing.cpu_count() o_piece = 1 piece_size = 20 n_pieces = int(round(matrix.shape[0] / piece_size + 0.5, 0)) filenames = [] pool = multiprocessing.Pool(processes=min(n_pieces, n_processors)) manager = multiprocessing.Manager() msg_queue = manager.Queue(1) # If InVesalius is running without GUI if wx.GetApp() is None: for i in range(n_pieces): init = i * piece_size end = init + piece_size + o_piece roi = slice(init, end) print("new_piece", roi) f = pool.apply_async( surface_process.create_surface_piece, args=(filename_img, matrix.shape, matrix.dtype, mask.temp_file, mask.matrix.shape, mask.matrix.dtype, roi, spacing, mode, min_value, max_value, decimate_reduction, smooth_relaxation_factor, smooth_iterations, language, flip_image, algorithm != 'Default', algorithm, imagedata_resolution), callback=lambda x: filenames.append(x)) while len(filenames) != n_pieces: time.sleep(0.25) f = pool.apply_async(surface_process.join_process_surface, args=(filenames, algorithm, smooth_iterations, smooth_relaxation_factor, decimate_reduction, keep_largest, fill_holes, options, msg_queue)) while not f.ready(): time.sleep(0.25) try: surface_filename, surface_measures = f.get() except Exception as e: print(_("InVesalius was not able to create the surface")) print(traceback.print_exc()) return reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(surface_filename) reader.Update() polydata = reader.GetOutput() proj = prj.Project() #Create Surface instance if overwrite: surface = Surface(index=self.last_surface_index) proj.ChangeSurface(surface) else: surface = Surface(name=surface_name) index = proj.AddSurface(surface) surface.index = index self.last_surface_index = index surface.colour = colour surface.polydata = polydata surface.volume = surface_measures['volume'] surface.area = surface_measures['area'] # With GUI else: sp = dialogs.SurfaceProgressWindow() for i in range(n_pieces): init = i * piece_size end = init + piece_size + o_piece roi = slice(init, end) print("new_piece", roi) try: f = pool.apply_async( surface_process.create_surface_piece, args=(filename_img, matrix.shape, matrix.dtype, mask.temp_file, mask.matrix.shape, mask.matrix.dtype, roi, spacing, mode, min_value, max_value, decimate_reduction, smooth_relaxation_factor, smooth_iterations, language, flip_image, algorithm != 'Default', algorithm, imagedata_resolution), callback=lambda x: filenames.append(x), error_callback=functools.partial( self._on_callback_error, dialog=sp)) # python2 except TypeError: f = pool.apply_async( surface_process.create_surface_piece, args=(filename_img, matrix.shape, matrix.dtype, mask.temp_file, mask.matrix.shape, mask.matrix.dtype, roi, spacing, mode, min_value, max_value, decimate_reduction, smooth_relaxation_factor, smooth_iterations, language, flip_image, algorithm != 'Default', algorithm, imagedata_resolution), callback=lambda x: filenames.append(x)) while len(filenames) != n_pieces: if sp.WasCancelled() or not sp.running: break time.sleep(0.25) sp.Update(_("Creating 3D surface...")) wx.Yield() if not sp.WasCancelled() or sp.running: try: f = pool.apply_async( surface_process.join_process_surface, args=(filenames, algorithm, smooth_iterations, smooth_relaxation_factor, decimate_reduction, keep_largest, fill_holes, options, msg_queue), callback=functools.partial( self._on_complete_surface_creation, overwrite=overwrite, surface_name=surface_name, colour=colour, dialog=sp), error_callback=functools.partial( self._on_callback_error, dialog=sp)) # python2 except TypeError: f = pool.apply_async( surface_process.join_process_surface, args=(filenames, algorithm, smooth_iterations, smooth_relaxation_factor, decimate_reduction, keep_largest, fill_holes, options, msg_queue), callback=functools.partial( self._on_complete_surface_creation, overwrite=overwrite, surface_name=surface_name, colour=colour, dialog=sp)) while sp.running: if sp.WasCancelled(): break time.sleep(0.25) try: msg = msg_queue.get_nowait() sp.Update(msg) except: sp.Update(None) wx.Yield() t_end = time.time() print("Elapsed time - {}".format(t_end - t_init)) sp.Close() if sp.error: dlg = GMD.GenericMessageDialog(None, sp.error, "Exception!", wx.OK | wx.ICON_ERROR) dlg.ShowModal() del sp pool.close() pool.terminate() del pool del manager del msg_queue import gc gc.collect()
def _on_complete_surface_creation(self, args, overwrite, surface_name, colour, dialog): surface_filename, surface_measures = args print(surface_filename, surface_measures) reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(surface_filename) reader.Update() polydata = reader.GetOutput() # Map polygonal data (vtkPolyData) to graphics primitives. mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polydata) mapper.ScalarVisibilityOff() # mapper.ReleaseDataFlagOn() mapper.ImmediateModeRenderingOn() # improve performance # Represent an object (geometry & properties) in the rendered scene actor = vtk.vtkActor() actor.SetMapper(mapper) del mapper #Create Surface instance if overwrite: surface = Surface(index=self.last_surface_index) else: surface = Surface(name=surface_name) surface.colour = colour surface.polydata = polydata surface.volume = surface_measures['volume'] surface.area = surface_measures['area'] del polydata # Set actor colour and transparency actor.GetProperty().SetColor(colour) actor.GetProperty().SetOpacity(1 - surface.transparency) prop = actor.GetProperty() interpolation = int(ses.Session().surface_interpolation) prop.SetInterpolation(interpolation) proj = prj.Project() if overwrite: proj.ChangeSurface(surface) else: index = proj.AddSurface(surface) surface.index = index self.last_surface_index = index session = ses.Session() session.ChangeProject() Publisher.sendMessage('Load surface actor into viewer', actor=actor) # Send actor by pubsub to viewer's render if overwrite and self.actors_dict.keys(): old_actor = self.actors_dict[self.last_surface_index] Publisher.sendMessage('Remove surface actor from viewer', actor=old_actor) # Save actor for future management tasks self.actors_dict[surface.index] = actor Publisher.sendMessage('Update surface info in GUI', surface=surface) Publisher.sendMessage('End busy cursor') dialog.running = False
default=0.0, dest="rot", help= "rotation of data in degrees anticlockwise about origin (this is done after any translation)" ) (opts, args) = p.parse_args() # get the com filename if len(args) != 2: p.print_help() sys.exit(1) (in_file, out_file) = args if opts.verbose: print "Reading", in_file if in_file.endswith(".vtp") and out_file.endswith(".vtp"): indata = vtk.vtkXMLPolyDataReader() writer = vtk.vtkXMLPolyDataWriter() outdata = vtk.vtkTransformPolyDataFilter() elif in_file.endswith(".vtu") and out_file.endswith(".vtu"): indata = vtk.vtkXMLUnstructuredGridReader() writer = vtk.vtkXMLUnstructuredGridWriter() outdata = vtk.vtkTransformFilter() elif in_file.endswith(".vtr") and out_file.endswith(".vtr"): indata = vtk.vtkXMLRectilinearGridReader() writer = vtk.vtkXMLRectilinearGridWriter() outdata = vtk.vtkTransformFilter() else: print "This program has not yet been configured to read", in_file, "and write", out_file p.print_help() sys.exit(2)
def main(args): WSS_CONV_FACTOR = 10000 P_CONV_FACTOR = .133333333333333 INTERPOLATING_RADIUS = 5 WALL_THRESHOLD = 30 NUCLEAR_THRESHOLD = 30 # First, read in the .vtp file for mesh and Dach1 datareader = vtk.vtkXMLPolyDataReader() datareader.SetFileName(args.filename) datareader.Update() ref = vtk.vtkXMLImageDataReader() ref.SetFileName('ImageData_Combined.vti') ref.Update() # Read your data into another polydata variable for reading mesh = vtk.vtkPolyData() mesh = datareader.GetOutput() imageData = vtk.vtkPolyData() imageData = ref.GetOutput() numPts = mesh.GetNumberOfPoints() factors = ['Dach1'] nuclearFactor = 'Cx40Nuclei' for molecularFactor in xrange(0, len(factors)): # Create new Dach1 Array to fill maxMFArray = vtk.vtkDoubleArray() meanMFArray = vtk.vtkDoubleArray() thresholdMFArray = vtk.vtkDoubleArray() nuclearMFArray = vtk.vtkDoubleArray() NuclearArray = vtk.vtkDoubleArray() # Loop through mesh points, find closest point in Dach1.vti, and add to Dach1 Array for meshPointID in xrange(0, numPts): meshPointCoordinate = mesh.GetPoint(meshPointID) x, y, z = mesh.GetPoint(meshPointID) pointsPool = np.array([[x, y, z]]) pointsPool = np.append(pointsPool, [[x + INTERPOLATING_RADIUS, y, z], [x - INTERPOLATING_RADIUS, y, z]], axis=0) pointsPool = np.append(pointsPool, [[x, y + INTERPOLATING_RADIUS, z], [x, y - INTERPOLATING_RADIUS, z]], axis=0) pointsPool = np.append(pointsPool, [[x, y, z + INTERPOLATING_RADIUS], [x, y, z - INTERPOLATING_RADIUS]], axis=0) maxMFValue = 0 meanMFValue = 0 x = pointsPool[0, 0] y = pointsPool[0, 1] z = pointsPool[0, 2] meshPointCoordinate = x, y, z thresholdWallValue = imageData.GetPointData().GetArray( 'ImageFile').GetValue(imageData.FindPoint(meshPointCoordinate)) for i in xrange(0, len(pointsPool)): x = pointsPool[i, 0] y = pointsPool[i, 1] z = pointsPool[i, 2] meshPointCoordinate = x, y, z meshPointID = imageData.FindPoint(meshPointCoordinate) MFValue = imageData.GetPointData().GetArray( factors[molecularFactor]).GetValue(meshPointID) meanMFValue += MFValue WallValue = imageData.GetPointData().GetArray( 'ImageFile').GetValue(meshPointID) if maxMFValue < MFValue: maxMFValue = MFValue if thresholdWallValue > WALL_THRESHOLD: x = pointsPool[0, 0] y = pointsPool[0, 1] z = pointsPool[0, 2] meshPointCoordinate = x, y, z thresholdMFArray.InsertNextValue( imageData.GetPointData().GetArray( factors[molecularFactor]).GetValue( imageData.FindPoint(meshPointCoordinate))) else: thresholdMFArray.InsertNextValue(0) if imageData.GetPointData().HasArray(nuclearFactor) == 1: thresholdNuclearValue = imageData.GetPointData().GetArray( nuclearFactor).GetValue( imageData.FindPoint(meshPointCoordinate)) NuclearArray.InsertNextValue(thresholdNuclearValue) if thresholdNuclearValue > NUCLEAR_THRESHOLD: x = pointsPool[0, 0] y = pointsPool[0, 1] z = pointsPool[0, 2] meshPointCoordinate = x, y, z if mesh.GetPointData().HasArray('Filtered ' + nuclearFactor) == 1: NuclearMultiplier = mesh.GetPointData().GetArray( 'Filtered ' + nuclearFactor).GetValue( meshPointCoordinate) / thresholdNuclearValue else: NuclearMultiplier = 1 nuclearMFArray.InsertNextValue( NuclearMultiplier * imageData.GetPointData().GetArray( factors[molecularFactor]).GetValue( imageData.FindPoint(meshPointCoordinate))) else: nuclearMFArray.InsertNextValue(-1) meanMFValue = meanMFValue / len(pointsPool) maxMFArray.InsertNextValue(maxMFValue) meanMFArray.InsertNextValue(meanMFValue) # Add Dach1 Array to point data maxMFArray.SetName('Max ' + factors[molecularFactor] + ' (' + str(INTERPOLATING_RADIUS) + ')') mesh.GetPointData().AddArray(maxMFArray) meanMFArray.SetName('Mean ' + factors[molecularFactor] + ' (' + str(INTERPOLATING_RADIUS) + ')') mesh.GetPointData().AddArray(meanMFArray) thresholdMFArray.SetName('Threshold ' + factors[molecularFactor] + ' (' + str(INTERPOLATING_RADIUS) + ')') mesh.GetPointData().AddArray(thresholdMFArray) if imageData.GetPointData().HasArray(nuclearFactor) == 1: nuclearMFArray.SetName('Nuclear ' + factors[molecularFactor] + ' (' + nuclearFactor + ')') mesh.GetPointData().AddArray(nuclearMFArray) NuclearArray.SetName('Nucleus ' + '(' + nuclearFactor + ')') mesh.GetPointData().AddArray(NuclearArray) # Convert TA_WSS and Pressure to micron units and new arrays to point data if mesh.GetPointData().HasArray('vTAWSS') == 1: TA_WSS = VN.vtk_to_numpy(mesh.GetPointData().GetArray('vTAWSS')) TA_WSS_numpy = WSS_CONV_FACTOR * TA_WSS TA_WSS_vtk = VN.numpy_to_vtk(TA_WSS_numpy) TA_WSS_vtk.SetName('vTAWSS (dynes/cm^2)') mesh.GetPointData().AddArray(TA_WSS_vtk) else: print('vTAWSS not found. No conversion done.') if mesh.GetPointData().HasArray('pressure_avg') == 1: pressure_avg = VN.vtk_to_numpy( mesh.GetPointData().GetArray('pressure_avg')) pressure_numpy = pressure_avg / P_CONV_FACTOR pressure_vtk = VN.numpy_to_vtk(pressure_numpy) pressure_vtk.SetName('pressure_avg (mmHg)') mesh.GetPointData().AddArray(pressure_vtk) else: print('pressure_avg not found. No conversion done.') # Write a new .vtp file that has all converted values and mapped values. w = vtk.vtkXMLPolyDataWriter() w.SetInputData(mesh) w.SetFileName('all_results_mapped_interpolated_threshold.vtp') w.Write()
import vtk from vmtk import vmtkscripts from VesselTruncation import * import GenerateCenterline precomputed = 0 diameters = [0.15, 0.1] inputSurface = '/media/microway/1TB/PhaseA/Case3/Surface2/PhaseA_LCA_3.stl' fname1 = '/media/microway/1TB/PhaseA/Case3/Surface2/PhaseA_LCA_3_sp.vtp' fname2 = '/media/microway/1TB/PhaseA/Case3/Surface2/PhaseA_LCA_3_clsp.vtp' if precomputed == 1: readSurface = vtk.vtkXMLPolyDataReader() readSurface.SetinputSurface(fname1) readSurface.Update() readCenterlines = vtk.vtkXMLPolyDataReader() readCenterlines.SetinputSurface(fname2) readCenterlines.Update() for diameter in diameters: outputName = fname1.split('.') + str(diameter) + 'mm.vtp' vessel = VesselTruncation() vessel.SetInputSurface(readSurface.GetOutput()) vessel.SetInputCenterlines(readCenterlines.GetOutput()) vessel.SetDiameter(diameter) vessel.Update() vessel.SetOutputinputSurface(outputName) vessel.Write() vessel.GetVolume()
def ptot_flux(FlowFileName,SurfFileName,velname,pressurename): import vtk as vtk rho = 1.06 # Read your flow data into another polydata variable for manipulation datareader=vtk.vtkXMLPolyDataReader() datareader.SetFileName(FlowFileName) datareader.Update() model=vtk.vtkPolyData() model=datareader.GetOutput() # Read your surf-of-interest data into another polydata variable for manipulation datareader_surf=vtk.vtkXMLPolyDataReader() datareader_surf.SetFileName(SurfFileName) datareader_surf.Update() surf=vtk.vtkPolyData() surf=datareader_surf.GetOutput() numPts=model.GetNumberOfPoints() numCells=model.GetNumberOfCells() surf_numPts=surf.GetNumberOfPoints() surf_numCells=surf.GetNumberOfCells() # Read your fav variables from the model vtp temp_pressure=vtk.vtkDoubleArray() temp_pressure=model.GetPointData().GetArray(pressurename) temp_vel=vtk.vtkDoubleArray() temp_vel=model.GetPointData().GetArray(velname) model_id = model.GetPointData().GetArray('GlobalNodeID') surf_id = surf.GetPointData().GetArray('GlobalNodeID') # print model_id # Find the normal vector to this face normalGenerator = vtk.vtkPolyDataNormals() normalGenerator.SetInput(surf) normalGenerator.ComputeCellNormalsOff() normalGenerator.ComputePointNormalsOn() normalGenerator.Update() normals_test = normalGenerator.GetOutput() normals_arr = normals_test.GetPointData().GetArray('Normals') # --- LOOP THROUGH SURFACE POINTS FOR MODEL AND SURF OF INTEREST ptot_flux = np.zeros(surf_numPts) for ipts_surf in xrange(0,surf_numPts): temp_sid = surf_id.GetTuple1(ipts_surf) for ipts_model in xrange(0,numPts): if temp_sid == model_id.GetTuple1(ipts_model): pt_normal = np.asarray(normals_arr.GetTuple3(ipts_surf)) pt_p = temp_pressure.GetTuple1(ipts_model) pt_vel = np.asarray(temp_vel.GetTuple3(ipts_model)) # print pt_p, pt_vel, pt_normal ptot_flux[ipts_surf] = (pt_p + 0.5*rho*sum(pt_vel*pt_vel))*np.dot(pt_vel,pt_normal) break # --- END LOOP totalflux = 0.0 # INTEGRATE PTOT_FLUX POINT DATA INTO A SINGLE VARIABLE - CELL LEVEL LOOP for icell in xrange(0,surf_numCells): temp_cell = surf.GetCell(icell) pts_cell_id = temp_cell.GetPointIds() vtkpt = temp_cell.GetPoints() p0 = vtkpt.GetPoint(0) p1 = vtkpt.GetPoint(1) p2 = vtkpt.GetPoint(2) v = [] for kpt in range(pts_cell_id.GetNumberOfIds()) : kid = pts_cell_id.GetId(kpt) v.append(ptot_flux[kid]) # print v, temp_cell.TriangleArea(p0,p1,p2) totalflux = totalflux + (centval_calc(p0,p1,p2,v[0],v[1],v[2]))*area_calc(p0,p1,p2) return totalflux
def _load_file(filename, c, alpha, threshold, spacing, unpack): fl = filename.lower() ################################################################# other formats: if fl.endswith(".xml") or fl.endswith(".xml.gz") or fl.endswith(".xdmf"): # Fenics tetrahedral file actor = loadDolfin(filename) elif fl.endswith(".neutral") or fl.endswith( ".neu"): # neutral tetrahedral file actor = loadNeutral(filename) elif fl.endswith(".gmsh"): # gmesh file actor = loadGmesh(filename) elif fl.endswith(".pcd"): # PCL point-cloud format actor = loadPCD(filename) actor.GetProperty().SetPointSize(2) elif fl.endswith(".off"): actor = loadOFF(filename) elif fl.endswith(".3ds"): # 3ds format actor = load3DS(filename) elif fl.endswith(".wrl"): importer = vtk.vtkVRMLImporter() importer.SetFileName(filename) importer.Read() importer.Update() actors = importer.GetRenderer().GetActors() #vtkActorCollection actors.InitTraversal() wacts = [] for i in range(actors.GetNumberOfItems()): act = actors.GetNextActor() wacts.append(act) actor = Assembly(wacts) ################################################################# volumetric: elif fl.endswith(".tif") or fl.endswith(".slc") or fl.endswith(".vti") \ or fl.endswith(".mhd") or fl.endswith(".nrrd") or fl.endswith(".nii") \ or fl.endswith(".dem"): img = loadImageData(filename, spacing) if threshold is False: if c is None and alpha == 1: c = ['b', 'lb', 'lg', 'y', 'r'] # good for blackboard background alpha = (0.0, 0.0, 0.2, 0.4, 0.8, 1) actor = Volume(img) else: actor = Volume(img).isosurface(threshold=threshold) actor.color(c).alpha(alpha) ################################################################# 2D images: elif fl.endswith(".png") or fl.endswith(".jpg") or fl.endswith( ".bmp") or fl.endswith(".jpeg"): if ".png" in fl: picr = vtk.vtkPNGReader() elif ".jpg" in fl or ".jpeg" in fl: picr = vtk.vtkJPEGReader() elif ".bmp" in fl: picr = vtk.vtkBMPReader() picr.SetFileName(filename) picr.Update() actor = Picture() # object derived from vtk.vtkImageActor() actor.SetInputData(picr.GetOutput()) if alpha is None: alpha = 1 actor.SetOpacity(alpha) ################################################################# multiblock: elif fl.endswith(".vtm") or fl.endswith(".vtmb"): read = vtk.vtkXMLMultiBlockDataReader() read.SetFileName(filename) read.Update() mb = read.GetOutput() if unpack: acts = [] for i in range(mb.GetNumberOfBlocks()): b = mb.GetBlock(i) if isinstance(b, (vtk.vtkPolyData, vtk.vtkImageData, vtk.vtkUnstructuredGrid, vtk.vtkStructuredGrid, vtk.vtkRectilinearGrid)): acts.append(b) return acts else: return mb ################################################################# numpy: elif fl.endswith(".npy"): acts = loadNumpy(filename) if unpack is False: return Assembly(acts) return acts elif fl.endswith(".geojson") or fl.endswith(".geojson.gz"): return loadGeoJSON(fl) elif fl.endswith(".pvd"): return loadPVD(fl) elif fl.endswith(".pdb"): return loadPDB(fl) ################################################################# polygonal mesh: else: if fl.endswith(".vtk"): # read all legacy vtk types #output can be: # PolyData, StructuredGrid, StructuredPoints, UnstructuredGrid, RectilinearGrid reader = vtk.vtkDataSetReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.ReadAllFieldsOn() reader.ReadAllNormalsOn() reader.ReadAllColorScalarsOn() elif fl.endswith(".ply"): reader = vtk.vtkPLYReader() elif fl.endswith(".obj"): reader = vtk.vtkOBJReader() elif fl.endswith(".stl"): reader = vtk.vtkSTLReader() elif fl.endswith(".byu") or fl.endswith(".g"): reader = vtk.vtkBYUReader() elif fl.endswith(".foam"): # OpenFoam reader = vtk.vtkOpenFOAMReader() elif fl.endswith(".pvd"): reader = vtk.vtkXMLGenericDataObjectReader() elif fl.endswith(".vtp"): reader = vtk.vtkXMLPolyDataReader() elif fl.endswith(".vts"): reader = vtk.vtkXMLStructuredGridReader() elif fl.endswith(".vtu"): reader = vtk.vtkXMLUnstructuredGridReader() elif fl.endswith(".vtr"): reader = vtk.vtkXMLRectilinearGridReader() elif fl.endswith(".pvtk"): reader = vtk.vtkPDataSetReader() elif fl.endswith(".pvtr"): reader = vtk.vtkXMLPRectilinearGridReader() elif fl.endswith("pvtu"): reader = vtk.vtkXMLPUnstructuredGridReader() elif fl.endswith(".txt") or fl.endswith(".xyz"): reader = vtk.vtkParticleReader() # (format is x, y, z, scalar) elif fl.endswith(".facet"): reader = vtk.vtkFacetReader() else: return None reader.SetFileName(filename) reader.Update() routput = reader.GetOutput() if not routput: colors.printc("~noentry Unable to load", filename, c=1) return None actor = Mesh(routput, c, alpha) if fl.endswith(".txt") or fl.endswith(".xyz"): actor.GetProperty().SetPointSize(4) actor.filename = filename return actor
def AddNewActor(self, pubsub_evt): """ Create surface actor, save into project and send it to viewer. """ slice_, mask, surface_parameters = pubsub_evt.data matrix = slice_.matrix filename_img = slice_.matrix_filename spacing = slice_.spacing algorithm = surface_parameters['method']['algorithm'] options = surface_parameters['method']['options'] surface_name = surface_parameters['options']['name'] quality = surface_parameters['options']['quality'] fill_holes = surface_parameters['options']['fill'] keep_largest = surface_parameters['options']['keep_largest'] mode = 'CONTOUR' # 'GRAYSCALE' min_value, max_value = mask.threshold_range colour = mask.colour try: overwrite = surface_parameters['options']['overwrite'] except KeyError: overwrite = False mask.matrix.flush() if quality in const.SURFACE_QUALITY.keys(): imagedata_resolution = const.SURFACE_QUALITY[quality][0] smooth_iterations = const.SURFACE_QUALITY[quality][1] smooth_relaxation_factor = const.SURFACE_QUALITY[quality][2] decimate_reduction = const.SURFACE_QUALITY[quality][3] #if imagedata_resolution: #imagedata = iu.ResampleImage3D(imagedata, imagedata_resolution) pipeline_size = 4 if decimate_reduction: pipeline_size += 1 if (smooth_iterations and smooth_relaxation_factor): pipeline_size += 1 if fill_holes: pipeline_size += 1 if keep_largest: pipeline_size += 1 ## Update progress value in GUI UpdateProgress = vu.ShowProgress(pipeline_size) UpdateProgress(0, _("Creating 3D surface...")) language = ses.Session().language if (prj.Project().original_orientation == const.CORONAL): flip_image = False else: flip_image = True n_processors = multiprocessing.cpu_count() pipe_in, pipe_out = multiprocessing.Pipe() o_piece = 1 piece_size = 2000 n_pieces = int(round(matrix.shape[0] / piece_size + 0.5, 0)) q_in = multiprocessing.Queue() q_out = multiprocessing.Queue() p = [] for i in xrange(n_processors): sp = surface_process.SurfaceProcess( pipe_in, filename_img, matrix.shape, matrix.dtype, mask.temp_file, mask.matrix.shape, mask.matrix.dtype, spacing, mode, min_value, max_value, decimate_reduction, smooth_relaxation_factor, smooth_iterations, language, flip_image, q_in, q_out, algorithm != 'Default', algorithm, imagedata_resolution) p.append(sp) sp.start() for i in xrange(n_pieces): init = i * piece_size end = init + piece_size + o_piece roi = slice(init, end) q_in.put(roi) print "new_piece", roi for i in p: q_in.put(None) none_count = 1 while 1: msg = pipe_out.recv() if (msg is None): none_count += 1 else: UpdateProgress(msg[0] / (n_pieces * pipeline_size), msg[1]) if none_count > n_pieces: break polydata_append = vtk.vtkAppendPolyData() # polydata_append.ReleaseDataFlagOn() t = n_pieces while t: filename_polydata = q_out.get() reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filename_polydata) # reader.ReleaseDataFlagOn() reader.Update() # reader.GetOutput().ReleaseDataFlagOn() polydata = reader.GetOutput() # polydata.SetSource(None) polydata_append.AddInputData(polydata) del reader del polydata t -= 1 polydata_append.Update() # polydata_append.GetOutput().ReleaseDataFlagOn() polydata = polydata_append.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del polydata_append if algorithm == 'ca_smoothing': normals = vtk.vtkPolyDataNormals() normals_ref = weakref.ref(normals) normals_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( normals_ref(), _("Creating 3D surface..."))) normals.SetInputData(polydata) # normals.ReleaseDataFlagOn() #normals.SetFeatureAngle(80) #normals.AutoOrientNormalsOn() normals.ComputeCellNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.Update() del polydata polydata = normals.GetOutput() # polydata.SetSource(None) del normals clean = vtk.vtkCleanPolyData() # clean.ReleaseDataFlagOn() # clean.GetOutput().ReleaseDataFlagOn() clean_ref = weakref.ref(clean) clean_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( clean_ref(), _("Creating 3D surface..."))) clean.SetInputData(polydata) clean.PointMergingOn() clean.Update() del polydata polydata = clean.GetOutput() # polydata.SetSource(None) del clean # try: # polydata.BuildLinks() # except TypeError: # polydata.BuildLinks(0) # polydata = ca_smoothing.ca_smoothing(polydata, options['angle'], # options['max distance'], # options['min weight'], # options['steps']) mesh = cy_mesh.Mesh(polydata) cy_mesh.ca_smoothing(mesh, options['angle'], options['max distance'], options['min weight'], options['steps']) # polydata = mesh.to_vtk() # polydata.SetSource(None) # polydata.DebugOn() else: #smoother = vtk.vtkWindowedSincPolyDataFilter() smoother = vtk.vtkSmoothPolyDataFilter() smoother_ref = weakref.ref(smoother) smoother_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( smoother_ref(), _("Creating 3D surface..."))) smoother.SetInputData(polydata) smoother.SetNumberOfIterations(smooth_iterations) smoother.SetRelaxationFactor(smooth_relaxation_factor) smoother.SetFeatureAngle(80) #smoother.SetEdgeAngle(90.0) #smoother.SetPassBand(0.1) smoother.BoundarySmoothingOn() smoother.FeatureEdgeSmoothingOn() #smoother.NormalizeCoordinatesOn() #smoother.NonManifoldSmoothingOn() # smoother.ReleaseDataFlagOn() # smoother.GetOutput().ReleaseDataFlagOn() smoother.Update() del polydata polydata = smoother.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del smoother if decimate_reduction: print "Decimating", decimate_reduction decimation = vtk.vtkQuadricDecimation() # decimation.ReleaseDataFlagOn() decimation.SetInputData(polydata) decimation.SetTargetReduction(decimate_reduction) decimation_ref = weakref.ref(decimation) decimation_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( decimation_ref(), _("Creating 3D surface..."))) #decimation.PreserveTopologyOn() #decimation.SplittingOff() #decimation.BoundaryVertexDeletionOff() # decimation.GetOutput().ReleaseDataFlagOn() decimation.Update() del polydata polydata = decimation.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del decimation #to_measure.Register(None) # to_measure.SetSource(None) if keep_largest: conn = vtk.vtkPolyDataConnectivityFilter() conn.SetInputData(polydata) conn.SetExtractionModeToLargestRegion() conn_ref = weakref.ref(conn) conn_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( conn_ref(), _("Creating 3D surface..."))) conn.Update() # conn.GetOutput().ReleaseDataFlagOn() del polydata polydata = conn.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del conn #Filter used to detect and fill holes. Only fill boundary edges holes. #TODO: Hey! This piece of code is the same from #polydata_utils.FillSurfaceHole, we need to review this. if fill_holes: filled_polydata = vtk.vtkFillHolesFilter() # filled_polydata.ReleaseDataFlagOn() filled_polydata.SetInputData(polydata) filled_polydata.SetHoleSize(300) filled_polydata_ref = weakref.ref(filled_polydata) filled_polydata_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( filled_polydata_ref(), _("Creating 3D surface..."))) filled_polydata.Update() # filled_polydata.GetOutput().ReleaseDataFlagOn() del polydata polydata = filled_polydata.GetOutput() #polydata.Register(None) # polydata.SetSource(None) # polydata.DebugOn() del filled_polydata to_measure = polydata # If InVesalius is running without GUI if wx.GetApp() is None: proj = prj.Project() #Create Surface instance if overwrite: surface = Surface(index=self.last_surface_index) proj.ChangeSurface(surface) else: surface = Surface(name=surface_name) index = proj.AddSurface(surface) surface.index = index self.last_surface_index = index surface.colour = colour surface.polydata = polydata # With GUI else: normals = vtk.vtkPolyDataNormals() # normals.ReleaseDataFlagOn() normals_ref = weakref.ref(normals) normals_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( normals_ref(), _("Creating 3D surface..."))) normals.SetInputData(polydata) normals.SetFeatureAngle(80) normals.AutoOrientNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.Update() del polydata polydata = normals.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del normals # Improve performance stripper = vtk.vtkStripper() # stripper.ReleaseDataFlagOn() stripper_ref = weakref.ref(stripper) stripper_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( stripper_ref(), _("Creating 3D surface..."))) stripper.SetInputData(polydata) stripper.PassThroughCellIdsOn() stripper.PassThroughPointIdsOn() # stripper.GetOutput().ReleaseDataFlagOn() stripper.Update() del polydata polydata = stripper.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del stripper # Map polygonal data (vtkPolyData) to graphics primitives. mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polydata) mapper.ScalarVisibilityOff() # mapper.ReleaseDataFlagOn() mapper.ImmediateModeRenderingOn() # improve performance # Represent an object (geometry & properties) in the rendered scene actor = vtk.vtkActor() actor.SetMapper(mapper) del mapper #Create Surface instance if overwrite: surface = Surface(index=self.last_surface_index) else: surface = Surface(name=surface_name) surface.colour = colour surface.polydata = polydata del polydata # Set actor colour and transparency actor.GetProperty().SetColor(colour) actor.GetProperty().SetOpacity(1 - surface.transparency) prop = actor.GetProperty() interpolation = int(ses.Session().surface_interpolation) prop.SetInterpolation(interpolation) proj = prj.Project() if overwrite: proj.ChangeSurface(surface) else: index = proj.AddSurface(surface) surface.index = index self.last_surface_index = index session = ses.Session() session.ChangeProject() measured_polydata = vtk.vtkMassProperties() # measured_polydata.ReleaseDataFlagOn() measured_polydata.SetInputData(to_measure) volume = float(measured_polydata.GetVolume()) area = float(measured_polydata.GetSurfaceArea()) surface.volume = volume surface.area = area self.last_surface_index = surface.index del measured_polydata del to_measure Publisher.sendMessage('Load surface actor into viewer', actor) # Send actor by pubsub to viewer's render if overwrite and self.actors_dict.keys(): old_actor = self.actors_dict[self.last_surface_index] Publisher.sendMessage('Remove surface actor from viewer', old_actor) # Save actor for future management tasks self.actors_dict[surface.index] = actor Publisher.sendMessage( 'Update surface info in GUI', (surface.index, surface.name, surface.colour, surface.volume, surface.area, surface.transparency)) #When you finalize the progress. The bar is cleaned. UpdateProgress = vu.ShowProgress(1) UpdateProgress(0, _("Ready")) Publisher.sendMessage('Update status text in GUI', _("Ready")) Publisher.sendMessage('End busy cursor') del actor
def convert(input, output, force=True, only_points=False): # print('Converting', len(input), 'files.') for file_i in input: if not os.path.exists(file_i): print('ERROR', 'Could not find file:', file_i) return # print('Converting', file_i) input_basename = os.path.basename(file_i) if input_basename.endswith('vtp'): r = vtk.vtkXMLPolyDataReader() r.SetFileName(file_i) r.Update() polydata = r.GetOutput() elif input_basename.endswith('vtk'): r = vtk.vtkPolyDataReader() r.SetFileName(file_i) r.Update() polydata = r.GetOutput() points = numpy_support.vtk_to_numpy(polydata.GetPoints().GetData()) lines = numpy_support.vtk_to_numpy(polydata.GetLines().GetData()) number_of_streamlines = polydata.GetLines().GetNumberOfCells() # if (number_of_streamlines == 0): # print('ERROR', 'No streamlines in file:', file_i) # continue # # scalars are per point # pointdata = polydata.GetPointData() number_of_scalars = pointdata.GetNumberOfArrays() scalars = []# np.zeros((points.shape[0], number_of_scalars)) scalar_names = ['']*10#np.empty((10,20),dtype=np.byte) for i in range(number_of_scalars): arr_name = pointdata.GetArrayName(i) scalar_names[i] = str.encode(arr_name)[0:20] # print('Loading Scalar', arr_name) scalars.append(numpy_support.vtk_to_numpy(pointdata.GetArray(i))) # # properties are per streamline # celldata = polydata.GetCellData() number_of_properties = celldata.GetNumberOfArrays() properties = np.zeros((number_of_streamlines, number_of_properties),dtype=np.float32) property_names =['']*10# np.empty((10,20),dtype=np.byte) for i in range(number_of_properties): arr_name = celldata.GetArrayName(i) property_names[i] = str.encode(arr_name)[0:20] # print('Loading Property', arr_name) current_array = numpy_support.vtk_to_numpy(celldata.GetArray(i)) if (current_array.ndim > 1): # print(' Warning: Combining Property', arr_name, '(mean)') current_array = np.mean(current_array) continue properties[:,i] = current_array # # convert to streamlines # streamlines = [] i = 0 current_fiber_id = 0 line_length = 0 if len(lines) > 0: line_length = lines[i] line_index = 0 while (line_index<number_of_streamlines): # print(line_index,'start',i+1,'len',line_length) current_line = lines[i+1+line_index:i+1+line_length+line_index] current_points = np.zeros((line_length, 3), dtype=np.float32) current_scalars = np.zeros((line_length, number_of_scalars), dtype=np.float32) current_properties = np.zeros((number_of_properties), dtype=np.float32) # current_properties = np.zeros() for p_i, p in enumerate(current_line): current_points[p_i] = points[p] current_scalars[p_i] = scalars[p] current_properties = properties[line_index] if only_points: streamlines.append((current_points, None, None)) else: streamlines.append((current_points, current_scalars, current_properties)) i += line_length line_index += 1 if line_index < number_of_streamlines: line_length = lines[i+line_index] # # create header # hdr = {'vox_to_ras':np.eye(4), 'voxel_size':np.ones(3), 'dim':np.array([256,256,256]), 'scalar_name':scalar_names, 'property_name':property_names} with open(output, 'wb') as f: nibabel.trackvis.write(f, streamlines, hdr)
def CopyData(): print args input_1 = vtk.vtkPolyData() # Read input_1. if os.path.splitext(args.input_1)[1] == ".vtp": reader1 = vtk.vtkXMLPolyDataReader() reader1.SetFileName(args.input_1) reader1.Update() input_1 = reader1.GetOutput() else: raise Exception("Expected vtp as input_1.") # print input_1 # Read input_2 if os.path.splitext(args.input_2)[1] == ".vtp": reader2 = vtk.vtkXMLPolyDataReader() reader2.SetFileName(args.input_2) reader2.Update() input_2 = reader2.GetOutput() else: raise Exception("Expected vtp as input_2.") # Names for arrays to copy. point_arrays = [] cell_arrays = [] for array_name in args.array_names: if input_1.GetPointData().HasArray(array_name): point_arrays.append(array_name) else: print array_name, "not found in point data arrays" if input_1.GetCellData().HasArray(array_name): cell_arrays.append(array_name) else: print array_name, "not found in cell data arrays" # These are the names of point arrays to copy. print "Point data arrys to copy", point_arrays print "Cell data arrays to copy", cell_arrays # Copy point arrays and save the output. output = vtk.vtkPolyData() output.DeepCopy(input_2) # Copy point data arrays. for array_name in point_arrays: array = input_1.GetPointData().GetArray(array_name) # Make sure the number of cells in the output matches the number of tuples in the source array. assert ( array.GetNumberOfTuples() == output.GetNumberOfCells() ), "Number of tuples in array from input_1 does not match the number of cells in input_2." output.GetCellData().AddArray(array) # Copy cell data arrays. for array_name in cell_arrays: array = input_1.GetCellData().GetArray(array_name) # Make sure the number of cells in the output matches the number of tuples in the source array. assert ( array.GetNumberOfTuples() == output.GetNumberOfCells() ), "Number of tuples in array from intput_1 does not match the number of cells in input_2." output.GetCellData().AddArray(array) # Write output. if os.path.splitext(args.output)[1] == ".vtp": writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(args.output) writer.SetInput(output) writer.Update() else: raise Exception("Expected vtp as output.")
def join_process_surface(filenames, algorithm, smooth_iterations, smooth_relaxation_factor, decimate_reduction, keep_largest, fill_holes, options, msg_queue): def send_message(msg): try: msg_queue.put_nowait(msg) except queue.Full as e: print(e) send_message('Joining surfaces ...') polydata_append = vtk.vtkAppendPolyData() for f in filenames: reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(f) reader.Update() polydata = reader.GetOutput() polydata_append.AddInputData(polydata) del reader del polydata polydata_append.Update() # polydata_append.GetOutput().ReleaseDataFlagOn() polydata = polydata_append.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del polydata_append send_message('Cleaning surface ...') clean = vtk.vtkCleanPolyData() # clean.ReleaseDataFlagOn() # clean.GetOutput().ReleaseDataFlagOn() clean_ref = weakref.ref(clean) # clean_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(clean_ref(), _("Creating 3D surface..."))) clean.SetInputData(polydata) clean.PointMergingOn() clean.Update() del polydata polydata = clean.GetOutput() # polydata.SetSource(None) del clean if algorithm == 'ca_smoothing': send_message('Calculating normals ...') normals = vtk.vtkPolyDataNormals() normals_ref = weakref.ref(normals) # normals_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(normals_ref(), _("Creating 3D surface..."))) normals.SetInputData(polydata) # normals.ReleaseDataFlagOn() #normals.SetFeatureAngle(80) #normals.AutoOrientNormalsOn() normals.ComputeCellNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.Update() del polydata polydata = normals.GetOutput() # polydata.SetSource(None) del normals clean = vtk.vtkCleanPolyData() # clean.ReleaseDataFlagOn() # clean.GetOutput().ReleaseDataFlagOn() clean_ref = weakref.ref(clean) # clean_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(clean_ref(), _("Creating 3D surface..."))) clean.SetInputData(polydata) clean.PointMergingOn() clean.Update() del polydata polydata = clean.GetOutput() # polydata.SetSource(None) del clean # try: # polydata.BuildLinks() # except TypeError: # polydata.BuildLinks(0) # polydata = ca_smoothing.ca_smoothing(polydata, options['angle'], # options['max distance'], # options['min weight'], # options['steps']) send_message('Context Aware smoothing ...') mesh = cy_mesh.Mesh(polydata) cy_mesh.ca_smoothing(mesh, options['angle'], options['max distance'], options['min weight'], options['steps']) # polydata = mesh.to_vtk() # polydata.SetSource(None) # polydata.DebugOn() # else: # #smoother = vtk.vtkWindowedSincPolyDataFilter() # send_message('Smoothing ...') # smoother = vtk.vtkSmoothPolyDataFilter() # smoother_ref = weakref.ref(smoother) # # smoother_ref().AddObserver("ProgressEvent", lambda obj,evt: # # UpdateProgress(smoother_ref(), _("Creating 3D surface..."))) # smoother.SetInputData(polydata) # smoother.SetNumberOfIterations(smooth_iterations) # smoother.SetRelaxationFactor(smooth_relaxation_factor) # smoother.SetFeatureAngle(80) # #smoother.SetEdgeAngle(90.0) # #smoother.SetPassBand(0.1) # smoother.BoundarySmoothingOn() # smoother.FeatureEdgeSmoothingOn() # #smoother.NormalizeCoordinatesOn() # #smoother.NonManifoldSmoothingOn() # # smoother.ReleaseDataFlagOn() # # smoother.GetOutput().ReleaseDataFlagOn() # smoother.Update() # del polydata # polydata = smoother.GetOutput() # #polydata.Register(None) # # polydata.SetSource(None) # del smoother if not decimate_reduction: print("Decimating", decimate_reduction) send_message('Decimating ...') decimation = vtk.vtkQuadricDecimation() # decimation.ReleaseDataFlagOn() decimation.SetInputData(polydata) decimation.SetTargetReduction(decimate_reduction) decimation_ref = weakref.ref(decimation) # decimation_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(decimation_ref(), _("Creating 3D surface..."))) #decimation.PreserveTopologyOn() #decimation.SplittingOff() #decimation.BoundaryVertexDeletionOff() # decimation.GetOutput().ReleaseDataFlagOn() decimation.Update() del polydata polydata = decimation.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del decimation #to_measure.Register(None) # to_measure.SetSource(None) if keep_largest: send_message('Finding the largest ...') conn = vtk.vtkPolyDataConnectivityFilter() conn.SetInputData(polydata) conn.SetExtractionModeToLargestRegion() conn_ref = weakref.ref(conn) # conn_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(conn_ref(), _("Creating 3D surface..."))) conn.Update() # conn.GetOutput().ReleaseDataFlagOn() del polydata polydata = conn.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del conn #Filter used to detect and fill holes. Only fill boundary edges holes. #TODO: Hey! This piece of code is the same from #polydata_utils.FillSurfaceHole, we need to review this. if fill_holes: send_message('Filling holes ...') filled_polydata = vtk.vtkFillHolesFilter() # filled_polydata.ReleaseDataFlagOn() filled_polydata.SetInputData(polydata) filled_polydata.SetHoleSize(300) filled_polydata_ref = weakref.ref(filled_polydata) # filled_polydata_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(filled_polydata_ref(), _("Creating 3D surface..."))) filled_polydata.Update() # filled_polydata.GetOutput().ReleaseDataFlagOn() del polydata polydata = filled_polydata.GetOutput() #polydata.Register(None) # polydata.SetSource(None) # polydata.DebugOn() del filled_polydata to_measure = polydata normals = vtk.vtkPolyDataNormals() # normals.ReleaseDataFlagOn() # normals_ref = weakref.ref(normals) # normals_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(normals_ref(), _("Creating 3D surface..."))) normals.SetInputData(polydata) normals.SetFeatureAngle(80) normals.SplittingOn() normals.AutoOrientNormalsOn() normals.NonManifoldTraversalOn() normals.ComputeCellNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.Update() del polydata polydata = normals.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del normals # # Improve performance # stripper = vtk.vtkStripper() # # stripper.ReleaseDataFlagOn() # # stripper_ref = weakref.ref(stripper) # # stripper_ref().AddObserver("ProgressEvent", lambda obj,evt: # # UpdateProgress(stripper_ref(), _("Creating 3D surface..."))) # stripper.SetInputData(polydata) # stripper.PassThroughCellIdsOn() # stripper.PassThroughPointIdsOn() # # stripper.GetOutput().ReleaseDataFlagOn() # stripper.Update() # del polydata # polydata = stripper.GetOutput() # #polydata.Register(None) # # polydata.SetSource(None) # del stripper send_message('Calculating area and volume ...') measured_polydata = vtk.vtkMassProperties() measured_polydata.SetInputData(to_measure) measured_polydata.Update() volume = float(measured_polydata.GetVolume()) area = float(measured_polydata.GetSurfaceArea()) del measured_polydata filename = tempfile.mktemp(suffix='_full.vtp') writer = vtk.vtkXMLPolyDataWriter() writer.SetInputData(polydata) writer.SetFileName(filename) writer.Write() del writer print("MY PID", os.getpid()) return filename, {'volume': volume, 'area': area}
domain_locator = vtk.vtkPointLocator() domain_locator.SetDataSet(domain) domain_locator.BuildLocator() velocity_arr = np.zeros((npts,3)) velocity_vtk = numpy_support.numpy_to_vtk(velocity_arr) velocity_vtk.SetName("velocity") frobenius_arr = np.zeros((npts,1)) frobenius_vtk = numpy_support.numpy_to_vtk(frobenius_arr) frobenius_vtk.SetName("frobenius") disp_arr = np.zeros((npts,3)) disp_vtk = numpy_support.numpy_to_vtk(disp_arr) disp_vtk.SetName("displacement") domain.GetPointData().AddArray(velocity_vtk) domain.GetPointData().AddArray(frobenius_vtk) # Get wall normals to compute inward velocity array surface_reader = vtk.vtkXMLPolyDataReader() surface_reader.SetFileName("rp-sp.vtp") surface_reader.Update() surface_normals = vtk.vtkPolyDataNormals() surface_normals.SetInputConnection(surface_reader.GetOutputPort()) surface_normals.Update() surface_normals_locator = vtk.vtkPointLocator() surface_normals_locator.SetDataSet(surface_normals.GetOutput()) surface_normals_locator.BuildLocator() allwnodes = open("allwnodes.nbc", 'r') cnt_lines = 0 allwnodes_list = [] for line in allwnodes: allwnodes_list.append(int(line.split()[0])) allwnodes_list = list(set(allwnodes_list)) # remove duplicates allwnodes_list.sort()
def _load_vtp(filepath, fieldname=None, point_arrays=[], cell_arrays=[]): reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filepath) reader.Update() return to_mesh_state(reader.GetOutput(), fieldname, point_arrays, cell_arrays)
def ReadPolyData(filename): reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filename) reader.Update() return reader.GetOutput()
style = vtkInteractorStyleTrackballCamera() render_window_interactor = vtkRenderWindowInteractor() render_window_interactor.SetRenderWindow(render_window) render_window_interactor.SetInteractorStyle(style) scene_a_readers = {} scene_a_mappers = {} scene_a_actors = {} scene_b_readers = {} scene_b_mappers = {} scene_b_actors = {} for i in scene_elements: ## Create and set the models readers scene_a_readers[i] = vtkXMLPolyDataReader() scene_a_readers[i].SetFileName(vars(args)[i + '_a']) scene_b_readers[i] = vtkXMLPolyDataReader() scene_b_readers[i].SetFileName(vars(args)[i + '_b']) scene_a_mappers[i] = vtkPolyDataMapper() scene_a_mappers[i].SetInputConnection( scene_a_readers[i].GetOutputPort()) scene_b_mappers[i] = vtkPolyDataMapper() scene_b_mappers[i].SetInputConnection( scene_b_readers[i].GetOutputPort()) scene_a_actors[i] = vtkActor() scene_a_actors[i].SetMapper(scene_a_mappers[i])
def _load_vtp(filepath, fieldname=None): reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filepath) reader.Update() if fieldname == None: return to_mesh_state(reader.GetOutput()) else: return to_mesh_state(reader.GetOutput(), fieldname)
def main(): ''' :return: The render window interactor. ''' nc = vtk.vtkNamedColors() # Provide some geometry resolution = 3 plane11 = vtk.vtkPlaneSource() plane11.SetXResolution(resolution) plane11.SetYResolution(resolution) plane12 = vtk.vtkPlaneSource() plane12.SetXResolution(resolution) plane12.SetYResolution(resolution) tableSize = max(resolution * resolution + 1, 10) # Force an update so we can set cell data plane11.Update() plane12.Update() # Get the lookup tables mapping cell data to colors lut1 = MakeLUT(tableSize) lut2 = MakeLUTFromCTF(tableSize) colorData1 = vtk.vtkUnsignedCharArray() colorData1.SetName('colors') # Any name will work here. colorData1.SetNumberOfComponents(3) print('Using a lookup table from a set of named colors.') MakeCellData(tableSize, lut1, colorData1) # Then use SetScalars() to add it to the vtkPolyData structure, # this will then be interpreted as a color table. plane11.GetOutput().GetCellData().SetScalars(colorData1) colorData2 = vtk.vtkUnsignedCharArray() colorData2.SetName('colors') # Any name will work here. colorData2.SetNumberOfComponents(3) print('Using a lookup table created from a color transfer function.') MakeCellData(tableSize, lut2, colorData2) plane12.GetOutput().GetCellData().SetScalars(colorData2) # Set up actor and mapper mapper11 = vtk.vtkPolyDataMapper() mapper11.SetInputConnection(plane11.GetOutputPort()) # Now, instead of doing this: # mapper11.SetScalarRange(0, tableSize - 1) # mapper11.SetLookupTable(lut1) # We can just use the color data that we created from the lookup table and # assigned to the cells: mapper11.SetScalarModeToUseCellData() mapper11.Update() mapper12 = vtk.vtkPolyDataMapper() mapper12.SetInputConnection(plane12.GetOutputPort()) mapper12.SetScalarModeToUseCellData() mapper12.Update() writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName('pdlut.vtp') writer.SetInputData(mapper11.GetInput()) # This is set so we can see the data in a text editor. writer.SetDataModeToAscii() writer.Write() writer.SetFileName('pdctf.vtp') writer.SetInputData(mapper12.GetInput()) writer.Write() actor11 = vtk.vtkActor() actor11.SetMapper(mapper11) actor12 = vtk.vtkActor() actor12.SetMapper(mapper12) # Let's read in the data we wrote out. reader1 = vtk.vtkXMLPolyDataReader() reader1.SetFileName("pdlut.vtp") reader2 = vtk.vtkXMLPolyDataReader() reader2.SetFileName("pdctf.vtp") mapper21 = vtk.vtkPolyDataMapper() mapper21.SetInputConnection(reader1.GetOutputPort()) mapper21.SetScalarModeToUseCellData() mapper21.Update() actor21 = vtk.vtkActor() actor21.SetMapper(mapper11) mapper22 = vtk.vtkPolyDataMapper() mapper22.SetInputConnection(reader2.GetOutputPort()) mapper22.SetScalarModeToUseCellData() mapper22.Update() actor22 = vtk.vtkActor() actor22.SetMapper(mapper22) # Define viewport ranges. # (xmin, ymin, xmax, ymax) viewport11 = [0.0, 0.0, 0.5, 0.5] viewport12 = [0.0, 0.5, 0.5, 1.0] viewport21 = [0.5, 0.0, 1.0, 0.5] viewport22 = [0.5, 0.5, 1.0, 1.0] # Set up the renderers. ren11 = vtk.vtkRenderer() ren12 = vtk.vtkRenderer() ren21 = vtk.vtkRenderer() ren22 = vtk.vtkRenderer() # Setup the render windows renWin = vtk.vtkRenderWindow() renWin.SetSize(800, 800) renWin.AddRenderer(ren11) renWin.AddRenderer(ren12) renWin.AddRenderer(ren21) renWin.AddRenderer(ren22) ren11.SetViewport(viewport11) ren12.SetViewport(viewport12) ren21.SetViewport(viewport21) ren22.SetViewport(viewport22) ren11.SetBackground(nc.GetColor3d('MidnightBlue')) ren12.SetBackground(nc.GetColor3d('MidnightBlue')) ren21.SetBackground(nc.GetColor3d('MidnightBlue')) ren22.SetBackground(nc.GetColor3d('MidnightBlue')) ren11.AddActor(actor11) ren12.AddActor(actor12) ren21.AddActor(actor21) ren22.AddActor(actor22) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renWin.Render() return iren
mesher.load_model(file_name) print("Load model: " + file_name) ## Compute model boundary faces. # # If the model has faces already computed (i.e. has 'ModelFaceID' array) then # don't call this, the face IDs will no longer match the original face IDs. #mesher.compute_model_boundary_faces(angle=60.0) face_ids = mesher.get_model_face_ids() print("Mesh face info: " + str(face_ids)) # Read centerlines. if True: #if False: centerlines_file = str(data_path / 'meshing' / 'demo-centerlines.vtp') reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(centerlines_file) reader.Update() centerlines = reader.GetOutput() # Compute centerlines. else: centerlines = mesher.compute_centerlines() ## Set general meshing options. options = sv.meshing.TetGenOptions(global_edge_size=0.4, surface_mesh_flag=True, volume_mesh_flag=True) options.optimization = 3 options.quality_ratio = 1.4 #options.use_mmg = True
def read_vtp(filepath): reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filepath) reader.Update() return reader.GetOutput()
default="0.5,0.5", dest="prts", help= "p1,p2: z_out = p1*z1 + p2*z2. Ie, take p1 parts of infile1 and p2 parts of infile2. Usually p1+p2=1.0. Default=%default" ) (opts, args) = p.parse_args() # get the com filename if len(args) != 3: p.print_help() sys.exit(1) (bot_file, top_file, vtp_out) = args if opts.verbose: print "Reading", bot_file if bot_file.endswith(".vtp"): bot = vtk.vtkXMLPolyDataReader() elif bot_file.endswith(".vts"): bot = vtk.vtkXMLStructuredGridReader() else: print "This program has not yet been configured to read", bot_file p.print_help() sys.exit(2) bot.SetFileName(bot_file) bot.Update() bot = bot.GetOutput() if opts.verbose: print "Reading", top_file if top_file.endswith(".vtp"): top = vtk.vtkXMLPolyDataReader()
def main(): colors = vtk.vtkNamedColors() fileName, numberOfCuts = get_program_parameters() reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(fileName) reader.Update() bounds = reader.GetOutput().GetBounds() print('Bounds:', ', '.join(['{:.3f}'.format(f) for f in bounds])) plane = vtk.vtkPlane() plane.SetOrigin((bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, bounds[4]) plane.SetNormal(0, 0, 1) # Create cutter high = plane.EvaluateFunction((bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, bounds[5]) cutter = vtk.vtkCutter() cutter.SetInputConnection(reader.GetOutputPort()) cutter.SetCutFunction(plane) cutter.GenerateValues(numberOfCuts, 0.99, 0.99 * high) cutterMapper = vtk.vtkPolyDataMapper() cutterMapper.SetInputConnection(cutter.GetOutputPort()) cutterMapper.ScalarVisibilityOff() # Create cut actor cutterActor = vtk.vtkActor() cutterActor.GetProperty().SetColor(colors.GetColor3d('Banana')) cutterActor.GetProperty().SetLineWidth(2) cutterActor.SetMapper(cutterMapper) # Create model actor modelMapper = vtk.vtkPolyDataMapper() modelMapper.SetInputConnection(reader.GetOutputPort()) modelMapper.ScalarVisibilityOff() modelActor = vtk.vtkActor() modelActor.GetProperty().SetColor(colors.GetColor3d('Flesh')) modelActor.SetMapper(modelMapper) # Create renderers and add actors of plane and model renderer = vtk.vtkRenderer() renderer.AddActor(cutterActor) renderer.AddActor(modelActor) # Add renderer to renderwindow and render renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetSize(600, 600) renderWindow.SetWindowName('CutWithCutFunction') interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderer.SetBackground(colors.GetColor3d('Burlywood')) renderer.GetActiveCamera().SetPosition(0, -1, 0) renderer.GetActiveCamera().SetFocalPoint(0, 0, 0) renderer.GetActiveCamera().SetViewUp(0, 0, 1) renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(30) renderer.ResetCamera() renderWindow.Render() interactor.Start()
def vis2hdf5(fname, step_start, step_stop, step_step, mesh_fname, surface_fname, extract_velocity_only, compute_lambdatwo): comm = mpi4py.MPI.COMM_WORLD rank = comm.Get_rank() def printRankZero(message): if rank == 0: tqdm.tqdm.write(message) nprocs = comm.Get_size() nsteps = old_div((step_stop - step_start + step_step), step_step) nstepsperproc = old_div(nsteps, nprocs) rest = nsteps % nprocs if rest: nstepsperproc += 1 curstep_start = step_start mesh_reader = vtk.vtkXMLUnstructuredGridReader() mesh_reader.SetFileName(mesh_fname) mesh_reader.Update() if not extract_velocity_only: surface_data = vtk.vtkXMLPolyDataReader() surface_data.SetFileName(surface_fname) surface_data.Update() surface_npts = surface_data.GetOutput().GetNumberOfPoints() npts = mesh_reader.GetOutput().GetNumberOfPoints() ncells = mesh_reader.GetOutput().GetNumberOfCells() # Open results file and in dictionary declare computed fields (name:n_of_components) printRankZero("Preparing hdf5 file...") fout = h5py.File("%s.h5" % fname, 'w', driver='mpio', comm=comm) groups = { "pressure": 1, "velocity": 3, "wall shear stress": 3, "traction": 3, "displacement": 3, "displacement_ref": 3, "frobenius": 1, "lambda two": 1, } # Create groups and datasets # Creating group and datasets are collective operations, all processes need to do it for group in groups: fout.create_group(group) for i in range(step_start, step_stop + step_step, step_step): fout[group].create_dataset("%d" % i, (npts, groups[group]), dtype='float64') # Create Mesh topology and coordinates printRankZero("Adding mesh data to hdf5 file...") fout.create_group("Mesh") fout["Mesh"].create_dataset("topology", (ncells, 4), dtype='int64') fout["Mesh"].create_dataset("coordinates", (npts, 3), dtype='float64') curnsteps = nstepsperproc if rank >= rest and rest: curnsteps -= 1 curstep_start += rest * (curnsteps + 1) * step_step + ( rank - rest) * curnsteps * step_step else: curstep_start += rank * curnsteps * step_step tmp_tawss = np.zeros(npts) tmp_wssint = np.zeros((npts, 3)) tmp_lambdatwo = np.zeros((npts, 1)) tmp_frobenius = np.zeros((npts, 1)) ######################################################### ####### PARSE VIS FILES ################################# ######################################################### arrayAttached = False for timestep_index in tqdm.trange(curstep_start, curstep_start + curnsteps * step_step, step_step, desc="Rank {}".format(rank)): currentVisFileName = "%s-%d.vis" % (fname, timestep_index) tqdm.tqdm.write("Rank {} Reading file {}.".format( rank, currentVisFileName)) startTime = time.time() fin = open(currentVisFileName, 'r') current_fin_line_index = 0 fin_duplicate_for_pandas = open(currentVisFileName, 'r') while True: # Get Group Name for line in fin: current_fin_line_index += 1 line_split = line.split('"') if (" analysis results " in line_split): break if line == '\n': break # Reached end of file" group_name = line_split[-2] if group_name not in fout: tqdm.tqdm.write("ERROR: GROUP '%s' IS NOT ON YOUR LIST" % group_name) # Determine size of vector and initialize line_split = (next(fin)).split() current_fin_line_index += 1 npts = int(line_split[-1]) for line in fin: current_fin_line_index += 1 line_split = line.split() if "length" in line_split: break ncols = int(line_split[-1]) # Get to the data for line in fin: current_fin_line_index += 1 line_split = line.split() if "data" in line_split: break #for j in xrange(npts): #tmp_vec[j] = [float(x) for x in fin.next().split()] tqdm.tqdm.write(group_name) if extract_velocity_only: if group_name == "velocity": read_datafield = copyFromVisToHdf5( fin_duplicate_for_pandas, npts, current_fin_line_index, group_name, timestep_index, ncols, fout) # break else: read_datafield = copyFromVisToHdf5(fin_duplicate_for_pandas, npts, current_fin_line_index, group_name, timestep_index, ncols, fout) # print "shape", np.shape(read_datafield) if group_name == "wall shear stress" and not extract_velocity_only: tmp_tawss += np.linalg.norm(read_datafield, axis=1) tmp_wssint += read_datafield if group_name == "velocity": # Compute gradient of velocity tmp_vec_vtk = None ctemp = np.ascontiguousarray(read_datafield) tmp_vec_vtk = numpy_support.numpy_to_vtk(ctemp) tmp_vec_vtk.SetName("tmp_velocity") mesh_reader = vtk.vtkXMLUnstructuredGridReader() mesh_reader.SetFileName(mesh_fname) mesh_reader.Update() mesh_reader.GetOutput().GetPointData().AddArray(tmp_vec_vtk) gradient_filter = vtk.vtkGradientFilter() gradient_filter.SetInputConnection(mesh_reader.GetOutputPort()) gradient_filter.SetInputScalars(0, "tmp_velocity") gradient_filter.SetResultArrayName("tmp_velocity_gradient") gradient_filter.Update() tmp_vel_gradient = numpy_support.vtk_to_numpy( gradient_filter.GetOutput().GetPointData().GetArray( "tmp_velocity_gradient")) tmp_vel_gradient = np.reshape(tmp_vel_gradient, (npts, 3, 3)) tmp_vel_gradient_t = np.transpose(tmp_vel_gradient, (0, 2, 1)) tmp_S = 0.5 * (tmp_vel_gradient + tmp_vel_gradient_t) tmp_frobenius[:] = np.reshape( np.linalg.norm(tmp_S, axis=(1, 2)), (npts, 1)) fout["/frobenius/%d" % (timestep_index, )][:] = tmp_frobenius if compute_lambdatwo: tmp_W = 0.5 * (tmp_vel_gradient - tmp_vel_gradient_t) tmp_S2 = np.einsum('abj,ajc->abc', tmp_S, tmp_S) tmp_W2 = np.einsum('abj,ajc->abc', tmp_W, tmp_W) eigvals = np.linalg.eigvals(tmp_S2 + tmp_W2) eigvals = np.sort(eigvals, axis=1) tmp_lambdatwo = eigvals[:, 1] fout["/lambda two/%d" % (timestep_index, )][:] = np.reshape( tmp_lambdatwo, (npts, 1)) if extract_velocity_only: break #?? not sure whether necessary fin.close() tqdm.tqdm.write("Elapsed time Rank {}: {}".format( rank, time.time() - startTime)) ####### END OF PARSING ################################# printRankZero("Finished reading vis files.") # Average indices TAWSS and OSI can be conveniently computed through reduction operations if rank == 0: total_tawss = np.zeros(npts) total_wssint = np.zeros((npts, 3)) else: total_tawss = None total_wssint = None comm.Reduce([tmp_tawss, mpi4py.MPI.DOUBLE], [total_tawss, mpi4py.MPI.DOUBLE], op=mpi4py.MPI.SUM, root=0) comm.Reduce([tmp_wssint, mpi4py.MPI.DOUBLE], [total_wssint, mpi4py.MPI.DOUBLE], op=mpi4py.MPI.SUM, root=0) if extract_velocity_only: printRankZero("NOT Adding TAWSS and OSI data to hdf5 file...") else: printRankZero("Adding TAWSS and OSI data to hdf5 file...") fout.create_group("TAWSS") fout["TAWSS"].create_dataset("0", (npts, ), dtype='float64') fout.create_group("WSSINT") fout["WSSINT"].create_dataset("0", (npts, 3), dtype='float64') fout.create_group("OSI") fout["OSI"].create_dataset("0", (npts, ), dtype='float64') if rank == 0: if not extract_velocity_only: # Also add TAWSS and OSI to HDF5 file total_tawss /= nsteps total_wssint /= nsteps idx_ok = np.where(total_tawss > 1e-6) total_wssint_norm = np.linalg.norm(total_wssint, axis=1) total_osi = np.zeros(npts) total_osi[idx_ok] = 0.5 * ( 1.0 - old_div(total_wssint_norm[idx_ok], total_tawss[idx_ok])) fout["/TAWSS/0"][:] = total_tawss fout["/OSI/0"][:] = total_osi fout["/WSSINT/0"][:] = total_wssint pts = numpy_support.vtk_to_numpy( mesh_reader.GetOutput().GetPoints().GetData()) cells = numpy_support.vtk_to_numpy( mesh_reader.GetOutput().GetCells().GetData()) cells = np.reshape(cells, (ncells, 5)) cells = cells[:, 1:] fout["/Mesh/coordinates"][:] = pts fout["/Mesh/topology"][:] = cells if not extract_velocity_only: mesh_locator = vtk.vtkPointLocator() mesh_locator.SetDataSet(mesh_reader.GetOutput()) mesh_locator.BuildLocator() map_surface_to_mesh = np.zeros(surface_npts, dtype=np.int64) for i in range(surface_npts): pt = surface_data.GetOutput().GetPoint(i) closept = mesh_locator.FindClosestPoint(pt) map_surface_to_mesh[i] = closept tawss_surface = total_tawss[map_surface_to_mesh] osi_surface = total_osi[map_surface_to_mesh] wssint_surface = total_wssint[map_surface_to_mesh] tawss_surface_vtk = numpy_support.numpy_to_vtk(tawss_surface) tawss_surface_vtk.SetName("TAWSS") osi_surface_vtk = numpy_support.numpy_to_vtk(osi_surface) osi_surface_vtk.SetName("OSI") wssint_surface_vtk = numpy_support.numpy_to_vtk(wssint_surface) wssint_surface_vtk.SetName("WSSINT") # Save the WSS based indices in VTK polydata format surface_data.GetOutput().GetPointData().AddArray(tawss_surface_vtk) surface_data.GetOutput().GetPointData().AddArray(osi_surface_vtk) surface_data.GetOutput().GetPointData().AddArray( wssint_surface_vtk) surface_writer = vtk.vtkXMLPolyDataWriter() surface_writer.SetInputConnection(surface_data.GetOutputPort()) surface_writer.SetFileName("%s-wss.vtp" % fname) surface_writer.Update() # Write XDMF File for visualization in Paraview xdmf_out = open("%s.xdmf" % fname, 'w') # Header xdmf_out.write("""<?xml version="1.0"?> <Xdmf Version="2.0" xmlns:xi="http://www.w3.org/2001/XInclude"> <Domain> <Grid Name="TimeSeries" GridType="Collection" CollectionType="Temporal"> <Time TimeType="List">\n""") # Line of timesteps timesteps_str = ' '.join( str(i) for i in range(step_start, step_stop + step_step, step_step)) xdmf_out.write( '<DataItem Format="XML" Dimensions="%d">%s</DataItem>\n</Time>' % (nsteps, timesteps_str)) # For each timestep point to grid topology and geometry, and attributes for i in range(step_start, step_stop + step_step, step_step): xdmf_out.write('<Grid Name="grid_%d" GridType="Uniform">\n' % i) xdmf_out.write( '<Topology NumberOfElements="%d" TopologyType="Tetrahedron">\n' % ncells) xdmf_out.write( '<DataItem Format="HDF" Dimensions="%d 4">%s.h5:/Mesh/topology</DataItem>\n' % (ncells, fname)) xdmf_out.write('</Topology>\n<Geometry GeometryType="XYZ">\n') xdmf_out.write( '<DataItem Format="HDF" Dimensions="%d 3">%s.h5:/Mesh/coordinates</DataItem>\n' % (npts, fname)) xdmf_out.write('</Geometry>\n') for group in groups: if groups[group] == 1: xdmf_out.write( '<Attribute Name="%s" AttributeType="Scalar" Center="Node">\n' % group) if groups[group] == 3: xdmf_out.write( '<Attribute Name="%s" AttributeType="Vector" Center="Node">\n' % group) xdmf_out.write( '<DataItem Format="HDF" Dimensions="%d %d">%s.h5:/%s/%d</DataItem>\n' % (npts, groups[group], fname, group, i)) xdmf_out.write('</Attribute>\n') xdmf_out.write('</Grid>\n') xdmf_out.write('</Grid>\n</Domain>\n</Xdmf>') xdmf_out.close() fout.close()
def read_vtp(input_file): reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(input_file) reader.Update() return reader.GetOutput()
def main(): colors = vtk.vtkNamedColors() sphereSource = vtk.vtkSphereSource() sphereSource.SetCenter(0.0, 0.0, 0.0) sphereSource.SetRadius(5) # Read poly data from vtp file reader = vtk.vtkXMLPolyDataReader() reader.SetFileName("data/diskout.vtp") reader.Update() poly_data = reader.GetOutput() print("check for poly data read") print(type(poly_data)) # Trial setting a 3D mesh for loaded poly data using Delaunay method dela = vtk.vtkDelaunay3D() print("vtkDelaunay3D variable set") dela.SetInputData(poly_data) print("input data set") # dela.SetTolerance(1) print("tolerance set") mapMesh = vtk.vtkPolyDataMapper() print("vtk poly data mapper set for mesh") mapMesh.SetInputConnection(dela.GetOutputPort()) print("mapper input data set with mesh - through output port") meshActor = vtk.vtkActor() print("mesh actor set") meshActor.SetMapper(mapMesh) print("mesh actor set with mesh mapper") meshActor.GetProperty().SetColor(colors.GetColor3d('MidnightBlue')) print("mesh actor set with blue color") # Trial for volume calculation using the mass poroperties # mass = vtk.vtkMassProperties() # mass.SetInputData(dela) # volume = mass.GetVolume() # print("show the volume of model") # print(volume) # print() # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() # mapper.SetInputConnection(sphereSource.GetOutputPort()) # Changed mapper to read data from loaded vtp file mapper.SetInputData(poly_data) actor = vtk.vtkActor() # Set different mapper - the one with mesh - for rendering actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d('Bisque')) # Setup a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() # renderWindow.SetWindowName("Test") renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actor to the scene renderer.AddActor(actor) # Add the actor of mesh to the scene print("before addition of mesh actor - checking it") print(type(meshActor)) print("for reference check the std actor") print(type(actor)) print() # renderer.AddActor(meshActor) renderer.SetBackground(colors.GetColor3d('Black')) # Render and interact renderWindow.Render() # *** SetWindowName after renderWindow.Render() is called *** renderWindow.SetWindowName("Test") renderWindowInteractor.Start()
def main(): inputFilename, numberOfCuts = get_program_parameters() colors = vtk.vtkNamedColors() reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(inputFilename) reader.Update() bounds = reader.GetOutput().GetBounds() print(bounds) plane = vtk.vtkPlane() plane.SetOrigin((bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, (bounds[5] + bounds[4]) / 2.0) plane.SetNormal(0, 0, 1) # Create Scalars. scalars = vtk.vtkDoubleArray() numberOfPoints = reader.GetOutput().GetNumberOfPoints() scalars.SetNumberOfTuples(numberOfPoints) pts = reader.GetOutput().GetPoints() for i in range(0, numberOfPoints): point = pts.GetPoint(i) scalars.SetTuple1(i, plane.EvaluateFunction(point)) reader.GetOutput().GetPointData().SetScalars(scalars) reader.GetOutput().GetPointData().GetScalars().GetRange() # Create the cutter. cutter = vtk.vtkContourFilter() cutter.SetInputConnection(reader.GetOutputPort()) cutter.ComputeScalarsOff() cutter.ComputeNormalsOff() cutter.GenerateValues( numberOfCuts, 0.99 * reader.GetOutput().GetPointData().GetScalars().GetRange()[0], 0.99 * reader.GetOutput().GetPointData().GetScalars().GetRange()[1]) cutterMapper = vtk.vtkPolyDataMapper() cutterMapper.SetInputConnection(cutter.GetOutputPort()) cutterMapper.ScalarVisibilityOff() # Create the cut actor. cutterActor = vtk.vtkActor() cutterActor.GetProperty().SetColor(colors.GetColor3d('Banana')) cutterActor.GetProperty().SetLineWidth(2) cutterActor.SetMapper(cutterMapper) # Create the model actor modelMapper = vtk.vtkPolyDataMapper() modelMapper.SetInputConnection(reader.GetOutputPort()) modelMapper.ScalarVisibilityOff() modelActor = vtk.vtkActor() modelActor.GetProperty().SetColor(colors.GetColor3d('Flesh')) modelActor.SetMapper(modelMapper) # Create renderers and add the plane and model actors. renderer = vtk.vtkRenderer() renderer.AddActor(cutterActor) renderer.AddActor(modelActor) # Add renderer to renderwindow and render renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetSize(600, 600) renderWindow.SetWindowName('CutWithCutScalars') interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderer.SetBackground(colors.GetColor3d('Burlywood')) renderer.GetActiveCamera().SetPosition(0, -1, 0) renderer.GetActiveCamera().SetFocalPoint(0, 0, 0) renderer.GetActiveCamera().SetViewUp(0, 0, 1) renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(30) renderer.ResetCamera() renderWindow.Render() interactor.Start()
def visualizeNewSrep(self, filename): """ Parse header.xml file, create models from the data, and visualize it. """ # 1. parse header file tree = ET.parse(filename) upFileName = '' crestFileName = '' downFileName = '' nCols = 0 nRows = 0 headerFolder = os.path.dirname(filename) for child in tree.getroot(): if child.tag == 'upSpoke': if os.path.isabs(child.text): upFileName = os.path.join(headerFolder, child.text) upFileName = os.path.join(headerFolder, child.text) elif child.tag == 'downSpoke': downFileName = os.path.join(headerFolder, child.text) elif child.tag == 'crestSpoke': crestFileName = os.path.join(headerFolder, child.text) elif child.tag == 'nRows': nRows = (int)(child.text) elif child.tag == 'nCols': nCols = (int)(child.text) logging.info("upSpoke file: " + upFileName) logging.info("downSpoke file: " + downFileName) logging.info("crestSpoke file: " + crestFileName) reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(upFileName) reader.Update() upSpokes = reader.GetOutput() upPointData = upSpokes.GetPointData() numberOfArrays = upPointData.GetNumberOfArrays() if numberOfArrays is 0: logging.warning("File: " + upFileName + " does not contain data") # medial_polyData = upSpokes # this is poly data for skeleton scene = slicer.mrmlScene # base line of medial sheet fidDisplayNode = slicer.vtkMRMLMarkupsDisplayNode() scene.AddNode(fidDisplayNode) fidNode = slicer.vtkMRMLMarkupsFiducialNode() # If we would have more than 100 fiducial points (meant for editing points) better to use a regular MRMLModelNode # In the future, we would like the user to be able to move the nodes, and the connected structures to update accordingly. # Meanwhile, we lock the moving. fidNode.SetLocked(True) fidDisplayNode.SetGlyphScale(0.01) fidDisplayNode.SetSelectedColor(1.0, 1.0, 0.0) fidDisplayNode.SetTextScale(0.0) scene.AddNode(fidNode) fidNode.SetAndObserveDisplayNodeID(fidDisplayNode.GetID()) # \TODO come up with better name later # prepare for arrows for upspokes upSpoke_points = vtk.vtkPoints() upSpoke_lines = vtk.vtkCellArray() arr_length = upPointData.GetArray('spokeLength') arr_dirs = upPointData.GetArray('spokeDirection') for i in range(upSpokes.GetNumberOfPoints()): pt = [0] * 3 upSpokes.GetPoint(i, pt) # base point of up arrows id0 = upSpoke_points.InsertNextPoint(pt) # head of up arrows spoke_length = arr_length.GetValue(i) baseIdx = i * 3 dirX = arr_dirs.GetValue(baseIdx) dirY = arr_dirs.GetValue(baseIdx + 1) dirZ = arr_dirs.GetValue(baseIdx + 2) pt1 = [0] * 3 pt1[0] = pt[0] + spoke_length * dirX pt1[1] = pt[1] + spoke_length * dirY pt1[2] = pt[2] + spoke_length * dirZ id1 = upSpoke_points.InsertNextPoint(pt1) up_arrow = vtk.vtkLine() up_arrow.GetPointIds().SetId(0, id0) up_arrow.GetPointIds().SetId(1, id1) upSpoke_lines.InsertNextCell(up_arrow) fidNode.AddFiducial(pt[0], pt[1], pt[2]) # boundary_point_ids = [] # model node for medial mesh medial_model = slicer.vtkMRMLModelNode() medial_model.SetScene(scene) medial_model.SetName("Medial Mesh") medial_model.SetAndObservePolyData(reader.GetOutput()) # model display node for the medial mesh medial_model_display = slicer.vtkMRMLModelDisplayNode() medial_model_display.SetColor(0, 0.5, 0) medial_model_display.SetScene(scene) medial_model_display.SetLineWidth(3.0) medial_model_display.SetRepresentation(1) medial_model_display.SetBackfaceCulling(0) scene.AddNode(medial_model_display) medial_model.SetAndObserveDisplayNodeID(medial_model_display.GetID()) scene.AddNode(medial_model) # model node for up spoke (poly data for arrows) upSpoke_polyData = vtk.vtkPolyData() upSpoke_polyData.SetPoints(upSpoke_points) upSpoke_polyData.SetLines(upSpoke_lines) upSpoke_model = slicer.vtkMRMLModelNode() upSpoke_model.SetScene(scene) upSpoke_model.SetName("Top Spoke") upSpoke_model.SetAndObservePolyData(upSpoke_polyData) # model display node for the top spoke # cyan for the top spoke upSpoke_model_display = slicer.vtkMRMLModelDisplayNode() upSpoke_model_display.SetColor(0, 1, 1) upSpoke_model_display.SetScene(scene) upSpoke_model_display.SetLineWidth(3.0) upSpoke_model_display.SetBackfaceCulling(0) scene.AddNode(upSpoke_model_display) upSpoke_model.SetAndObserveDisplayNodeID(upSpoke_model_display.GetID()) scene.AddNode(upSpoke_model) # prepare for down spokes reader.SetFileName(downFileName) reader.Update() downSpokes = reader.GetOutput() downSpoke_polyData = vtk.vtkPolyData() downSpoke_lines = vtk.vtkCellArray() downSpoke_points = vtk.vtkPoints() downPointData = downSpokes.GetPointData() arr_length = downPointData.GetArray('spokeLength') arr_dirs = downPointData.GetArray('spokeDirection') for i in range(downSpokes.GetNumberOfPoints()): # tail of arrows pt_tail = [0] * 3 downSpokes.GetPoint(i, pt_tail) id0 = downSpoke_points.InsertNextPoint(pt_tail) # head of arrows pt_head = [0] * 3 spoke_length = arr_length.GetValue(i) baseIdx = i * 3 dirX = arr_dirs.GetValue(baseIdx) dirY = arr_dirs.GetValue(baseIdx + 1) dirZ = arr_dirs.GetValue(baseIdx + 2) pt_head[0] = pt_tail[0] + spoke_length * dirX pt_head[1] = pt_tail[1] + spoke_length * dirY pt_head[2] = pt_tail[2] + spoke_length * dirZ id1 = downSpoke_points.InsertNextPoint(pt_head) # connection between head and tail con = vtk.vtkLine() con.GetPointIds().SetId(0, id0) con.GetPointIds().SetId(1, id1) downSpoke_lines.InsertNextCell(con) downSpoke_polyData.SetPoints(downSpoke_points) downSpoke_polyData.SetLines(downSpoke_lines) downSpoke_model = slicer.vtkMRMLModelNode() downSpoke_model.SetScene(scene) downSpoke_model.SetName("Bottom Spoke") downSpoke_model.SetAndObservePolyData(downSpoke_polyData) # model display node for the down spoke downSpoke_model_display = slicer.vtkMRMLModelDisplayNode() downSpoke_model_display.SetColor(1, 0, 1) downSpoke_model_display.SetScene(scene) downSpoke_model_display.SetLineWidth(3.0) downSpoke_model_display.SetBackfaceCulling(0) scene.AddNode(downSpoke_model_display) downSpoke_model.SetAndObserveDisplayNodeID( downSpoke_model_display.GetID()) scene.AddNode(downSpoke_model) # crest spoke new_reader = vtk.vtkXMLPolyDataReader() new_reader.SetFileName(crestFileName) new_reader.Update() foldCurve_polyData = new_reader.GetOutput() foldPointData = foldCurve_polyData.GetPointData() arr_length = foldPointData.GetArray('spokeLength') arr_dirs = foldPointData.GetArray('spokeDirection') crest_arrows_polydata = vtk.vtkPolyData() crest_arrows_points = vtk.vtkPoints() crest_arrows_lines = vtk.vtkCellArray() for i in range(foldCurve_polyData.GetNumberOfPoints()): # tail of crest arrows pt_tail = [0] * 3 foldCurve_polyData.GetPoint(i, pt_tail) id0 = crest_arrows_points.InsertNextPoint(pt_tail) # head of crest arrows pt_head = [0] * 3 spoke_length = arr_length.GetValue(i) baseIdx = i * 3 dirX = arr_dirs.GetValue(baseIdx) dirY = arr_dirs.GetValue(baseIdx + 1) dirZ = arr_dirs.GetValue(baseIdx + 2) pt_head[0] = pt_tail[0] + spoke_length * dirX pt_head[1] = pt_tail[1] + spoke_length * dirY pt_head[2] = pt_tail[2] + spoke_length * dirZ id1 = crest_arrows_points.InsertNextPoint(pt_head) crest_line = vtk.vtkLine() crest_line.GetPointIds().SetId(0, id0) crest_line.GetPointIds().SetId(1, id1) crest_arrows_lines.InsertNextCell(crest_line) crest_arrows_polydata.SetPoints(crest_arrows_points) crest_arrows_polydata.SetLines(crest_arrows_lines) # show crest arrows crestSpoke_model = slicer.vtkMRMLModelNode() crestSpoke_model.SetScene(scene) crestSpoke_model.SetName("Crest Spoke") crestSpoke_model.SetAndObservePolyData(crest_arrows_polydata) # model display node crestSpoke_model_display = slicer.vtkMRMLModelDisplayNode() crestSpoke_model_display.SetColor(1, 1, 0) crestSpoke_model_display.SetScene(scene) crestSpoke_model_display.SetLineWidth(3.0) crestSpoke_model_display.SetBackfaceCulling(0) scene.AddNode(crestSpoke_model_display) crestSpoke_model.SetAndObserveDisplayNodeID( crestSpoke_model_display.GetID()) scene.AddNode(crestSpoke_model) # show fold curve foldCurve_model = slicer.vtkMRMLModelNode() foldCurve_model.SetScene(scene) foldCurve_model.SetName("Fold Curve") foldCurve_model.SetAndObservePolyData(foldCurve_polyData) # model display node foldCurve_model_display = slicer.vtkMRMLModelDisplayNode() foldCurve_model_display.SetColor(1, 1, 0) foldCurve_model_display.SetScene(scene) foldCurve_model_display.SetLineWidth(3.0) foldCurve_model_display.SetBackfaceCulling(0) scene.AddNode(foldCurve_model_display) foldCurve_model.SetAndObserveDisplayNodeID( foldCurve_model_display.GetID()) scene.AddNode(foldCurve_model) # show connections to fold curve point from nearby interior points # compute the nearest interior point connection_polydata = vtk.vtkPolyData() connection_points = vtk.vtkPoints() connection_lines = vtk.vtkCellArray() for i in range(foldCurve_polyData.GetNumberOfPoints()): min_dist = 100000.0 nearest_index = 0 pt_fold = [0] * 3 foldCurve_polyData.GetPoint(i, pt_fold) id0 = connection_points.InsertNextPoint(pt_fold) for j in range(upSpokes.GetNumberOfPoints()): pt_interior = [0] * 3 upSpokes.GetPoint(j, pt_interior) dist = self.distance(pt_fold, pt_interior) if dist < min_dist: min_dist = dist nearest_index = j pt_nearest_interior = upSpokes.GetPoint(nearest_index) id1 = connection_points.InsertNextPoint(pt_nearest_interior) line = vtk.vtkLine() line.GetPointIds().SetId(0, id0) line.GetPointIds().SetId(1, id1) connection_lines.InsertNextCell(line) connection_polydata.SetPoints(connection_points) connection_polydata.SetLines(connection_lines) connection_model = slicer.vtkMRMLModelNode() connection_model.SetScene(scene) connection_model.SetName("Connection to Fold Curve") connection_model.SetAndObservePolyData(connection_polydata) # model display node connection_model_display = slicer.vtkMRMLModelDisplayNode() connection_model_display.SetColor(0, 0, 0) connection_model_display.SetScene(scene) connection_model_display.SetLineWidth(3.0) connection_model_display.SetBackfaceCulling(0) scene.AddNode(connection_model_display) connection_model.SetAndObserveDisplayNodeID( connection_model_display.GetID()) scene.AddNode(connection_model)
# PATH OF OUTPUT FILE FOR RESULTS output_filename = 'all_results_pressures.dat' output_collection = [] if __name__ == "__main__": for file in input_filenames: # Load in the mesh file for the outlet you want pressures at. This can be found in the mesh-surfaces folder command_string = 'cd mesh-complete/mesh-surfaces' print(command_string) os.chdir('mesh-complete/mesh-surfaces') # Read geometry (mesh) information from this cap outlet_reader = vtk.vtkXMLPolyDataReader() # Create vtk instance outlet_reader.SetFileName('cap_' + file + '.vtp') # Open file outlet_reader.Update() outlet_model = vtk.vtkPolyData() outlet_model = outlet_reader.GetOutput( ) # Read file into new variable for manipulation numPts = outlet_model.GetNumberOfPoints( ) # Determine number of points in the mesh at this outlet outlet_IDs = outlet_model.GetPointData().GetArray( "GlobalNodeID" ) # Extract node IDs to match with full model solution # Load in the pressure information from the vtp file command_string = 'cd ../..' print(command_string) os.chdir('../..')
def _update(self): reader = vtkXMLPolyDataReader() reader.SetFileName(self.filename_) reader.Update() self._polydata = reader.GetOutput()
def read_vtp(self): reader = vtk.vtkXMLPolyDataReader() reader.SetFileName('.'.join([self.filename, self.input_type])) reader.Update() scalar_range = reader.GetOutput().GetScalarRange() return reader, scalar_range