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
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
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 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 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 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 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 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 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 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 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 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 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 # }}}
w.addData("connectivity", connections ) w.addData("offsets", offset) w.addData("types", celltype) w.closeElement("Cells") # Set up force data w.openData("Cell") w.addData("force", forceClean) # w.addData("area", area) # w.addData("heatflux", heatflux) # w.closeData("Cell") # Set up connectionLength data # w.openData("Cell") w.addData("connectionLength", connectionLengthClean) w.closeData("Cell") # and contact area # w.openData("Cell") # w.addData("area", area) # w.closeData("Cell") # and heat flux # w.openData("Cell") # w.addData("heatflux", heatflux) # w.closeData("Cell") # Wrap up w.closePiece() w.closeGrid()
w.addData("connectivity", connections) w.addData("offsets", offset) w.addData("types", celltype) w.closeElement("Cells") # Set up force data w.openData("Cell") w.addData("force", forceClean) # w.addData("area", area) # w.addData("heatflux", heatflux) # w.closeData("Cell") # Set up connectionLength data # w.openData("Cell") w.addData("connectionLength", connectionLengthClean) w.closeData("Cell") # and contact area # w.openData("Cell") # w.addData("area", area) # w.closeData("Cell") # and heat flux # w.openData("Cell") # w.addData("heatflux", heatflux) # w.closeData("Cell") # Wrap up w.closePiece() w.closeGrid()
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()
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) 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()
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()