class VtkWriter(): def __init__(self, path, dim, scale): os.makedirs(path[:path.rfind("/")], exist_ok=True) self.path = path self.vtk_group = VtkGroup(path) self.spacing = scale / (dim - 1) def record_epoch(self, epoch, sdf, grad): out_fn = f"{self.path}_{epoch}" imageToVTK(out_fn, [0]*3, [self.spacing]*3, pointData={"sdf" : sdf, "grad": grad}) self.vtk_group.addFile(filepath=out_fn + ".vti", sim_time=epoch)
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()
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()
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()
fgrid[i, :, :, ] = ndimage.median_filter(grid[i, :, :, :], 3) fgrid -= fgrid.min() fgrid /= fgrid.max() from pyevtk.hl import gridToVTK from pyevtk.vtk import VtkGroup try: os.mkdir(path + "3d/") except: pass wavelengths = np.arange(400, 910, 10) #nm os.chdir(path + '3d/') 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()
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()
w.addData(str(key), np.array(f[key][step])) vx = np.array(f['u'][step]) vy = np.array(f['v'][step]) vz = np.array(f['w'][step]) w.addData("Velocity", (vx, vy, vz)) w.closeData("Point") # Coordinates of cell vertices w.openElement("Points") w.addData("points", (X, Y, Z)) w.closeElement("Points") w.closePiece() w.closeGrid() # Need to modify parameters for key in scalar_vars: w.appendData(data=np.array(f[key][step])) w.appendData(data=(vx, vy, vz)) w.appendData((X, Y, Z)) w.save() print("file: " + filename + " added") g = VtkGroup(new_dir + "/group") for step in times: g.addFile(filepath=new_data + '/' + str(step) + '.vts', sim_time=float(step)) g.save() print("group file: group.pvd added")
# * * # * 2. Redistributions in binary form must reproduce the above copyright notice, * # * this list of conditions and the following disclaimer in the documentation * # * and/or other materials provided with the distribution. * # * * # * THIS SOFTWARE IS PROVIDED BY PAULO A. HERRERA ``AS IS'' AND ANY EXPRESS OR * # * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * # * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * # * EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * # * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * # * BUT NOT LIMITED TO, PROCUREMEN OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * # * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * # * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * # * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * # * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * # *********************************************************************************** # ************************************************************** # * Example of how to create a VTK group to visualize time * # * dependent data. * # ************************************************************** from pyevtk.vtk import VtkGroup g = VtkGroup("./group") g.addFile(filepath="sim0000.vtu", sim_time=0.0) g.addFile(filepath="sim0001.vtu", sim_time=1.0) g.addFile(filepath="sim0002.vtu", sim_time=2.0) g.addFile(filepath="sim0003.vtu", sim_time=3.0) g.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()
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()
def __init__(self, path, dim, scale): os.makedirs(path[:path.rfind("/")], exist_ok=True) self.path = path self.vtk_group = VtkGroup(path) self.spacing = scale / (dim - 1)