def export_attributes(self, particulator): path = self.attributes_file_path + '_num' + self.add_leading_zeros(particulator.n_steps) self.exported_times['attributes'][path] = particulator.n_steps * particulator.dt if self.verbose: print("Exporting Attributes to vtk, path: " + path) payload = {} for k in particulator.attributes.keys(): if len(particulator.attributes[k].shape) != 1: tmp = particulator.attributes[k].to_ndarray(raw=True) tmp_dict = {k + '[' + str(i) + ']' : tmp[i] for i in range(len(particulator.attributes[k].shape))} payload.update(tmp_dict) else: payload[k] = particulator.attributes[k].to_ndarray(raw=True) payload.update({k: np.array(v) for k, v in payload.items() if not (v.flags['C_CONTIGUOUS'] or v.flags['F_CONTIGUOUS'])}) if particulator.mesh.dimension == 2: y = particulator.mesh.size[0]/particulator.mesh.grid[0] * (payload['cell origin[0]'] + payload['position in cell[0]']) x = particulator.mesh.size[1]/particulator.mesh.grid[1] * (payload['cell origin[1]'] + payload['position in cell[1]']) z = np.full_like(x, 0) else: raise NotImplementedError("Only 2 dimensions array is supported at the moment.") pointsToVTK(path, x, y, z, data = payload)
def WriteResults(self, time): self.ConvertParticlesToNumpyArrays() particles_filename = self.problem_name + "_DEM_" + str(self.counter) path = os.path.join(self.vtk_post_path_directory, particles_filename) hl.pointsToVTK( path, self.particles_X, self.particles_Y, self.particles_Z, { 'radius': self.particles_R, 'material': self.particles_material, 'velocity': (self.velocities_X, self.velocities_Y, self.velocities_Z) }) self.ConvertWallsToNumpyArrays() walls_filename = self.problem_name + "_Walls_" + str(self.counter) path = os.path.join(self.vtk_post_path_directory, walls_filename) hl.unstructuredGridToVTK(path, self.walls_X, self.walls_Y, self.walls_Z, self.walls_connectivity, self.walls_offsets, self.walls_cell_types, cellData=None, pointData=None) self.counter += 1
def vtk_export_unstructured(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 (.vtu) 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` Unstructured 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.zeros_like(x) if z is None: z = np.zeros_like(x) for field in fields: fields[field] = fields[field].reshape(-1) if (len(fields[field]) != len(x) or len(fields[field]) != len(y) or len(fields[field]) != len(z)): raise ValueError("gstools.vtk_export_unstructured: " + "field shape doesn't match the given mesh") pointsToVTK(filename, x, y, z, data=fields)
def vtk_export_unstructured(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` Unstructured 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.zeros_like(x) if z is None: z = np.zeros_like(x) field = np.array(field).reshape(-1) if len(field) != len(x) or len(field) != len(y) or len(field) != len(z): raise ValueError("gstools.vtk_export_unstructured: " + "field shape doesn't match the given mesh") pointsToVTK(filename, x, y, z, data={fieldname: field})
def printvtk(iddata, x, y, z, rad, vx, vy, vz, fx, fy, fz, omegax, omegay, omegaz, tx, ty, tz, counts, mask_pos, mask_floating, ii): auxlog = INFOPRINT("Printing to vtk ") pointsToVTK(f"post/particles-{ii}", x, y, z, data={ "id": iddata + 1, "idnew": iddata, "radius": rad, "counts": counts, "mask_pos": mask_pos.astype(np.int32), "mask_floating": mask_floating.astype(np.int32), "vx": vx, "vy": vy, "vz": vz, "fx": fx, "fy": fy, "fz": fz, "omegax": omegax, "omegay": omegay, "omegaz": omegaz, "tx": tx, "ty": ty, "tz": tz })
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 write_vtk(vname, xyz): print "output polyline data points: " + vname d = {} # vtk file null = np.full(pcount, 0.0) # d["null"] = null # pointsToVTK(vname, xyz[:,0]-35.33, 35.33-xyz[:,1], 12.36-xyz[:,2], d) #pointsToVTK(fname, xyz[:,0], xyz[:,1], xyz[:,2], d) return
def export_vtu(self): print("Creating .vtu file...", end="\r") pointsToVTK( self.vtufilename, numpy.ascontiguousarray(self.VoxelsData[:, 0]), numpy.ascontiguousarray(self.VoxelsData[:, 1]), numpy.ascontiguousarray(self.VoxelsData[:, 2]), data={"Intensity": numpy.ascontiguousarray(self.VoxelsData[:, 3])}) print("*.vtu file: " + self.vtufilename + ".vtu")
def save_vtu(self, r, filename): x = np.ascontiguousarray(r[:, 0], dtype=np.float32) y = np.ascontiguousarray(r[:, 1], dtype=np.float32) if r.shape[1] == 2: z = np.zeros_like(x) pointsToVTK(filename[0:-4], x, y, z) elif r.shape[1] == 3: z = np.ascontiguousarray(r[:, 2], dtype=np.float32) pointsToVTK(filename[0:-4], x, y, z) return
def save_boundary_vtk(path, dictionary): filename = path.replace('/vtk', '') + '/boundary' #vtk filename pointsToVTK(filename, asarray([dictionary[d].get('X') for d in dictionary]), asarray([dictionary[d].get('Y') for d in dictionary]), asarray([dictionary[d].get('Z') for d in dictionary]), data={ "mass": asarray([dictionary[d].get('Mass') for d in dictionary]) })
def regular_grid(savefile, step=20, z=5, size=400, margin=5): n = size // step X = np.linspace(margin, size - margin, n) Y = np.linspace(margin, size - margin, n) Z = np.array([z]) X, Y, Z = np.meshgrid(X, Y, Z) X, Y, Z = X.flatten(), Y.flatten(), Z.flatten() data = np.ones(np.shape(X)[0]) pointsToVTK(savefile, X, Y, Z, {'source': data}) return None
def export_walk(self, image=None, path=None, sub='data', prefix='rw_', sample=1): r''' Export big image to vti and walker coords to vtu Parameters ---------- image: ndarray of int size (Default is None) Can be used to export verisons of the image path: string (default = None) the filepath to save the data, defaults to current working dir prefix: string (default = 'rw_) a string prefix for all the data sample: int (default = 1) used to down-sample the number of walkers to export by this factor ''' if path is None: path = os.getcwd() if sub is not None: subdir = os.path.join(path, sub) # if it doesn't exist, make it if not os.path.exists(subdir): os.makedirs(subdir) path = subdir if image is not None: if len(np.shape(image)) == 2: image = image[:, :, np.newaxis] im_fp = os.path.join(path, prefix + 'image') imageToVTK(im_fp, cellData={'image_data': image}) # number of zeros to fill the file index zf = np.int(np.ceil(np.log10(self.nt * 10))) w_id = np.arange(0, self.nw, sample) nw = len(w_id) time_data = np.ascontiguousarray(np.zeros(nw, dtype=int)) if self.dim == 2: z_coords = np.ascontiguousarray(np.ones(nw, dtype=int)) coords = self.real_coords for t in range(np.shape(coords)[0]): st = self.stride * t time_data.fill(st) x_coords = np.ascontiguousarray(coords[t, w_id, 0]) y_coords = np.ascontiguousarray(coords[t, w_id, 1]) if self.dim == 3: z_coords = np.ascontiguousarray(coords[t, w_id, 2]) wc_fp = os.path.join(path, prefix + 'coords_' + str(st).zfill(zf)) pointsToVTK(path=wc_fp, x=x_coords, y=y_coords, z=z_coords, data={'time': time_data})
def save_vtk(fd, label, pnts, size): n = pnts.shape[0] print(" label:%-4s count:%i"% (label, n)) xyz = np.zeros((n,3), dtype=np.float) for i, p in enumerate(pnts): xyz[i] = i2xyz(p, size) np.savetxt(fd+'geom_'+label+".dat", xyz, fmt='%2.4f') # text file d = {} # vtk file if len(label) <= 3: null = np.full(n, 0.0) else: null = np.full(n, 1.0) d["null"] = null # pointsToVTK(fd+'geom_'+label, xyz[:,0], xyz[:,1], xyz[:,2], d) return
def save_vtk(fd, label, pnts, size): n = pnts.shape[0] print(" label:%-4s count:%i" % (label, n)) xyz = np.zeros((n, 3), dtype=np.float) for i, p in enumerate(pnts): xyz[i] = i2xyz(p, size) np.savetxt(fd + 'geom_' + label + ".dat", xyz, fmt='%2.4f') # text file d = {} # vtk file if len(label) <= 3: null = np.full(n, 0.0) else: null = np.full(n, 1.0) d["null"] = null # pointsToVTK(fd + 'geom_' + label, xyz[:, 0], xyz[:, 1], xyz[:, 2], d) return
def save_poits_to_vtk(df, xcol, ycol, zcol, flname): df = df.copy() x = np.array(df[xcol]) y = np.array(df[ycol]) z = np.array(df[zcol]) dataframe_vars = list(df.drop(columns=[xcol, ycol, zcol])) vardict = {} for var in dataframe_vars: vardict[var] = df[var].values pointsToVTK(flname, x, y, z, data=vardict)
def _write_vol_evtk(model, file_name, data_label, nsteps, real_coords=True): """ Writes out the model as a 3d volume grid in VTK points format Parameters ---------- model : GeologicalModel object Geological model to export file_name : string Name of file that model is exported to, including path, but without the file extension data_label : string A data label to insert into export file nsteps : np.array([num-x-steps, num-y-steps, num-z-steps]) 3d array dimensions Returns ------- True if successful """ # Define grid spacing loop_X = np.linspace(model.bounding_box[0, 0], model.bounding_box[1, 0], nsteps[0]) loop_Y = np.linspace(model.bounding_box[0, 1], model.bounding_box[1, 1], nsteps[1]) loop_Z = np.linspace(model.bounding_box[0, 2], model.bounding_box[1, 2], nsteps[2]) # Generate model values in 3d grid xx, yy, zz = np.meshgrid(loop_X, loop_Y, loop_Z, indexing="ij") # xyz is N x 3 vector array xyz = np.array([xx.flatten(), yy.flatten(), zz.flatten()]).T vals = model.evaluate_model(xyz, scale=False) if real_coords: model.rescale(xyz) # Define vertices - xyz.shape[0] is length of vector array x = np.zeros(xyz.shape[0]) y = np.zeros(xyz.shape[0]) z = np.zeros(xyz.shape[0]) for i in range(xyz.shape[0]): x[i], y[i], z[i] = xyz[i][0], xyz[i][1], xyz[i][2] # Write to grid try: pointsToVTK(file_name, x, y, z, data={data_label: vals}) except Exception as e: logger.warning(f"Cannot export volume to VTK file {file_name}: {e}") return False return True
def shp_to_vtk( shp_fn, vtk_fn, final_epsg, model_center, model_depth=0, x="latitude", y="longitude" ): model_east, model_north = project_points( model_center[0], model_center[1], pyproj.CRS("EPSG:4326"), pyproj.CRS(f"EPSG:{final_epsg}"), ) x, y, z = shape_to_points( shp_fn, final_epsg, model_east, model_north, model_depth=model_depth, x=x, y=y ) pointsToVTK(vtk_fn, y, x, z)
def vtkdata(): if tsstart <= top.it <= tsend: if top.it % tsint == 0: vtkPartDir = './{dirName}/'.format(dirName=dirName) if not os.path.exists(vtkPartDir): os.mkdir(vtkPartDir) nnn = part.getn() xxx = part.getx() yyy = part.gety() zzz = part.getz() val = [1 for i in range(nnn)] npval = np.array(val) pointsToVTK("./{dirName}/{fileName}_{ts}_ts".\ format(dirName=dirName, fileName=fileName, ts=top.it), xxx, yyy, zzz,data={"particle" : npval})
def main(): mesh_path = sys.argv[-2] o_path = sys.argv[-1] #remove possible file extensions since pointsToVTK already appends .vtu o_path = ('.').join(o_path.split('.')[:-1]) x, y, z = loadMesh(mesh_path) y = 1 - y #flip y axis temp = np.zeros(len(x)) pointsToVTK("{}".format(o_path), x, y, z, data={"temp": temp})
def write_particles(output_path, timestep, particles, particles_group, current_time): ppath = pointsToVTK("{}/particles{:04d}".format(output_path, timestep), particles[:, 0], particles[:, 1], np.zeros_like(particles[:, 0]), data={"visc": particles[:, 2]}) particles_group.addFile(filepath=ppath, sim_time=current_time)
def source_points(filename, savefile, radius=5, density=3, z_level=5): _, endpoints = read_looptrace(filename) X = [] Y = [] Z = [] for _, v in endpoints.items(): for xy in v: x, y, z = spherical_grid(xy[0], xy[1], z_level, radius, density) X.append(x) Y.append(y) Z.append(z) X = np.array(X).flatten() Y = np.array(Y).flatten() Z = np.array(Z).flatten() data = np.ones(np.shape(X)[0]) pointsToVTK(savefile, X, Y, Z, {'source': data}) return None
def writeToVTK(self, fname): from pyevtk.hl import pointsToVTK pointsToVTK(fname, self.nodes[:, 1], self.nodes[:, 2], self.nodes[:, 3], data={ "grp1": self.angleIntFlux[0, :], "grp2": self.angleIntFlux[1, :], "grp3": self.angleIntFlux[2, :], "grp4": self.angleIntFlux[3, :], "grp5": self.angleIntFlux[4, :], "grp6": self.angleIntFlux[5, :], "grp7": self.angleIntFlux[6, :], "grp8": self.angleIntFlux[7, :], "grp9": self.angleIntFlux[8, :], "grp10": self.angleIntFlux[9, :], "tot": self.totFlux[:] })
def write_vtu(input_file, output_vtu): # Read coordinates x, y, z = get_coords(input_file) # Calculate the number of fields data num_flds = get_num_flds(input_file) print "num_flds=", num_flds # Set the name of each field flds_list = set_flds_name(num_flds) print flds_list # Read the fields data flds_data = set_data_flds(input_file, flds_list, num_flds) #output to vtu #pointsToVTK(output_vtu, x, y, z, data = {"divr" : fld1, "volume" : fld2}) pointsToVTK(output_vtu, x, y, z, data=flds_data) print 'output vtufile name is', output_vtu + ".vtu"
def export_particles(self, core): path = self.particles_file_path + '_num' + self.add_leading_zeros( self.particles_file_number) if self.verbose: print("Exporting Particles to vtk, path: " + path) self.particles_file_number += 1 payload = {} particles = core.particles for k in particles.attributes.keys(): if len(particles[k].shape) != 1: tmp = particles[k].to_ndarray(raw=True) tmp_dict = { k + '[' + str(i) + ']': tmp[i] for i in range(len(particles[k].shape)) } payload.update(tmp_dict) else: payload[k] = particles[k].to_ndarray(raw=True) payload.update({ k: np.array(v) for k, v in payload.items() if not (v.flags['C_CONTIGUOUS'] or v.flags['F_CONTIGUOUS']) }) if core.mesh.dimension == 2: x = payload['cell origin[0]'] + payload['position in cell[0]'] y = np.full_like(x, 0) z = payload['cell origin[1]'] + payload['position in cell[1]'] else: raise NotImplementedError( "Only 2 dimensions array is supported at the moment.") pointsToVTK(path, x, y, z, data=payload)
def vtkwrite(): file_name = "particle"#"rhoNeutral" #"P" if os.path.exists(pjoin('data','vtkdata')) == False: os.mkdir(pjoin('data','vtkdata')) h5 = h5py.File(pjoin('data',file_name+'.hdf5'),'r') Lx = h5.attrs["Lx"] Ly = h5.attrs["Ly"] Lz = h5.attrs["Lz"] dp = h5.attrs["dp"] Nt = h5.attrs["Nt"] data_num = np.arange(start=0, stop=Nt, step=dp, dtype=int) for i in range(len(data_num)): datax = h5["/%d"%data_num[i]+"/position/x"] datay = h5["/%d"%data_num[i]+"/position/y"] dataz = h5["/%d"%data_num[i]+"/position/z"] datax = np.array(datax) datay = np.array(datay) dataz = np.array(dataz) pointsToVTK(pjoin('data','vtkdata','points_%d'%i), datax, datay, dataz)
def loops_to_vtk_sources(loops, savefile, radius=5, density=3, z_level=5): X = [] Y = [] Z = [] for j, t_l in enumerate(loops): x, y, z = spherical_grid(t_l[0, 0], t_l[0, 1], z_level, radius, density) X.append(x) Y.append(y) Z.append(z) x, y, z = spherical_grid(t_l[-1, 0], t_l[-1, 1], z_level, radius, density) X.append(x) Y.append(y) Z.append(z) X = np.array(X).flatten() Y = np.array(Y).flatten() Z = np.array(Z).flatten() data = np.ones(np.shape(X)[0]) pointsToVTK(savefile, X, Y, Z, {'source': data}) return None
def convertData(parameters, jump_print, data_keep): import numpy as np from pyevtk.hl import pointsToVTK cwd = os.getcwd() path_data = cwd + "/data/" path_vtk = cwd + "/visualization/dataVTK/" seed_name = "Seed" + parameters['seed'] N = parameters['N'] ext = ".dat" # create directory for VTK data under "visualization" if it does not already exist if (not os.path.isdir(path_vtk)): os.makedirs(path_vtk) # delete contents of directory otherwise else: os.chdir(path_vtk) os.system("perl -e 'for(<*>){((stat)[9]<(unlink))}'") os.chdir('../..') # create z-coordinates z = np.zeros(N) for k in xrange(0, parameters['nTime'] - 1, jump_print): extension = seed_name + "_" + str(k).zfill(9) + ext # load data x = loadBinaryDouble(path_data + "particleX_" + extension)[0:N] y = loadBinaryDouble(path_data + "particleY_" + extension)[0:N] # multiply by 1 to implicitly cast bool array as int s = loadBinaryBool(path_data + "particleS_" + extension)[0:N] * 1 # write data as VTK pointsToVTK(path_vtk + "particles_" + str(k).zfill(9), x, y, z, data={"Coop_def": s})
def vtk_export_unstructured(filename, pos, fields): # pragma: no cover """Export a field to vtk unstructured grid file. Parameters ---------- filename : :class:`str` Filename of the file to be saved, including the path. Note that an ending (.vtu) 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` Unstructured fields to be saved. Either a single numpy array as returned by SRF, or a dictionary of fields with theirs names as keys. """ x, y, z, fields = _vtk_unstructured_helper(pos=pos, fields=fields) return pointsToVTK(filename, x, y, z, data=fields)
grid = "grid1" direction_data = "05strike" ratio_data = "05ratio" # Initializing prop = sgems.get_property(grid,direction_data) ratio = sgems.get_property(grid,ratio_data) propX = sgems.get_property(grid,"_X_") propY = sgems.get_property(grid,"_Y_") propZ = sgems.get_property(grid,"_Z_") npoints = len(propX) x = np.array(propX) y = np.array(propY) z = np.array(propZ) vx = np.zeros(npoints) vy = np.zeros(npoints) vz = np.zeros(npoints) rang = np.zeros(npoints) # Calculating vectors to display at Paraview as Glyph for i in range(npoints): vx[i] = np.sin(np.deg2rad(prop[i])) vy[i] = np.cos(np.deg2rad(prop[i])) if (ratio[i] < 0.2): rang[i] = 1/0.2 else: rang[i] = 1/ratio[i] pointsToVTK("./points", x, y, z, data = {"direction" : (vx, vy, vz), "range" : rang}) print "Done"
def save_moving_vtk(path, iteration, dictionary): filename = path + '/iter_' + str(iteration) #vtk filename X = asarray([dictionary[d].get('X') for d in dictionary]) Y = asarray([dictionary[d].get('Y') for d in dictionary]) Z = asarray([dictionary[d].get('Z') for d in dictionary]) Vx = asarray([dictionary[d].get('X Velocity') for d in dictionary]) Vy = asarray([dictionary[d].get('Y Velocity') for d in dictionary]) Vz = asarray([dictionary[d].get('Z Velocity') for d in dictionary]) V_Mag = array(sqrt(Vx**2 + Vy**2 + Vz**2)) # V_vector = asarray([[dictionary[d].get('X Velocity'), dictionary[d].get('Y Velocity'),dictionary[d].get('Z Velocity')] for d in dictionary]) rho = asarray([dictionary[d].get('Density') for d in dictionary]) p = asarray([dictionary[d].get('Pressure') for d in dictionary]) try: # Total forces total_force_x = asarray( [dictionary[d].get('Total Force')[0] for d in dictionary]) total_force_y = asarray( [dictionary[d].get('Total Force')[1] for d in dictionary]) total_force_z = asarray( [dictionary[d].get('Total Force')[2] for d in dictionary]) # Pressure forces p_force_x = asarray( [dictionary[d].get('Pressure Force')[0] for d in dictionary]) p_force_y = asarray( [dictionary[d].get('Pressure Force')[1] for d in dictionary]) p_force_z = asarray( [dictionary[d].get('Pressure Force')[2] for d in dictionary]) # # Boundary-Fluid Pressure forces # fb_p_force_x = asarray([dictionary[d].get('Boundary-Fluid Pressure')[0] for d in dictionary]) # fb_p_force_y = asarray([dictionary[d].get('Boundary-Fluid Pressure')[1] for d in dictionary]) # fb_p_force_z = asarray([dictionary[d].get('Boundary-Fluid Pressure')[2] for d in dictionary]) # # Boundary-Fluid Friction forces # fb_f_force_x = asarray([dictionary[d].get('Boundary-Fluid Friction')[0] for d in dictionary]) # fb_f_force_y = asarray([dictionary[d].get('Boundary-Fluid Friction')[1] for d in dictionary]) # fb_f_force_z = asarray([dictionary[d].get('Boundary-Fluid Friction')[2] for d in dictionary]) # Viscosity forces v_force_x = asarray( [dictionary[d].get('Viscosity Force')[0] for d in dictionary]) v_force_y = asarray( [dictionary[d].get('Viscosity Force')[1] for d in dictionary]) v_force_z = asarray( [dictionary[d].get('Viscosity Force')[2] for d in dictionary]) # Surface tension forces st_force_x = asarray([ dictionary[d].get('Surface Tension Force')[0] for d in dictionary ]) st_force_y = asarray([ dictionary[d].get('Surface Tension Force')[1] for d in dictionary ]) st_force_z = asarray([ dictionary[d].get('Surface Tension Force')[2] for d in dictionary ]) except: # Total forces total_force_x = zeros(len(X)) total_force_y = zeros(len(X)) total_force_z = zeros(len(X)) # Pressure forces p_force_x = zeros(len(X)) p_force_y = zeros(len(X)) p_force_z = zeros(len(X)) # # Boundary-Fluid Pressure forces # fb_p_force_x = zeros(len(X)) # fb_p_force_y = zeros(len(X)) # fb_p_force_z = zeros(len(X)) # # Boundary-Fluid Friction forces # fb_f_force_x = zeros(len(X)) # fb_f_force_y = zeros(len(X)) # fb_f_force_z = zeros(len(X)) # Viscosity forces v_force_x = zeros(len(X)) v_force_y = zeros(len(X)) v_force_z = zeros(len(X)) # Surface tension forces st_force_x = zeros(len(X)) st_force_y = zeros(len(X)) st_force_z = zeros(len(X)) pointsToVTK(filename, X, Y, Z, data={ "Vx": Vx, "Vy": Vy, "Vz": Vz, "V_Mag": V_Mag, "rho": rho, "p": p, "Total Force X": total_force_x, "Total Force Y": total_force_y, "Total Force Z": total_force_z, "Pressure X": p_force_x, "Pressure Y": p_force_y, "Pressure Z": p_force_z, "Viscosity X": v_force_x, "Viscosity Y": v_force_y, "Viscosity Z": v_force_z, "ST X": st_force_x, "ST Y": st_force_y, "ST Z": st_force_z })
print mesh_name nodes, tris = get_mesh_tris(mesh_name) #print " surface node count: ", nodes.shape[0] #print " surface triangle count: ", tris.shape[0] normals = create_normals(nodes, tris) curvatures = calc_curvature(nodes, tris, normals) print " curvature min: ", curvatures.min() print " curvature mean: ", curvatures.mean() print " curvature max: ", curvatures.max() print " curvature median: ", np.median(curvatures) plots[7-i].set_ylim([0, 450]) plots[7-i].set_ylabel(cell_name) plots[7-i].hist(curvatures, bins=61, range=(-1.0, 1.0)) save_mesh(cell_name, nodes, tris, curvatures) # write out to vtk file fname = cell_name d = {} d["curvature"] = curvatures nodes = np.transpose(nodes) pointsToVTK(fname, nodes[0,:], nodes[1,:], nodes[2,:], data = d) # write out vtk file open('temp.pdf', 'w').close() plt.savefig('temp.pdf') os.rename('temp.pdf', 'curvature_histograms.pdf') plt.show()
def dump_vtk(pa, filename, base = ".", **data): """Dumps vtk output to file 'base/filename'""" if not data: data = {'v_x': pa.v_x, 'v_y': pa.v_y, 'v_z': pa.v_z} pointsToVTK(base + "/" + filename, pa.x, pa.y, pa.z, data = data)
# -*- coding: utf-8 -*- """ Created on Wed Jul 3 11:10:43 2019 @author: jpeacock """ import pandas as pd from mtpy.utils import gis_tools from pyevtk.hl import pointsToVTK import numpy as np fn = r"c:\Users\jpeacock\OneDrive - DOI\Geysers\Top_Felsite_Points_WGS84.csv" model_center = (38.831979, -122.828190) model_east, model_north, zone = gis_tools.project_point_ll2utm( model_center[0], model_center[1] ) df = pd.read_csv( fn, delimiter=",", usecols=[0, 1, 2], names=["lat", "lon", "depth"], skiprows=1 ) east, north, zone = gis_tools.project_points_ll2utm(df.lat, df.lon) x = (east - model_east) / 1000.0 y = (north - model_north) / 1000.0 z = (df.depth.to_numpy() / 3.25) / 1000.0 pointsToVTK(fn[:-4], y, x, z, {"depth": z})
from pyevtk.hl import pointsToVTK import numpy as np # Example 1 npoints = 100 x = np.random.rand(npoints) y = np.random.rand(npoints) z = np.random.rand(npoints) pressure = np.random.rand(npoints) temp = np.random.rand(npoints) pointsToVTK("./rnd_points", x, y, z, data={"temp": temp, "pressure": pressure}) # Example 2 x = np.arange(1.0, 10.0, 0.1) y = np.arange(1.0, 10.0, 0.1) z = np.arange(1.0, 10.0, 0.1) pointsToVTK("./line_points", x, y, z, data={"elev": z})
In this file,data is exported as points to be visulized at Paraview The output file goes to SGeMS main folder as "points.vtu" """ import numpy as np import sgems from pyevtk.hl import pointsToVTK # Input properties (NEED TO INPUT grid object name and property name) grid = "walker" point_data = "V" # Initializing prop = sgems.get_property(grid,point_data) propX = sgems.get_property(grid,"_X_") propY = sgems.get_property(grid,"_Y_") propZ = sgems.get_property(grid,"_Z_") npoints = len(propX) x = np.array(propX) y = np.array(propY) z = np.array(propZ) output = np.array(prop) # Output pointsToVTK("./points", x, y, z, data = {point_data : output}) print "Done"
from pyevtk.hl import pointsToVTK from pyevtk.vtk import VtkGroup import numpy as np g = VtkGroup("./group") for i in range(1,nt+1): x = np.random.rand(100) y = np.random.rand(100) z = np.random.rand(100) pointsToVTK("sim"+str(i), x, y, z, {"V":(x,y,z)}) g.addFile("sim"+str(i)+".vtu", sim_time=i*l3d.dt) g.save()
def write_particles(output_path, timestep, particles, particles_group, current_time): ppath = pointsToVTK("{}/particles{:04d}".format(output_path, timestep), particles[:,0], particles[:,1], np.zeros_like(particles[:,0]), data = {"visc": particles[:,2]}) particles_group.addFile(filepath = ppath, sim_time = current_time)
#!/bin/bash import numpy as np import libtiff as tf from pyevtk.hl import pointsToVTK fdir = "layers/" fname = "cellsN8R" f1 = tf.TIFF3D.open(fdir+fname+".tif", mode='r') images = f1.read_image() # load the image stack f1.close() print images.shape icount = images.shape[0] # image count in stack isize = images.shape[1] # side dimension of images cvs = np.unique(images) for cv in cvs[1:]: print cv xyz = np.where(images == cv) z = (24.73 / 2) - ((xyz[0] + 1) * 24.73 / icount) x = (xyz[2] * 70.66 / isize) - (70.66 / 2) y = (70.66 / 2) - (xyz[1] * 70.66 / isize) null = np.full(x.shape, cv) d = {} d["null"] = null pointsToVTK(fdir+fname+str(cv), x, y, z, d) # write out vtk file