def _get_writer(filetype, filename): import vtk if filetype in "vtk-ascii": logging.warning("VTK ASCII files are only meant for debugging.") writer = vtk.vtkUnstructuredGridWriter() writer.SetFileTypeToASCII() elif filetype == "vtk-binary": writer = vtk.vtkUnstructuredGridWriter() writer.SetFileTypeToBinary() elif filetype == "vtu-ascii": logging.warning("VTU ASCII files are only meant for debugging.") writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetDataModeToAscii() elif filetype == "vtu-binary": writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetDataModeToBinary() elif filetype == "xdmf2": writer = vtk.vtkXdmfWriter() elif filetype == "xdmf3": writer = vtk.vtkXdmf3Writer() else: assert filetype == "exodus", "Unknown file type '{}'.".format(filename) writer = vtk.vtkExodusIIWriter() # if the mesh contains vtkmodeldata information, make use of it # and write out all time steps. writer.WriteAllTimeStepsOn() return writer
def TestXdmfConversion(dataInput, fileName): global CleanUpGood, timer fileName = OutputDir + fileName xdmfFile = fileName + ".xmf" hdf5File = fileName + ".h5" vtkFile = fileName + ".vtk" xWriter = vtk.vtkXdmf3Writer() xWriter.SetLightDataLimit(LightDataLimit) xWriter.WriteAllTimeStepsOn() xWriter.SetFileName(xdmfFile) xWriter.SetInputData(dataInput) timer.StartTimer() xWriter.Write() timer.StopTimer() print "vtkXdmf3Writer took", timer.GetElapsedTime(), "seconds to write",\ xdmfFile ds = vtk.vtkDataSet.SafeDownCast(dataInput) if ds: dsw = vtk.vtkDataSetWriter() dsw.SetFileName(vtkFile) dsw.SetInputData(ds) dsw.Write() if not DoFilesExist(xdmfFile, None, None, False): message = "Writer did not create " + xdmfFile raiseErrorAndExit(message) xReader = vtk.vtkXdmf3Reader() xReader.SetFileName(xdmfFile) timer.StartTimer() xReader.Update() timer.StopTimer() print "vtkXdmf3Reader took", timer.GetElapsedTime(), "seconds to read",\ xdmfFile rOutput = xReader.GetOutputDataObject(0) fail = DoDataObjectsDiffer(dataInput, rOutput) if fail: raiseErrorAndExit("Xdmf conversion test failed") else: if ds: DoFilesExist(xdmfFile, hdf5File, vtkFile, CleanUpGood) else: DoFilesExist(xdmfFile, hdf5File, None, CleanUpGood)
def RunTest(): fail = False print "TEST SET 1 - verify reader/writer work for range of canonical datasets" print MemUsage("Before starting TEST SET 1") dog = vtk.vtkDataObjectGenerator() i = 0 for testObject in testObjects: fileName = "xdmfIOtest_" + str(i) print "Test vtk object", testObject dog.SetProgram(testObject) dog.Update() TestXdmfConversion(dog.GetOutput(), fileName) i += 1 print "TEST SET 2 - verify reader/writer work for Graphs" print MemUsage("Before starting TEST SET 2") print "Test Graph data" gsrc = vtk.vtkRandomGraphSource() gsrc.DirectedOn() gsrc.Update() gFilePrefix = "xdmfIOtest_Graph" gFileName = OutputDir + gFilePrefix + ".xdmf" ghFileName = OutputDir + gFilePrefix + ".h5" xWriter = vtk.vtkXdmf3Writer() xWriter.SetLightDataLimit(LightDataLimit) xWriter.SetFileName(gFileName) xWriter.SetInputConnection(0, gsrc.GetOutputPort(0)) timer.StartTimer() xWriter.Write() timer.StopTimer() print "vtkXdmf3Writer took", timer.GetElapsedTime(), "seconds to write",\ gFileName xReader = vtk.vtkXdmf3Reader() xReader.SetFileName(gFileName) xReader.Update() rOutput = xReader.GetOutputDataObject(0) fail = DoDataObjectsDiffer(gsrc.GetOutputDataObject(0), xReader.GetOutputDataObject(0)) if fail: raiseErrorAndExit("Failed graph conversion test") if not DoFilesExist(gFileName, ghFileName, None, CleanUpGood): raiseErrorAndExit("Failed to write Graph file") print "TEST SET 3 - verify reader/writer handle time varying data" print MemUsage("Before starting TEST SET 3") print "Test temporal data" tsrc = vtk.vtkTimeSourceExample() tsrc.GrowingOn() tsrc.SetXAmplitude(2.0) tFilePrefix = "xdmfIOTest_Temporal" tFileName = OutputDir + tFilePrefix + ".xdmf" thFileName = OutputDir + tFilePrefix + ".h5" xWriter = vtk.vtkXdmf3Writer() xWriter.SetLightDataLimit(LightDataLimit) xWriter.WriteAllTimeStepsOn() xWriter.SetFileName(tFileName) xWriter.SetInputConnection(0, tsrc.GetOutputPort(0)) timer.StartTimer() xWriter.Write() timer.StopTimer() print "vtkXdmf3Writer took", timer.GetElapsedTime(), "seconds to write",\ tFileName xReader = vtk.vtkXdmf3Reader() xReader.SetFileName(tFileName) xReader.UpdateInformation() oi = xReader.GetOutputInformation(0) timerange = oi.Get(vtk.vtkCompositeDataPipeline.TIME_STEPS()) ii = tsrc.GetOutputInformation(0) correcttimes = ii.Get(vtk.vtkCompositeDataPipeline.TIME_STEPS()) #compare number of and values for temporal range if len(timerange) != len(correcttimes): print "timesteps failed" print timerange, "!=", correcttimes raiseErrorAndExit("Failed to get same times") for i in xrange(0, len(correcttimes)): if abs(abs(timerange[i]) - abs(correcttimes[i])) > 0.000001: print "time result failed" print timerange, "!=", correcttimes raiseErrorAndExit("Failed to get same times") #exercise temporal processing and compare geometric bounds at each tstep indices = range(0, len(timerange)) + range(len(timerange) - 2, -1, -1) for x in indices: xReader.GetExecutive().SetUpdateTimeStep(0, timerange[x]) xReader.Update() obds = xReader.GetOutputDataObject(0).GetBounds() tsrc.GetExecutive().SetUpdateTimeStep( 0, timerange[x] + 0.0001) #workaround a precision bug in TSE tsrc.Update() ibds = tsrc.GetOutputDataObject(0).GetBounds() print timerange[x], obds for i in (0, 1, 2, 3, 4, 5): if abs(abs(obds[i]) - abs(ibds[i])) > 0.000001: print "time result failed" print obds, "!=", ibds raiseErrorAndExit("Failed to get same data for this timestep") fail = DoFilesExist(tFileName, thFileName, None, CleanUpGood) if not fail: raiseErrorAndExit("Failed Temporal Test") print MemUsage("End of Testing")
def write(filetype, filename, points, cells, point_data=None, cell_data=None, field_data=None ): # pylint: disable=import-error import vtk def _create_vtkarray(X, name): array = vtk.util.numpy_support.numpy_to_vtk(X, deep=1) array.SetName(name) return array point_data = {} if point_data is None else point_data cell_data = {} if cell_data is None else cell_data field_data = {} if field_data is None else field_data # assert data integrity for key in point_data: assert len(point_data[key]) == len(points), \ 'Point data mismatch.' for key in cell_data: assert key in cells, 'Cell data without cell' for key2 in cell_data[key]: assert len(cell_data[key][key2]) == len(cells[key]), \ 'Cell data mismatch.' vtk_mesh = _generate_vtk_mesh(points, cells) # add point data pd = vtk_mesh.GetPointData() for name, X in point_data.items(): # There is a naming inconsistency in VTK when it comes to multivectors # in Exodus files: # If a vector 'v' has two components, they are called 'v_x', 'v_y' # (note the underscore), if it has three, then they are called 'vx', # 'vy', 'vz'. See bug <http://www.vtk.org/Bug/view.php?id=15894>. # For VT{K,U} files, no underscore is ever added. pd.AddArray(_create_vtkarray(X, name)) # Add cell data. # The cell_data is structured like # # cell_type -> # key -> array # key -> array # [...] # cell_type -> # key -> array # key -> array # [...] # [...] # # VTK expects one array for each `key`, so assemble the keys across all # mesh_types. This requires each key to be present for each mesh_type, of # course. all_keys = [] for cell_type in cell_data: all_keys += cell_data[cell_type].keys() # create unified cell data for key in all_keys: for cell_type in cell_data: assert key in cell_data[cell_type] unified_cell_data = { key: numpy.concatenate([ cell_data[cell_type][key] for cell_type in cell_data ]) for key in all_keys } # add the array data to the mesh cd = vtk_mesh.GetCellData() for name, array in unified_cell_data.items(): cd.AddArray(_create_vtkarray(array, name)) # add field data fd = vtk_mesh.GetFieldData() for key, value in field_data.items(): fd.AddArray(_create_vtkarray(value, key)) if filetype in 'vtk-ascii': logging.warning('ASCII files are only meant for debugging.') writer = vtk.vtkUnstructuredGridWriter() writer.SetFileTypeToASCII() elif filetype == 'vtk-binary': writer = vtk.vtkUnstructuredGridWriter() writer.SetFileTypeToBinary() elif filetype == 'vtu-ascii': logging.warning('ASCII files are only meant for debugging.') writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetDataModeToAscii() elif filetype == 'vtu-binary': writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetDataModeToBinary() elif filetype == 'xdmf': writer = vtk.vtkXdmfWriter() elif filetype == 'xdmf3': writer = vtk.vtkXdmf3Writer() else: assert filetype == 'exodus', \ 'Unknown file type \'{}\'.'.format(filename) writer = vtk.vtkExodusIIWriter() # if the mesh contains vtkmodeldata information, make use of it # and write out all time steps. writer.WriteAllTimeStepsOn() writer.SetFileName(filename) try: writer.SetInput(vtk_mesh) except AttributeError: writer.SetInputData(vtk_mesh) writer.Write() return
def RunTest(): fail = False print "TEST SET 1 - verify reader/writer work for range of canonical datasets" print MemUsage("Before starting TEST SET 1") dog = vtk.vtkDataObjectGenerator() i = 0 for testObject in testObjects: fileName = "xdmfIOtest_" + str(i) print "Test vtk object", testObject dog.SetProgram(testObject) dog.Update() TestXdmfConversion(dog.GetOutput(), fileName) i += 1 print "TEST SET 2 - verify reader/writer work for Graphs" print MemUsage("Before starting TEST SET 2") print "Test Graph data" gsrc = vtk.vtkRandomGraphSource() gsrc.DirectedOn() gsrc.Update() gFilePrefix = "xdmfIOtest_Graph" gFileName = OutputDir + gFilePrefix + ".xdmf" ghFileName = OutputDir + gFilePrefix + ".h5" xWriter = vtk.vtkXdmf3Writer() xWriter.SetLightDataLimit(LightDataLimit) xWriter.SetFileName(gFileName) xWriter.SetInputConnection(0, gsrc.GetOutputPort(0)) timer.StartTimer() xWriter.Write() timer.StopTimer() print "vtkXdmf3Writer took", timer.GetElapsedTime(), "seconds to write",\ gFileName xReader = vtk.vtkXdmf3Reader() xReader.SetFileName(gFileName) xReader.Update() rOutput = xReader.GetOutputDataObject(0) fail = DoDataObjectsDiffer(gsrc.GetOutputDataObject(0), xReader.GetOutputDataObject(0)) if fail: raiseErrorAndExit("Failed graph conversion test") if not DoFilesExist(gFileName, ghFileName, None, CleanUpGood): raiseErrorAndExit("Failed to write Graph file") print "TEST SET 3 - verify reader/writer handle time varying data" print MemUsage("Before starting TEST SET 3") print "Test temporal data" tsrc = vtk.vtkTimeSourceExample() tsrc.GrowingOn() tsrc.SetXAmplitude(2.0) tFilePrefix = "xdmfIOTest_Temporal" tFileName = OutputDir + tFilePrefix + ".xdmf" thFileName = OutputDir + tFilePrefix + ".h5" xWriter = vtk.vtkXdmf3Writer() xWriter.SetLightDataLimit(LightDataLimit) xWriter.WriteAllTimeStepsOn() xWriter.SetFileName(tFileName) xWriter.SetInputConnection(0, tsrc.GetOutputPort(0)) timer.StartTimer() xWriter.Write() timer.StopTimer() print "vtkXdmf3Writer took", timer.GetElapsedTime(), "seconds to write",\ tFileName xReader = vtk.vtkXdmf3Reader() xReader.SetFileName(tFileName) xReader.UpdateInformation() oi = xReader.GetOutputInformation(0) timerange = oi.Get(vtk.vtkCompositeDataPipeline.TIME_STEPS()) ii = tsrc.GetOutputInformation(0) correcttimes = ii.Get(vtk.vtkCompositeDataPipeline.TIME_STEPS()) #compare number of and values for temporal range if len(timerange) != len(correcttimes): print "timesteps failed" print timerange, "!=", correcttimes raiseErrorAndExit("Failed to get same times") for i in xrange(0, len(correcttimes)): if abs(abs(timerange[i])-abs(correcttimes[i])) > 0.000001: print "time result failed" print timerange, "!=", correcttimes raiseErrorAndExit("Failed to get same times") #exercise temporal processing and compare geometric bounds at each tstep indices = range(0,len(timerange)) + range(len(timerange)-2,-1,-1) for x in indices: xReader.UpdateTimeStep(timerange[x]) obds = xReader.GetOutputDataObject(0).GetBounds() tsrc.Update(timerange[x]+0.0001) #workaround a precision bug in TSE ibds = tsrc.GetOutputDataObject(0).GetBounds() print timerange[x], obds for i in (0,1,2,3,4,5): if abs(abs(obds[i])-abs(ibds[i])) > 0.000001: print "time result failed" print obds, "!=", ibds raiseErrorAndExit("Failed to get same data for this timestep") fail = DoFilesExist(tFileName, thFileName, None, CleanUpGood) if not fail: raiseErrorAndExit("Failed Temporal Test") print MemUsage("End of Testing")