def visBrain( self, brain_map_path,spacing): output_brain_vtk_path = brain_map_path.split('.')[0] +'_visBrain' with open(brain_map_path) as f: first_line = f.readline() Dx,Dy,Dz = [int(t.split('=')[1]) for t in first_line[1:].split(',')[0:3] ] print("Readed Array Size",Dx,Dy,Dz) # lines = f.readlines() lines = f.read().splitlines() lines = list(filter(None, lines)) print("Total lines number should be :" + str(Dy*Dz) + ", readed line numbers: " + str(len(lines))) Vol = np.zeros((Dx,Dy,Dz)) for i in range(Dz): try: one_slice = [t[:-1] if t[-1]==',' else t for t in lines[0+(Dy)*i:Dy+(Dy)*i] ] # one_slice = [t.replace(',\n','\n') for t in lines[0+(Dy)*i:Dy+(Dy)*i]] # print(one_slice) # print(len(one_slice)) Vol[:,:,i] = np.loadtxt(one_slice, delimiter=',',dtype=int,unpack=True) except: print("error happens on z index: "+ str(i)) imageToVTK( output_brain_vtk_path, spacing=spacing, pointData={'brain':Vol} )
def dict_to_vtk(data, path='./dictvtk', voxel_size=1, origin=(0, 0, 0)): r""" Accepts multiple images as a dictionary and compiles them into a vtk file Parameters ---------- data : dict A dictionary of *key: value* pairs, where the *key* is the name of the scalar property stored in each voxel of the array stored in the corresponding *value*. path : string Path to output file voxel_size : int The side length of the voxels (voxels are cubic) origin : float data origin (according to selected voxel size) Notes ----- Outputs a vtk, vtp or vti file that can opened in ParaView """ vs = voxel_size for entry in data: if data[entry].dtype == bool: data[entry] = data[entry].astype(np.int8) if data[entry].flags['C_CONTIGUOUS']: data[entry] = np.ascontiguousarray(data[entry]) imageToVTK(path, cellData=data, spacing=(vs, vs, vs), origin=origin)
def file2paraview(fname, vname='view'): from scipy.io import loadmat from pyevtk.hl import imageToVTK from subprocess import run x = loadmat(fname)[vname] imageToVTK('temp', pointData={'intensity': x}) run(['paraview', '--data=temp.vti'])
def tiled_net_out(dataset, net, is_cuda, gt_vol=None, evaluate=True, write_vols=False, filename='vol'): net.eval() full_vol = field_from_net(dataset, net, is_cuda, tiled_res=32) psnr = 0 print('writing to VTK...') if evaluate and gt_vol is not None: diff_vol = gt_vol - full_vol sqd_max_diff = (th.max(gt_vol) - th.min(gt_vol))**2 #full_vol = full_vol.cpu().transpose(1,2).transpose(0,1).transpose(1,2) l1_diff = th.mean(th.abs(diff_vol)) mse = th.mean(th.pow(diff_vol, 2)) psnr = 10 * th.log10(sqd_max_diff / th.mean(diff_vol**2)) print('PSNR:', psnr, 'l1:', l1_diff, 'mse:', mse, 'rmse:', th.sqrt(mse)) if write_vols: imageToVTK(filename, pointData={'sf': full_vol.numpy()}) if gt_vol is not None: imageToVTK('gt', pointData={'sf': gt_vol.numpy()}) # print('back to training...') net.train() return psnr
def GenVTK(XCrop, YCrop, XYScale): Names = sorted(gb.glob('*.tif')) for kat in Names: print(kat) Idx = 0 rdr1, TempStack1, Zsize, Xsize, Ysize = ReadStackSize( kat) #rdr,TempStack,StackLength #Zsize=ReadStackSize() XPart, YPart = Xsize * XCrop / 100, Ysize * YCrop / 100 Vol = np.zeros([XPart - 1, YPart - 1, Zsize]) for katSlc in np.arange(Zsize): Pix = ReadImageSlice(rdr1, katSlc, TempStack1) ##pp.matshow(Pix) ##raw_input("press enter") ##pp.close() Pix = zoom(Pix, XYScale * 0.01) Vol[:, :, Idx] = Pix[1:XPart, 1:YPart] #print(Idx) #pp.matshow(Pix[1:XPart,1:YPart]) #raw_input("press enter") #pp.close() Idx += 1 FoldOut = kat[0:-4] imageToVTK("VTK_" + FoldOut, cellData={"Fluorescence Signal": Vol}) print("VTK_" + FoldOut) return Vol
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 generateImage(gridList,filename): cellData=[] for i in range (len(gridList)): #print gridList[i].p cellData.append(gridList[i].p) pressure=numpy.asarray(cellData).reshape(gridnum, gridnum, gridnum,order='F') #print pressure imageToVTK(filename, cellData = {"pressure" : pressure})
def ExportToVTK(self): FileName = 'WindField_' + str(self.block_num) h = 1 / self.wind_field.shape[0] spacing = (h, h, h) wind_field_ = tuple( [np.copy(self.wind_field[..., i], order='C') for i in range(3)]) cellData = { 'grid': np.zeros(self.wind_field[..., 0].shape), 'velocity': wind_field_ } imageToVTK(FileName, cellData=cellData, spacing=spacing)
def to_vtk(im, path='./voxvtk', divide=False, downsample=False, voxel_size=1, vox=False): r""" Converts an array to a vtk file. Parameters ---------- im : 3D image The image of the porous material path : string Path to output file divide : bool vtk files can get very large, this option allows you for two output files, divided at z = half. This allows for large data sets to be imaged without loss of information downsample : bool very large images acan be downsampled to half the size in each dimension, this doubles the effective voxel size voxel_size : int The side length of the voxels (voxels are cubic) vox : bool For an image that is binary (1's and 0's) this reduces the file size by using int8 format (can also be used to reduce file size when accuracy is not necessary ie: just visulization) Notes ----- Outputs a vtk, vtp or vti file that can opened in paraview """ if len(im.shape) == 2: im = im[:, :, np.newaxis] if im.dtype == bool: vox = True if vox: im = im.astype(np.int8) vs = voxel_size if divide: split = np.round(im.shape[2] / 2).astype(np.int) im1 = im[:, :, 0:split] im2 = im[:, :, split:] imageToVTK(path + '1', cellData={'im': np.ascontiguousarray(im1)}, spacing=(vs, vs, vs)) imageToVTK(path + '2', origin=(0.0, 0.0, split * vs), cellData={'im': np.ascontiguousarray(im2)}, spacing=(vs, vs, vs)) elif downsample: im = spim.interpolation.zoom(im, zoom=0.5, order=0, mode='reflect') imageToVTK(path, cellData={'im': np.ascontiguousarray(im)}, spacing=(2 * vs, 2 * vs, 2 * vs)) else: imageToVTK(path, cellData={'im': np.ascontiguousarray(im)}, spacing=(vs, vs, vs))
def exportVTK(FileName, cellData): shape = list(cellData.values())[0].shape ndim = len(shape) N = min(shape) spacing = (1./N, 1./N, 1./N) if ndim==3: imageToVTK(FileName, cellData = cellData, spacing = spacing) elif ndim==2: cellData2D = {} for key in cellData.keys(): cellData2D[key] = np.expand_dims(cellData[key], axis=2) imageToVTK(FileName, cellData = cellData2D, spacing = spacing) else: msgDimError(ndim)
def saveVol(vol, W, name, folder): grid = W.vshape[::-1] winX = [W.vg['options']['WindowMinX'], W.vg['options']['WindowMaxX']] winY = [W.vg['options']['WindowMinY'], W.vg['options']['WindowMaxY']] winZ = [W.vg['options']['WindowMinZ'], W.vg['options']['WindowMaxZ']] win = [winX, winY, winZ] grid = [np.linspace(*w, g) for (w, g) in zip(win, grid)] limits = [[-999, 999]] * 3 center_x = -0.37 center_y = 0.9 center_z = 0.2 cropX = [np.argmin(np.abs(grid[0] - x)) for x in limits[0]] cropY = [np.argmin(np.abs(grid[1] - y)) for y in limits[1]] cropZ = [np.argmin(np.abs(grid[2] - z)) for z in limits[2]] vol2 = np.array(vol[cropZ[0]:cropZ[1], cropY[0]:cropY[1], cropX[0]:cropX[1]], order='F') gridX = grid[0][cropX[0]:cropX[1]] gridY = grid[1][cropY[0]:cropY[1]] gridZ = grid[2][cropZ[0]:cropZ[1]] voxelSize = [ np.mean(np.diff(gridX)), np.mean(np.diff(gridY)), np.mean(np.diff(gridZ)) ] originX = (gridX - center_x)[0] originY = (gridY - center_y)[0] originZ = (gridZ - center_z)[0] # Save volume folder = create_folder(folder) imageToVTK( '{0}/{1}'.format(folder, name), origin=[originZ, originY, originX], spacing=np.flip(voxelSize, axis=0).tolist(), pointData={'LVF': (vol2 / density_KIinH2O(50)).astype(np.int16)}) return
def createDensityData(trajs, filename="densityData", radius=2.0): MSMradius = radius X = np.arange(-MSMradius, MSMradius, 0.05) Y = np.arange(-MSMradius, MSMradius, 0.05) Z = np.arange(-MSMradius, MSMradius, 0.05) Zfull = np.zeros([X.shape[0] - 1, Y.shape[0] - 1, Z.shape[0] - 1]) for traj in trajs: hist = np.histogramdd(traj, bins=(X, Y, Z)) Zfull += hist[0] # Dimensions nx, ny, nz = X.shape[0] - 1, Y.shape[0] - 1, Z.shape[0] - 1 ncells = nx * ny * nz npoints = (nx + 1) * (ny + 1) * (nz + 1) # Variables filename = "../data/visit/" + filename imageToVTK(filename, cellData={"Density": Zfull})
def visBrain( self, brain_map_path,spacing): output_brain_vtk_path = brain_map_path.split('.')[0] +'_visBrain' with open(brain_map_path) as f: first_line = f.readline() Dx,Dy,Dz = [int(t.split('=')[1]) for t in first_line[1:].split(',')[0:3] ] lines = f.readlines() Vol = np.zeros((Dx,Dy,Dz)) for i in range(Dz): try: Vol[:,:,i] = np.loadtxt([t.replace(',\n','\n') for t in lines[0+(Dy+1)*i:Dy+(Dy+1)*i]], delimiter=',').T except: print("error happens on: "+ str(i)) imageToVTK( output_brain_vtk_path, spacing=spacing, pointData={'brain':Vol} )
def GenVTK(): Names = sorted(gb.glob('IM*')) XScale, YScale, ZScale = 100, 100, 25 #% Zsize = 150 #len(Names) Idx = 0 if Zsize == 0: Zsize = len(Names) for kat in Names[0:Zsize]: DI = dicom.read_file(kat) Pix = DI.pixel_array Pix = zoom(Pix, ZScale * 0.01) Pix2 = Pix Xsize, Ysize = Pix2.shape XPart, YPart = Pix.shape[0] * XScale / 100, Pix.shape[1] * YScale / 100 #patata if kat == Names[0]: ###allocate Volume Vol = np.zeros([XPart - 1, YPart - 1, Zsize]) Vol[:, :, Idx] = Pix2[1:XPart, 1:YPart] Idx += 1 #patata imageToVTK("./VTKimage", cellData={"Scattering": Vol})
def snap(self, name): plt.clf(); plt.imshow(sqrt(self.u[0] ** 2 + self.u[1] ** 2).transpose(), cmap=cm.coolwarm) plt.savefig("vel" + name + ".png") temp = sqrt(self.u[0] ** 2 + self.u[1] ** 2) # print(temp[119,82]) vel_y = np.dstack((self.u[1, :, 1:-1], self.u[1, :, 1:-1])) vel_x = np.dstack((self.u[0, :, 1:-1], self.u[0, :, 1:-1])) magn = np.dstack((temp[:, 1:-1], temp[:, 1:-1])) if self.nx != nx: imageToVTK("./test" + name, pointData={"vel_x": vel_x, "vel_y": vel_y, "magnitude":magn}) else: vfunc = np.vectorize(lambda x: int(x)) fframe = vfunc(frame) fframe = fframe[:,1:-1] fframe = np.dstack((fframe, fframe)) bborder = vfunc(border) bborder = bborder[:,1:-1] bborder = np.dstack((bborder, bborder)) imageToVTK("./test" + name, pointData={"vel_x": vel_x, "vel_y": vel_y, "magnitude":magn, "frame":fframe, "border":bborder})
def GenVTK(): Names=sorted(gb.glob('IM*')) XScale, YScale, ZScale =100,100, 25 #% Zsize=150#len(Names) Idx = 0 if Zsize==0: Zsize=len(Names) for kat in Names[0:Zsize]: DI = dicom.read_file(kat) Pix = DI.pixel_array Pix=zoom(Pix, ZScale*0.01) Pix2 = Pix Xsize, Ysize = Pix2.shape XPart, YPart = Pix.shape[0]*XScale/100, Pix.shape[1]*YScale/100 #patata if kat == Names[0]: ###allocate Volume Vol=np.zeros([XPart-1, YPart-1, Zsize]) Vol[:,:,Idx]=Pix2[1:XPart,1:YPart] Idx+=1 #patata imageToVTK("./VTKimage", cellData = {"Scattering" : Vol} )
def _write_vtk(self, V, g, a, p): if p['Dimensions'] == '2D': V_vtk = np.expand_dims(V, axis=3) V_vtk_rho = np.copy(np.swapaxes(V_vtk, 1, 2)[rho, g.jbeg:g.jend, g.ibeg:g.iend, :], order='F') V_vtk_prs = np.copy(np.swapaxes(V_vtk, 1, 2)[prs, g.jbeg:g.jend, g.ibeg:g.iend, :], order='F') V_vtk_vx1 = np.copy(np.swapaxes(V_vtk, 1, 2)[vx1, g.jbeg:g.jend, g.ibeg:g.iend, :], order='F') V_vtk_vx2 = np.copy(np.swapaxes(V_vtk, 1, 2)[vx2, g.jbeg:g.jend, g.ibeg:g.iend, :], order='F') hl.imageToVTK(self._file_name, origin=(g.x1[g.ibeg], g.x2[g.jbeg], 0.0), spacing=(g.dx1, g.dx2, 0.0), cellData={ "rho": V_vtk_rho, "prs": V_vtk_prs, "vx1": V_vtk_vx1, "vx2": V_vtk_vx2 }) if p['Dimensions'] == '3D': hl.gridToVTK(self._file_name, g.x1_verts, g.x2_verts, g.x3_verts, cellData={ "rho": V[rho].T, "prs": V[prs].T, "vx1": V[vx1].T, "vx2": V[vx2].T, "vx3": V[vx3].T }) return
def visJ(self,output_j_vtk_path,result_file_name,varibale_name='J',conductivity=1,assign_idx=-1): txt_keyword = varibale_name +':' with open(result_file_name, 'r') as f: for line in f: if line[:3] == 'LD:': # first_line = f.readline() lengths,dim = line.replace('LD:', '').split(':') lengths = [float(l)*1e3 for l in lengths.split(',')] # self.Lx,self.Ly,self.Lz = lengths # origin = tuple([-t/2 for t in lengths]) dim = [int(num) for num in dim.split(',')] print("lengthe is " + str(lengths)) print("dim is " + str(dim)) spacing = tuple([lengths[i]/dim[i] for i in range(3)]) jx = np.zeros(dim) jy = np.zeros(dim) jz = np.zeros(dim) elif line[:2] == 'J:': index,j_vec = line.replace('J:','').split('=') material = int(index.split(',')[-1]) if assign_idx != -1 and assign_idx!=material: continue index = tuple([int(t) for t in index.split(',')][:-1]) j_vec = [float(t) for t in j_vec.split(',')] jx[index] = j_vec[0]/conductivity jy[index] = j_vec[1]/conductivity jz[index] = j_vec[2]/conductivity else: print("This line didn't processed :" + line) continue jmag = np.sqrt(jx**2+jy**2+jz**2) self.jmag = jmag self.jx = jx self.jy = jy self.jz = jz # self.jmag = jmag.copy() dict_key = [ varibale_name + t for t in ['x','y','z','mag']] write_file_name = imageToVTK( output_j_vtk_path, origin=(0,0,0), spacing=spacing, pointData={dict_key[0]:jx,dict_key[1]:jy,dict_key[2]:jz,dict_key[3]:jmag} ) print(write_file_name) return jmag
def create_http_dataset(output_dir, filename, cell_data, point_data, dx): """ Write the data to a HTTPDataSet in the directory output_dir/filename.vti/ Uses temporary directory output_dir/temp/ to store intermediate .vti files :param output_dir: :type output_dir: :param filename: :type filename: :param cell_data: :type cell_data: :param point_data: :type point_data: :return: :rtype: """ temp_dir = os.path.join(output_dir, "temp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) vti_file = os.path.join(temp_dir, filename) finest_refinement = 0 # TODO for field, data in point_data.items(): point_data[field] = np.ascontiguousarray(data) actual_num_cells = 1 / dx - 2 * finest_refinement scaled_dx = 1 / actual_num_cells temp_filename = imageToVTK( vti_file, cellData=cell_data, pointData=point_data, # origin = (0,0,0), # cell centered data starts here origin=(dx / 2, dx / 2, dx / 2), spacing=(dx, dx, dx)) data_converter(temp_filename, output_dir)
def saveCube(name, data, shape): uCube = np.reshape(data, shape[::-1]) uCube = np.ascontiguousarray(np.transpose(uCube, axes=[2, 1, 0])) imageToVTK(name, pointData={"u": uCube})
a = np.ones(NWorld, order='F') apFlat = a.flatten(order='F') MLoc = gridlod.fem.localMassMatrix(gp.NPatchCoarse) MFull = gridlod.fem.assemblePatchMatrix(gp.NPatchCoarse, MLoc) ALoc = gridlod.fem.localStiffnessMatrix(gp.NPatchCoarse) AFull = gridlod.fem.assemblePatchMatrix(gp.NPatchCoarse, ALoc, apFlat) fixedMask = np.abs(np.prod(np.abs(p - 0.5) - 0.5, axis=1)) == 0 freeMask = np.logical_not(fixedMask) up = np.sin(2 * np.pi * p[:, 0]) * np.sin(2 * np.pi * p[:, 1]) * np.sin( 2 * np.pi * p[:, 2]) fp = 3 * 4 * (np.pi**2) * up bFull = MFull * fp bFree = bFull[freeMask] AFree = AFull[freeMask][:, freeMask] uFree, _ = sparse.linalg.cg(AFree, bFree) u = np.zeros(Np) u[freeMask] = uFree uCube = u.reshape(NWorld + 1) print(np.sqrt(np.dot(u - up, AFull * (u - up)))) imageToVTK("./image", pointData={"u": uCube})
# pressure = np.random.rand(ncells).reshape( (nx, ny, nz), order = 'C') # print pressure.shape print FTLE.shape # FTLE = Omega[:156,:178,:389]+0.1 print FTLE.shape # temp = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1)) print np.max(FTLE) aFTLE = (FTLE / np.max(FTLE)) * (1 + Omega / np.max(Omega)) FTLE = FTLE / np.max(FTLE) FTLE *= 10000 FTLE.astype(int) FTLE = np.ascontiguousarray(FTLE, dtype=np.int32) fileName = os.path.split(os.path.splitext(os.getcwd())[0])[1][:-5] + '_ftleATT' imageToVTK(fileName, origin=(xmin, ymin, zmin), spacing=(0.0075, 0.0075, 0.0075), pointData={"FTLE": FTLE}) Omega = Omega / np.max(Omega) Omega *= 10000 Omega.astype(int) Omega = np.ascontiguousarray(Omega, dtype=np.int32) fileName = os.path.split(os.path.splitext( os.getcwd())[0])[1][:-5] + '_omegaATT' imageToVTK(fileName, origin=(xmin, ymin, zmin), spacing=(0.0075, 0.0075, 0.0075), pointData={"Omega": Omega}) aFTLE *= 10000 aFTLE.astype(int)
def image3d(name, **scalars): ''' Export scalar field to vtk image file of name. ''' scalars = {k: to_numpy(v) for k, v in scalars.items()} imageToVTK(name, pointData=scalars)
os.chdir('Input') np.savetxt('perf-' + str(num), perfil, fmt='%11.4e', delimiter=" ") os.chdir('../Output/0_Termal/Perfiles') copy2('../../../../../t_data.pkl', '../') np.savetxt('perf-' + str(num), perfilT, fmt='%11.4e', delimiter=" ") os.chdir('../../../Output/0_Termal/0_Mecanico/Perfiles') copy2('../../../../../../m_data.pkl', '../') np.savetxt('perfT-' + str(num), perfilM_T, fmt='%11.4e', delimiter=" ") np.savetxt('perfC-' + str(num), perfilM_C, fmt='%11.4e', delimiter=" ") os.chdir('../../../../') if n == 174: break # get_old_output(t_data, m_data, areas) B = compute(t_data, m_data) geotherm = B.thermal_model.get_geotherm() yse_t, yse_c = B.get_yse() imageToVTK("./thermomecanic", spacing=(10.0, 10.0, 1.0), pointData={ "temperature": geotherm, "yield_strength": yse_t })
def test_3d(self): return NWorldFine = np.array([60, 220, 50]) NpFine = np.prod(NWorldFine + 1) NtFine = np.prod(NWorldFine) NWorldCoarse = np.array([6, 22, 5]) NCoarseElement = NWorldFine / NWorldCoarse NtCoarse = np.prod(NWorldCoarse) NpCoarse = np.prod(NWorldCoarse + 1) boundaryConditions = np.array([[1, 1], [0, 0], [1, 1]]) world = World(NWorldCoarse, NCoarseElement, boundaryConditions) aBase = np.loadtxt( os.path.dirname(os.path.realpath(__file__)) + '/data/upperness_x.txt') #aBase = aBase[::8] print 'a' coords = util.pCoordinates(NWorldFine) gFine = 1 - coords[:, 1] uFineFull, AFine, _ = femsolver.solveFine(world, aBase, None, -gFine, boundaryConditions) print 'b' rCoarse = np.ones(NtCoarse) self.assertTrue(np.size(aBase) == NtFine) if True: IPatchGenerator = lambda i, N: interp.L2ProjectionPatchMatrix( i, N, NWorldCoarse, NCoarseElement, boundaryConditions) aCoef = coef.coefficientCoarseFactor(NWorldCoarse, NCoarseElement, aBase, rCoarse) k = 2 printLevel = 1 pglod = pg.PetrovGalerkinLOD(world, k, IPatchGenerator, 1e-1, printLevel) pglod.updateCorrectors(aCoef, clearFineQuantities=True) KmsFull = pglod.assembleMsStiffnessMatrix() coords = util.pCoordinates(NWorldCoarse) g = 1 - coords[:, 1] bFull = -KmsFull * g boundaryMap = boundaryConditions == 0 fixed = util.boundarypIndexMap(NWorldCoarse, boundaryMap) free = np.setdiff1d(np.arange(0, NpCoarse), fixed) KmsFree = KmsFull[free][:, free] bFree = bFull[free] xFree = sparse.linalg.spsolve(KmsFree, bFree) uCoarse = np.zeros(NpCoarse) uCoarse[free] = xFree uCoarse += g uCube = np.reshape(uCoarse, (NWorldCoarse + 1)[::-1]) uCube = np.ascontiguousarray(np.transpose(uCube, axes=[2, 1, 0])) imageToVTK("./image", pointData={"u": uCube}) if False: coord = util.pCoordinates(NWorldCoarse) uCoarse = coord[:, 1].flatten() uCube = np.reshape(uCoarse, (NWorldCoarse + 1)[::-1]) uCube = np.ascontiguousarray(np.transpose(uCube, axes=[2, 1, 0])) imageToVTK("./image", pointData={"u": uCube})
# * Example of how to use the high level imageToVTK function. * # ************************************************************** from pyevtk.hl import imageToVTK import numpy as np # Dimensions nx, ny, nz = 6, 6, 2 ncells = nx * ny * nz npoints = (nx + 1) * (ny + 1) * (nz + 1) # Variables pressure = np.random.rand(ncells).reshape((nx, ny, nz), order="C") temp = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1)) imageToVTK("./image", cellData={"pressure": pressure}, pointData={"temp": temp}) fluxx = np.random.rand(ncells).reshape((nx, ny, nz), order="F") fluxy = np.random.rand(ncells).reshape((nx, ny, nz), order="F") fluxz = np.random.rand(ncells).reshape((nx, ny, nz), order="F") flux = (fluxx, fluxy, fluxz) Efieldx = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1), order="F") Efieldy = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1), order="F") Efieldz = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1), order="F") Efield = (Efieldx, Efieldy, Efieldz) imageToVTK("./image", cellData={"flux": flux}, pointData={"Efield": Efieldx})
def write_mesh(output_path, timestep, domain, point_data, mesh_group, current_time): mpath = imageToVTK("{}/mesh{:04d}".format(output_path, timestep), spacing = (domain["dx"], domain["dy"], 1.0), pointData = point_data) mesh_group.addFile(filepath = mpath, sim_time = current_time)
def convertVTK(ij_inp, rot, ij_out, density): """ Converts individual IJ volumes. VARIABLES --------- ij_inp: Input folder containing each of the LaVision DaVis volumes. rot: Rotation dict to correct the volumes (see Jupyter notebook). ij_out: Location to save the VTK files. density: Density of the liquid to use for conversion to LVF. Use density=1 for no correction for the mixing cases. """ # Create folders as needed create_folder('{0}/VTK'.format(ij_out)) create_folder('{0}/PIM'.format(ij_out)) create_folder('{0}/Slice-4'.format(ij_out)) create_folder('{0}/SliceIJ'.format(ij_out)) create_folder('{0}/Slice+4'.format(ij_out)) create_folder('{0}/Slice+8'.format(ij_out)) # Get total number of volumes and initialize the impingement point var ijPtn4_den = np.zeros((len(ij_inp), 1)) ijPt0_den = np.zeros((len(ij_inp), 1)) ijPt4_den = np.zeros((len(ij_inp), 1)) ijPt8_den = np.zeros((len(ij_inp), 1)) for i, inp in enumerate(ij_inp): # Load in the density volume # Only load in the X/Y/Z values on the first volume (always the same) if i == 0: volume, x_mm, y_mm, z_mm = load_davis(inp) # Flip the Y values y_mm = y_mm[::-1] # Get the location of the impingement point in mm space X, Y, Z = np.meshgrid(x_mm, y_mm, z_mm, indexing='ij') # Rotate the X, Y, Z meshgrids X = rotate(X, rot['Angle'], axes=rot['Axes'], reshape=False) Y = rotate(Y, rot['Angle'], axes=rot['Axes'], reshape=False) Z = rotate(Z, rot['Angle'], axes=rot['Axes'], reshape=False) # Center point in voxels center_X = 90 center_Y = 129 center_Z = 195 # Impingement point in voxel coordinates (found from the rotated # projection images) ij_X = X[center_X, center_Y, center_Z] ij_Y = Y[center_X, center_Y, center_Z] ij_Z = Z[center_X, center_Y, center_Z] # Center the x, y, z vectors x_mm -= ij_X y_mm -= ij_Y z_mm -= ij_Z # Crop down the volume (see Jupyter notebook) x1 = np.argmin(np.abs(x_mm - -4.7)) x2 = np.argmin(np.abs(x_mm - 4.7)) y1 = np.argmin(np.abs(y_mm - -5)) y2 = np.argmin(np.abs(y_mm - 14)) z1 = np.argmin(np.abs(z_mm - -10)) z2 = np.argmin(np.abs(z_mm - 10)) # Get the origin (defines corner of the grid) origin = [x_mm[x1], y_mm[y1], z_mm[z1]] # Cropping x_mm = x_mm[x1:x2] y_mm = y_mm[y1:y2] z_mm = z_mm[z1:z2] # Save the volume extents np.save('{0}/VTK/x_mm.npy'.format(ij_out), x_mm, allow_pickle=False) np.save('{0}/VTK/y_mm.npy'.format(ij_out), y_mm, allow_pickle=False) np.save('{0}/VTK/z_mm.npy'.format(ij_out), z_mm, allow_pickle=False) # Get the APS locations ind0X = np.argmin(np.abs(x_mm - 0)) ind0Z = np.argmin(np.abs(z_mm - 0)) indn4Y = np.argmin(np.abs(y_mm - -4)) ind0Y = np.argmin(np.abs(y_mm - 0)) ind4Y = np.argmin(np.abs(y_mm - 4)) ind8Y = np.argmin(np.abs(y_mm - 8)) else: volume, _, _, _ = load_davis(inp) # Rotate the volume volume = rotate(volume, rot['Angle'], axes=rot['Axes'], reshape=False) # Mask out invalid values volume[volume < 0] = 0 # Calculate optical depth for the mixing cases # Volumes were inverted (1 - buffer) in DaVis if density == 1: volume = -np.log(1 - volume) # Get voxel size dx = np.abs(x_mm[1] - x_mm[0]) dy = np.abs(y_mm[1] - y_mm[0]) dz = np.abs(z_mm[1] - z_mm[0]) voxelSize = (dx, dy, dz) # Cropping volume = volume[x1:x2, y1:y2, z1:z2].astype('float32') # Calculate the PIM as a function of y # Convert volume to density, then project onto all XZ planes PIM = np.sum(volume / dx, axis=(0, 2)) * dx**2 # Save the PIM trace np.save('{0}/PIM/{1:04d}'.format(ij_out, i), PIM, allow_pickle=False) # Get the intensity value at the impingement point (as density) ijPtn4_den[i] = volume[ind0X, indn4Y, ind0Z] / dx ijPt0_den[i] = volume[ind0X, ind0Y, ind0Z] / dx ijPt4_den[i] = volume[ind0X, ind4Y, ind0Z] / dx ijPt8_den[i] = volume[ind0X, ind8Y, ind0Z] / dx # Extract the slices as solution density slicen4 = volume[:, indn4Y, :].astype('float32') / dx slice0 = volume[:, ind0Y, :].astype('float32') / dx slice4 = volume[:, ind4Y, :].astype('float32') / dx slice8 = volume[:, ind8Y, :].astype('float32') / dx # Save slices as numpy files np.save('{0}/Slice-4/{1:04d}'.format(ij_out, i), slicen4, allow_pickle=False) np.save('{0}/SliceIJ/{1:04d}'.format(ij_out, i), slice0, allow_pickle=False) np.save('{0}/Slice+4/{1:04d}'.format(ij_out, i), slice4, allow_pickle=False) np.save('{0}/Slice+8/{1:04d}'.format(ij_out, i), slice8, allow_pickle=False) # Bin volumes down and smooth #volume = zoom(volume, (0.5, 0.5, 0.5)) volume = gaussian_filter(volume, 1) # Convert density to liquid volume fraction (LVF) LVF = volume / density breakpoint() # Convert files to VTK format (make sure to normalize by grid size!) imageToVTK( '{0}/VTK/{1:04d}'.format(ij_out, i), origin=origin, spacing=voxelSize, pointData={'LVF': LVF / dx}, ) # Create a time series file seriesVTK(ij_out) # Save the impingement point values as density and LVF np.save('{0}/ijPtn4_den'.format(ij_out), ijPtn4_den) np.save('{0}/ijPtn4_LVF'.format(ij_out), ijPtn4_den / density) np.save('{0}/ijPt0_den'.format(ij_out), ijPt0_den) np.save('{0}/ijPt0_LVF'.format(ij_out), ijPt0_den / density) np.save('{0}/ijPt4_den'.format(ij_out), ijPt4_den) np.save('{0}/ijPt4_LVF'.format(ij_out), ijPt4_den / density) np.save('{0}/ijPt8_den'.format(ij_out), ijPt8_den) np.save('{0}/ijPt8_LVF'.format(ij_out), ijPt8_den / density)
# plt.imshow(wind_field[:,0,:,0]) # plt.show() # # total_wind = wind.total_wind # # plt.imshow(total_wind[:,0,:,0]) # # plt.show() JCSS_law = lambda z, z_0, delta, u_ast: u_ast/0.41 * ( np.log(z/z_0+1.0) + 5.57*z/delta - 1.87*(z/delta)**2 - 1.33*(z/delta)**3 + 0.25*(z/delta)**4 ) log_law = lambda z, z_0, u_ast: u_ast * np.log(z/z_0+1.0)/0.41 z = np.linspace(0.0,grid_dimensions[2], 2**(grid_levels[2])+1) # mean_profile_z = JCSS_law(z, roughness_height, 10.0, friction_velocity) mean_profile_z = log_law(z, roughness_height, friction_velocity) mean_profile = np.zeros_like(wind_field) mean_profile[...,0] = np.tile(mean_profile_z.T, (mean_profile.shape[0], mean_profile.shape[1], 1)) # wind_field = mean_profile wind_field += mean_profile ################### ## Export to vtk FileName = 'OntheFlyWindField' spacing = tuple(grid_dimensions/(2.0**grid_levels + 1)) wind_field_vtk = tuple([np.copy(wind_field[...,i], order='C') for i in range(3)]) cellData = {'grid': np.zeros_like(wind_field[...,0]), 'wind': wind_field_vtk} imageToVTK(FileName, cellData = cellData, spacing=spacing)
# Read VASP CAR format (CHGCAR, AECCAR, LOCPOT) and write the field as a vti file! import numpy import argparse from VASPutils import readCAR from pyevtk.hl import imageToVTK # --------------------------------------------- parser = argparse.ArgumentParser( description='Read a CAR file and write as vti') parser.add_argument('--infile', metavar='(infile)', required=True, nargs=1, help='Input CAR file') args = parser.parse_args() infilename = args.infile[0] # --------------------------------------------- (sysname, scalingfactor, lattice, species, pos, grid, data) = readCAR(infilename, True) spacings = (scalingfactor * lattice[0][0] / (grid[0] - 1), scalingfactor * lattice[1][1] / (grid[1] - 1), scalingfactor * lattice[2][2] / (grid[2] - 1)) # --------------------------------------------- # now, write the data print 'Writing', infilename + '.vti' imageToVTK(infilename, spacing=spacings, pointData={"charge": data})
# * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * # * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * # * EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * # * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * # * BUT NOT LIMITED TO, PROCUREMEN OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * # * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * # * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * # * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * # * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * # *********************************************************************************** # ************************************************************** # * Example of how to use the high level imageToVTK function. * # ************************************************************** from pyevtk.hl import imageToVTK import numpy as np # Dimensions nx, ny, nz = 6, 6, 2 ncells = nx * ny * nz npoints = (nx + 1) * (ny + 1) * (nz + 1) # Variables pressure = np.random.rand(ncells).reshape((nx, ny, nz), order='C') temp = np.random.rand(npoints).reshape((nx + 1, ny + 1, nz + 1)) imageToVTK("./image", cellData={"pressure": pressure}, pointData={"temp": temp})
def save_scalar_data(s, scalar_name, filename): imageToVTK(filename, pointData={scalar_name: s}) return None
foldNum.append([val0,DateAcq,val1])#int(TMP[len(TMP)-1])) #patata list1=sorted(foldNum, key=operator.itemgetter(0, 1, 2)) matchesSort=[] #patata###This loop converts the elements of the path that were sorted into the path appropriate path for katL in list1: Item=0#for katM in matches: while (~np.isnan(Item)): katM=matches[Item] if (katL[0] in katM and '/'+str(katL[1])+'/' in katM and '/'+str(katL[2])+'_OCT' in katM): matchesSort.append(katM) Item=np.nan Item+=1 #SortPos = np.argsort(foldNum) TimeP = len(matchesSort) OoM=str(TimeP).count('')-1 OutFmt="%0"+str(OoM)+"d" TimeP=0 for katF in matchesSort: #CWDst = os.getcwd() os.chdir(katF) #patata VolVTK=GenVTK() FoldOut=katF.split('export')[0] #os.chdir(CWDst) OutNum=OutFmt % (TimeP,) imageToVTK(FoldOut+TempFileprefix+"_"+OutNum, cellData = {"Scattering" : VolVTK} ) TimeP+=1 print(TempFileprefix+"_"+OutNum)