def time_fields_write_data(fname, x, y, z, time, conn, offs, ctypes, **kwargs): """ Write data to vtk files """ pfields = kwargs.get('pointdata', None) cfields = kwargs.get('celldata', None) if (pfields is None and cfields is None): raise RuntimeError("No field data given, give either " "a point field or cell field or both.") group = VtkGroup(fname + "/" + fname) for i, t in enumerate(time): if pfields is None: pdata = None else: pdata = {k: pack_field(f[i, ...]) for k, f in pfields.items()} if cfields is None: cdata = None else: cdata = {k: pack_field(f[i, ...]) for k, f in cfields.items()} unstructuredGridToVTK(fname + "/step_" + str(i), x, y, z, connectivity=conn, offsets=offs, cell_types=ctypes, pointData=pdata, cellData=cdata) group.addFile(filepath=fname + "/step_" + str(i) + ".vtu", sim_time=t) group.save()
def seriesVTK(ij_out): """ Creates a PVD file that can visualize all time steps in ParaView. VARIABLES --------- ij_out: Location of the VTK files from convertVTK() """ # Read in the VTK files made from convertVTK() files = glob.glob('{0}/VTK/*.vti'.format(ij_out)) # Initialize the group g = VtkGroup('{0}/VTK/timeSeries'.format(ij_out)) for vtkFile in files: # Get time step i = int(vtkFile.rsplit('\\vol')[-1].rsplit('.')[0]) # Calculate time step in us (10 kHz imaging) timeStep = (i / (10E3)) * 1E6 # Add file to group g.addFile(filepath=vtkFile, sim_time=timeStep) # Save the group (will be a ParaView PVD file) g.save()
def write_pvd(self): pvd_attributes = VtkGroup(self.attributes_file_path) for k, v in self.exported_times['attributes'].items(): pvd_attributes.addFile(k + '.vtu', sim_time=v) pvd_attributes.save() pvd_products = VtkGroup(self.products_file_path) for k, v in self.exported_times['products'].items(): pvd_products.addFile(k + '.vts', sim_time=v) pvd_products.save()
def __exit__(self, type, value, traceback): assert len(self._assemFiles) == len(self._blockFiles) if len(self._assemFiles) > 1: # multiple files need to be wrapped up into groups. VTK doesnt like having # multiple meshes in the same group, so we write out separate Collection # files for them asyGroup = VtkGroup(f"{self._baseName}_asm") for path, time in self._assemFiles: asyGroup.addFile(filepath=path, sim_time=time) asyGroup.save() blockGroup = VtkGroup(f"{self._baseName}_blk") for path, time in self._blockFiles: blockGroup.addFile(filepath=path, sim_time=time) blockGroup.save()
from pyevtk.hl import pointsToVTK from pyevtk.vtk import VtkGroup import numpy as np g = VtkGroup("./group") for i in range(1,nt+1): x = np.random.rand(100) y = np.random.rand(100) z = np.random.rand(100) pointsToVTK("sim"+str(i), x, y, z, {"V":(x,y,z)}) g.addFile("sim"+str(i)+".vtu", sim_time=i*l3d.dt) g.save()
g = VtkGroup("3dscan") #fileNames = [] for wavelength in wavelengths: wl_ind = np.argmin(np.abs(wl - wavelength)) #gridToVTK("3d/3dscan"+str(round(wavelength)), x, y, z, cellData = {"intensity" : fgrid[wl_ind,:,:,]}, pointData = {"intensityp" : fgrid[wl_ind,:,:,]}) gridToVTK("3dscan" + str(round(wavelength)), nx.ravel(), ny.ravel(), nz.ravel(), pointData={"intensityp": fgrid[wl_ind, :, :, ]}) #gridToVTK("3d/3dscan"+str(round(wavelength)), x.ravel(), y.ravel(), z.ravel(), cellData = {"intensity" : fgrid[wl_ind,:,:,].ravel()}) g.addFile(filepath="./3dscan" + str(round(wavelength)) + '.vtr', sim_time=round(wavelength)) #fileNames.append("3dscan" + str(round(wavelength))) g.save() os.chdir('..') # import vtk_export # # vtk_writer = vtk_export.VTK_XML_Serial_Structured() # wavelengths = np.arange(400,900,10) #nm # os.chdir('3d/') # for wavelength in wavelengths: # wl_ind = np.argmin(np.abs(wl - wavelength)) # vtk_writer.snapshot("3dscan"+str(round(wavelength))+".vtu", gridx.ravel(), gridy.ravel(), gridz.ravel(), intensity=fgrid[wl_ind,:,:,].ravel()) # vtk_writer.writePVD("3dscan.pvd") # os.chdir('..') # fgrid = fgrid[:,5:-3,5:-3,:] # fgrid -= fgrid.min()
def _write_vtu_series(grid, coordinates, connectivity, data, filename_base, last_step, is_cell_data): steps = last_step + 1 if last_step is not None else len(data) fn_tpl = "{}_{:08d}" npoints = len(coordinates[0]) ncells = len(connectivity) ref = grid.reference_element if ref is ref is referenceelements.triangle: points_per_cell = 3 vtk_el_type = VtkTriangle.tid elif ref is referenceelements.square: points_per_cell = 4 vtk_el_type = VtkQuad.tid else: raise NotImplementedError( "vtk output only available for grids with triangle or rectangle reference elments" ) connectivity = connectivity.reshape(-1) cell_types = np.empty(ncells, dtype='uint8') cell_types[:] = vtk_el_type offsets = np.arange(start=points_per_cell, stop=ncells * points_per_cell + 1, step=points_per_cell, dtype='int32') group = VtkGroup(filename_base) for i in range(steps): fn = fn_tpl.format(filename_base, i) vtk_data = data[i, :] w = VtkFile(fn, VtkUnstructuredGrid) w.openGrid() w.openPiece(ncells=ncells, npoints=npoints) w.openElement("Points") w.addData("Coordinates", coordinates) w.closeElement("Points") w.openElement("Cells") w.addData("connectivity", connectivity) w.addData("offsets", offsets) w.addData("types", cell_types) w.closeElement("Cells") if is_cell_data: _addDataToFile(w, cellData={"Data": vtk_data}, pointData=None) else: _addDataToFile(w, cellData=None, pointData={"Data": vtk_data}) w.closePiece() w.closeGrid() w.appendData(coordinates) w.appendData(connectivity).appendData(offsets).appendData(cell_types) if is_cell_data: _appendDataToFile(w, cellData={"Data": vtk_data}, pointData=None) else: _appendDataToFile(w, cellData=None, pointData={"Data": vtk_data}) w.save() group.addFile(filepath=fn + '.vtu', sim_time=i) group.save()
def build_particle_file(fname_in, fname_outbase, ignore_xtime): """ Take existing netCDF4 input f_in and produce vtu files for f_outbase with all the particle data Phillip Wolfram LANL 07/15/2014 """ # initialize the starting points fullpath = fname_in.split(os.sep) # don't want to place this in starting directory g = VtkGroup(fname_outbase + '_' + os.path.splitext(fullpath[-1])[0]) # open the database f_in = netCDF4.Dataset(fname_in, 'r') # num particles and data frames Ntime = len(f_in.dimensions['Time']) # initialize empty dictionary particleData = dict() for t in np.arange(Ntime): # get the points locations x = f_in.variables['xParticle'][t] y = f_in.variables['yParticle'][t] z = f_in.variables['zParticle'][t] print(f'{t+1}/{Ntime}...') particleType = f_in.variables['xParticle'].dimensions particleTypeStatic = f_in.variables['indexToParticleID'].dimensions # get particle data particleData.clear() coordinateVars = ['xParticle', 'yParticle', 'zParticle'] nonCoords = [i for i in f_in.variables if i not in coordinateVars] for v in nonCoords: dim = f_in.variables[v].dimensions if dim == particleType: particleData[str(v)] = cleanup(f_in.variables[v][t]) if dim == particleTypeStatic: particleData[str(v)] = cleanup(f_in.variables[v][:]) if (ignore_xtime) or ('xtime' not in f_in.variables): # Set time to a simple index. time = 2 * t else: # Set decimal time similar to that in `paraview_vtk_extractor` so # that the `annotate_date` macro from MPAS-Tools can be used. xtime = f_in.variables['xtime'][t].tostring().decode('utf-8') \ .strip() date = datetime(int(xtime[0:4]), int(xtime[5:7]), int(xtime[8:10]), int(xtime[11:13]), int(xtime[14:16]), int(xtime[17:19])) time = date2num( date, units='days since 0000-01-01', calendar='noleap') / 365 # file name f_out = f'{fname_outbase}_{os.path.splitext(fullpath[-1])[0]}_{str(t)}' # output file pointsToVTK(f_out, x, y, z, data=particleData) # make sure the file is added to the time vector g.addFile(filepath=f_out + '.vtu', sim_time=time) # save the animation file g.save()