def _load_file(self, filename): """Load a vtkMultiBlockDataSet from a file. The supported extensions are: ``.vtm`` or ``.vtmb``. """ filename = os.path.abspath(os.path.expanduser(filename)) # test if file exists if not os.path.isfile(filename): raise Exception('File %s does not exist' % filename) # Get extension ext = pyvista.get_ext(filename) # Extensions: .vtm and .vtmb # Select reader if ext in ['.vtm', '.vtmb']: reader = vtk.vtkXMLMultiBlockDataReader() else: raise IOError('File extension must be either "vtm" or "vtmb"') # Load file reader.SetFileName(filename) reader.Update() self.shallow_copy(reader.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkXMLMultiBlockDataReader(), 'Reading vtkXMLMultiBlockData.', (), ('vtkXMLMultiBlockData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def ReadMultiBlockFile(self): if (self.InputFileName == ''): self.PrintError('Error: no InputFileName.') self.PrintLog('Reading MultiBlockData File.') reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(self.InputFileName) reader.Update() self.Surface = reader.GetOutput()
def readDataSet(fileName, **kwargs): """Read the dataset from a file. The reader type used is determined from the file extension. Returns: +------------+----------------------+ | File ext. | Return type | +============+======================+ | .vtp | vtkPolyData | +------------+----------------------+ | .vtu | vtkUnstructuredGrid | +------------+----------------------+ | .vti | vtkImageData | +------------+----------------------+ | .stl | vtkPolyData | +------------+----------------------+ | .case | vtkMultiBlockDataSet | +------------+----------------------+ """ if not os.path.isfile(fileName): raise RuntimeError('The file', fileName, 'did not exist') filePrefix, fileExtension = os.path.splitext(fileName) if fileExtension == '.vtp': reader = vtk.vtkXMLPolyDataReader() elif fileExtension == '.vtu': reader = vtk.vtkXMLUnstructuredGridReader() elif fileExtension == '.vti': reader = vtk.vtkXMLImageDataReader() elif fileExtension == '.vtm': reader = vtk.vtkXMLMultiBlockDataReader() elif fileExtension == '.stl': reader = vtk.vtkSTLReader() elif fileExtension == '.vtk': #reader = _createVTKReader(fileName) reader = vtk.vtkDataSetReader() elif fileExtension == '.case': reader = vtk.vtkEnSightGoldBinaryReader() for k, v in kwargs.items(): if k == 'disableCellArrays': for arrName in v: reader.GetCellDataArraySelection().DisableArray(arrName) elif k == 'disablePointArrays': for arrName in v: reader.GetPointDataArraySelection().DisableArray(arrName) else: raise RuntimeError('Unknown keyword argument' + str(k)) else: raise RuntimeError('Unknown file extension', fileExtension) if fileExtension == '.case': reader.SetCaseFileName(fileName) else: reader.SetFileName(fileName) reader.Update() return reader.GetOutput()
def __init__(self, fileName): Reader.__init__(self, fileName) self._vtkReader = vtk.vtkXMLMultiBlockDataReader() self._fileName = fileName self._vtkReader.SetFileName(self._fileName) self._vtkReader.Update() self._data = self._vtkReader.GetOutput()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkXMLMultiBlockDataReader(), 'Reading vtkXMLMultiBlockData.', (), ('vtkXMLMultiBlockData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def __init__(self, fileName): Reader.__init__(self, fileName) self._vtkReader = vtk.vtkXMLMultiBlockDataReader() self._fileName = fileName self._vtkReader.SetFileName(self._fileName) self._vtkReader.Update() self._data = self._vtkReader.GetOutput() for i in range(self._data.GetNumberOfBlocks()): points = dsa.WrapDataObject(self._data.GetBlock(i)).Points points[:, 2] = 0
def vtk_geom_to_np(geom_vtm): reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(Path(geom_vtm).absolute().as_posix()) reader.Update() data = reader.GetOutput() data_iterator = data.NewIterator() img_data = data_iterator.GetCurrentDataObject() point_data = img_data.GetPointData() array_data = point_data.GetArray(0) np_array = vtk_to_numpy(array_data) img_shape = img_data.GetExtent()#.GetWholeExtent() np_shape = [img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1, 1] geometry_array = np_array.reshape(np_shape) return geometry_array # vtm = VTK_data() # vtm.load_data() # print(vtm.results)
def load_vtk_structured(self, file_name): self.fname = file_name #reader = vtk.vtkUnstructuredGridReader() reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(file_name) reader.Update() Merge = vtk.vtkMultiBlockMergeFilter() Merge.AddInput(reader.GetOutput()) Merge.Update() Mb = vtk.vtkStructuredGridOutlineFilter() if vtk.VTK_MAJOR_VERSION <= 5: Mb.SetInput(Merge.GetOutput()) else: Mb.SetInputData(Merge.GetOutput()) Geom01 = vtk.vtkCompositeDataGeometryFilter() Geom01.SetInputConnection(Merge.GetOutputPort()) self.output = Geom01.GetOutput() self.vtk_pts = self.output.GetPointData() self.vtk_n_pts = self.output.GetNumberOfPoints() self.vtk_n_cells = self.output.GetNumberOfCells() self.vtk_n_props = self.vtk_pts.GetNumberOfArrays() self.reader = reader #get_range = self.output.GetScalarRange() #print get_range print " [Vtk_unstructured_reader]:" print " Cells: %d" % (self.vtk_n_cells) print " Point: %d" % (self.vtk_n_pts) print " Props: ", for i in range(self.vtk_n_props): print "\'%s\'" % (self.vtk_pts.GetArrayName(i)), print print "\n+[Vtk_multiblock_reader]: \'%s\'" % file_name
def vtk_results_to_np(results_vtm): # read file for steady state flow reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(Path(results_vtm).absolute().as_posix()) reader.Update() data = reader.GetOutput() data_iterator = data.NewIterator() img_data = data_iterator.GetCurrentDataObject() point_data = img_data.GetPointData() velocity_array_data = point_data.GetArray(0) pressure_array_data = point_data.GetArray(1) velocity_np_array = vtk_to_numpy(velocity_array_data) pressure_np_array = vtk_to_numpy(pressure_array_data) img_shape = img_data.GetExtent()#.GetWholeExtent() velocity_np_shape = [img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1, 2] pressure_np_shape = [img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1, 1] velocity_np_array = velocity_np_array.reshape(velocity_np_shape) pressure_np_array = pressure_np_array.reshape(pressure_np_shape) steady_flow_array = np.concatenate([velocity_np_array, pressure_np_array], axis=2) return steady_flow_array
def read_vtm_data(in_file): reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(in_file) reader.Update() return reader.GetOutput().GetBlock(0)
def load_data(self): # reads in all xml data into lists # get list of all xml file in dataset xml_files = glob.glob(self.base_dir + "/xml_runs/*.xml") for f in xml_files: # parse xml file tree = ET.parse(f) root = tree.getroot() dir_name = root.find('save_path').find('dirname').text # get needed filenames geometry_file = dir_name + "vtkData/geometry_iT0000000.vtm" steady_flow_file = glob.glob(dir_name + "/vtkData/data/*.vtm") if len(steady_flow_file) == 0: continue else: steady_flow_file = steady_flow_file[0] drag_vector_file = dir_name + "gnuplotData/data/drag.dat" # read file for geometry reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(geometry_file) reader.Update() data = reader.GetOutput() data_iterator = data.NewIterator() img_data = data_iterator.GetCurrentDataObject() img_data.Update() point_data = img_data.GetPointData() array_data = point_data.GetArray(0) np_array = vtk_to_numpy(array_data) img_shape = img_data.GetWholeExtent() np_shape = [ img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1, 1 ] geometry_array = np_array.reshape(np_shape) if np.isnan(geometry_array).any(): continue # read file for steady state flow reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(steady_flow_file) reader.Update() data = reader.GetOutput() data_iterator = data.NewIterator() img_data = data_iterator.GetCurrentDataObject() img_data.Update() point_data = img_data.GetPointData() velocity_array_data = point_data.GetArray(0) pressure_array_data = point_data.GetArray(1) velocity_np_array = vtk_to_numpy(velocity_array_data) pressure_np_array = vtk_to_numpy(pressure_array_data) img_shape = img_data.GetWholeExtent() velocity_np_shape = [ img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1, 2 ] pressure_np_shape = [ img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1, 1 ] velocity_np_array = velocity_np_array.reshape(velocity_np_shape) pressure_np_array = pressure_np_array.reshape(pressure_np_shape) steady_flow_array = np.concatenate( [velocity_np_array, pressure_np_array], axis=2) if np.isnan(steady_flow_array).any(): continue # read file for drag vector reader = open(drag_vector_file, "r") drag_values = reader.readlines() drag_array = np.zeros((len(drag_values))) for i in range(len(drag_values)): values = drag_values[i].split(' ') drag_array[i] = float(values[1]) if np.isnan(drag_array).any(): continue # if no nans then store self.geometries.append(geometry_array) self.steady_flows.append(steady_flow_array) self.drag_vectors.append(drag_array) self.split_line = int(self.train_test_split * len(self.geometries))
g.Update() mb = g.GetOutputDataObject(0) a = vtk.vtkFloatArray() a.SetName("foo") a.SetNumberOfTuples(1) a.SetValue(0, 10) mb.GetFieldData().AddArray(a) file_root = VTK_TEMP_DIR + '/testxml' file0 = file_root + ".vtm" wri = vtk.vtkXMLMultiBlockDataWriter() wri.SetInputData(mb) wri.SetFileName(file0) wri.Write() read = vtk.vtkXMLMultiBlockDataReader() read.SetFileName(file0) read.Update() output = read.GetOutputDataObject(0) assert(output.GetFieldData().GetArray("foo")) assert(output.GetFieldData().GetArray("foo").GetValue(0) == 10) os.remove(file0) os.remove(file_root + "/testxml_0.vti") os.rmdir(file_root)
def _load_file(filename, c, alpha, threshold, spacing, unpack): fl = filename.lower() ################################################################# other formats: if fl.endswith(".xml") or fl.endswith(".xml.gz") or fl.endswith(".xdmf"): # Fenics tetrahedral file actor = loadDolfin(filename) elif fl.endswith(".neutral") or fl.endswith(".neu"): # neutral tetrahedral file actor = loadNeutral(filename) elif fl.endswith(".gmsh"): # gmesh file actor = loadGmesh(filename) elif fl.endswith(".pcd"): # PCL point-cloud format actor = loadPCD(filename) actor.GetProperty().SetPointSize(2) elif fl.endswith(".off"): actor = loadOFF(filename) elif fl.endswith(".3ds"): # 3ds format actor = load3DS(filename) elif fl.endswith(".wrl"): importer = vtk.vtkVRMLImporter() importer.SetFileName(filename) importer.Read() importer.Update() actors = importer.GetRenderer().GetActors() #vtkActorCollection actors.InitTraversal() wacts = [] for i in range(actors.GetNumberOfItems()): act = actors.GetNextActor() wacts.append(act) actor = Assembly(wacts) ################################################################# volumetric: elif fl.endswith(".tif") or fl.endswith(".slc") or fl.endswith(".vti") \ or fl.endswith(".mhd") or fl.endswith(".nrrd") or fl.endswith(".nii") \ or fl.endswith(".dem"): img = loadImageData(filename, spacing) if threshold is False: if c is None and alpha == 1: c = ['b','lb','lg','y','r'] # good for blackboard background alpha = (0.0, 0.0, 0.2, 0.4, 0.8, 1) actor = Volume(img, c, alpha) else: actor = Volume(img).isosurface(threshold=threshold) actor.color(c).alpha(alpha) ################################################################# 2D images: elif fl.endswith(".png") or fl.endswith(".jpg") or fl.endswith(".bmp") or fl.endswith(".jpeg"): if ".png" in fl: picr = vtk.vtkPNGReader() elif ".jpg" in fl or ".jpeg" in fl: picr = vtk.vtkJPEGReader() elif ".bmp" in fl: picr = vtk.vtkBMPReader() picr.SetFileName(filename) picr.Update() actor = Picture() # object derived from vtk.vtkImageActor() actor.SetInputData(picr.GetOutput()) if alpha is None: alpha = 1 actor.SetOpacity(alpha) ################################################################# multiblock: elif fl.endswith(".vtm") or fl.endswith(".vtmb"): read = vtk.vtkXMLMultiBlockDataReader() read.SetFileName(filename) read.Update() mb = read.GetOutput() if unpack: acts = [] for i in range(mb.GetNumberOfBlocks()): b = mb.GetBlock(i) if isinstance(b, (vtk.vtkPolyData, vtk.vtkImageData, vtk.vtkUnstructuredGrid, vtk.vtkStructuredGrid, vtk.vtkRectilinearGrid)): acts.append(b) return acts else: return mb ################################################################# numpy: elif fl.endswith(".npy"): acts = loadNumpy(filename) if unpack == False: return Assembly(acts) return acts elif fl.endswith(".geojson") or fl.endswith(".geojson.gz"): return loadGeoJSON(fl) ################################################################# polygonal mesh: else: if fl.endswith(".vtk"): # read all legacy vtk types #output can be: # PolyData, StructuredGrid, StructuredPoints, UnstructuredGrid, RectilinearGrid reader = vtk.vtkDataSetReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.ReadAllFieldsOn() reader.ReadAllNormalsOn() reader.ReadAllColorScalarsOn() elif fl.endswith(".ply"): reader = vtk.vtkPLYReader() elif fl.endswith(".obj"): reader = vtk.vtkOBJReader() elif fl.endswith(".stl"): reader = vtk.vtkSTLReader() elif fl.endswith(".byu") or fl.endswith(".g"): reader = vtk.vtkBYUReader() elif fl.endswith(".foam"): # OpenFoam reader = vtk.vtkOpenFOAMReader() elif fl.endswith(".pvd"): reader = vtk.vtkXMLGenericDataObjectReader() elif fl.endswith(".vtp"): reader = vtk.vtkXMLPolyDataReader() elif fl.endswith(".vts"): reader = vtk.vtkXMLStructuredGridReader() elif fl.endswith(".vtu"): reader = vtk.vtkXMLUnstructuredGridReader() elif fl.endswith(".vtr"): reader = vtk.vtkXMLRectilinearGridReader() elif fl.endswith(".pvtk"): reader = vtk.vtkPDataSetReader() elif fl.endswith(".pvtr"): reader = vtk.vtkXMLPRectilinearGridReader() elif fl.endswith("pvtu"): reader = vtk.vtkXMLPUnstructuredGridReader() elif fl.endswith(".txt") or fl.endswith(".xyz"): reader = vtk.vtkParticleReader() # (format is x, y, z, scalar) elif fl.endswith(".facet"): reader = vtk.vtkFacetReader() else: return None reader.SetFileName(filename) reader.Update() routput = reader.GetOutput() if not routput: colors.printc("~noentry Unable to load", filename, c=1) return None actor = Actor(routput, c, alpha) if fl.endswith(".txt") or fl.endswith(".xyz"): actor.GetProperty().SetPointSize(4) actor.filename = filename return actor
def __init__(self): self.reader = vtk.vtkXMLMultiBlockDataReader()
def load_data(self, dim, size): # reads in all xml data into lists # get list of all xml file in dataset tree = etree.parse(self.base_dir + "experiment_runs_master.xml") root = tree.getroot() run_roots = root.findall("run") print("loading dataset") reader = vtk.vtkXMLMultiBlockDataReader() #stopper = 0 for run_root in tqdm(run_roots): #stopper += 1 #if stopper > 10000: # break # check if right size xml_size = int(run_root.find("size").text) if xml_size != size: continue # check if right dim xml_dim = int(run_root.find("dim").text) if xml_dim != dim: continue # parse xml file xml_file = run_root.find("xml_filename").text tree = etree.parse(xml_file) root = tree.getroot() # check if flow data is availible is_availible = root.find("flow_data").find("availible").text if is_availible == "False": continue # get needed filenames geometry_file = root.find("flow_data").find("geometry_file").text steady_flow_file = root.find("flow_data").find("flow_file").text drag_vector_file = root.find("flow_data").find("drag_file").text # read file for geometry reader.SetFileName(geometry_file) try: reader.Update() except: continue data = reader.GetOutput() data_iterator = data.NewIterator() img_data = data_iterator.GetCurrentDataObject() try: img_data.Update() except: continue point_data = img_data.GetPointData() array_data = point_data.GetArray(0) np_array = vtk_to_numpy(array_data) img_shape = img_data.GetWholeExtent() if img_shape[-1] == 0: np_shape = [ img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1, 1 ] else: np_shape = [ img_shape[5] - img_shape[4] + 1, img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1, 1 ] if len(np_array.shape) == 2: continue geometry_array = np_array.reshape(np_shape) geometry_array = geometry_array[..., 0:np_shape[0], :] geometry_array = np.abs(geometry_array - 1.0) geometry_array = np.minimum(geometry_array, 1.0) geometry_array = np.abs(np.abs(geometry_array - 1.0) - 1.0) if img_shape[-1] == 0: geometry_array = fill_gaps(geometry_array, [size / 2, size / 2], size) geometry_array = 2.0 * geometry_array - 1.0 if np.isnan(geometry_array).any(): continue # read file for steady state flow #reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(steady_flow_file) try: reader.Update() except: continue data = reader.GetOutput() data_iterator = data.NewIterator() img_data = data_iterator.GetCurrentDataObject() try: img_data.Update() except: continue point_data = img_data.GetPointData() velocity_array_data = point_data.GetArray(0) pressure_array_data = point_data.GetArray(1) velocity_np_array = vtk_to_numpy(velocity_array_data) pressure_np_array = vtk_to_numpy(pressure_array_data) img_shape = img_data.GetWholeExtent() if img_shape[-1] == 0: np_shape = [ img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1 ] velocity_np_shape = np_shape + [2] pressure_np_shape = np_shape + [1] else: np_shape = [ img_shape[5] - img_shape[4] + 1, img_shape[3] - img_shape[2] + 1, img_shape[1] - img_shape[0] + 1 ] velocity_np_shape = np_shape + [3] pressure_np_shape = np_shape + [1] velocity_np_array = velocity_np_array.reshape(velocity_np_shape) pressure_np_array = pressure_np_array.reshape(pressure_np_shape) steady_flow_array = np.concatenate( [velocity_np_array, pressure_np_array], axis=-1) steady_flow_array = steady_flow_array[..., 0:np_shape[0], :] if np.isnan(steady_flow_array).any(): continue # read file for drag vector csv_reader = open(drag_vector_file, "r") drag_values = csv_reader.readlines() drag_array = np.zeros((len(drag_values))) for i in xrange(len(drag_values)): values = drag_values[i].split(' ') drag_array[i] = float(values[1]) if np.isnan(drag_array).any(): continue csv_reader.close() # if no nans then store self.geometries.append(geometry_array) self.steady_flows.append(steady_flow_array) self.drag_vectors.append(drag_array) self.split_line = int(self.train_test_split * len(self.geometries))
def compute(whole, split): # prepare controller = vtk.vtkMPIController() vtk.vtkMultiProcessController.SetGlobalController(controller) rank = controller.GetLocalProcessId() nprocs = controller.GetNumberOfProcesses() # print('rank={0}'.format(rank)) # print('nprocs={0}'.format(nprocs)) # whole (wholeDataset, bounds, dimension) = readDataset(whole) if pow(2,dimension) != nprocs: print 'the number of procs must be 2^dimension' sys.exit() # coarse coarseData = vtk.vtkImageData() coarseData.CopyStructure(wholeDataset) coarseData.SetSpacing(0.1,0.1,0.1) if dimension == 2: coarseData.SetDimensions(11,11,1) else: coarseData.SetDimensions(11,11,11) # print data # print coarseData # compute moments momentsFilter = vtk.vtkComputeMoments() momentsFilter.SetFieldData(wholeDataset) momentsFilter.SetGridData(coarseData) momentsFilter.SetNameOfPointData(nameOfPointData) momentsFilter.SetUseFFT(0) momentsFilter.SetNumberOfIntegrationSteps(numberOfIntegrationSteps) momentsFilter.SetOrder(order) momentsFilter.SetRadiiArray([radius,0,0,0,0,0,0,0,0,0]) momentsFilter.Update() # if rank ==0: print momentsFilter # this is to make sure each proc only loads their piece ids_to_read = [rank] reqs = vtk.vtkInformation() reqs.Set(vtk.vtkCompositeDataPipeline.UPDATE_COMPOSITE_INDICES(), ids_to_read, 1) reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(split) reader.Update(reqs) # print('reader={0}'.format(reader.GetOutput())) multiblock = vtk.vtkMultiBlockDataSet.SafeDownCast(reader.GetOutput()) # print('multiblock={0}'.format(multiblock)) multipiece = vtk.vtkMultiPieceDataSet.SafeDownCast(multiblock.GetBlock(0)) # print('multipiece={0}'.format(multipiece)) data = vtk.vtkImageData.SafeDownCast(multipiece.GetPiece(rank)) # print('data={0}'.format(data)) # coarse coarseData = vtk.vtkImageData() coarseData.CopyStructure(data) coarseData.SetSpacing(0.1,0.1,0.1) if dimension == 2: coarseData.SetDimensions(6,6,1) else: coarseData.SetDimensions(6,6,6) # print data # coarseData # parallel pMomentsFilter = vtk.vtkPComputeMoments() pMomentsFilter.SetFieldData(data) pMomentsFilter.SetGridData(coarseData) pMomentsFilter.SetNameOfPointData(nameOfPointData) pMomentsFilter.SetNumberOfIntegrationSteps(numberOfIntegrationSteps) pMomentsFilter.SetRadiiArray([radius, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]) pMomentsFilter.Update(reqs) # if rank ==0: print pMomentsFilter # check for difference except for the global boundary (the probe and parallel probe filters behave differently there. So, there is a difference if numberOfIntegrationSteps > 0 ) diff = 0 for i in xrange(pMomentsFilter.GetOutput().GetPointData().GetNumberOfArrays()): diffArray = vtk.vtkDoubleArray() diffArray.SetName( pMomentsFilter.GetOutput().GetPointData().GetArrayName(i) ) diffArray.SetNumberOfComponents( 1 ) diffArray.SetNumberOfTuples( pMomentsFilter.GetOutput().GetNumberOfPoints() ) diffArray.Fill( 0.0 ) momentsArray = momentsFilter.GetOutput().GetPointData().GetArray(i) pMomentsArray = pMomentsFilter.GetOutput().GetPointData().GetArray(i) for j in xrange(pMomentsFilter.GetOutput().GetNumberOfPoints()): diffArray.SetTuple1(j, abs(momentsArray.GetTuple1(momentsFilter.GetOutput().FindPoint(pMomentsFilter.GetOutput().GetPoint(j))) - pMomentsArray.GetTuple1(j))) if (dimension == 2 and pMomentsFilter.GetOutput().GetPoint(j)[0] > 0 and pMomentsFilter.GetOutput().GetPoint(j)[0] < 1 and pMomentsFilter.GetOutput().GetPoint(j)[1] > 0 and pMomentsFilter.GetOutput().GetPoint(j)[1] < 1) or (dimension == 3 and pMomentsFilter.GetOutput().GetPoint(j)[0] > 0 and pMomentsFilter.GetOutput().GetPoint(j)[0] < 1 and pMomentsFilter.GetOutput().GetPoint(j)[1] > 0 and pMomentsFilter.GetOutput().GetPoint(j)[1] < 1 and pMomentsFilter.GetOutput().GetPoint(j)[2] > 0 and pMomentsFilter.GetOutput().GetPoint(j)[2] < 1): # if diffArray.GetTuple1(j) > 1e-10: # print rank, i, j, pMomentsFilter.GetOutput().GetPoint(j), diffArray.GetTuple(j) diff = max(diff, diffArray.GetTuple1(j)) if diff > 1e-10: print "test failed, maxdiff =", diff else: print "test successful" if rank == 0: print 'all done!'
try: shutil.rmtree(prefix) except OSError: pass print("Output: %s" % fname) # put a barrier here to make sure that the files are deleted by process 0 # before going further with the test if contr: contr.Barrier() writer.SetFileName(fname) writer.SetInputDataObject(createMB(rank, nranks)) writer.Write() if contr: contr.Barrier() if rank == 0: reader = vtk.vtkXMLMultiBlockDataReader() reader.SetFileName(fname) reader.Update() # since verifying the md structure won't reveal if we have written the write # set of files, let's just look at the files we wrote out. files = os.listdir(prefix) expected_file_count = nranks + nranks + 2 * (nranks * nranks) print("Expecting %d files for the leaf nodes" % expected_file_count) assert (len(files) == expected_file_count)
def getOutputVTKwithPointDataFromFile(fileName): """ Uses the correct VTK reader to obtain a VTK output object so that one can work with the data in *fileName*. NOTE : the cell data are transfered to the nodes. Parameters ---------- fileName : string The .vt* file to open Returns ------- data_outVTK : VTK output object from a VTK reader VTK output object associated to the file type of *fileName* """ # function display print '\n---- DAEPy::getOutputVTKwithPointDataFromFile ----' # test if the file exists print '\n--> Reading', fileName if not os.path.isfile(fileName): raise ValueError("Error : file does not exists") extension = os.path.splitext(fileName)[-1] if extension == '.vtu': reader = vtk.vtkXMLUnstructuredGridReader() elif extension == '.vtk': reader = vtk.vtkStructuredGridReader() elif extension == '.pvtu': reader = vtk.vtkXMLPUnstructuredGridReader() elif extension == '.vtp': reader = vtk.vtkXMLPolyDataReader() elif extension == '.vtm': # TODO : To check reader = vtk.vtkXMLMultiBlockDataReader() reader = vtk.MergeBlocks(reader) else: raise ValueError("Error: unknown extension of file " + fileName) reader.SetFileName(fileName) reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.Update() data_outVTK = reader.GetOutput() # # All the data are transfered to the nodes # c2p = vtk.vtkCellDataToPointData() # c2p.SetInputData(data_outVTK) # c2p.Update() # data_outVTK = c2p.GetOutput() # list the fields available n_fields = data_outVTK.GetPointData().GetNumberOfArrays() print '\n--> Available:', n_fields, 'fields\n' for i in range(n_fields): print ' -', data_outVTK.GetPointData().GetArrayName(i) print '' return data_outVTK