def __init__(self, filename, path='', timestep=0, npx=1, npy=1, npz=1, init_pvd=False): self.timestep = timestep prefix = '_{0}_{1}'.format(timestep, mpi.COMM_WORLD.Get_rank()) if not os.path.exists(path) and mpi.COMM_WORLD.Get_rank() == 0: os.mkdir(path) # All the processes wait for the creation of the output directory mpi.COMM_WORLD.Barrier() self.path = path self.filename = filename self.vtkfile = VtkFile(path + '/' + filename + prefix, VtkRectilinearGrid) self.end = np.zeros(3, dtype=np.int) self.x = None self.y = None self.z = None self.scalars = {} self.vectors = {} self._init_grid = True self._init_pvd = init_pvd self.npx = npx self.npy = npy self.npz = npz self.log = setLogger(__name__)
def convertRainfluxToVTK(self, i, cfile): rainflux = cfile.getField('rainflux').data rainflux = rainflux.reshape(rainflux.shape + (1, )) (nx, ny, nz) = rainflux.shape print nx, ny, nz ncells = nx * ny * nz start = (0, 0, 0) end = (nx, ny, nz) origin = (0.0, 0.0, 0.0) spacing = (1.0, 1.0, 1.0) w = VtkFile("rainflux." + self.filename(i), VtkImageData) w.openGrid(start, end, origin, spacing) w.openPiece(start, end) w.openData("Cell", scalars="rainflux") w.addData("rainflux", rainflux) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data=rainflux) w.save()
def rainfluxDiffToVTK(self, i, altPrefix): """ Get Candis filenames based on the prefix and a given integer""" file1 = self.prefix + "/" + self.prefix + "." + self.ipad(i) file2 = altPrefix + "/" + altPrefix + "." + self.ipad(i) """Get Candis file objects based on the prefix and a given integer""" cfile1 = ReadCandis(file1) cfile2 = ReadCandis(file2) rainflux1 = cfile1.getField('rainflux').data rainflux2 = cfile2.getField('rainflux').data nx,ny = rainflux1.shape nz = 1 ncells = nx*ny*nz start = ( 0, 0, 0) end = ( nx, ny, nz) origin = (0.0,0.0,0.0) spacing = (1.0,1.0,1.0) rainflux1 = rainflux1.reshape(rainflux1.shape + (1,)) rainflux2 = rainflux2.reshape(rainflux2.shape + (1,)) rain_diff = rainflux2 - rainflux1 print "Maximum diff for", i, "is", rain_diff.max() w = VtkFile("rainflux_diff." + self.ipad(i), VtkImageData) w.openGrid(start, end, origin, spacing) w.openPiece(start, end) w.openData("Cell", scalars = "rainflux_diff") w.addData("rainflux_diff", rain_diff) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data = rain_diff) w.save()
connections[2*pair],connections[2*pair+1] = ids.index(id1_masked[pair]),ids.index(id2_masked[pair]) # The offset array is simply generated from 2*(1..ncells) offset=(np.arange(nconnex,dtype=int)+1)*2 # The type array is simply ncells x 3 (i.e. a VTKLine type) celltype = np.ones(nconnex,dtype=int)*3 # ****************************************** # Write DATA to FILE (binary) # ****************************************** # create a VTK unstructured grid (.vtu) file vtufile = fileprefix+'_'+str(timestep) vtufile = os.path.join(outputdir,vtufile) w = VtkFile(vtufile, VtkUnstructuredGrid) vtufile += '.vtu' w.openGrid() w.openPiece(npoints=npoints, ncells=nconnex) # Set up Points (x,y,z) data XML w.openElement("Points") w.addData("points", (x,y,z) ) w.closeElement("Points") # Set up Cell data w.openElement("Cells") w.addData("connectivity", connections ) w.addData("offsets", offset) w.addData("types", celltype)
connections[2 * pair], connections[2 * pair + 1] = ids.index( id1_masked[pair]), ids.index(id2_masked[pair]) # The offset array is simply generated from 2*(1..ncells) offset = (np.arange(nconnex, dtype=int) + 1) * 2 # The type array is simply ncells x 3 (i.e. a VTKLine type) celltype = np.ones(nconnex, dtype=int) * 3 # ****************************************** # Write DATA to FILE (binary) # ****************************************** # create a VTK unstructured grid (.vtu) file vtufile = fileprefix + '_' + str(timestep) vtufile = os.path.join(outputdir, vtufile) w = VtkFile(vtufile, VtkUnstructuredGrid) vtufile += '.vtu' w.openGrid() w.openPiece(npoints=npoints, ncells=nconnex) # Set up Points (x,y,z) data XML w.openElement("Points") w.addData("points", (x, y, z)) w.closeElement("Points") # Set up Cell data w.openElement("Cells") w.addData("connectivity", connections) w.addData("offsets", offset) w.addData("types", celltype)
def pc2vtkxml(varfile = 'var.dat', datadir = 'data/', proc = -1, variables = ['rho','uu','bb'], magic = [], destination = 'work', quiet = True): """ Convert data from PencilCode format to XML vtk. Write .vts Structured Grid, not Rectilinear Grid as VisIt screws up reading Rectilinear Grid. However, this is set to write large grids in VTK XML, which is not yet suported by VisIt anyways. Use ParaView. call signature:: pc2xmlvtk(varfile = 'var.dat', datadir = 'data/', proc = -1, variables = ['rho','uu','bb'], magic = [], destination = 'work.vtk') Read *varfile* and convert its content into vtk format. Write the result in *destination*. Keyword arguments: *varfile*: The original varfile. *datadir*: Directory where the data is stored. *proc*: Processor which should be read. Set to -1 for all processors. *variables* = [ 'rho' , 'lnrho' , 'uu' , 'bb', 'b_mag', 'jj', 'j_mag', 'aa', 'tt', 'lnTT', 'cc', 'lncc', 'ss', 'vort', 'eth' ] Variables which should be written. *magic*: [ 'vort' , 'bb' ] Additional variables which should be written. *destination*: Destination file. """ # this should correct for the case the user type only one variable if (len(magic) > 0): if (len(magic[0]) == 1): magic = [magic] # make sure magic is set when writing 'vort' or 'bb' try: index = variables.index('vort') magic.append('vort') except: pass try: index = variables.index('bb') magic.append('bb') except: pass try: index = variables.index('b_mag') magic.append('bb') except: pass try: index = variables.index('tt') magic.append('tt') except: pass # get endian format of the data format = pc.get_format(datadir = datadir) # reading pc variables and setting dimensions var = pc.read_var(varfile = varfile, datadir = datadir, proc = proc, magic = magic, trimall = True, quiet = quiet, format = format) grid = pc.read_grid(datadir = datadir, proc = proc, trim = True, quiet = True, format = format) dimx = len(grid.x) dimy = len(grid.y) dimz = len(grid.z) dim = dimx * dimy * dimz scalardata = {} if ('rho' in variables) : rho = np.transpose(var.rho.copy()) scalardata['rho'] = rho if ('lnrho' in variables) : lnrho = np.transpose(var.lnrho.copy()) scalardata['lnrho'] = lnrho if ('tt' in variables) : tt = np.transpose(var.tt.copy()) scalardata['tt'] = tt if ('lntt' in variables) : lntt = np.transpose(var.lntt.copy()) scalardata['lntt'] = lntt if ('cc' in variables) : cc = np.transpose(var.cc.copy()) scalardata['cc'] = cc if ('lncc' in variables) : lncc = np.transpose(var.lncc.copy()) scalardata['lncc'] = lncc if ('ss' in variables) : ss = np.transpose(var.ss.copy()) scalardata['ss'] = ss if ('eth' in variables) : eth = np.transpose(var.eth.copy()) scalardata['eth'] = eth vectordata = {} if ('uu' in variables) : uu1 = np.transpose(var.uu[0,:,:,:].copy()) uu2 = np.transpose(var.uu[1,:,:,:].copy()) uu3 = np.transpose(var.uu[2,:,:,:].copy()) vectordata['uu'] = (uu1,uu2,uu3) if ('bb' in variables) : bb1 = np.transpose(var.bb[0,:,:,:].copy()) bb2 = np.transpose(var.bb[1,:,:,:].copy()) bb3 = np.transpose(var.bb[2,:,:,:].copy()) vectordata['bb'] = (bb1,bb2,bb3) if ('jj' in variables) : jj1 = np.transpose(var.jj[0,:,:,:].copy()) jj2 = np.transpose(var.jj[1,:,:,:].copy()) jj3 = np.transpose(var.jj[2,:,:,:].copy()) vectordata['jj'] = (jj1,jj2,jj3) if ('aa' in variables) : aa1 = np.transpose(var.aa[0,:,:,:].copy()) aa2 = np.transpose(var.aa[1,:,:,:].copy()) aa3 = np.transpose(var.aa[2,:,:,:].copy()) vectordata['aa'] = (aa1,aa2,aa3) if ('vort' in variables) : vort1 = np.transpose(var.vort[0,:,:,:].copy()) vort2 = np.transpose(var.vort[1,:,:,:].copy()) vort3 = np.transpose(var.vort[2,:,:,:].copy()) vectordata['vort'] = (vort1,vort2,vort3) X = np.zeros([dimx,dimy,dimz]) Y = np.zeros([dimx,dimy,dimz]) Z = np.zeros([dimx,dimy,dimz]) for k in range(dimz): for j in range(dimy): for i in range(dimx): X[i,j,k] = grid.x[i] Y[i,j,k] = grid.y[j] Z[i,j,k] = grid.z[k] start = (0,0,0) end = (dimx-1, dimy-1, dimz-1) time = np.array([var.t]) w = VtkFile(destination, VtkStructuredGrid,largeFile=True) w.openGrid(start = start, end = end) #this s for wirting Time in VisIt files. However, when usign large grid Visit does not work anyways. #w.openFieldData() #w.addTuple('TIME', time.dtype.name,len(time)) #w.closeFieldData() w.openPiece(start = start, end = end) w.openElement("Points") w.addData("points", (X,Y,Z)) w.closeElement("Points") w.openData("Point", scalars = scalardata.keys(), vectors = vectordata.keys()) for key in scalardata: w.addData(key,scalardata[key]) for key in vectordata: w.addData(key,vectordata[key]) w.closeData("Point") w.closePiece() w.closeGrid() #w.appendData( time ) w.appendData( (X,Y,Z) ) for key in scalardata: w.appendData(data = scalardata[key]) for key in vectordata: w.appendData(data = vectordata[key]) w.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, sim_time=i) group.save()
def triangle_faces_to_VTK(filename, x, y, z, faces, point_data, cell_data): vertices = (x, y, z) x2 = x * 1. y2 = y * 1. z2 = z * 1. vert2 = (x2, y2, z2) w = VtkFile(filename, VtkUnstructuredGrid) w.openGrid() w.openPiece(npoints=len(x), ncells=len(faces)) w.openElement("Points") w.addData("Points", vertices) w.closeElement("Points") # Create some temporary arrays to write grid topology. ncells = len(faces) # Index of last node in each cell. offsets = np.arange(start=3, stop=3 * (ncells + 1), step=3, dtype='uint32') # Connectivity as unrolled array. connectivity = faces.reshape(ncells * 3).astype('int32') cell_types = np.ones(ncells, dtype='uint8') * VtkTriangle.tid w.openElement("Cells") w.addData("connectivity", connectivity) w.addData("offsets", offsets) w.addData("types", cell_types) w.closeElement("Cells") _addDataToFile(w, cellData=cell_data, pointData=point_data) w.closePiece() w.closeGrid() w.appendData(vert2) w.appendData(connectivity).appendData(offsets).appendData(cell_types) _appendDataToFile(w, cellData=cell_data, pointData=point_data) w.save() return w.getFileName()
def save2DcellVecVTK(self, resPath, fileName, U, V): '''Function to save single frame data for 2D vector field in VTK format ''' nx, ny, nz = self.cols, self.lins, 1 origin, spacing = (0.0,0.0,0.0), (self.xscale,self.yscale,0.0001) start, end = (0,0,0), (nx, ny, nz) Uvtk = np.ascontiguousarray(np.rot90(U,k=1, axes=(1,0))) Vvtk = np.ascontiguousarray(np.rot90(V,k=1, axes=(1,0))) w = VtkFile(resPath + '/' + fileName, VtkImageData) w.openGrid(start = start, end = end, origin = origin, spacing = spacing) w.openPiece( start = start, end = end) # Cell data zeroScalar = np.zeros([nx, ny, nz], dtype="float64", order='C') w.openData("Cell", vectors = "Velocities") w.addData("Velocities", (Uvtk, Vvtk, zeroScalar)) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data = (Uvtk,Vvtk,zeroScalar)) w.save() return 0
def save2DcellVecTransientVTK(self, resPath, fileName, U, V): '''function to save transient data for 2D vector field in VTK format ''' nx, ny, nz = self.cols, self.lins, 1 origin, spacing = (0.0,0.0,0.0), (self.xscale,self.yscale,0.0001) start, end = (0,0,0), (nx, ny, nz) print('Saving transient data into paraview format') for time,name in enumerate(self.fRes): Ut = U[:,:,time] Vt = V[:,:,time] Uvtk = np.ascontiguousarray(np.rot90(Ut,k=1, axes=(1,0))) Vvtk = np.ascontiguousarray(np.rot90(Vt,k=1, axes=(1,0))) w = VtkFile(resPath + '/' + fileName + str(time), VtkImageData) w.openGrid(start = start, end = end, origin = origin, spacing = spacing) w.openPiece( start = start, end = end) # Cell data zeroScalar = np.zeros([nx, ny, nz], dtype="float64", order='C') w.openData("Cell", vectors = "Velocities") w.addData("Velocities", (Uvtk, Vvtk, zeroScalar)) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data = (Uvtk,Vvtk,zeroScalar)) w.save() return 0
class VTKFile(object): def __init__(self, filename, path='', timestep=0, npx=1, npy=1, npz=1, init_pvd=False): self.timestep = timestep prefix = '_{0}_{1}'.format(timestep, mpi.COMM_WORLD.Get_rank()) if not os.path.exists(path) and mpi.COMM_WORLD.Get_rank() == 0: os.mkdir(path) # All the processes wait for the creation of the output directory mpi.COMM_WORLD.Barrier() self.path = path self.filename = filename self.vtkfile = VtkFile(path + '/' + filename + prefix, VtkRectilinearGrid) self.end = np.zeros(3, dtype=np.int) self.x = None self.y = None self.z = None self.scalars = {} self.vectors = {} self._init_grid = True self._init_pvd = init_pvd self.npx = npx self.npy = npy self.npz = npz self.log = setLogger(__name__) def set_grid(self, x, y=None, z=None): if not self._init_grid: self.log.warning("vtk grid redefined.") self.x = x self.y = y self.z = z self.dim = 1 self.end[0] = x.size - 1 if y is not None: self.dim = 2 self.end[1] = y.size - 1 if z is not None: self.dim = 3 self.end[2] = z.size - 1 self.vtkfile.openGrid(start=(0, ) * 3, end=self.end.tolist()) self.vtkfile.openPiece(start=(0, ) * 3, end=self.end.tolist()) self._init_grid = False def add_scalar(self, name, f, *fargs): if self._init_grid: self.log.error("""You must define the grid before to add scalar (see set_grid method)""") if isinstance(f, np.ndarray): data = f else: data = f(*fargs) if np.all(np.asarray(data.shape) != (self.end + 1)[:self.dim]): self.log.error("""The shape of the scalar data {0} ({1}) must have the shape of the grid ({2})""".format( name, data.shape, self.end + 1)) self.scalars[name] = data.ravel(order='F') def add_vector(self, name, f, *fargs): if self._init_grid: self.log.error("""You must define the grid before to add scalar (see set_grid method)""") if isinstance(f, list): data = f else: data = f(*fargs) for d in data: if np.all(np.asarray(d.shape) != (self.end + 1)[:self.dim]): self.log.error("""The shape of each component of the vector data {0} must have the shape of the grid ({1})""".format( name, self.end + 1)) tdata = () for d in data: tdata += (d.ravel(order='F'), ) if self.dim == 2: tdata += (np.zeros(tdata[0].shape), ) self.vectors[name] = tdata def save(self): if self._init_grid: self.log.error("""You must define the grid before save data (see set_grid method)""") if len(self.scalars) == 0 and len(self.vectors) == 0: self.log.error("""You must provide scalar or vector data to save the vtkfile""") # Point data self.vtkfile.openData("Point", scalars=list(self.scalars.keys()), vectors=list(self.vectors.keys())) for k, v in list(self.scalars.items()): self.vtkfile.addData(k, v) for k, v in list(self.vectors.items()): self.vtkfile.addData(k, v) self.vtkfile.closeData("Point") # Coordinates of cell vertices self.vtkfile.openElement("Coordinates") self.vtkfile.addData("x_coordinates", self.x) if self.y is not None: self.vtkfile.addData("y_coordinates", self.y) if self.z is not None: self.vtkfile.addData("z_coordinates", self.z) else: self.vtkfile.addData("z_coordinates", np.zeros(self.x.shape)) self.vtkfile.closeElement("Coordinates") self.vtkfile.closePiece() self.vtkfile.closeGrid() for k, v in list(self.scalars.items()): self.vtkfile.appendData(data=v) for k, v in list(self.vectors.items()): self.vtkfile.appendData(data=v) if self.y is not None and self.z is not None: self.vtkfile.appendData(self.x).appendData(self.y).appendData( self.z) elif self.y is not None: self.vtkfile.appendData(self.x).appendData(self.y) else: self.vtkfile.appendData(self.x) if mpi.COMM_WORLD.Get_rank() == 0: self._write_pvd() self.vtkfile.save() def _write_pvd(self): size = mpi.COMM_WORLD.Get_size() if self._init_pvd: pvd = """<VTKFile type="Collection" version="0.1" byte_order="LittleEndian"> <Collection> """ for i in range(size): pvd += "<DataSet timestep=\"{2}\" part=\"{0}\" file=\"./{1}_{2}_{0}.vtr\"/>\n".format( i, self.filename, self.timestep) pvd += """</Collection> </VTKFile> """ f = open(self.path + '/' + self.filename + '.pvd', 'w') self._init_pvd = False f.write(pvd) f.close() else: oldlines = open(self.path + '/' + self.filename + '.pvd').readlines() pvd = '' for i in range(size): pvd += "<DataSet timestep=\"{2}\" part=\"{0}\" file=\"./{1}_{2}_{0}.vtr\"/>\n".format( i, self.filename, self.timestep) pvd += """</Collection> </VTKFile> """ f = open(self.path + '/' + self.filename + '.pvd', 'w') f.writelines(oldlines[:-2]) f.write(pvd) f.close()
def convertVelocitiesToVTK(self, i, cfile): vx = cfile.getField('vx').data vy = cfile.getField('vy').data vz = cfile.getField('vz').data nx,ny,nz = vx.shape ncells = nx*ny*nz start = ( 0, 0, 0) end = ( nx, ny, nz) origin = (0.0,0.0,0.0) spacing = (1.0,1.0,1.0) w = VtkFile("v." + self.filename(i), VtkImageData) w.openGrid(start, end, origin, spacing) w.openPiece(start, end) w.openData("Cell", vectors = "velocity") w.addData("velocity", (vx,vy,vz)) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data = (vx,vy,vz)) w.save()
def convertRainfluxToVTK(self, i, cfile): rainflux = cfile.getField('rainflux').data rainflux = rainflux.reshape(rainflux.shape + (1,)) (nx,ny,nz) = rainflux.shape print nx, ny, nz ncells = nx*ny*nz start = ( 0, 0, 0) end = ( nx, ny, nz) origin = (0.0,0.0,0.0) spacing = (1.0,1.0,1.0) w = VtkFile("rainflux." + self.filename(i), VtkImageData) w.openGrid(start, end, origin, spacing) w.openPiece(start, end) w.openData("Cell", scalars = "rainflux") w.addData("rainflux", rainflux) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data = rainflux) w.save()
def convertVelocitiesToVTK(self, i, cfile): vx = cfile.getField('vx').data vy = cfile.getField('vy').data vz = cfile.getField('vz').data nx, ny, nz = vx.shape ncells = nx * ny * nz start = (0, 0, 0) end = (nx, ny, nz) origin = (0.0, 0.0, 0.0) spacing = (1.0, 1.0, 1.0) w = VtkFile("v." + self.filename(i), VtkImageData) w.openGrid(start, end, origin, spacing) w.openPiece(start, end) w.openData("Cell", vectors="velocity") w.addData("velocity", (vx, vy, vz)) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data=(vx, vy, vz)) w.save()
def save2DcellReynoldsVTK(self, resPath, fileName, uu, vv, uv): '''Function to save single frame data for 3D vector field in VTK format now working for Reynolds Stress tensor 3 components ''' nx, ny, nz = self.cols, self.lins, 1 origin, spacing = (0.0,0.0,0.0), (self.xscale,self.yscale,0.0001) start, end = (0,0,0), (nx, ny, nz) uuvtk = np.ascontiguousarray(np.rot90(uu,k=1, axes=(1,0))) vvvtk = np.ascontiguousarray(np.rot90(vv,k=1, axes=(1,0))) uvvtk = np.ascontiguousarray(np.rot90(uv,k=1, axes=(1,0))) w = VtkFile(resPath + '/' + fileName, VtkImageData) w.openGrid(start = start, end = end, origin = origin, spacing = spacing) w.openPiece( start = start, end = end) # Cell data #zeroScalar = np.zeros([nx, ny, nz], dtype="float64", order='C') w.openData("Cell", vectors = fileName) w.addData(fileName, (uuvtk, vvvtk, uvvtk)) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data = (uuvtk,vvvtk,uvvtk)) w.save() return 0
force = np.sqrt( np.array(forcedata.snaps[fileindex].atoms[:,forcedata.names["fx"]],dtype=np.float64)**2 + \ np.array(forcedata.snaps[fileindex].atoms[:,forcedata.names["fy"]],dtype=np.float64)**2 + \ np.array(forcedata.snaps[fileindex].atoms[:,forcedata.names["fz"]],dtype=np.float64)**2 ) # Now we have enough data to create the file: # Points - (x,y,z) (npoints) # Cells # Connectivity - connections (ncells,2) # Offset - offset (ncells) # type - celltype (ncells) # Celldata - force (ncells) # create a VTK unstructured grid (.vtu) file vtufile = fileprefix+'_'+str(timestep) vtufile = os.path.join(outputdir,vtufile) w = VtkFile(vtufile, VtkUnstructuredGrid) vtufile += '.vtu' w.openGrid() w.openPiece(npoints=npoints, ncells=ncells) # Set up Points data w.openElement("Points") w.addData("points", (x,y,z) ) w.closeElement("Points") # Set up Cell data w.openElement("Cells") w.addData("connectivity", connections ) w.addData("offsets", offset)
def writeVTK(filename,xdim, ydim, pointData=None, cellData=None): """ Writes data values as a rectilinear or rectangular grid. PARAMETERS: path: name of the file without extension where data should be saved. cellData: dictionary containing arrays with cell centered data. Keys should be the names of the data arrays. Arrays must have the same dimensions in all directions and must contain only scalar data. nodeData: dictionary containing arrays with node centered data. Keys should be the names of the data arrays. Arrays must have same dimension in each direction and they should be equal to the dimensions of the cell data plus one and must contain only scalar data. RETURNS: Full path to saved file. """ nx, ny, nz = xdim, ydim, 0 lx, ly, lz = xdim/10.0, ydim/10.0, 0 dx, dy, dz = lx/nx, ly/ny, 0 ncells = nx * ny npoints = (nx + 1) * (ny + 1) * (nz + 1) x = np.arange(0, lx + 0.1*dx, dx, dtype='float64') y = np.arange(0, ly + 0.1*dy, dy, dtype='float64') z = np.arange(0,0, dtype='float64') start, end = (0,0,0), (nx, ny, nz) # Set up object w = VtkFile(filename, VtkRectilinearGrid) #Open XML tags w.openGrid(start = start, end = end) w.openPiece( start = start, end = end) # Coordinates of cell vertices w.openElement("Coordinates") w.addData("x_coordinates", x); w.addData("y_coordinates", y); w.addData("z_coordinates", z); w.closeElement("Coordinates"); # Add data from the dictionary #temp = np.random.rand(npoints) __addDataToFile(w, cellData, pointData) #Close XML tags w.closePiece() w.closeGrid() #Append Coordinate Data to file in binary form w.appendData(x).appendData(y).appendData(z) #Append Cell and Point Data to file in binary form __appendDataToFile(w, cellData, pointData) w.save() return w.getFileName()
data4 = file['/Fields/Ex'][...] data5 = file['/Fields/Ey'][...] data6 = file['/Fields/Ez'][...] data7 = file['/Fields/Rho_0'][...] data8 = file['/Fields/Rho_1'][...] data9 = file['/Fields/Jx_0'][...] data10 = file['/Fields/Jy_0'][...] data11 = file['/Fields/Jz_0'][...] data12 = file['/Fields/Jx_1'][...] data13 = file['/Fields/Jy_1'][...] data14 = file['/Fields/Jz_1'][...] # Write the VTK file start, end = (0, 0, 0), (nx, ny, nz) w = VtkFile(vtkfilename+"_"+cycle, VtkRectilinearGrid) w.openGrid (start = start, end = end) w.openPiece(start = start, end = end) # Cell data w.openData("Cell", scalars = "Rho_0, Rho_1", vectors = "B, E, J_0, J_1") w.addData ("Rho_0", data7) w.addData ("Rho_1", data8) w.addData ("B", (data1, data2, data3 )) w.addData ("E", (data4, data5, data6 )) w.addData ("J_0", (data9, data10, data11)) w.addData ("J_1", (data12, data13, data14)) w.closeData("Cell") # Coordinates of cell vertices w.openElement("Coordinates")
data4 = file['/Fields/Ex'][...] data5 = file['/Fields/Ey'][...] data6 = file['/Fields/Ez'][...] data7 = file['/Fields/Rho_0'][...] data8 = file['/Fields/Rho_1'][...] data9 = file['/Fields/Jx_0'][...] data10 = file['/Fields/Jy_0'][...] data11 = file['/Fields/Jz_0'][...] data12 = file['/Fields/Jx_1'][...] data13 = file['/Fields/Jy_1'][...] data14 = file['/Fields/Jz_1'][...] # Write the VTK file start, end = (0, 0, 0), (nx, ny, nz) w = VtkFile(vtkfilename + "_" + cycle, VtkRectilinearGrid) w.openGrid(start=start, end=end) w.openPiece(start=start, end=end) # Cell data w.openData("Cell", scalars="Rho_0, Rho_1", vectors="B, E, J_0, J_1") w.addData("Rho_0", data7) w.addData("Rho_1", data8) w.addData("B", (data1, data2, data3)) w.addData("E", (data4, data5, data6)) w.addData("J_0", (data9, data10, data11)) w.addData("J_1", (data12, data13, data14)) w.closeData("Cell") # Coordinates of cell vertices w.openElement("Coordinates")
# ************************************************************** from evtk.vtk import VtkFile, VtkRectilinearGrid import numpy as np nx, ny, nz = 6, 6, 2 lx, ly, lz = 1.0, 1.0, 1.0 dx, dy, dz = lx / nx, ly / ny, lz / nz ncells = nx * ny * nz npoints = (nx + 1) * (ny + 1) * (nz + 1) x = np.arange(0, lx + 0.1 * dx, dx, dtype='float64') y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64') z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64') start, end = (0, 0, 0), (nx, ny, nz) w = VtkFile("./evtk_test", VtkRectilinearGrid) w.openGrid(start=start, end=end) w.openPiece(start=start, end=end) # Point data temp = np.random.rand(npoints) vx = vy = vz = np.zeros([nx + 1, ny + 1, nz + 1], dtype="float64", order='F') w.openData("Point", scalars="Temperature", vectors="Velocity") w.addData("Temperature", temp) w.addData("Velocity", (vx, vy, vz)) w.closeData("Point") # Cell data pressure = np.zeros([nx, ny, nz], dtype="float64", order='F') w.openData("Cell", scalars="Pressure") w.addData("Pressure", pressure)
def export_to_vtk(xgrid, ygrid, data, data_name): """ Export the specified 2D structured grid to file """ from evtk.vtk import VtkFile, VtkStructuredGrid #stupid reshape data oldshape = data.shape newshape = oldshape + (1,) data = data.reshape(newshape) xgrid = xgrid.reshape(newshape) ygrid = ygrid.reshape(newshape) path = './{}'.format(data_name) w = VtkFile(path, VtkStructuredGrid) #Header stuff? nx, ny = oldshape[0] - 1, oldshape[1] - 1 w.openGrid(start = (0, 0, 0), end = (nx, ny, 0)) w.openPiece(start = (0, 0, 0), end = (nx, ny, 0)) w.openElement("Points") w.addData("points", (xgrid, ygrid, data)) w.closeElement("Points") w.openData("Point", scalars = data_name) w.addData(data_name, data) w.closeData("Point") w.closePiece() w.closeGrid() #Now add the actual data? w.appendData((xgrid, ygrid, data)) w.appendData(data) #finished w.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 = grid.size(2) ncells = grid.size(0) 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, sim_time=i) group.save()
def convertRainMixingToVTK(self, i, cfile): rr = cfile.getField('rr').data nx, ny, nz = rr.shape ncells = nx * ny * nz start = (0, 0, 0) end = (nx, ny, nz) origin = (0.0, 0.0, 0.0) spacing = (1.0, 1.0, 1.0) w = VtkFile("rr." + self.filename(i), VtkImageData) w.openGrid(start, end, origin, spacing) w.openPiece(start, end) w.openData("Cell", scalars="rr") w.addData("rr", rr) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data=rr) w.save()
def run(): print("Running lowlevel...") nx, ny, nz = 6, 6, 2 lx, ly, lz = 1.0, 1.0, 1.0 dx, dy, dz = lx / nx, ly / ny, lz / nz ncells = nx * ny * nz npoints = (nx + 1) * (ny + 1) * (nz + 1) x = np.arange(0, lx + 0.1 * dx, dx, dtype='float64') y = np.arange(0, ly + 0.1 * dy, dy, dtype='float64') z = np.arange(0, lz + 0.1 * dz, dz, dtype='float64') start, end = (0, 0, 0), (nx, ny, nz) w = VtkFile(FILE_PATH, VtkRectilinearGrid) w.openGrid(start=start, end=end) w.openPiece(start=start, end=end) # Point data temp = np.random.rand(npoints) vx = vy = vz = np.zeros([nx + 1, ny + 1, nz + 1], dtype="float64", order='F') w.openData("Point", scalars="Temperature", vectors="Velocity") w.addData("Temperature", temp) w.addData("Velocity", (vx, vy, vz)) w.closeData("Point") # Cell data pressure = np.ones([nx, ny, nz], dtype="float64", order='F') w.openData("Cell", scalars="Pressure") w.addData("Pressure", pressure) w.closeData("Cell") # Coordinates of cell vertices w.openElement("Coordinates") w.addData("x_coordinates", x) w.addData("y_coordinates", y) w.addData("z_coordinates", z) w.closeElement("Coordinates") w.closePiece() w.closeGrid() w.appendData(data=temp) w.appendData(data=(vx, vy, vz)) w.appendData(data=pressure) w.appendData(x).appendData(y).appendData(z) w.save()
def rainfluxDiffToVTK(self, i, altPrefix): """ Get Candis filenames based on the prefix and a given integer""" file1 = self.prefix + "/" + self.prefix + "." + self.ipad(i) file2 = altPrefix + "/" + altPrefix + "." + self.ipad(i) """Get Candis file objects based on the prefix and a given integer""" cfile1 = ReadCandis(file1) cfile2 = ReadCandis(file2) rainflux1 = cfile1.getField('rainflux').data rainflux2 = cfile2.getField('rainflux').data nx, ny = rainflux1.shape nz = 1 ncells = nx * ny * nz start = (0, 0, 0) end = (nx, ny, nz) origin = (0.0, 0.0, 0.0) spacing = (1.0, 1.0, 1.0) rainflux1 = rainflux1.reshape(rainflux1.shape + (1, )) rainflux2 = rainflux2.reshape(rainflux2.shape + (1, )) rain_diff = rainflux2 - rainflux1 print "Maximum diff for", i, "is", rain_diff.max() w = VtkFile("rainflux_diff." + self.ipad(i), VtkImageData) w.openGrid(start, end, origin, spacing) w.openPiece(start, end) w.openData("Cell", scalars="rainflux_diff") w.addData("rainflux_diff", rain_diff) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data=rain_diff) w.save()
def write_vtp_header(path, prefix, active_var_index, var_indices, variable_list, all_dim_vals, vertices, connectivity, offsets, nPoints, nPolygons, outType, cellData=True, pointData=False, xtime=None): # {{{ vtkFile = VtkFile("{}/{}".format(path, prefix), VtkPolyData) if xtime is not None: vtkFile.openElement(str("metadata")) vtkFile.openElement(str("xtime")) vtkFile.xml.addText(str(xtime)) vtkFile.closeElement(str("xtime")) vtkFile.closeElement(str("metadata")) vtkFile.openElement(vtkFile.ftype.name) vtkFile.openPiece(npoints=nPoints, npolys=nPolygons) vtkFile.openElement(str("Points")) vtkFile.addData(str("points"), vertices) vtkFile.closeElement(str("Points")) vtkFile.openElement(str("Polys")) vtkFile.addData(str("connectivity"), connectivity) vtkFile.addData(str("offsets"), offsets) vtkFile.closeElement(str("Polys")) if (cellData): vtkFile.openData( str("Cell"), scalars=[str(var) for var in variable_list[active_var_index]]) for iVar in var_indices: var_name = variable_list[iVar] (out_var_names, dim_list) = \ get_hyperslab_name_and_dims(var_name, all_dim_vals[var_name]) for out_var_name in out_var_names: vtkFile.addHeader(str(out_var_name), outType, nPolygons, 1) vtkFile.closeData(str("Cell")) if (pointData): vtkFile.openData( str("Point"), scalars=[str(var) for var in variable_list[active_var_index]]) for iVar in var_indices: var_name = variable_list[iVar] (out_var_names, dim_list) = \ get_hyperslab_name_and_dims(var_name, all_dim_vals[var_name]) for out_var_name in out_var_names: vtkFile.addHeader(str(out_var_name), outType, nPoints, 1) vtkFile.closeData(str("Point")) vtkFile.closePiece() vtkFile.closeElement(vtkFile.ftype.name) vtkFile.appendData(vertices) vtkFile.appendData(connectivity) vtkFile.appendData(offsets) return vtkFile # }}}
def convertRainMixingToVTK(self, i, cfile): rr = cfile.getField('rr').data nx,ny,nz = rr.shape ncells = nx*ny*nz start = ( 0, 0, 0) end = ( nx, ny, nz) origin = (0.0,0.0,0.0) spacing = (1.0,1.0,1.0) w = VtkFile("rr." + self.filename(i), VtkImageData) w.openGrid(start, end, origin, spacing) w.openPiece(start, end) w.openData("Cell", scalars = "rr") w.addData("rr", rr) w.closeData("Cell") w.closePiece() w.closeGrid() w.appendData(data = rr) w.save()