def to_vtr(data_dict, file_name, grid, points=None): """ Save a numpy array into a ``.vtr`` rectilinear grid of voxels using pyevtk Parameters: data_dict (numpy array): e.g. {'fac': fac, 'mat': mat} file_name (str): Name of the file for the output. grid (class Grid): The information about the grid can be also provided as a grid object. points (bool), optional: Set as True for exporting cell-centered points for contouring (e.g., hydraulic heads) Returns: A VTK STRUCTURED_POINTS dataset file containing the input numpy data. .. note: * Only 'STRUCTURED_POINTS' output allowed. * The type of the data is extracted from the input array. * Only 3D of 2D input data allowed. * The default output is set to 'POINT_DATA'. """ if points is True: gvec = grid.vec() gridToVTK(file_name, gvec[0], gvec[1], gvec[2], pointData=data_dict) else: gvec = grid.vec_node() gridToVTK(file_name, gvec[0], gvec[1], gvec[2], cellData=data_dict)
def export_to_vtk(self, vtk_filename="geo_grid", real_coords=True, **kwds): """Export grid to VTK for visualisation **Arguments**: - *vtk_filename* = string : vtk filename (obviously...) - *real_coords* = bool : model extent in "real world" coordinates **Optional Keywords**: - *grid* = numpy grid : grid to save to vtk (default: self.grid) - *var_name* = string : name of variable to plot (default: Geology) Note: requires pyevtk, available at: https://bitbucket.org/pauloh/pyevtk """ grid = kwds.get("grid", self.grid) var_name = kwds.get("var_name", "Geology") # from evtk.hl import gridToVTK import pyevtk from pyevtk.hl import gridToVTK # define coordinates x = np.zeros(self.nx + 1) y = np.zeros(self.ny + 1) z = np.zeros(self.nz + 1) x[1:] = np.cumsum(self.delx) y[1:] = np.cumsum(self.dely) z[1:] = np.cumsum(self.delz) # plot in coordinates if real_coords: x += self.xmin y += self.ymin z += self.zmin gridToVTK(vtk_filename, x, y, z, cellData={var_name: grid})
def vtk_export_structured(filename, pos, field, fieldname="field"): """Export a field to vtk structured rectilinear grid file Parameters ---------- filename : :class:`str` Filename of the file to be saved, including the path. Note that an ending (\*.vtr or \*.vtu) will be added to the name. pos : :class:`list` the position tuple, containing main direction and transversal directions field : :class:`numpy.ndarray` Structured field to be saved. As returned by SRF. fieldname : :class:`str`, optional Name of the field in the VTK file. Default: "field" """ x, y, z = pos2xyz(pos) if y is None: y = np.array([0]) if z is None: z = np.array([0]) # need fortran order in VTK field = field.reshape(-1, order="F") if len(field) != len(x) * len(y) * len(z): raise ValueError("gstools.vtk_export_structured: " + "field shape doesn't match the given mesh") gridToVTK(filename, x, y, z, pointData={fieldname: field})
def MNT(file): hi = 2 ncfile1 = Dataset(file, 'r') ZS = ncfile1.variables['ZS'][:, :] Y = ncfile1.variables['YHAT'][:].data X = ncfile1.variables['XHAT'][:].data IIE = len(X) IJE = len(Y) x = np.zeros((hi, len(X), len(Y))) y = np.zeros((hi, len(X), len(Y))) x[0, :, :], y[0, :, :] = np.meshgrid(X, Y) for i in range(hi): x[i, :, :] = x[0, :, :] y[i, :, :] = y[0, :, :] x = np.rot90(np.float64(x), 1, (2, 0))[1:, 1:, :] y = np.rot90(np.float64(y), 1, (2, 0))[1:, 1:, :] x = np.copy(x, order='F') y = np.copy(y, order='F') z0 = np.zeros((len(X), len(Y))) z = np.linspace(z0, ZS, hi).data Z = np.rot90(np.float64(z), 1, (2, 0))[1:, 1:, :] Z = np.copy(Z, order='F') na = os.path.split(file)[-1][:-3] gridToVTK('./MNT' + na, x, y, Z, pointData={"Z": Z}) print(na + 'MNT')
def export_to_vtk(self, filename: str): """Writes the WW instance in VTK format with the name filename. Works for both types of coordinates. The implementation is different depending on the type of coordinates""" if self.coordinates == 'cyl': self._export_to_vtk_cyl(filename) return # VTK writing for cart coordinates # Create and fill the "cellData" dictionary cell_data: dict = { } # Key: name of the data_array, Value: np.array of values in 3D dimensions [[[]]] for particle in self.particles: for energy in self.energies[particle]: array_name = f'{particle}_{energy:.3e}MeV' cell_data[array_name] = self.values[particle][energy] # If the ratios are calculated add them to the data arrays if self.ratios is not None: for particle in self.particles: for energy in self.energies[particle]: array_name = f'Max_ratio_{particle}_{energy:.3e}MeV' cell_data[array_name] = self.ratios[particle][energy] cell_data[ f'Total_max_ratio_{particle}'] = self.ratios_total_max[ particle] # Export to VTR format gridToVTK(f'./{filename}', self.vector_i, self.vector_j, self.vector_k, cellData=cell_data) return
def execute(self): #aqui vai o codigo #getting variables pts_grid = self.params['gridselectorbasic']['value'] pts_props = self.params['orderedpropertyselector']['value'].split(';') grids_grid = self.params['gridselectorbasic_2']['value'] grids_props = self.params['orderedpropertyselector_2']['value'].split( ';') flname_pts = self.params['filechooser']['value'] flname_grid = self.params['filechooser_2']['value'] if len(pts_props) != 0: x, y, z = np.array(sgems.get_X(pts_grid)), np.array( sgems.get_Y(pts_grid)), np.array(sgems.get_Z(pts_grid)) vardict = {} for v in pts_props: values = np.array(sgems.get_property(pts_grid, v)) vardict[v] = values pointsToVTK(flname_pts, x, y, z, data=vardict) print('Point set saved to {}'.format(flname_pts)) if len(grids_props) != 0: X, Y, Z = grid_vertices(grids_grid) vardict = {} for v in grids_props: values = np.array(sgems.get_property(grids_grid, v)) vardict[v] = values gridToVTK(flname_grid, X, Y, Z, cellData=vardict) print('Grid saved to {}'.format(flname_grid)) return True
def export_products(self, particulator): if len(particulator.products) != 0: path = self.products_file_path + '_num' + self.add_leading_zeros(particulator.n_steps) self.exported_times['products'][path] = particulator.n_steps * particulator.dt if self.verbose: print("Exporting Products to vtk, path: " + path) payload = {} if particulator.mesh.dimension == 2: data_shape = (particulator.mesh.grid[0], particulator.mesh.grid[1], 1) for k in particulator.products.keys(): v = particulator.products[k].get() if isinstance(v, np.ndarray): if v.shape == particulator.mesh.grid: payload[k] = v.T[:, :, np.newaxis] else: if self.verbose: print(f'{k} shape {v.shape} not equals data shape {data_shape} and will not be exported', file=sys.stderr) elif isinstance(v, numbers.Number): if self.verbose: print(f'{k} is a Number and will not be exported', file=sys.stderr) else: if self.verbose: print(f'{k} export is not possible', file=sys.stderr) x, y, z = np.mgrid[:particulator.mesh.grid[0] + 1, :particulator.mesh.grid[1] + 1, :1] else: raise NotImplementedError("Only 2 dimensions data is supported at the moment.") gridToVTK(path, x, y, z, cellData = payload) else: if self.verbose: print('No products to export')
def buildMesh(self, outfolder='.'): """ Create a vtk unstructured grid based on current time step stratal parameters. Parameters ---------- variable : outfolder Folder path to store the stratal vtk mesh. """ vtkfile = '%s/stratalMesh.time%s'%(outfolder, self.timestep) x = np.zeros((self.nx, self.ny, self.nz)) y = np.zeros((self.nx, self.ny, self.nz)) z = np.zeros((self.nx, self.ny, self.nz)) e = np.zeros((self.nx, self.ny, self.nz)) h = np.zeros((self.nx, self.ny, self.nz)) t = np.zeros((self.nx, self.ny, self.nz)) for k in range(self.nz): for j in range(self.ny): for i in range(self.nx): x[i,j,k] = self.xi[i] y[i,j,k] = self.yi[j] z[i,j,k] = self.dep[j,i,k] e[i,j,k] = self.elev[j,i,k] h[i,j,k] = self.th[j,i,k] t[i,j,k] = k gridToVTK(vtkfile, x, y, z, pointData = {"relative elevation" : e, "thickness" :h, "layer ID" :t}) return
def fci_to_vtk(infile, outfile, scale=5): if not have_evtk: return with bdata.DataFile(infile, write=False, create=False) as f: dx = f.read('dx') dy = f.read('dy') bx = f.read('bx') by = np.ones(bx.shape) bz = f.read('bz') if bx is None: xt_prime = f.read('forward_xt_prime') zt_prime = f.read('forward_zt_prime') array_indices = indices(xt_prime.shape) bx = xt_prime - array_indices[0, ...] by = by * dy bz = zt_prime - array_indices[2, ...] nx, ny, nz = bx.shape dz = nx * dx / nz x = np.linspace(0, nx * dx, nx) y = np.linspace(0, ny * dy, ny, endpoint=False) z = np.linspace(0, nz * dz, nz, endpoint=False) gridToVTK(outfile, x * scale, y, z * scale, pointData={'B': (bx * scale, by, bz * scale)})
def saveVTK3D(macrsDict, filenameWrite, points=True, normVal=0): info = getSimInfo() if (normVal == 0): normVal = info['NX'] if (points == True): normVal -= 1 dx, dy, dz = 1.0 / normVal, 1.0 / normVal, 1.0 / normVal if info['Prc'] == 'double': prc = 'float64' elif info['Prc'] == 'float': prc = 'float32' if (points == False): # grid x = np.arange(0, info['NX'] / normVal + 0.1 * dx, dx, dtype=prc) y = np.arange(0, info['NY'] / normVal + 0.1 * dy, dy, dtype=prc) z = np.arange(0, info['NZ'] / normVal + 0.1 * dz, dz, dtype=prc) gridToVTK(PATH + filenameWrite, x, y, z, cellData=macrsDict) else: # grid x = np.arange(0, (info['NX'] - 1) / normVal + 0.1 * dx, dx, dtype=prc) y = np.arange(0, (info['NY'] - 1) / normVal + 0.1 * dy, dy, dtype=prc) z = np.arange(0, (info['NZ'] - 1) / normVal + 0.1 * dz, dz, dtype=prc) gridToVTK(PATH + filenameWrite, x, y, z, pointData=macrsDict)
def vtk_export_structured(filename, pos, fields): # pragma: no cover """Export a field to vtk structured rectilinear grid file. Parameters ---------- filename : :class:`str` Filename of the file to be saved, including the path. Note that an ending (.vtr) will be added to the name. pos : :class:`list` the position tuple, containing main direction and transversal directions fields : :class:`dict` or :class:`numpy.ndarray` Structured fields to be saved. Either a single numpy array as returned by SRF, or a dictionary of fields with theirs names as keys. """ if not isinstance(fields, dict): fields = {"field": fields} x, y, z = pos2xyz(pos) if y is None: y = np.array([0]) if z is None: z = np.array([0]) # need fortran order in VTK for field in fields: fields[field] = fields[field].reshape(-1, order="F") if len(fields[field]) != len(x) * len(y) * len(z): raise ValueError("gstools.vtk_export_structured: " + "field shape doesn't match the given mesh") gridToVTK(filename, x, y, z, pointData=fields)
def fci_to_vtk(infile, outfile, scale=5): if not have_evtk: return with bdata.DataFile(infile, write=False, create=False) as f: dx = f.read('dx') dy = f.read('dy') bx = f.read('bx') by = np.ones(bx.shape) bz = f.read('bz') if bx is None: xt_prime = f.read('forward_xt_prime') zt_prime = f.read('forward_zt_prime') array_indices = indices(xt_prime.shape) bx = xt_prime - array_indices[0,...] by = by * dy bz = zt_prime - array_indices[2,...] nx, ny, nz = bx.shape dz = nx*dx / nz x = np.linspace(0, nx*dx, nx) y = np.linspace(0, ny*dy, ny, endpoint=False) z = np.linspace(0, nz*dz, nz, endpoint=False) gridToVTK(outfile, x*scale, y, z*scale, pointData={'B' : (bx*scale, by, bz*scale)})
def export_to_vtk(self, vtk_filename="geo_grid", real_coords=True, **kwds): """Export grid to VTK for visualisation **Arguments**: - *vtk_filename* = string : vtk filename (obviously...) - *real_coords* = bool : model extent in "real world" coordinates **Optional Keywords**: - *grid* = numpy grid : grid to save to vtk (default: self.grid) - *var_name* = string : name of variable to plot (default: Geology) Note: requires pyevtk, available at: https://bitbucket.org/pauloh/pyevtk """ grid = kwds.get("grid", self.grid) var_name = kwds.get("var_name", "Geology") #from evtk.hl import gridToVTK import pyevtk from pyevtk.hl import gridToVTK # define coordinates x = np.zeros(self.nx + 1) y = np.zeros(self.ny + 1) z = np.zeros(self.nz + 1) x[1:] = np.cumsum(self.delx) y[1:] = np.cumsum(self.dely) z[1:] = np.cumsum(self.delz) # plot in coordinates if real_coords: x += self.xmin y += self.ymin z += self.zmin gridToVTK(vtk_filename, x, y, z, cellData={var_name: grid})
def to_vtk(self, filename): from pyevtk.hl import gridToVTK g = self.gamma() ntor = g.shape[0] npol = g.shape[1] x = self.gamma()[:, :, 0].reshape((1, ntor, npol)).copy() y = self.gamma()[:, :, 1].reshape((1, ntor, npol)).copy() z = self.gamma()[:, :, 2].reshape((1, ntor, npol)).copy() n = self.normal().reshape((1, ntor, npol, 3)) dphi = self.gammadash1().reshape((1, ntor, npol, 3)) dtheta = self.gammadash2().reshape((1, ntor, npol, 3)) contig = np.ascontiguousarray gridToVTK(filename, x, y, z, pointData={ "dphi x dtheta": (contig(n[..., 0]), contig(n[..., 1]), contig(n[..., 2])), "dphi": (contig(dphi[..., 0]), contig(dphi[..., 1]), contig(dphi[..., 2])), "dtheta": (contig(dtheta[..., 0]), contig(dtheta[..., 1]), contig(dtheta[..., 2])), })
def plotPhiStrainEnerg(nPred, xGrid, yGrid, zGrid, phi_pred, frac_energy_pred, iStep): nx, ny, nz = nPred[0], nPred[1], nPred[2] phi = phi_pred.reshape(nx, ny, nz) fracEnergy = frac_energy_pred.reshape(nx, ny, nz) filename = 'Phase_Field_Step_' + iStep gridToVTK("./"+filename, xGrid, yGrid, zGrid, pointData = {"Phi" : phi, "Fracture Energy" : fracEnergy})
def logLawFitting(dfBase, df, uTauV, dUPlusV, nu, dyV, saveName): errorGrid = np.zeros([len(uTauV), len(dyV), len(dUPlusV)]) ### estimate kappa and C from base profile # initialise fields tUPlusBase = dfBase.UxMean.as_matrix() / dfBase.uTau.as_matrix()[0] tyPlusBase = dfBase.y.as_matrix() * dfBase.uTau.as_matrix( )[0] / dfBase.nu.as_matrix()[0] # limit to log-region UPlusBase = tUPlusBase[(tyPlusBase > 50) & (dfBase.y < 0.8 * dfBase.delta.as_matrix()[0])] yPlusBase = tyPlusBase[(tyPlusBase > 50) & (dfBase.y < 0.8 * dfBase.delta.as_matrix()[0])] # find alpha and beta from linearRegression [a, b, R] = linearReg(UPlusBase, np.log(yPlusBase)) # use these to estimate denticle params uTau and deltaU # # i.e denticle case: u+ = 1/kappa * ln(y+) + C + deltaU # tdelta = df.z.as_matrix()[df.UxMean.as_matrix() > 0.98 * np.mean(df.UxMean.as_matrix()[-4:])][0] * 1e-3 tU = df.UxMean.as_matrix() for k in range(len(dyV)): ty = df.z.as_matrix() * 1e-3 - dyV[k] for i in range(len(uTauV)): # construct fields tUPlus = tU / uTauV[i] tyPlus = ty * uTauV[i] / nu UPlus = tUPlus[(tyPlus > 50) & (df.z.as_matrix() * 1e-3 < 0.8 * tdelta)] yPlus = tyPlus[(tyPlus > 50) & (df.z.as_matrix() * 1e-3 < 0.8 * tdelta)] for j in range(len(dUPlusV)): Ufit = b * np.log(yPlus) + a nrms = np.sqrt(np.mean(Ufit - UPlus - dUPlusV[j])** 2) / np.mean(Ufit) errorGrid[i][k][j] = nrms errorGrid[np.isnan(errorGrid)] = 1 errorGrid[errorGrid > 1] = 1 locmax = np.unravel_index(errorGrid.argmax(), errorGrid.shape) locmin = np.unravel_index(errorGrid.argmin(), errorGrid.shape) uTaunorm = (uTauV - np.min(uTauV)) / (np.max(uTauV) - np.min(uTauV)) # dynorm = (dYV-np.min(dYV))/(np.max(dYV)-np.min(dYV)) dUPlusnorm = (dUPlusV - np.min(dUPlusV)) / (np.max(dUPlusV) - np.min(dUPlusV)) enorm = (errorGrid - errorGrid[locmin]) / (errorGrid[locmax] - errorGrid[locmin]) # print(enorm) gridToVTK(str('./' + saveName), uTaunorm, np.array([0, 1]), dUPlusnorm, pointData={'enorm': enorm}) # gridToVTK(str('./' + saveName), kappa,deltaY,a, pointData={'error':errorGrid}) print(str('rms error = ' + str(errorGrid[locmin]))) return ([uTauV[locmin[0]], dyV[locmin[1]], dUPlusV[locmin[2]]])
def write_vtr(self): """Write rectilinear VTR file.""" from pyevtk.hl import gridToVTK gridToVTK(self.vtrname, self.axis0, self.axis1, self.axis2, pointData={self.dataname: self.data})
def save_scalar_cube(cube, data_name, filename, origin=(0., 0., 0.), spacing=(1., 1., 1.)): X = np.arange(origin[0], np.shape(cube)[0], spacing[0], dtype='float64') Y = np.arange(origin[1], np.shape(cube)[1], spacing[1], dtype='float64') Z = np.arange(origin[2], np.shape(cube)[2], spacing[2], dtype='float64') gridToVTK(filename, X, Y, Z, pointData={data_name: cube}) return None
def plotDispStrainEnerg(nPred, xGrid, yGrid, zGrid, u_pred, v_pred, w_pred, elas_energy_pred, iStep): nx, ny, nz = nPred[0], nPred[1], nPred[2] u = u_pred.reshape(nx, ny, nz) v = v_pred.reshape(nx, ny, nz) w = w_pred.reshape(nx, ny, nz) disp = (u, v, w) elasEnergy = elas_energy_pred.reshape(nx, ny, nz) filename = 'Elastic_Step_' + iStep gridToVTK("./"+filename, xGrid, yGrid, zGrid, pointData = {"Displacement" : disp, "Elastic Energy" : elasEnergy})
def main(matfile="Zdisp4D.mat", Xmm='Xmm', Ymm='Ymm', Zmm='Zmm', Zdisp='Zdisp', tms='tms'): """extract 4D displacement data from Matlab file and write to Paraview PVD/VTR format Args: matfile: Matlab file Xmm: X-axis array Ymm: Y-axis array Zmm: Z-axis array Zdisp: 4D displacement matrix (X x Y x Z x time) tms: time array Returns: """ from scipy.io import loadmat from pyevtk.hl import gridToVTK from pathlib import Path matdata = Path(matfile) datafile_prefix = matdata.with_suffix('') data = loadmat(matdata) with open(f'{datafile_prefix.name}.pvd', 'w') as pvd: pvd.write('<?xml version="1.0"?>\n') pvd.write('<VTKFile type="Collection" version="0.1" ' 'byte_order="LittleEndian" ' 'compressor="vtkZLibDataCompressor">\n') pvd.write(' <Collection>\n') for ts, time in enumerate(data[tms].ravel()): zdisp = data[Zdisp][:, :, :, ts] vtrfilename = Path(f'{datafile_prefix.name}_T{ts:04d}.vtr') logger.info(f'Writing file: {vtrfilename}') pvd.write( f' <DataSet timestep="{time}" group="" part="" file="{vtrfilename.name}"/>\n' ) gridToVTK(vtrfilename.with_suffix('').name, data[Xmm].ravel(), data[Ymm].ravel(), data[Zmm].ravel(), pointData={Zdisp: zdisp}) pvd.write(' </Collection>\n') pvd.write('</VTKFile>\n')
def model_to_vtk(model_ds, paradir, fname, layer=14, datavar='kh', nan_factor=0.01): """ Parameters ---------- model_ds : xarray DataSet model dataset within the extent that is exported to vtk. paradir : str directory to save the vtk file. fname : str filename of the vtk file. layer : int number of the regis layer you want to convert to vtk datavar : str name of the data variabel you want to convert to vtk nan_factor : float if the value in a cell is more than (0.01) part influenced by nan values make it a nan value Returns ------- 1 if succesfull. """ X = np.append(model_ds.x.values - (model_ds.delr / 2), model_ds.x.values[-1] + (model_ds.delr / 2)) Y = np.append(model_ds.y.values[::-1] - (model_ds.delc / 2), model_ds.y.values[::-1][-1] + (model_ds.delc / 2)) Z = np.linspace(-1, 1, 2) x, y, z = np.meshgrid(X, Y, Z, indexing='ij') x = x.astype(float) y = y.astype(float) if layer == 0: top = project_to_grid(model_ds['top'], X, Y, nan_factor) else: top = project_to_grid(model_ds['bot'][layer - 1], X, Y, nan_factor) bot = project_to_grid(model_ds['bot'][layer], X, Y, nan_factor) z[:, :, 0] = (top.T * 100) z[:, :, 1] = (bot.T * 100) arr = model_ds[datavar][layer:layer + 1].values arr[0] = arr[0][::-1] arr = arr.T gridToVTK(os.path.join(paradir, fname), x, y, z, cellData={datavar: arr}) return 1
def savepvd(ts_start=0, part=0, **kwargs): """Save Paraview PVD rectilinear (VTR) time series data. Paraview data formats: https://www.paraview.org/Wiki/ParaView/Data_formats Args: ts_start (int): override starting timestep index from 0 to this value arfidata (float): 4D arfidata matrix axial (float): depth axis vector [mm] lat (float): lateral axis vector [mm] elev (float): elevation axis vector [mm] t (float): time vector (s) resfile (str): 'res_sim.pvd' Raises: ValueError: Not saving 3D time series data. FileExistsError: PVD file directory cannot be created. """ from pyevtk.hl import gridToVTK import os import numpy as np if kwargs['arfidata'].ndim != 4: raise ValueError("Trying to save timeseries VTR data not supported.") resfileprefix = os.path.splitext(kwargs['resfile'])[0] with open(kwargs['resfile'], 'w') as pvd: pvd.write('<?xml version="1.0"?>\n') pvd.write('<VTKFile type="Collection" version="0.1" ' 'byte_order="LittleEndian" ' 'compressor="vtkZLibDataCompressor">\n') pvd.write(' <Collection>\n') for ts, time in enumerate(kwargs['t']): arfidata = np.asfortranarray( np.squeeze(kwargs['arfidata'][:, :, :, ts])).transpose() timestep = ts_start + ts vtrfilename = '{}_T{:04d}'.format(resfileprefix, ts) pvd.write(' <DataSet timestep="{}" group="" part="{}" ' 'file="{}.vtr"/>\n'.format( timestep, part, os.path.basename(vtrfilename))) gridToVTK('{}'.format(vtrfilename), kwargs['elev'].ravel(), kwargs['lat'].ravel(), kwargs['axial'].ravel(), pointData={'arfidata': arfidata}) pvd.write(' </Collection>\n') pvd.write('</VTKFile>\n')
def output_mask(self, no_collision_mask): """Outputs the no_collision_mask of the simulation object as VTK-file with range [0,1] Usage: vtk_reporter.output_mask(simulation.no_collision_mask)""" point_dict = dict() if self.lattice.D == 2: point_dict["mask"] = self.lattice.convert_to_numpy(no_collision_mask)[..., None].astype(int) else: point_dict["mask"] = self.lattice.convert_to_numpy(no_collision_mask).astype(int) vtk.gridToVTK(self.filename_base + "_mask", np.arange(0, point_dict["mask"].shape[0]), np.arange(0, point_dict["mask"].shape[1]), np.arange(0, point_dict["mask"].shape[2]), pointData=point_dict)
def generateVTK(fin, fout): ''' Generates a VTK file out of a given file :param fin: File name of the input file :param fout: File name of the output file ''' # Read in general info count = 11 fname = fin from pyevtk.hl import gridToVTK r, th, ph, x, y, z, pointData = pp.readDataFile(fname) fOut = fout gridToVTK(fOut, x, y, z, pointData=pointData)
def save_vector_data(vx, vy, vz, vector_name, filename, origin=(0., 0., 0.), spacing=(1., 1., 1.)): """CORRECTLY SAVES VECTOR DATA LIKE IN IDL's: sav2vtk.pro""" assert np.shape(vx) == np.shape(vy) == np.shape(vz) X = np.arange(origin[0], np.shape(vx)[0], spacing[0], dtype='float64') Y = np.arange(origin[1], np.shape(vx)[1], spacing[1], dtype='float64') Z = np.arange(origin[2], np.shape(vx)[2], spacing[2], dtype='float64') gridToVTK(filename, X, Y, Z, pointData={vector_name: (vx, vy, vz)}) return None
def save_VTR(data, file): """ save as a .vtr file for VisIt :param data: :param file: :return: """ dim = data.shape x = np.arange(0, dim[0] + 1) y = np.arange(0, dim[1] + 1) z = np.arange(0, dim[2] + 1) filename = "./" + file gridToVTK(filename, x, y, z, cellData={file: data})
def save_VTR(data, file): """ save as a .vtr file for VisIt obtained/adapted from https://pyscience.wordpress.com/2014/09/06/numpy-to-vtk-converting-your-numpy-arrays-to-vtk-arrays-and-files/ :param data: array :param file: filename """ dim = data.shape x = np.arange(0, dim[0] + 1) y = np.arange(0, dim[1] + 1) z = np.arange(0, dim[2] + 1) filename = "./" + file gridToVTK(filename, x, y, z, cellData={file: data})
def vector_field(): # directly copied from the pyevtk github examples: # pyevtk/examples/structured.py, # and then we modified this but now for vector data from pyevtk.hl import gridToVTK import numpy as np import random as rnd # Dimensions nx, ny, nz = 4, 9, 1 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) # Coordinates 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") x = np.zeros((nx + 1, ny + 1, nz + 1)) y = np.zeros((nx + 1, ny + 1, nz + 1)) z = np.zeros((nx + 1, ny + 1, nz + 1)) # We add some random fluctuation to make the grid # more interesting for k in range(nz + 1): for j in range(ny + 1): for i in range(nx + 1): x[i, j, k] = X[i] #+ (0.5 - rnd.random()) * 0.1 * dx y[i, j, k] = Y[j] #+ (0.5 - rnd.random()) * 0.1 * dy z[i, j, k] = Z[k] #+ (0.5 - rnd.random()) * 0.1 * dz # Variables pressure = np.random.rand(ncells).reshape((nx, ny, nz)) temp = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1)) fname = os.path.join(outdir, 'vector') gridToVTK( fname, x, y, z, cellData={"pressure": pressure}, pointData={"vel": (temp, -temp, temp)}, ) return 0
def minFunc(U, yTilde, kappa, deltaY, a, nu, PI, method, saveName): errorGrid = np.zeros([len(kappa), len(deltaY), len(a)]) for k in range(len(kappa)): print( str('Matrix construction ' + str(k * 100 / len(kappa)) + ' % complete')) for dy in range(len(deltaY)): y = (yTilde - deltaY[dy]) [uTau, deltaStar, theta, H] = clauserEstimation(U, y, kappa[k], nu) yPlus = y * uTau / nu UPlus = U / uTau for i in range(len(a)): e = compositeLeastSquares(UPlus, yPlus, kappa[k], nu, a[i], PI, 'none') if np.isnan(e): errorGrid[k][dy][i] = 1.0 else: errorGrid[k][dy][i] = e # print(e) locmin = np.unravel_index(errorGrid.argmin(), errorGrid.shape) locmax = np.unravel_index(errorGrid.argmax(), errorGrid.shape) if saveName is not False: if len(kappa) == 1: knorm = np.array([0, 1]) else: knorm = (kappa - np.min(kappa)) / (np.max(kappa) - np.min(kappa)) if len(deltaY) == 1: dynorm = np.array([0, 1]) else: dynorm = (deltaY - np.min(deltaY)) / (np.max(deltaY) - np.min(deltaY)) if len(a) == 1: anorm = np.array([0, 1]) else: anorm = (a - np.min(a)) / (np.max(a) - np.min(a)) enorm = (errorGrid - errorGrid[locmin]) / (errorGrid[locmax] - errorGrid[locmin]) # print(enorm) gridToVTK(str('./' + saveName), knorm, dynorm, anorm, pointData={'enorm': enorm}) # gridToVTK(str('./' + saveName), kappa,deltaY,a, pointData={'error':errorGrid}) print(str('rms error = ' + str(errorGrid[locmin]))) return ([kappa[locmin[0]], deltaY[locmin[1]], a[locmin[2]]])
def write_vts(grid_obj, path_to_file, nx_cells, ny_cells, nz_cells): """ Write the energy grid as a binary vtk (.vts) file. :type grid_obj: instance of the grid3D class :param grid_obj: Contains all the info regarding the energy grid :type path_to_file: str :param path_to_file: path to the output file including full file name and no extension. :raises: :rtype: Just writes the file. """ import numpy as np from pyevtk.hl import gridToVTK # For we need the grid x, y, z, E style # Define the crazy unstructured grid # dx, dy, dz = 1.0 / grid_obj.nx_total, 1.0 / grid_obj.ny_total, 1.0 / grid_obj.nz_total X = np.arange(0, 1 + 0.1 * dx, dx, dtype='float64') Y = np.arange(0, 1 + 0.1 * dy, dy, dtype='float64') Z = np.arange(0, 1 + 0.1 * dz, dz, dtype='float64') x = np.zeros((grid_obj.nx_total, grid_obj.ny_total, grid_obj.nz_total)) y = np.zeros((grid_obj.nx_total, grid_obj.ny_total, grid_obj.nz_total)) z = np.zeros((grid_obj.nx_total, grid_obj.ny_total, grid_obj.nz_total)) for k in range(grid_obj.nz_total): for j in range(grid_obj.ny_total): for i in range(grid_obj.nx_total): x[i, j, k] = X[i] y[i, j, k] = Y[j] z[i, j, k] = Z[k] for k in range(grid_obj.nz_total): for j in range(grid_obj.ny_total): for i in range(grid_obj.nx_total): [x[i, j, k], y[i, j, k], z[i, j, k]] = np.dot(grid_obj.A, [x[i, j, k], y[i, j, k], z[i, j, k]]) #Write pot into .vts file gridToVTK(path_to_file, x, y, z, pointData={ "Potential": np.tile(grid_obj.pot, (nx_cells, ny_cells, nz_cells)) })
def writeVTKcell(fileName, data_name, data, time_level, spacingx, spacingy, spacingz): data2 = np.fliplr( np.flipud( np.rot90(data[2:np.size(spacingy, 2) + 1, 2:np.size(spacingx, 0) + 1]))) plot_data = np.zeros( (np.size(spacingx, 0) - 1, 1, np.size(spacingy, 2) - 1)) plot_data[:, 0, :] = data2 gridToVTK(fileName + str(time_level), spacingx, spacingz, spacingy, cellData={data_name: plot_data})
def save_to_vtk(data, filepath): """ save the 3d data to a .vtk file. Parameters ------------ data : 3d np.array 3d matrix that we want to visualize filepath : str where to save the vtk model, do not include vtk extension, it does automatically """ x = np.arange(data.shape[0] + 1) y = np.arange(data.shape[1] + 1) z = np.arange(data.shape[2] + 1) gridToVTK(filepath, x, y, z, cellData={'data': data.copy()})
def print_vtk(self, data, print_type=True): if print_type == 'binary': print 'PRINT VTR {name}'.format(name=self.name) nx, ny, nz = self.number_of_nodes['x']-1, self.number_of_nodes['y']-1, self.number_of_nodes['z']-1 lx, ly, lz = self.length['x'], self.length['y'] , self.length['z'] dx, dy, dz = 1.0*lx/nx, 1.0*ly/ny, 1.0*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') gridToVTK(self.name, x, y, z, pointData = {self.name:data}) else: c = self.create_lexico() print 'PRINT VTK {name}'.format(name=self.name) file='{}.vtk'.format(self.name) with open(file, 'w') as f: f.write('# vtk DataFile Version 2.0\n') f.write('{}\n'.format(self.name)) f.write('ASCII\nDATASET STRUCTURED_GRID\n') if self.dim == 2: f.write('DIMENSIONS {x} {y} 1\n\n'.format(**self.number_of_nodes)) else: f.write('DIMENSIONS {x} {y} {z}\n\n'.format(**self.number_of_nodes)) f.write('POINTS {} float\n'.format(np.prod([n for n in self.number_of_nodes.itervalues()]))) if self.dim == 2: for x, y in zip(c['x'], c['y']): f.write('{x} {y} 0.0\n'.format(x=x, y=y)) else: for x, y, z in zip(c['x'], c['y'], c['z']): f.write('{x} {y} {z}\n'.format(x=x, y=y, z=z)) f.write('\n') f.write('POINT_DATA {}\n'.format(np.prod([n for n in self.number_of_nodes.itervalues()]))) f.write('SCALARS {} float 1\n'.format(self.name)) f.write('LOOKUP_TABLE default\n') for r in data.flatten(order='F'): f.write('{}\n'.format(r)) f.write('\n')
def print_vtk(p, d, type='points'): nx, ny, nz = p.n['x']-1, p.n['y']-1, p.n['z']-1 lx, ly, lz = p.l['x'], p.l['y'] , p.l['z'] dx, dy, dz = 1.0*lx/nx, 1.0*ly/ny, 1.0*lz/nz ncells = nx * ny * nz npoints = (nx + 1) * (ny + 1) * (nz + 1) #print 'Number of points: ', nx, ny, nz #print 'lengths: ', lx, ly, lz #print 'dlength: ', dx, dy, dz #print 'Number of cells', ncells #print 'Number of points', npoints 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') if type is 'points': print 'PRINT POINTS' gridToVTK(p.name, x, y, z, pointData = {p.name:d}) if type is 'cells': print 'PRINT CELLS' gridToVTK(p.name, x, y, z, cellData = {p.name:d})
def write_Bfield_to_vtk(grid, magnetic_field, scale=5, vtkfile="fci_zoidberg", psi=True): """Write the magnetic field to a VTK file Parameters ---------- grid : :py:obj:`zoidberg.grid.Grid` Grid generated by Zoidberg magnetic_field : :py:obj:`zoidberg.field.MagneticField` Zoidberg magnetic field object scale : int, optional Factor to scale x, z dimensions by [5] vtkfile : str, optional Output filename without extension ["fci_zoidberg"] psi : bool, optional Write psi? Returns ------- path - Full path to vtkfile """ point_data = {'B' : (magnetic_field.bx*scale, magnetic_field.by, magnetic_field.bz*scale)} if psi: psi = make_surfaces(grid, magnetic_field) point_data['psi'] = psi path = gridToVTK(vtkfile, grid.xarray*scale, grid.yarray, grid.zarray*scale, pointData=point_data) return path
def saveToVTK(velocity, rho, prefix, saveNumber, grid): name = "./" + prefix + "." + saveNumber gridToVTK(name, grid[0], grid[1], grid[2], pointData = {'velocity': velocity, 'pressure': rho})
sp.call(['rm', '-rf', asc_dir]) if not os.path.exists(asc_dir): # per flow field os.mkdir(asc_dir) ascOutput = folderName+'/'+folderName sp.call(['field2ascii', '-p', k, ascOutput]) data = rc.main_read_construct(asc_dir, [0, 'all', 'all', 17]) #### CONVERSION # Now we convert the data from numpy to vtk. u_comp = data['flowField']['physical'][0, :, :, :] x = np.linspace(0, data['geometry']['physical']['Lx'], data['geometry']['physical']['Nx']) y = 0 gridToVTK("./julia", x, y, z, cellData = {'julia': u_comp}) # Delete the folder witht eh ASCII file and geom file. sp.call(['rm', '-rf', asc_dir]) print('Deleted\n\n', folderName) print('\n All done! \n')
from pyevtk.hl import gridToVTK import numpy as np import sgems # Parameters (NEED TO INPUT grid name and property name) g = "grid1" p = "30strike" prop = sgems.get_property(g,p) # Grid parameters (NEED TO INPUT lx, ly and lz as the dimensions of the grid) nd = sgems.get_dims(g) ox, oy, oz = 0.0, 0.0, 0.0 lx, ly, lz = 260.0, 300.0, 1.0 dx, dy, dz = lx/nd[0], ly/nd[1], lz/nd[2] ncells = nd[0] * nd[1] * nd[2] npoints = (nd[0] + 1) * (nd[1] + 1) * (nd[2] + 1) # Coordinates x = np.arange(ox, ox + lx + 0.1*dx, dx, dtype='float64') y = np.arange(oy, oy + ly + 0.1*dy, dy, dtype='float64') z = np.arange(oz, oz + lz + 0.1*dz, dz, dtype='float64') # Writing output output = np.array(prop) # Variables gridToVTK("./structured", x, y, z, cellData = {p : output}) print "Done"
x = np.zeros((nx + 1, ny + 1, nz + 1)) y = np.zeros((nx + 1, ny + 1, nz + 1)) z = np.zeros((nx + 1, ny + 1, nz + 1)) for k in range(nz + 1): for j in range(ny + 1): for i in range(nx + 1): x[i,j,k] = X[i] y[i,j,k] = Y[j] (i_ind, j_ind, k_ind) = (i,j,k) if i==nx: i_ind = nx-1 if j==ny: j_ind = ny-1 if k==nz: z_ind = nz-1 z[i,j,k] = Z[k] # mesh_pad[i_ind,j_ind,k_ind] #Z[k] gridToVTK("./mesh_test", x, y, z, pointData = {"z_elev" : z}) # cellData = {"zone" : zone},
kernel = read_fortran_record(kernelfile, count=npoints * nktype, dtype=np.float32,filetype='direct') kernel = kernel.reshape(nktype, ntheta, nphi, nr) kernelfile.close() # write vtk file xgrid = np.outer(np.sin(np.radians(thetas)) * np.cos(np.radians(phis)), radii) ygrid = np.outer(np.sin(np.radians(thetas)) * np.sin(np.radians(phis)), radii) zgrid = np.outer(np.cos(np.radians(thetas)), radii) xgrid = xgrid.reshape(ntheta, nphi, nr) ygrid = ygrid.reshape(ntheta, nphi, nr) zgrid = zgrid.reshape(ntheta, nphi, nr) point_data = {'{:d}'.format(name): data for name, data in zip(range(nktype), kernel)} gridToVTK('kernel', xgrid, ygrid, zgrid, pointData=point_data) phis = phis.reshape(ntheta, nphi) thetas = phis.reshape(ntheta, nphi) # read kernel data: # write some output information r_min, r_max = radii[0], radii[-1] phi_min, phi_max = phis[0, 0], phis[0, -1] theta_min, theta_max = thetas[0, 0], thetas[-1, 0] print ('kernel dimensions (nr={}, nphi={}, ntheta={})'.format(nr, nphi, ntheta)) print ('kernel types: {}'.format(nktype)) print ('radius range = {} -> {}'.format(r_min, r_max)) print ('phis range = {} -> {}'.format(phi_min, phi_max)) print ('thetas range = {} -> {}'.format(theta_min, theta_max))
def build_vtk_from_array(grid_info, mesh_z, point_array_names, point_arrays, cell_array_names, cell_arrays, out_path, vtk_out): """ :param grid_info: :param mesh_z: :param point_array_names: :param point_arrays: :param cell_array_names: :param cell_arrays: :param out_path: :param vtk_out: """ # Dimensions ncol = grid_info[0] nrow = grid_info[1] delc = grid_info[2] delr = grid_info[3] x0 = grid_info[4] y0 = grid_info[5] (nz, ny, nx) = mesh_z.shape # Coordinates X = np.arange(x0, x0 + (ncol + 1) * delc, delc, dtype='float64') Y = np.arange(y0 - (nrow + 1) * delr, y0, delr, dtype='float64') x = np.zeros((nx, ny, nz)) y = np.zeros((nx, ny, nz)) z = np.zeros((nx, ny, nz)) for k in range(nz): for j in range(ny): for i in range(nx): x[i, j, k] = X[i] y[i, j, k] = Y[j] (i_ind, j_ind, k_ind) = (i, j, k) if i == nx: i_ind = nx - 1 if j == ny: j_ind = ny - 1 if k == nz: k_ind = nz - 1 z[i, j, k] = mesh_z[k_ind, j_ind, i_ind] # mesh_pad[i_ind,j_ind,k_ind] #Z[k] # End for cellData = {} for index, cell_array in enumerate(cell_arrays): zone = np.zeros((nx - 1, ny - 1, nz - 1)) for k in range(nz - 1): for j in range(ny - 1): for i in range(nx - 1): zone[i, j, k] = cell_array[k, j, i] cellData[cell_array_names[index]] = zone # End for pointData = {} for index, point_array in enumerate(point_arrays): if point_array_names[index] == "z_elev": pointData[point_array_names[index]] = z else: pointData[point_array_names[index]] = point_array # End if # End for gridToVTK(os.path.join(out_path, vtk_out), x, y, z, cellData=cellData, pointData=pointData)
kernel = read_fortran_record(kernelfile, count=npoints * nktype, dtype=np.float32,filetype='direct') kernel = kernel.reshape(nktype, ntheta, nphi, nr) kernelfile.close() # write vtk file xgrid = np.outer(np.sin(np.radians(thetas)) * np.cos(np.radians(phis)), radii) ygrid = np.outer(np.sin(np.radians(thetas)) * np.sin(np.radians(phis)), radii) zgrid = np.outer(np.cos(np.radians(thetas)), radii) xgrid = xgrid.reshape(ntheta, nphi, nr) ygrid = ygrid.reshape(ntheta, nphi, nr) zgrid = zgrid.reshape(ntheta, nphi, nr) point_data = {'{:d}'.format(name): data for name, data in zip(range(nktype), kernel)} gridToVTK(fname_vtk, xgrid, ygrid, zgrid, pointData=point_data) phis = phis.reshape(ntheta, nphi) thetas = phis.reshape(ntheta, nphi) else: print("this is a video") print(kernel_inf['timeStart']) print(kernel_inf['timeEnd']) numSnaps=int((float(kernel_inf['timeEnd'].replace("d","e"))-float(kernel_inf['timeStart'].replace("d","e")))/float(kernel_inf['timeIncrementSec'].replace("d","e")))+1 print(numSnaps) # il me faut calculer le nombre de snapshots pour video mode
def saveToVTK(rho, u, prefix, saveNumber, grid): name = "./" + prefix + "." + saveNumber reorderedU = (u[0], u[1], u[2]) gridToVTK(name, grid[0], grid[1], grid[2], pointData = {'velocity': reorderedU, 'pressure': rho})
print t def_array = sitk.GetArrayFromImage(def_map) def_array = def_array.swapaxes(0,2) origin = img1.GetOrigin() size = img1.GetSize() spacing = img1.GetSpacing() x = np.arange(origin[0],float(size[0])*spacing[0],spacing[0]) y = np.arange(origin[1],float(size[1])*spacing[1],spacing[1]) z = np.arange(origin[2],float(size[2])*spacing[2],spacing[2]) dx = def_array[:,:,:,0] dx[not_cells] = np.NaN hl.gridToVTK("./structured",x,y,z,pointData= {"x displacement": dx}) ## E = [] ## for i in xrange(3): ## row = np.gradient(def_array[:,:,:,i],0.34,0.41,0.41) ## E.append(row[2]) ## E.append(row[1]) ## E.append(row[0]) ## E33 = sitk.GetImageFromArray(E[8]) ## E33.SetSpacing([0.41,0.41,0.34]) ## dx = sitk.GetImageFromArray(def_array[:,:,:,0]) ## dy = sitk.GetImageFromArray(def_array[:,:,:,1]) ## dz = sitk.GetImageFromArray(def_array[:,:,:,2]) ## sitk.Cast(img1,sitk.sitkUInt8)
#extent=cat2_extent, vmin=-0.5, vmax=0.5) #mlab.outline(surf_cat2, color=(0.7, .7, .7), extent=cat2_extent) #mlab.text(-4, -3, '2 photons', z=-4, width=0.14) #cat3_extent = (6, 14, -4, 4, 0, 5) #surf_cat3 = mlab.surf(x + 10, y, cat3, colormap='Spectral', warp_scale=5, #extent=cat3_extent, vmin=-0.5, vmax=0.5) #mlab.outline(surf_cat3, color=(.7, .7, .7), extent=cat3_extent) #mlab.text(6, -2.5, '3 photons', z=-4, width=0.14) #mlab.title('Multi-photons cats Wigner function') #mlab.view(142, -72, 32) #mlab.show() import time, sys from scitools.std import * import numpy from mayavi import mlab from pyevtk.hl import gridToVTK print "it workks here" w,h,noSlices = 1,2,3 x = numpy.arange(0, w+1) y = numpy.arange(0, h+1) z = numpy.arange(0, noSlices+1) gridToVTK("./julia", x, y, z)