def run_pde(self): t0 = self.parameter.simulation_start_time # Start time for simulation current_time = t0 # Variable to store the current time t_step = self.parameter.time_step pde_equation = self.pde_equation sol_variable = self.solution_variable if self.parameter.plotting: viewer = Viewer(vars=sol_variable, datamin=0, datamax=1.) viewer.plotMesh() # source_flag = True # currently not implemented while current_time < t0 + self.parameter.simulation_duration: ### This code was to allow boundary flux to change, but non-flux boundaries are not working # if source_flag and current_time > self.parameter.source_end_time: # sol_variable = self.define_solution_variable(sol_variable, boundary_source='no flux') # sol_variable.faceGrad.constrain(0 * self.mesh.faceNormals, self.mesh.exteriorFaces) pde_equation.solve(var=sol_variable, dt=t_step) # solve one time step # Increment time previous_time = current_time current_time += t_step # Check for change in convection data if self.detect_change_in_convection_data(previous_time, current_time): pde_equation = self.define_ode(current_time) # Check if the solution should be saved if self.detect_save_time(previous_time, current_time): self.add_current_state_to_save_file(current_time) if self.parameter.plotting: viewer.plot() # If the final time step goes beyond the duration, do a shorter finishing step. if current_time > t0 + self.parameter.simulation_duration: t_step = current_time - (t0 + self.parameter.simulation_duration) current_time = t0 + self.parameter.simulation_duration # set current time to the final time pde_equation.solve(var=sol_variable, dt=t_step) # solve one time step print('Current time step: {}, finish time: {}'.format(current_time, self.parameter.simulation_duration)) # At completion, save the final state self.add_current_state_to_save_file(current_time) print('PDE solving complete')
where=((x0 < x) & (x < x1)) & ((x0 < y) & (y < x1))) surfactantVariable = SurfactantVariable(distanceVar=distanceVariable, value=1.) from fipy.variables.surfactantConvectionVariable import SurfactantConvectionVariable surfactantEquation = TransientTerm() - \ ExplicitUpwindConvectionTerm(SurfactantConvectionVariable(distanceVariable)) advectionEquation = TransientTerm() + AdvectionTerm(velocity) if __name__ == '__main__': distanceViewer = Viewer(vars=distanceVariable, datamin=-.001, datamax=.001) surfactantViewer = Viewer(vars=surfactantVariable, datamin=0., datamax=2.) distanceVariable.calcDistanceFunction() for step in range(steps): print numerix.sum(surfactantVariable) distanceVariable.updateOld() surfactantEquation.solve(surfactantVariable, dt=1) advectionEquation.solve(distanceVariable, dt=timeStepDuration) distanceViewer.plot() surfactantViewer.plot() surfactantEquation.solve(surfactantVariable, dt=1) distanceViewer.plot() surfactantViewer.plot() print surfactantVariable raw_input('finished')
KMView = KMVar / KMVar.cellVolumeAverage KMView.setName('KM') KMViewer = Viewer(KMView, datamax=2., datamin=0., title='') TMView = TMVar / TMVar.cellVolumeAverage TMView.setName('TM') TMViewer = Viewer(TMView, datamax=2., datamin=0., title='') for i in range(100): for var, eqn in eqs: var.updateOld() for var, eqn in eqs: eqn.solve(var, dt=1.) x, y = mesh.cellCenters RVar[:] = L / sqrt((x - L / 2)**2 + (y - 2 * L)**2) for i in range(100): for var, eqn in eqs: var.updateOld() for var, eqn in eqs: eqn.solve(var, dt=1.) PNViewer.plot() KMViewer.plot() TMViewer.plot() input("finished")
mesh = SkewedGrid2D(dx = 1.0, dy = 1.0, nx = 20, ny = 20, rand = 0.1) var = CellVariable(name = "solution variable", mesh = mesh, value = valueLeft) viewer = Viewer(vars = var) var.constrain(valueLeft, mesh.facesLeft) var.constrain(valueRight, mesh.facesRight) DiffusionTerm().solve(var) varArray = numerix.array(var) x = mesh.cellCenters[0] analyticalArray = valueLeft + (valueRight - valueLeft) * x / 20 errorArray = varArray - analyticalArray errorVar = CellVariable(name = 'absolute error', mesh = mesh, value = abs(errorArray)) errorViewer = Viewer(vars = errorVar) NonOrthoVar = CellVariable(name = "non-orthogonality", mesh = mesh, value = mesh._nonOrthogonality) NOViewer = Viewer(vars = NonOrthoVar) viewer.plot() NOViewer.plot() input("finished")
var.constrain(valueBottomTop, mesh.facesTop) var.constrain(valueBottomTop, mesh.facesBottom) #do the 2D problem for comparison nx = 8 # FIXME: downsized temporarily from 10 due to https://github.com/usnistgov/fipy/issues/622 ny = 5 dx = 1. dy = 1. mesh2 = Grid2D(dx = dx, dy = dy, nx = nx, ny = ny) var2 = CellVariable(name = "solution variable 2D", mesh = mesh2, value = valueBottomTop) var2.constrain(valueLeftRight, mesh2.facesLeft) var2.constrain(valueLeftRight, mesh2.facesRight) var2.constrain(valueBottomTop, mesh2.facesTop) var2.constrain(valueBottomTop, mesh2.facesBottom) eqn = DiffusionTerm() if __name__ == '__main__': eqn.solve(var2) viewer = Viewer(var2) viewer.plot() input("finished")
KCEq = TransientTerm() - KCscCoeff + ImplicitSourceTerm(KCspCoeff) eqs = ((KMVar, KMEq), (TMVar, TMEq), (TCVar, TCEq), (P3Var, P3Eq), (P2Var, P2Eq), (KCVar, KCEq)) if __name__ == '__main__': v1 = KMVar / KMVar.cellVolumeAverage v2 = PN / PN.cellVolumeAverage v3 = TMVar / TMVar.cellVolumeAverage v1.setName('KM') v2.setName('PN') v3.setName('TM') KMViewer = Viewer((v1, v2, v3), title = 'Gradient Stimulus: Profile') KMViewer.plot() for i in range(100): for var, eqn in eqs: var.updateOld() for var, eqn in eqs: eqn.solve(var, dt = 1.) RVar[:] = params['S'] + (1 + params['S']) * params['G'] * cos((2 * pi * mesh.cellCenters[0]) / L) for i in range(100): for var, eqn in eqs: var.updateOld() for var, eqn in eqs: eqn.solve(var, dt = 0.1) KMViewer.plot()
timeStepDuration = cfl * dx / abs(velocity) steps = 1000 mesh = Grid1D(dx = dx, nx = nx) startingArray = numerix.zeros(nx, 'd') startingArray[50:90] = 1. var = CellVariable( name = "advection variable", mesh = mesh, value = startingArray) var.constrain(valueLeft, mesh.facesLeft) var.constrain(valueRight, mesh.facesRight) eq = TransientTerm() - PowerLawConvectionTerm(coeff = (velocity,)) if __name__ == '__main__': viewer = Viewer(vars=(var,)) viewer.plot() raw_input("press key to continue") for step in range(steps): eq.solve(var, dt = timeStepDuration, solver = LinearLUSolver(tolerance = 1.e-15)) viewer.plot() viewer.plot() raw_input('finished')
eqs = ((KMVar, KMEq), (TMVar, TMEq), (TCVar, TCEq), (P3Var, P3Eq), (P2Var, P2Eq), (KCVar, KCEq)) if __name__ == '__main__': v1 = KMVar / KMVar.cellVolumeAverage v2 = PN / PN.cellVolumeAverage v3 = TMVar / TMVar.cellVolumeAverage v1.setName('KM') v2.setName('PN') v3.setName('TM') KMViewer = Viewer((v1, v2, v3), title='Gradient Stimulus: Profile') KMViewer.plot() for i in range(100): for var, eqn in eqs: var.updateOld() for var, eqn in eqs: eqn.solve(var, dt=1.) RVar[:] = params['S'] + (1 + params['S']) * params['G'] * cos( (2 * pi * mesh.cellCenters[0]) / L) for i in range(100): for var, eqn in eqs: var.updateOld() for var, eqn in eqs: eqn.solve(var, dt=0.1)
#!/usr/bin/env python from fipy import Grid1D, CellVariable, TransientTerm, DiffusionTerm, Viewer # m = Grid1D(nx=100, Lx=1.) # v0 = CellVariable(mesh=m, hasOld=True, value=0.5) v1 = CellVariable(mesh=m, hasOld=True, value=0.5) # v0.constrain(0, m.facesLeft) v0.constrain(1, m.facesRight) # v1.constrain(1, m.facesLeft) v1.constrain(0, m.facesRight) # eq0 = TransientTerm() == DiffusionTerm(coeff=0.01) - v1.faceGrad.divergence eq1 = TransientTerm() == v0.faceGrad.divergence + DiffusionTerm(coeff=0.01) # vi = Viewer((v0, v1)) # for t in range(100): v0.updateOld() v1.updateOld() res0 = res1 = 1e100 while max(res0, res1) > 0.1: res0 = eq0.sweep(var=v0, dt=1e-5) res1 = eq1.sweep(var=v1, dt=1e-5) if t % 10 == 0: vi.plot()
v1.constrain(1, m.facesLeft) v1.constrain(0, m.facesRight) eq0 = TransientTerm() == DiffusionTerm(coeff=0.01) - v1.faceGrad.divergence eq1 = TransientTerm() == v0.faceGrad.divergence + DiffusionTerm(coeff=0.01) vi = Viewer((v0, v1)) for t in range(100): v0.updateOld() v1.updateOld() res0 = res1 = 1e100 while max(res0, res1) > 0.1: res0 = eq0.sweep(var=v0, dt=1e-5) res1 = eq1.sweep(var=v1, dt=1e-5) if t % 10 == 0: vi.plot() # eqn0 = TransientTerm(var=v0) == DiffusionTerm(0.01, var=v0) - DiffusionTerm(1, var=v1) # eqn1 = TransientTerm(var=v1) == DiffusionTerm(1, var=v0) + DiffusionTerm(0.01, var=v1) # eqn = eqn0 & eqn1 # for t in range(1): # v0.updateOld() # v1.updateOld() # eqn.solve(dt=1.e-3) # vi.plot()
advectionEquation = TransientTerm() + AdvectionTerm(velocity) from fipy.variables.surfactantConvectionVariable import SurfactantConvectionVariable surfactantEquation = TransientTerm() - \ ExplicitUpwindConvectionTerm(SurfactantConvectionVariable(distanceVariable)) if __name__ == '__main__': distanceViewer = Viewer(vars=distanceVariable, datamin=-initialRadius, datamax=initialRadius) surfactantViewer = Viewer(vars=surfactantVariable, datamin=0., datamax=100.) velocityViewer = Viewer(vars=velocity, datamin=0., datamax=200.) distanceViewer.plot() surfactantViewer.plot() velocityViewer.plot() totalTime = 0 for step in range(steps): print('step', step) velocity.setValue(surfactantVariable.interfaceVar * k) distanceVariable.extendVariable(velocity) timeStepDuration = cfl * dx / velocity.max() distanceVariable.updateOld() advectionEquation.solve(distanceVariable, dt=timeStepDuration) surfactantEquation.solve(surfactantVariable, dt=1) totalTime += timeStepDuration
KMView = KMVar / KMVar.cellVolumeAverage KMView.setName('KM') KMViewer = Viewer(KMView, datamax=2., datamin=0., title='') TMView = TMVar / TMVar.cellVolumeAverage TMView.setName('TM') TMViewer = Viewer(TMView, datamax=2., datamin=0., title='') for i in range(100): for var, eqn in eqs: var.updateOld() for var, eqn in eqs: eqn.solve(var, dt = 1.) x, y = mesh.cellCenters RVar[:] = L / sqrt((x - L / 2)**2 + (y - 2 * L)**2) for i in range(100): for var, eqn in eqs: var.updateOld() for var, eqn in eqs: eqn.solve(var, dt = 1.) PNViewer.plot() KMViewer.plot() TMViewer.plot() input("finished")
#mesh = Gmsh2D("C:\\Users\\muel_hd\\Desktop\\test.geo") mesh = Gmsh2D(geometryTemplate) phi = CellVariable(name="Temperature", mesh=mesh, value=T0) # Die Waermeleitungsgleichung equation = TransientTerm() == DiffusionTerm(coeff=D) # boundry conditions ---------------------------------------------------------- phi.constrain(Ti, where=mesh.physicalFaces["inner"]) phi.constrain(Te, where=mesh.physicalFaces["outer"]) # Viewer mit Limits entsprechend den Werten initialisieren viewer = Viewer(vars=phi, datamin=0., datamax=Te * 1.1) if steady_state: DiffusionTerm(coeff=D).solve(var=phi) viewer.plot() else: viewer.plot() raw_input("Press enter to start the show") for i in range(intervals): equation.solve(var=phi, dt=dt) if __name__ == '__main__': viewer.plot() # Interactive plot raw_input("Press enter to close ...")
value = initialSurfactantValue, distanceVar = distanceVariable ) advectionEquation = TransientTerm() + AdvectionTerm(velocity) from fipy.variables.surfactantConvectionVariable import SurfactantConvectionVariable surfactantEquation = TransientTerm() - \ ExplicitUpwindConvectionTerm(SurfactantConvectionVariable(distanceVariable)) if __name__ == '__main__': distanceViewer = Viewer(vars=distanceVariable, datamin=-initialRadius, datamax=initialRadius) surfactantViewer = Viewer(vars=surfactantVariable, datamin=-1., datamax=100.) distanceViewer.plot() surfactantViewer.plot() print('total surfactant before:', numerix.sum(surfactantVariable * mesh.cellVolumes)) for step in range(steps): distanceVariable.updateOld() surfactantEquation.solve(surfactantVariable, dt=1.) advectionEquation.solve(distanceVariable, dt = timeStepDuration) distanceViewer.plot() surfactantViewer.plot() surfactantEquation.solve(surfactantVariable, dt=1.) print('total surfactant after:', numerix.sum(surfactantVariable * mesh.cellVolumes))
where=mesh.exteriorFaces) #dPion/dx = 0 at the exterior faces of the mesh Nion.faceGrad.constrain( 0., where=mesh.exteriorFaces) #dNion/dx = 0 at the exterior faces of the mesh potential.constrain( 0., where=mesh.exteriorFaces) #potential = 0 at the exterior faces of the mesh ################################################################ #################''' SOLVE EQUATIONS '''######################## ################################################################ eq = Pion.equation & Nion.equation & potential.equation #Couple all of the equations together steps = 100 #How many time steps to take dt = 1 #How long each time step is in seconds if __name__ == "__main__": #viewer = Viewer(vars=(potential,),datamin=-1.1,datamax=1.1) #Sets up viewer for the potential with y-axis limits viewer = Viewer( vars=(Pion, ), datamin=0, datamax=1e21 ) #Sets up viewer for negative ion density with y-axis limits #viewer = Viewer(vars=(Nion,),datamin=-1e21,datamax=0) #Sets up viewer for positive ion density with y-axis limits for steps in range(steps): #Time loop to step through eq.solve(dt=dt) #Solves all coupled equation with timestep dt if __name__ == '__main__': viewer.plot() #Plots results using matplotlib plt.pause(1) #Pauses each frame for n amount of time #plt.autoscale() #Autoscale axes if necessary
valueRight = 1. mesh = SkewedGrid2D(dx=1.0, dy=1.0, nx=20, ny=20, rand=0.1) var = CellVariable(name="solution variable", mesh=mesh, value=valueLeft) viewer = Viewer(vars=var) var.constrain(valueLeft, mesh.facesLeft) var.constrain(valueRight, mesh.facesRight) DiffusionTerm().solve(var) varArray = numerix.array(var) x = mesh.cellCenters[0] analyticalArray = valueLeft + (valueRight - valueLeft) * x / 20 errorArray = varArray - analyticalArray errorVar = CellVariable(name='absolute error', mesh=mesh, value=abs(errorArray)) errorViewer = Viewer(vars=errorVar) NonOrthoVar = CellVariable(name="non-orthogonality", mesh=mesh, value=mesh._nonOrthogonality) NOViewer = Viewer(vars=NonOrthoVar) viewer.plot() NOViewer.plot() input("finished")
dx = L / nx dy = L / ny mesh = Grid2D(dx, dy, nx, ny) phase = CellVariable(name = 'PhaseField', mesh = mesh, value = 1.) theta = ModularVariable(name = 'Theta', mesh = mesh, value = 1.) x, y = mesh.cellCenters theta.setValue(0., where=(x - L / 2.)**2 + (y - L / 2.)**2 < (L / 4.)**2) mPhiVar = phase - 0.5 + temperature * phase * (1 - phase) thetaMag = theta.old.grad.mag implicitSource = mPhiVar * (phase - (mPhiVar < 0)) implicitSource += (2 * s + epsilon**2 * thetaMag) * thetaMag phaseEq = TransientTerm(phaseTransientCoeff) == \ ExplicitDiffusionTerm(alpha**2) \ - ImplicitSourceTerm(implicitSource) \ + (mPhiVar > 0) * mPhiVar * phase if __name__ == '__main__': phaseViewer = Viewer(vars = phase) phaseViewer.plot() for step in range(steps): phaseEq.solve(phase, dt = timeStepDuration) phaseViewer.plot() input('finished')
density.updateOld() temperature.updateOld() Z.updateOld() Diffusivity.setValue(D_choice_local) calculate_coeffs() # --------------- Solving Loop -------------------- while current_residual > config.res_tol: print(t, current_residual) current_residual = full_equation.sweep(dt=config.timeStep, solver=GMRES_Solver) # Plot solution and save, if option is True if config.generate_plots is True: if config.save_plots is True: viewer.plot(filename=config.save_directory + "/" + str(t).zfill(4) + ".png") # Save auxiliary plots if config.aux_plots is True: for current_aux in range(len(aux_plot_array)): aux_plot_array[current_aux]\ .plot(filename=config.save_directory + "/aux" + str(current_aux) + "_" + str(t).zfill(4) + ".png") # If not set to save elif config.save_plots is False: viewer.plot() if config.aux_plots is True: for current_aux in aux_plot_array:
alpha = 0.015 temperature = 1. dx = L / nx mesh = Grid1D(dx=dx, nx=nx) phase = CellVariable(name='PhaseField', mesh=mesh, value=1.) theta = ModularVariable(name='Theta', mesh=mesh, value=1.) theta.setValue(0., where=mesh.cellCenters[0] > L / 2.) mPhiVar = phase - 0.5 + temperature * phase * (1 - phase) thetaMag = theta.old.grad.mag implicitSource = mPhiVar * (phase - (mPhiVar < 0)) implicitSource += (2 * s + epsilon**2 * thetaMag) * thetaMag phaseEq = TransientTerm(phaseTransientCoeff) == \ ExplicitDiffusionTerm(alpha**2) \ - ImplicitSourceTerm(implicitSource) \ + (mPhiVar > 0) * mPhiVar * phase if __name__ == '__main__': phaseViewer = Viewer(vars=phase) phaseViewer.plot() for step in range(steps): phaseEq.solve(phase, dt=timeStepDuration) phaseViewer.plot() input('finished')
def solve_Te(Qe_tot=2e6, H0=0, Hw=0.1, Te_bc=100, chi=1, a0=1, R0=3, E0=1.5, b_pos=0.98, b_height=6e19, b_sol=2e19, b_width=0.01, b_slope=0.01, nr=100, dt=100, plots=True): """ :param Qe_tot: heating power [W] :type Qe_tot: numpy float :param H0: position of Gaussian [-] :type H0: numpy float :param Hw: width of Gaussian [-] :type Hw: numpy float :param Te_bc: outer edge Te boundary condition [eV] :type Te_bc: numpy float :param chi: thermal diffusivity [?] :type chi: numpy float :param a0: minor radius [m] :type a0: numpy float :param R0: major radius [m] :type R0: numpy float :param E0: ellipticity :type E0: numpy float :param b_pos: position of density pedestal [-] :type b_pos: numpy float :param b_height: height of density pedestal [m^-3] :type b_height: numpy float :param b_sol: sol value for density pedestal [m^-3] :type b_sol: numpy float :param b_width: width of density pedestal [-] :type b_width: numpy float :param b_slope: slope of density pedestal [?] :type b_slope: numpy float :param nr: number of radial grid points :type nr: inteher :param dt: time-step [s] :type dt: numpy float :param plots: enable plots :type plots: boolean :return: array of Te values [eV] :type: numpy float array :return: array of ne values [m^-3] :type: numpy float array :return: rho values corresponding to the Te and ne values [m] :type: numpy float array :return: rho_norm values corresponding to the Te and ne values [-] :type: numpy float array [email protected] """ if plots: import os import matplotlib if not os.getenv("DISPLAY"): matplotlib.use('Agg') import matplotlib.pylab as plt import scipy.constants from fipy import Variable, FaceVariable, CellVariable, TransientTerm, DiffusionTerm, Viewer, meshes a = a0 * np.sqrt(E0) V = 2 * np.pi * 2 * np.pi * R0 mesh = meshes.CylindricalGrid1D(nr=nr, Lr=a) Te = CellVariable(name="Te", mesh=mesh, value=1e3) ne = CellVariable(name="ne", mesh=mesh, value=F_ped(mesh.cellCenters.value[0] / a, b_pos, b_height, b_sol, b_width, b_slope)) Qe = CellVariable(name="Qe", mesh=mesh, value=np.exp(-((mesh.cellCenters.value / a - H0) / (Hw))**2)[0]) Qe = Qe * Qe_tot / ((mesh.cellVolumes * Qe.value).sum() * V) print('Volume = %s m^3' % (mesh.cellVolumes.sum() * V)) print('Heating power = %0.3e W' % ((mesh.cellVolumes * Qe).sum() * V)) Te.constrain(Te_bc, mesh.facesRight) eqI = TransientTerm( coeff=scipy.constants.e * ne * 1.5) == DiffusionTerm(coeff=scipy.constants.e * ne * chi) + Qe if plots: viewer = Viewer(vars=(Te), title='Heating power = %0.3e W\nchi = %s' % (Qe.cellVolumeAverage.value * V, chi), datamin=0, datamax=5000) eqI.solve(var=Te, dt=dt) if plots: viewer.plot() return Te.value, ne.value, mesh.cellCenters.value[ 0], mesh.cellCenters.value[0] / a
startingArray[2 * nx // 10:3 * nx // 10] = 1. var1 = CellVariable(name="non-periodic", mesh=mesh, value=startingArray) var2 = CellVariable(name="periodic", mesh=periodicMesh, value=startingArray[:nx // 2]) eq1 = TransientTerm() - VanLeerConvectionTerm(coeff=(-velocity, )) eq2 = TransientTerm() - VanLeerConvectionTerm(coeff=(-velocity, )) if __name__ == '__main__': viewer1 = Viewer(vars=var1) viewer2 = Viewer(vars=var2) viewer1.plot() viewer2.plot() newVar2 = var2.copy() for step in range(steps): eq1.solve(var=var1, dt=dt, solver=DefaultAsymmetricSolver()) eq2.solve(var=var2, dt=dt, solver=DefaultAsymmetricSolver()) viewer1.plot() viewer2.plot() newVar2[:nx / 4] = var2[nx / 4:] newVar2[nx / 4:] = var2[:nx / 4] print 'maximum absolute difference between periodic and non-periodic grids:', abs( var1[nx / 4:3 * nx / 4] - newVar2).max()
while current_residual > config.res_tol: print t, current_residual current_residual = full_equation.sweep(dt=config.timeStep,\ solver=GMRES_Solver) # "Turn on" NBI # if t == 50: # config.Gamma_c = 1.0e1*config.Gamma_c # config.q_c = 5.0e2*config.Gamma_c # set_boundary_values(config.Gamma_c, config.q_c) # Plot solution and save, if option is True if config.generate_plots == True: if config.save_plots == True: density_viewer.plot(filename=config.save_directory + "/n"\ +str(t).zfill(4)+ ".png") temp_viewer.plot(filename=config.save_directory + "/T" \ +str(t).zfill(4)+ ".png") ZD_viewer.plot(filename=config.save_directory + "/Z" \ +str(t).zfill(4)+ ".png") # D_viewer.plot(filename=config.save_directory + "/D" \ # +str(t).zfill(4)+ ".png") # Save auxiliary plots if config.aux_plots == True: for current_aux in range(len(aux_plot_array)): aux_plot_array[current_aux].plot(filename =\ config.save_directory + "/aux"\ +str(current_aux)+"_"+str(t).zfill(4)+ ".png") # If not set to save