def Scanning_laser_welding(initial_temp,heat_input,final_time,time_step,velocity,radius_of_heat_source,dimen,material): temp_profile_new = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) temp_profile_old = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) temp_profile_old[:][:][:] = initial_temp temp_profile_new[:][:][:] = initial_temp*2 constant = (heat_input)/(material.density*material.specific_heat*(np.pi**1.5)*(material.alpha**0.5)) string= "./media/vishal/General1/Vishal_ubuntu/Additive_Manufacturing/All_functions/scan_laser_steel/Scanning_laser_welding_2_2d_test" m=0 t = 0.0 y1 = float(dimen.ny)/2000.0 while t<=final_time: filename=string+str(m) t_dash = t + time_step for i in range (dimen.nx+1): x = float (i)/1000.0 for j in range (dimen.ny+1): y = float (j)/1000.0 for k in range (dimen.nz+1): z = float (k)/1000.0 integ1 = (integration(t,x,y,z,velocity,radius_of_heat_source,y1,material)) integ2 = (integration(t_dash,x,y,z,velocity,radius_of_heat_source,y1,material)) integ = ((integ1+integ2)/2) temp_profile_new[i][j][k] = (constant*integ*time_step) + temp_profile_old[i][j][k] print t,i,j,k,integ1,integ2 print t,np.amax(temp_profile_new),np.amin(temp_profile_new) imageToVTK(filename, cellData = None, pointData = {"temp" : temp_profile_new} ) temp_profile_old = temp_profile_new t = t + (time_step) m=m+1
def Scanning_laser_welding(initial_temp,heat_input,final_time,time_step,velocity,radius_of_heat_source,dimen,material): temp_profile_new = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) temp_profile_old = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) temp_profile_old[:][:][:] = initial_temp temp_profile_new[:][:][:] = initial_temp*2 constant = (heat_input)/(material.density*material.specific_heat*(np.pi**1.5)*(material.alpha**0.5)) string= "./scan_laser_steel/scan_laser_steel" m=0 t = 0.0 x1 = dimen.lx/2 y1 = dimen.ly/2 while t<=final_time: filename=string+str(m) t_dash = t + time_step for i in range (dimen.nx+1): x = float (i)*(dimen.lx)/dimen.nx for j in range (dimen.ny+1): y = float (j)*(dimen.ly)/dimen.ny for k in range (dimen.nz+1): z = float (k)*(dimen.lz)/dimen.nz integ1 = (integration(t,x,y,z,velocity,radius_of_heat_source,x1,y1,material)) integ2 = (integration(t_dash,x,y,z,velocity,radius_of_heat_source,x1,y1,material)) integ = ((integ1+integ2)/2) temp_profile_new[i][j][k] = (constant*integ*time_step) + temp_profile_old[i][j][k] print t,np.amax(temp_profile_new),np.amin(temp_profile_new) imageToVTK(filename, cellData = None, pointData = {"temp" : temp_profile_new} ) temp_profile_old = temp_profile_new t = t + (time_step) m=m+1
def Uniform_Surface_heating(final_temp,initial_temp,final_time,step_count,h, dimen, material): temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string= "./media/vishal/General/Vishal_ubuntu/Additive_Manufacturing/All_functions/Uniform_surface_quenching/1_Uniform_Surface_quenching" m=0 l = 2.0 theta1 = lambda t : erf(l) + (np.exp(t + (t*t/(4*l*l))))*(1-erf(t + t/(2*l))) t = (step_count)/2 while t<=final_time: filename=string+str(m) for i in range (dimen.nx+1): filename=string+str(m) a = (float(i))/(np.sqrt(4*material.alpha*t)) b = h*i/material.thermal_conductivity c = ((h**2)*(material.alpha)*t)/(material.thermal_conductivity**2) d = np.sqrt(c) theta = erf(a) + (np.exp(b+c)*(1-erf(a+d))) temp=final_temp + (initial_temp-final_temp)*theta temp_profile[i][:][:]=temp imageToVTK(filename, cellData = None, pointData = {"temp" : temp_profile} ) print t,np.amax(temp_profile),np.amin(temp_profile) t = t + step_count m=m+1 x = np.linspace(0.0,1.0,100) pl.plot(x,theta1(x)) pl.grid(b =1) pl.show()
def Spot_laser_welding(initial_temp, heat_input, final_time, time_step, dimen, material): temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string = "./media/vishal/General1/Vishal_ubuntu/Additive_Manufacturing/All_functions/spot_laser_steel/Spot_laser_welding_steel_test1" t = 0.0 m = 0 x1 = dimen.nx / 2 y1 = dimen.ny / 2 t = time_step / 2 while t < final_time: filename = string + str(m) for i in range(dimen.nx + 1): x = float(i) / 1000.0 for j in range(dimen.ny + 1): y = float(j) / 1000.0 for k in range(dimen.nz + 1): z = float(k) / 1000.0 l = ((((x - x1)**2) + ((y - y1)**2) + (z**2)) / (4 * material.alpha * t)) exponen = np.exp((-1.0) * l) a = 2 * heat_input b = material.density * material.specific_heat c = ((4 * np.pi * material.alpha * t)**1.5) temp_profile[i][j][k] = initial_temp + ( (a / (b * c)) * exponen) imageToVTK(filename, cellData=None, pointData={"temp": temp_profile}) print t, np.amax(temp_profile), np.amin(temp_profile) t = t + time_step m = m + 1
def strip_casting(mold_temp, casting_speed, h, dimen, material): phase_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string = "./media/vishal/General1/Vishal_ubuntu/Additive_Manufacturing/All_functions/strip_casting/3_strip_casting" const = ((200 * h * (mold_temp - material.melting_temp)) / (casting_speed * material.density * material.heat_of_fusion * dimen.ny)) phase_profile[:][:][:] = 50 z = dimen.nz / 2 y = dimen.ny / 2 fs = 0 theta1 = lambda t: const * t for i in range(dimen.nx + 1): x = float(i) / 100.0 fs = const * x if fs < 1: a = (np.sqrt(dimen.area * (1 - fs))) * 100.0 y1 = int(y - (a / 2)) y2 = int(y + (a / 2)) z1 = int(z - (a / 2)) z2 = int(z + (a / 2)) for j in range(y1, y2 + 1): for k in range(z1, z2 + 1): phase_profile[i][j][k] = 100 else: break print i, fs imageToVTK(string, cellData=None, pointData={"phase": phase_profile}) x = np.linspace(0.0, 1.0, 100) pl.plot(x, theta1(x)) pl.grid(b=1) pl.show()
def sand_casting(mold_temp,step_count,h,dimen, material,mold_material): phase_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string= "./media/vishal/General/Vishal_ubuntu/Additive_Manufacturing/All_functions/sand_casting/1_sand_casting" a = (2/(np.sqrt(np.pi))) b = ((material.melting_temp-mold_temp)/(material.density*material.heat_of_fusion)) c = (np.sqrt(mold_material.thermal_conductivity*mold_material.density*mold_material.specific_heat)) d = a*b*c m=0 X =0 theta1 = lambda t : d*np.sqrt(t) phase_profile[:][:][:]=100 t =0.0 X = d*np.sqrt(t) filename=string+str(m) print a , b , c , d while X<1: i = int( X * dimen.nx ) phase_profile[0:i][:][:] = 50 print t , X imageToVTK(filename, cellData = None, pointData = {"phase" : phase_profile} ) m =m +1 filename=string+str(m) phase_profile[:][:][:]=100 t =t +step_count X = d*np.sqrt(t) x = np.linspace(0.0,40,100) pl.plot(x,theta1(x)) pl.grid(b =1) pl.show()
def uniform_surface_heating(initial_temp, heat_input, t_on, final_time, step_count, dimen, material): temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string = "./media/vishal/General/Vishal_ubuntu/Additive_Manufacturing/All_functions/uniform_surfacce_heating/uniform_surface_heating" l = (2 * heat_input * (np.sqrt(material.alpha))) / material.thermal_conductivity n = 0 t = step_count / 2 while t < t_on: filename = string + str(n) m = np.sqrt(4 * material.alpha * t) for i in range(dimen.nx + 1): x = float(i) / 1000.0 temp_profile[i][:][:] = initial_temp + l * np.sqrt(t) * (ierfc( x / m)) imageToVTK(filename, cellData=None, pointData={"temp": temp_profile}) n = n + 1 t = t + step_count while t < final_time: filename = string + str(n) m1 = np.sqrt(4 * material.alpha * t) m2 = np.sqrt(4 * material.alpha * (t - t_on)) for i in range(dimen.nx + 1): x = float(i) / 1000.0 c = np.sqrt(t) * ierfc(x / m1) d = np.sqrt(t - t_on) * ierfc(x / m2) temp_profile[i][:][:] = initial_temp + l * (c - d) imageToVTK(filename, cellData=None, pointData={"temp": temp_profile}) n = n + 1 t = t + step_count
def die_casting(mold_temp, step_count, h, dimen, material): phase_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string = "./media/vishal/General/Vishal_ubuntu/Additive_Manufacturing/All_functions/die_casting/die_casting" s = (h * (material.melting_temp - mold_temp)) / (material.density * material.heat_of_fusion) m = 0 X = 0 theta1 = lambda t: (h * t * (material.melting_temp - mold_temp)) / ( material.density * material.heat_of_fusion) phase_profile[:][:][:] = 100 t = (step_count) / 2 X = s * t filename = string + str(m) while X < 1: i = int(X * dimen.nx) phase_profile[0:i][:][:] = 50 print t, X imageToVTK(filename, cellData=None, pointData={"phase": phase_profile}) m = m + 1 filename = string + str(m) phase_profile[:][:][:] = 100 t = t + step_count X = s * t x = np.linspace(0.0, 1.0, 100) pl.plot(x, theta1(x)) pl.grid(b=1) pl.show()
def convertToVTK(self, i, key): cfile = self.read(i) vfield = cfile.getField(key) data = vfield.data if len(vfield.dims) == 2: data = data.reshape(data.shape + (1, )) d = {} d[key] = data imageToVTK(key + "." + self.filename(i), cellData=d)
def convertToVTK(self, i, key): cfile = self.read(i) vfield = cfile.getField(key) data = vfield.data if len(vfield.dims) == 2: data = data.reshape(data.shape + (1,)) d = {} d[key] = data imageToVTK(key + "." + self.filename(i), cellData = d)
def run(): resolution=0.1 doplot=True doexportvtk=False if doexportvtk: resolution=0.5 deb=time.time() #Init Voxelisation with precision in meter voxelizator=fv.TriangleScalarFieldCreator(resolution) #Load PLY polygonal file voxelizator.load_ply_model("elmia.ply") print "Process done in %f sec" % (time.time()-deb) #Extract the cell i,j,k values corresponding to position in meter (a position in the volume to extract) cellid=voxelizator.get_cell_id_by_coord(vec3(7,-0.5,1)) #Get the corresponding volume id elmiavol=voxelizator.get_matrix_value(cellid) #Extract Boundary of this volume minv=fv.ivec3() maxv=fv.ivec3() voxelizator.get_cell_value_boundaries(minv,maxv,elmiavol) minv-=fv.ivec3(1,1,1) maxv+=fv.ivec3(1,1,1) extract_shape=maxv-minv print "Matrix Size is %ix%ix%i" % (extract_shape[0],extract_shape[1],extract_shape[2]) #Plotting if doplot: print "voxelizator.get_first_volume_index():",voxelizator.get_first_volume_index() nbmarkers=voxelizator.get_first_volume_index()+voxelizator.get_volume_count() #Create a matrix to extract only an Y slice of the 3D voxelisation (save lot of memory) pieceof=np.zeros((extract_shape[0],1,extract_shape[2]),dtype=np.short) #Transfer data from voxel to numpy matrix data_filt=np.arange(nbmarkers,dtype=np.short) data_filt[voxelizator.get_first_volume_index():]=-1 #Set -1 to all volumes data_filt[elmiavol]=0 #Set 0 to air voxelizator.copy_matrix_filtered(pieceof,minv+ivec3(0,cellid[1],0),data_filt) import matplotlib.pyplot as plt from matplotlib import cm from pylab import show,colorbar p=plt.matshow(np.rot90(pieceof[:,0,:]),fignum=2,cmap=cm.get_cmap('jet', nbmarkers)) colorbar(p,ticks=range(nbmarkers)) show() elif doexportvtk: from evtk.hl import imageToVTK #Create a matrix to extract only an Y slice of the 3D voxelisation (save lot of memory) pieceof=np.zeros((extract_shape[0],extract_shape[1],extract_shape[2]),dtype=np.short) #Transfer data from voxel to numpy matrix voxelizator.copy_matrix(pieceof,minv) imageToVTK(r"C:\tmp\elmia",cellData = {"materials" : np.array(pieceof,dtype="float32")}) time.sleep(1)
def Welding_Consumble_electrode(initial_temp,feed_rate,dimen, material): temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string= "./media/vishal/General1/Vishal_ubuntu/Additive_Manufacturing/All_functions/Welding_consumable/Welding_consumable_electrode_2" l = np.exp(feed_rate*(dimen.nx/100.0)/material.alpha) for i in range (dimen.nx+1): x = float(i)/100.0 theta = (np.exp(feed_rate*x/material.alpha)-1)/(l-1) temp=initial_temp + (material.melting_temp - initial_temp)*(theta) temp_profile[i][:][:] = temp print i, theta imageToVTK(string, cellData = None, pointData = {"temp" : temp_profile} )
def export_vtk(lattice, moments): for i, m in enumerate(moments): print("Export VTK file %d of %d." % (i + 1, len(moments))) imageToVTK("result/ldc_3d_%03d" % i, cellData={ 'velocity_x': m[1, :].reshape(lattice.geometry.size(), order='F'), 'velocity_y': m[2, :].reshape(lattice.geometry.size(), order='F'), 'velocity_z': m[3, :].reshape(lattice.geometry.size(), order='F') })
def nii2vtk(in_file, out_file=None): from evtk.hl import imageToVTK nii = nb.load(in_file) data = np.array(nii.get_data(), order='C') if out_file is None: out_file, ext = op.splitext(op.basename(in_file)) if ext == '.gz': out_file, _ = op.splitext(out_file) out_file = op.abspath(out_file) imageToVTK(out_file, pointData={'scalar': data}) return out_file
def run(): print("Running image...") # 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)) comments = [ "comment 1", "comment 2" ] imageToVTK(FILE_PATH, cellData = {"pressure" : pressure}, pointData = {"temp" : temp}, comments = comments )
def nii2vtk(in_file, out_file=None): from evtk.hl import imageToVTK nii = nb.load(in_file) data = np.array(nii.get_data(), order="C") if out_file is None: out_file, ext = op.splitext(op.basename(in_file)) if ext == ".gz": out_file, _ = op.splitext(out_file) out_file = op.abspath(out_file) imageToVTK(out_file, pointData={"scalar": data}) return out_file
def welding_thin_plate(initial_temp,heat_input,velocity,dimen,material): temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string= "./media/vishal/General1/Vishal_ubuntu/Additive_Manufacturing/All_functions/welding_thin_plate/welding_thin_plate_6.2" l = ((heat_input*1000.0)/(4*np.pi*material.thermal_conductivity*dimen.nz)) expo = (velocity/(2*material.alpha)) for i in range (dimen.nx+1): x = float(i-50) / 1000.0 for j in range (dimen.ny+1): y = float(j-30) / 1000.0 for k in range (dimen.nz+1): r= np.sqrt((x**2)+(y**2)) if r == 0.0: r = 0.001 temp_profile[i][j][k] = (l*np.exp(expo*x)*kn(0,expo*r))+ initial_temp imageToVTK(string, cellData = None, pointData = {"temp" : temp_profile} )
def Welding_Non_consumable_electrode(final_temp, initial_temp, current_density, dimen, material): temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string = "./media/vishal/General1/Vishal_ubuntu/Additive_Manufacturing/All_functions/Welding_non_consumable/1_Welding_Non_consumable_electrode_" s = (current_density)**2 / (material.elecric_conductivity) l = float(dimen.nx) / 1000.0 for i in range(dimen.nx + 1): x = float(i) / 1000.0 temp = initial_temp + ((s * x * (l - x)) / (2 * material.thermal_conductivity) ) + x * (final_temp - initial_temp) / (l) temp_profile[i][:][:] = temp print i, temp_profile[i][0][0] imageToVTK(string, cellData=None, pointData={"temp": temp_profile})
def Invisid_melt_spinning(initial_temp, feed_rate, dimen, material): temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string = "./media/vishal/General1/Vishal_ubuntu/Additive_Manufacturing/All_functions/invisid_melt_spinning/4_Invisid_melt_spinning" l = ((material.heat_of_fusion / (material.specific_heat * (material.melting_temp - initial_temp))) + 1) print l, material.alpha for i in range(dimen.nx + 1): x = float(i) / 1000.0 theta = (np.exp((feed_rate * x) / material.alpha) - 1) * (l) temp = initial_temp + (material.melting_temp - initial_temp) * (theta) temp_profile[i][:][:] = temp print i, temp_profile[i][0][0], theta imageToVTK(string, cellData=None, pointData={"temp": temp_profile})
def image2VTK( arr, vname=None ): """ Save cubical or array 'image' data to VTK format. Requires: EVTK package """ if type( arr ) == str: # set vtk prefix to same as array name vname = fname = arr # time shit tstart = time.time() print "Loading cubical complex coordinates..." if not fname.endswith( 'txt' ): fname+='.txt' # arr is now a numpy array arr = numpy.loadtxt( fname, dtype='int' ) print "Time to write vtk file:", time.time() - tstart else: if vname == None: raise ValueError, "Must provide a name for VTK file if passing in numpy array!" nx, ny = arr.shape print "Loaded! shape=(", nx, ny, ")" print "shape", arr.shape # shift the origin to (0,0,0) # for i in range( ny ): # arr[:,i] = arr[:,i] - arr[:,i].min() # arr records corners of cubical grid (structured grid) in # 3-space; the extent of the grid is found by the max value # in each dimension. dx, dy, dz = [ int( arr[:,i].max() ) for i in range( ny ) ] print "dx, dy, dz:", dx, dy, dz # total number of cells in structured grid ncells = (dx+1) * (dy+1) * (dz+1) cells = numpy.zeros( ncells, dtype='uint' ).reshape( (dx+1,dy+1,dz+1), order='C' ) #cells = numpy.ones( ncells, dtype='uint' ).reshape( (dx+1,dy+1,dz+1), order='C' ) print "Converting cubical structure to VTK grid structure..." print "Size of cell complex", cells.shape tstart = time.time() cells[ arr[:,0], arr[:,1], arr[:,2] ] = 1 print cells # for row in arr: # print row # cells[ row[0], row[1], row[2] ] = 1 imageToVTK( vname, cellData = {"cells" : cells} ) print "Wrote", vname, "to file." print "Time to write vtk file:", time.time() - tstart
def saveVTK(U, filename): """ Main IO routine. Save U array into a vtk file. filename should include .vti suffix """ # enum for hydro variables (taken from hydroParam) ID = hp.ID IP = hp.IP IU = hp.IU IV = hp.IV # filename without suffix (.vti) # use vtk module if available if vtkModuleFound: #writer = vtk.vtkXMLImageDataWriter() #writer.SetFileName(filename) # TO BE CONTINUED pass # use evtk module if available if evtkModuleFound: isize = U.shape[0] jsize = U.shape[1] from evtk.hl import imageToVTK # compelled to deepcopy array # apparently slices are not accepted by imageToVTK d = U[:,:,ID].reshape(isize,jsize,1).copy() p = U[:,:,IP].reshape(isize,jsize,1).copy() u = U[:,:,IU].reshape(isize,jsize,1).copy() v = U[:,:,IV].reshape(isize,jsize,1).copy() imageToVTK(filename, cellData = {"rho" : d, "E" : p, "mx" : u, "my" : v}) else: # ? try to write a vtk file by hand .... later pass
def Bulk_heating(final_temp, initial_temp, final_time, step_count, h, dimen, material): temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string = "./media/vishal/General/Vishal_ubuntu/Additive_Manufacturing/All_functions/Bulk_heating/Bulk_heating" biot = (h * dimen.nx) / (2000 * material.thermal_conductivity) roots = np.zeros(5) a = np.zeros(5) b = np.zeros(5) m1 = 0 l = float(dimen.nx) / 1000.0 print l t = 0.0 solve = lambda x: (x * math.tan(x * np.pi / 180.0)) - biot roots[0] = fsolve(solve, 1) roots[1] = fsolve(solve, 180) roots[2] = fsolve(solve, 360) roots[3] = fsolve(solve, 540) roots[4] = fsolve(solve, 720) print roots for i in range(5): a[i] = math.sin(roots[i] * np.pi / 180.0) / (roots[i] + (math.sin( roots[i] * np.pi / 180.0) * math.cos(roots[i] * np.pi / 180.0))) print a while t <= final_time: filename = string + str(m1) f0 = (material.alpha * t * 1000000) / (dimen.nx * dimen.nx) for j in range(5): b[j] = np.exp((-1) * roots[j] * roots[j] * f0) for i in range(dimen.nx + 1): x = float(i) / 1000.0 sum_root = 0.0 for k in range(5): sum_root = sum_root + a[k] * b[k] * math.cos( roots[k] * x * np.pi / (l * 180.0)) theta = 2 * sum_root print t, i, theta temp = final_temp + (initial_temp - final_temp) * theta temp_profile[i][:][:] = temp imageToVTK(filename, cellData=None, pointData={"temp": temp_profile}) print t, np.amax(temp_profile), np.amin(temp_profile) t = t + step_count m1 = m1 + 1
def saveVTK(U, filename): """ Main IO routine. Save U array into a vtk file. filename should include .vti suffix """ # enum for hydro variables (taken from hydroParam) ID = hp.ID IP = hp.IP IU = hp.IU IV = hp.IV # filename without suffix (.vti) # use vtk module if available if vtkModuleFound: #writer = vtk.vtkXMLImageDataWriter() #writer.SetFileName(filename) # TO BE CONTINUED pass # use evtk module if available if evtkModuleFound: isize = U.shape[0] jsize = U.shape[1] from evtk.hl import imageToVTK # compelled to deepcopy array # apparently slices are not accepted by imageToVTK d = U[:, :, ID].reshape(isize, jsize, 1).copy() p = U[:, :, IP].reshape(isize, jsize, 1).copy() u = U[:, :, IU].reshape(isize, jsize, 1).copy() v = U[:, :, IV].reshape(isize, jsize, 1).copy() imageToVTK(filename, cellData={"rho": d, "E": p, "mx": u, "my": v}) else: # ? try to write a vtk file by hand .... later pass
def Quenching_of_thin_sheet(final_temp,initial_temp,final_time,step_count,h, dimen, material): mass = dimen.volume*material.density temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string= "./media/vishal/General/Vishal_ubuntu/Additive_Manufacturing/All_functions/thin_sheet/1_thin_sheet_quenching_2" m=0 t=0.0 theta1 = lambda t : np.exp((-1.0*dimen.area*t)/(mass*material.specific_heat)) while t<=final_time: filename=string+str(m) theta = np.exp((-1.0*dimen.area*t)/(mass*material.specific_heat)) temp=final_temp + (initial_temp-final_temp)*theta temp_profile[:][:][:]=temp imageToVTK(filename, cellData = None, pointData = {"temp" : temp_profile} ) print t,np.amax(temp_profile),np.amin(temp_profile) t = t + step_count m=m+1 x = np.linspace(0.0,0.01,100) pl.plot(x,theta1(x)) pl.grid(b =1) pl.show()
def welding_thick_plate(initial_temp, heat_input, velocity, dimen, material): temp_profile = np.random.rand(dimen.npoints).reshape( (dimen.nx + 1, dimen.ny + 1, dimen.nz + 1)) string = "./media/vishal/General1/Vishal_ubuntu/Additive_Manufacturing/All_functions/welding_thick_plate/welding_thick_plate_test_1_6.2" l = ((heat_input) / (2 * np.pi * material.thermal_conductivity)) expo = (velocity / (2 * material.alpha)) x = 0.0 y = 0.0 for i in range(dimen.nx + 1): x = float(i - 50) / 1000.0 for j in range(dimen.ny + 1): y = float(j - 24) / 1000.0 for k in range(dimen.nz + 1): z = float(k) / 1000.0 r = np.sqrt((x**2) + (y**2) + (z)) if r == 0.0: r = 0.001 temp_profile[i][j][k] = ( (l / r) * np.exp(expo * (x - r))) + initial_temp print i, j, k, temp_profile[i][j][k] print np.amax(temp_profile), np.amin(temp_profile) imageToVTK(string, cellData=None, pointData={"temp": temp_profile})
def write_vti_scalar(self, arr, x=None, y=None, z=None, name=None, output_dir=''): ''' Writes a 3D numpy array into a VTI file. Only works for scalar values. Must be uniform spacing. arr: the data you want to write. If str: writes from sim.arr If numpy array: writes the numpy array. Assumes the same size as sim unless x, y and z are specified If dict: writes multiple numpy arrays in dict to vti. Assumes the same size as sim unless x, y and z are specified x, y, z: the x, y and z position array, name: Name of the file/data array. Needed for np.array or dict arr input output_dir: Specify a different output folder. ''' from evtk.hl import imageToVTK if (output_dir is not ''): output_dir += '/' if (x is None): x = self.x y = self.y z = self.z # If x, y, and z are different from the array d = np.array([x[1] - x[0], y[1] - y[0], z[1] - z[0]]) xc = np.array([x[0], y[0], z[0]]) #-0.5*d if (type(arr) is type('')): imageToVTK(output_dir + self.index + '_' + arr + '-' + self.time, cellData={arr: self.arr[arr]}, origin=xc.tolist(), spacing=d.tolist()) else: if name is None: print( 'For arr of type np.array or dict, you need to specify a name' ) return fname = output_dir + self.index + '_' + name + '-' + self.time if type(arr) is type(dict()): imageToVTK(fname, cellData=arr, origin=xc.tolist(), spacing=d.tolist()) elif type(arr) is type(np.array([])): imageToVTK(fname, cellData={name: arr}, origin=xc.tolist(), spacing=d.tolist()) else: print('arr must be of type str, np.array or dict')
def image2VTK( arr, vname=None ): """ Save cubical or array 'image' data to VTK format. Requires: EVTK package """ if type( arr ) == str: # set vtk prefix to same as array name vname = fname = arr # time shit tstart = time.time() print "Loading cubical complex coordinates..." if not fname.endswith( 'txt' ): fname+='.txt' # arr is now a numpy array arr = numpy.loadtxt( fname, dtype='int' ) nx, ny = arr.shape print "Loaded! shape=(", nx, ny, ")" print "Elapsed time:", time.time() - tstart else: if vname == None: raise ValueError, "Must provide a name for VTK file if passing in numpy array!" # shift the origin to (0,0,0) for i in range( ny ): arr[:,i] = arr[:,i] - arr[:,i].min() dx, dy, dz = [ int( arr[:,i].max() ) for i in range( ny ) ] # total number of cells in structured grid ncells = (dx+1) * (dy+1) * (dz+1) cells = numpy.zeros( ncells, dtype='uint' ).reshape( (dx+1,dy+1,dz+1), order='C' ) print "Converting cubical structure to VTK grid structure..." print "Size of cell complex", cells.shape tstart = time.time() w = numpy.where for row in arr: cells[ row[0], row[1], row[2] ] = 1 imageToVTK("./"+vname, cellData = {"cell" : cells} ) print "Elapsed time:", time.time() - tstart
from scipy import io import numpy as np from evtk.hl import imageToVTK from evtk.hl import gridToVTK test = {} io.loadmat('iCPC3D04a_v3d_x1_uint8.mat',mdict=test) vox3dnp = np.array(test['vox3d']) imageToVTK('./test', origin=(0.0,0.0,0.0), spacing = (sp,sp,sp), cellData = {'grayscale': np.ascontiguousarray(vox3dnp)}) sp = test['voxsize'][0][0] w, h, d = vox3dnp.shape x = np.linspace(0.0, sp*(w), w+1, dtype=np.float32) y = np.linspace(0.0, sp*(h), h+1, dtype=np.float32) z = np.linspace(0.0, sp*(d), d+1, dtype=np.float32) from tvtk.api import tvtk, write_data grid = tvtk.ImageData(spacing=(sp, sp, sp), origin=(0.0, 0.0, 0.0), dimensions=vox3dnp.shape) grid.point_data.scalars = np.ravel(vox3dnp, order='F') grid.point_data.scalars.name = 'grayscale' # Writes legacy ".vtk" format if filename ends with "vtk", otherwise # this will write data using the newer xml-based format. write_data(grid, 'test3.vtk')
def saveVTK(U, filename): """ Main IO routine. Save U array into a vtk file. filename should include .vti suffix """ # enum for hydro variables (taken from hydroParam) ID = hp.ID IP = hp.IP IU = hp.IU IV = hp.IV # filename without suffix (.vti) # use tvtk module if available if tvtkModuleFound: # create an imageData i = tvtk.ImageData(spacing=(1, 1, 1), origin=(0, 0, 0)) # add density field i.cell_data.scalars = U[:,:,ID].ravel() i.cell_data.scalars.name = 'rho' i.dimensions = (U[:,:,ID].shape[0]+1, U[:,:,ID].shape[1]+1, 1) # add total energy i.cell_data.add_array(U[:,:,IP].ravel()) i.cell_data.get_array(1).name = 'E' i.cell_data.update() # add velocity i.cell_data.add_array(U[:,:,IU].ravel()) i.cell_data.get_array(2).name = 'mx' i.cell_data.update() i.cell_data.add_array(U[:,:,IV].ravel()) i.cell_data.get_array(3).name = 'my' i.cell_data.update() # actual write data on disk tvtk_write_data(i, filename) #writer = tvtk.vtkXMLImageDataWriter() #writer.SetFileName(filename) # use evtk module if available elif evtkModuleFound: isize = U.shape[0] jsize = U.shape[1] from evtk.hl import imageToVTK # compelled to deepcopy array # apparently slices are not accepted by imageToVTK d = U[:,:,ID].reshape(isize,jsize,1).copy() p = U[:,:,IP].reshape(isize,jsize,1).copy() u = U[:,:,IU].reshape(isize,jsize,1).copy() v = U[:,:,IV].reshape(isize,jsize,1).copy() imageToVTK(filename, cellData = {"rho" : d, "E" : p, "mx" : u, "my" : v}) else: # ? try to write a vtk file by hand .... later pass
def saveVTK(U, filename): """ Main IO routine. Save U array into a vtk file. filename should include .vti suffix """ # filename without suffix (.vti) # use tvtk module if available if tvtkModuleFound: # create an imageData i = tvtk.ImageData(spacing=(1, 1, 1), origin=(0, 0, 0)) # add density field i.cell_data.scalars = U[:,:,ID].ravel() i.cell_data.scalars.name = 'rho' i.dimensions = (U[:,:,ID].shape[0]+1, U[:,:,ID].shape[1]+1, 1) # add total energy i.cell_data.add_array(U[:,:,IP].ravel()) i.cell_data.get_array(1).name = 'E' i.cell_data.update() # add velocity i.cell_data.add_array(U[:,:,IU].ravel()) i.cell_data.get_array(2).name = 'mx' i.cell_data.update() i.cell_data.add_array(U[:,:,IV].ravel()) i.cell_data.get_array(3).name = 'my' i.cell_data.update() # actual write data on disk tvtk_write_data(i, filename) #writer = tvtk.vtkXMLImageDataWriter() #writer.SetFileName(filename) # use evtk module if available elif evtkModuleFound: isize = U.shape[0] jsize = U.shape[1] from evtk.hl import imageToVTK # compelled to deepcopy array # apparently slices are not accepted by imageToVTK d = U[:,:,ID].reshape(isize,jsize,1).copy() p = U[:,:,IP].reshape(isize,jsize,1).copy() u = U[:,:,IU].reshape(isize,jsize,1).copy() v = U[:,:,IV].reshape(isize,jsize,1).copy() imageToVTK(filename, cellData = {"rho" : d, "E" : p, "mx" : u, "my" : v}) else: # ? try to write a vtk file by hand .... later pass
# * 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 evtk.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)) comments = [ b"comment 1", b"comment 2" ] imageToVTK("./image", cellData = {"pressure" : pressure}, pointData = {"temp" : temp}, comments = comments )
from evtk.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} )
#file to create vtk file for paraview visualisation using python from evtk.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})
#!/usr/bin/env python import numpy as np from evtk.hl import imageToVTK def gen_image(x, y, t): xm, ym = np.meshgrid(x, y) d = np.power(xm, 2) + np.power(ym, 2) return np.cos(np.sqrt(d) * 2.0 - t) / (1.0 + d) nx = 101 ny = 101 nt = 30 x = np.linspace(-10.0, 10.0, nx, dtype=np.float32) y = np.linspace(-10.0, 10.0, ny, dtype=np.float32) t = np.linspace(0, 2 * np.pi, nt, dtype=np.float32) for it, vt in enumerate(t): N = gen_image(x, y, vt) filename = 'anim_%04d' % it imageToVTK( filename, pointData={'N': N.astype(np.float32).reshape((nx, ny, 1), order='C')}) print('%s.vti generated' % (filename))