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')
def integrate_slump(ts, date_final=date_final, fnout=None, fnoutfig=None, viewer_variable='T', viewer_min=-5, viewer_max=30): if viewer_variable is not None: viewer = Viewer(vars=(ts.variables[viewer_variable]), datamin=viewer_min, datamax=viewer_max, title=ts.date) else: viewer = None # integrate ts.integrate(date_final, viewer=viewer) if viewer is not None: plt.close(viewer.id) if fnoutfig is not None: plot_time_series(ts, fnout=fnoutfig) if fnout is not None: ts.exportOutput(fnout) return ts
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')
KCspCoeff = params['lambdaKstar'] / (params['kappaKstar'] + KCVar) 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()
>>> print var.allclose(analyticalArray) 1 """ __docformat__ = 'restructuredtext' from fipy import Tri2D, CellVariable, DiffusionTerm, Viewer nx = 50 dx = 1. mesh = Tri2D(dx = dx, nx = nx) valueLeft = 0. valueRight = 1. var = CellVariable(name = "solution-variable", mesh = mesh, value = valueLeft) var.constrain(valueLeft, mesh.facesLeft) var.constrain(valueRight, mesh.facesRight) if __name__ == '__main__': DiffusionTerm().solve(var) viewer = Viewer(vars=var) viewer.plot() x = mesh.cellCenters[0] Lx = nx * dx analyticalArray = valueLeft + (valueRight - valueLeft) * x / Lx print var.allclose(analyticalArray) raw_input("finished")
charge.setValue(-1, where=mesh.physicalCells["Cathode"]) potential = CellVariable(mesh=mesh, name=r"$\psi$") potential.constrain(0., where=mesh.physicalFaces["Ground"]) eq = DiffusionTerm(coeff=1.) == -charge res0 = eq.sweep(var=potential) res = eq.justResidualVector(var=potential) res1 = numerix.L2norm(res) res1a = CellVariable(mesh=mesh, value=abs(res)) res = CellVariable(mesh=mesh, name="residual", value=abs(res) / mesh.cellVolumes**(1./mesh.dim) / 1e-3) # want cells no bigger than 1 and no smaller than 0.001 maxSize = 1. minSize = 0.001 monitor = CellVariable(mesh=mesh, name="monitor", value= 1. / (res + maxSize) + minSize) viewer = Viewer(vars=potential, xmin=3.5, xmax=4.5, ymin=3.5, ymax=4.5) # viewer = Viewer(vars=(potential, charge)) viewer.plot() # resviewer = Viewer(vars=res1a, log=True, datamin=1e-6, datamax=1e-2, cmap=cm.gray) # monviewer = Viewer(vars=monitor, log=True, datamin=1e-3, datamax=1) raw_input("refinement %d, res0: %g, res: %g:%g, N: %d, min: %g, max: %g, avg: %g. Press <return> to proceed..." \ % (refinement, res0, res1, res1a.cellVolumeAverage, mesh.numberOfCells, numerix.sqrt(min(mesh.cellVolumes)), numerix.sqrt(max(mesh.cellVolumes)), numerix.mean(numerix.sqrt(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
# ----------------- PDE Declarations ---------------------- density.equation = (DiffusionTerm(coeff=Diffusivity, var=density) == 0) temperature.equation = (0 ==\ DiffusionTerm(coeff=(Diffusivity*density/zeta), var=temperature)\ + DiffusionTerm(coeff=-Diffusivity*temperature, var=density)) G = a + b * (Z - Z_S) + c * (Z - Z_S)**3 S_Z = ((c_n*temperature) / density**2) * density.grad[0]\ + (c_T / density) * temperature.grad[0] + G Z.equation = (0 == DiffusionTerm(coeff=mu, var=Z) + S_Z) full_equation = density.equation & temperature.equation & Z.equation viewer = Viewer((density, temperature, Z, Diffusivity), xmin=0.0, xmax=L) restol = 1e-1 res_D = res_n = res_T = res_Z = 1.0e10 if __name__ == '__main__': while res_n > restol: res_n = density.equation.sweep(var=density, solver=mySolver) viewer.plot() raw_input("n_res = %f" % res_n) while res_T > restol: res_T = temperature.equation.sweep(var=temperature, solver=mySolver) viewer.plot() raw_input("T_res = %f" % res_T) # while res_Z > restol:
def runGold(faradaysConstant=9.6e4, consumptionRateConstant=2.6e+6, molarVolume=10.21e-6, charge=1.0, metalDiffusion=1.7e-9, metalConcentration=20.0, catalystCoverage=0.15, currentDensity0=3e-2 * 16, currentDensity1=6.5e-1 * 16, cellSize=0.1e-7, trenchDepth=0.2e-6, aspectRatio=1.47, trenchSpacing=0.5e-6, boundaryLayerDepth=90.0e-6, numberOfSteps=10, taperAngle=6.0, displayViewers=True): cflNumber = 0.2 numberOfCellsInNarrowBand = 20 mesh = TrenchMesh(cellSize=cellSize, trenchSpacing=trenchSpacing, trenchDepth=trenchDepth, boundaryLayerDepth=boundaryLayerDepth, aspectRatio=aspectRatio, angle=numerix.pi * taperAngle / 180.) narrowBandWidth = numberOfCellsInNarrowBand * cellSize distanceVar = GapFillDistanceVariable(name='distance variable', mesh=mesh, value=-1.) distanceVar.setValue(1., where=mesh.electrolyteMask) distanceVar.calcDistanceFunction() catalystVar = SurfactantVariable(name="catalyst variable", value=catalystCoverage, distanceVar=distanceVar) metalVar = CellVariable(name='metal variable', mesh=mesh, value=metalConcentration) exchangeCurrentDensity = currentDensity0 + currentDensity1 * catalystVar.interfaceVar currentDensity = metalVar / metalConcentration * exchangeCurrentDensity depositionRateVariable = currentDensity * molarVolume / charge / faradaysConstant extensionVelocityVariable = CellVariable(name='extension velocity', mesh=mesh, value=depositionRateVariable) catalystSurfactantEquation = AdsorbingSurfactantEquation( catalystVar, distanceVar=distanceVar, bulkVar=0, rateConstant=0, consumptionCoeff=consumptionRateConstant * extensionVelocityVariable) advectionEquation = TransientTerm() + FirstOrderAdvectionTerm( extensionVelocityVariable) metalEquation = buildMetalIonDiffusionEquation( ionVar=metalVar, distanceVar=distanceVar, depositionRate=depositionRateVariable, diffusionCoeff=metalDiffusion, metalIonMolarVolume=molarVolume) metalVar.constrain(metalConcentration, mesh.facesTop) if displayViewers: try: from .mayaviSurfactantViewer import MayaviSurfactantViewer viewer = MayaviSurfactantViewer(distanceVar, catalystVar.interfaceVar, zoomFactor=1e6, datamax=1.0, datamin=0.0, smooth=1, title='catalyst coverage', animate=True) except: class PlotVariable(CellVariable): def __init__(self, var=None, name=''): CellVariable.__init__(self, mesh=mesh.fineMesh, name=name) self.var = self._requires(var) def _calcValue(self): return numerix.array(self.var(self.mesh.cellCenters)) viewer = MultiViewer( viewers=(Viewer( PlotVariable( var=distanceVar), datamax=1e-9, datamin=-1e-9), Viewer(PlotVariable(var=catalystVar.interfaceVar)))) else: viewer = None levelSetUpdateFrequency = int(0.7 * narrowBandWidth / cellSize / cflNumber / 2) step = 0 while step < numberOfSteps: if step % 10 == 0 and viewer is not None: viewer.plot() if step % levelSetUpdateFrequency == 0: distanceVar.calcDistanceFunction() extensionVelocityVariable.setValue( numerix.array(depositionRateVariable)) dt = cflNumber * cellSize / max(extensionVelocityVariable.globalValue) distanceVar.extendVariable(extensionVelocityVariable) advectionEquation.solve(distanceVar, dt=dt) catalystSurfactantEquation.solve(catalystVar, dt=dt) metalEquation.solve(metalVar, dt=dt) step += 1 point = ((5e-09, ), (1.15e-07, )) value = 1.45346701e-09 return abs(float(distanceVar(point, order=1)) - value) < cellSize / 10.0
# ----------------- Choose Solver ------------------------- # Available: LinearPCGSolver (Default), LinearGMRESSolver, LinearLUSolver, # LinearJORSolver <-- Not working exactly PCG_Solver = LinearPCGSolver(iterations=100, tolerance=1.0e-6) GMRES_Solver = LinearGMRESSolver(iterations=100) LLU_Solver = LinearLUSolver(iterations=100, tolerance=1.0e-6) # Does not work if __name__ == '__main__': # Declare viewer if config.generate_plots is True: viewer = Viewer((density, temperature, -Z, Diffusivity), xmin=0.0, xmax=L, datamin=-0.2, datamax=config.ploty_max, legend='best', title=config.plot_title) input("Pause for Viewing Initial Conditions") # Auxiliary viewers if config.aux_plots is True: aux_plot_array = [] for k in range(len(config.aux_vars)): aux_plot_array\ .append(Viewer(variable_dictionary [config.aux_vars[k]], xmin=0.0, xmax=L, datamin=config.aux_ymin[k], datamax=config.aux_ymax[k], legend='best', title=config.aux_titles[k]))
from builtins import input if __name__ == '__main__': import sys import os from fipy import SkewedGrid2D, CellVariable, Viewer, DiffusionTerm from fipy.tools import numerix valueLeft = 0. 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)
#are automatically applied to the top-right and bottom-left corners. facesTopLeft = ((mesh.facesLeft & (Y > L / 2)) | (mesh.facesTop & (X < L / 2))) facesBottomRight = ((mesh.facesRight & (Y < L / 2)) | (mesh.facesBottom & (X > L / 2))) phi.constrain(valueTopLeft, facesTopLeft) phi.constrain(valueBottomRight, facesBottomRight) #We create a viewer to see the results #.. index:: # module: fipy.viewers if __name__ == '__main__': if doBlob: try: viewer = Viewer(vars=phi, datamin=-1.5, datamax=1.) viewer.plot() raw_input("Irregular circular mesh. Press <return> to proceed..." ) # doctest: +GMSH except: print "Unable to create a viewer for an irregular mesh (try Matplotlib2DViewer or MayaviViewer)" elif doCirc: try: viewer = Viewer(vars=phi, datamin=-1, datamax=1.) viewer.plotMesh() raw_input("Irregular circular mesh. Press <return> to proceed..." ) # doctest: +GMSH except: print "Unable to create a viewer for an irregular mesh (try Matplotlib2DViewer or MayaviViewer)" else: viewer = Viewer(vars=phi, datamin=0., datamax=1.)
def runLeveler(kLeveler=0.018, bulkLevelerConcentration=0.02, cellSize=0.1e-7, rateConstant=0.00026, initialAcceleratorCoverage=0.0, levelerDiffusionCoefficient=5e-10, numberOfSteps=400, displayRate=10, displayViewers=True): kLevelerConsumption = 0.0005 aspectRatio = 1.5 faradaysConstant = 9.6485e4 gasConstant = 8.314 acceleratorDiffusionCoefficient = 4e-10 siteDensity = 6.35e-6 atomicVolume = 7.1e-6 charge = 2 metalDiffusionCoefficient = 4e-10 temperature = 298. overpotential = -0.25 bulkMetalConcentration = 250. bulkAcceleratorConcentration = 50.0e-3 initialLevelerCoverage = 0. cflNumber = 0.2 cellsBelowTrench = 10 trenchDepth = 0.4e-6 trenchSpacing = 0.6e-6 boundaryLayerDepth = 98.7e-6 i0Suppressor = 0.3 i0Accelerator = 22.5 alphaSuppressor = 0.5 alphaAccelerator = 0.4 alphaAdsorption = 0.62 m = 4 b = 2.65 A = 0.3 Ba = -40 Bb = 60 Vd = 0.098 Bd = 0.0008 etaPrime = faradaysConstant * overpotential / gasConstant / temperature mesh = TrenchMesh(cellSize=cellSize, trenchSpacing=trenchSpacing, trenchDepth=trenchDepth, boundaryLayerDepth=boundaryLayerDepth, aspectRatio=aspectRatio, angle=numerix.pi * 4. / 180.) distanceVar = GapFillDistanceVariable(name='distance variable', mesh=mesh, value=-1.) distanceVar.setValue(1., where=mesh.electrolyteMask) distanceVar.calcDistanceFunction() levelerVar = SurfactantVariable(name="leveler variable", value=initialLevelerCoverage, distanceVar=distanceVar) acceleratorVar = SurfactantVariable(name="accelerator variable", value=initialAcceleratorCoverage, distanceVar=distanceVar) bulkAcceleratorVar = CellVariable(name='bulk accelerator variable', mesh=mesh, value=bulkAcceleratorConcentration) bulkLevelerVar = CellVariable(name='bulk leveler variable', mesh=mesh, value=bulkLevelerConcentration) metalVar = CellVariable(name='metal variable', mesh=mesh, value=bulkMetalConcentration) def depositionCoeff(alpha, i0): expo = numerix.exp(-alpha * etaPrime) return 2 * i0 * (expo - expo * numerix.exp(etaPrime)) coeffSuppressor = depositionCoeff(alphaSuppressor, i0Suppressor) coeffAccelerator = depositionCoeff(alphaAccelerator, i0Accelerator) exchangeCurrentDensity = acceleratorVar.interfaceVar * ( coeffAccelerator - coeffSuppressor) + coeffSuppressor currentDensity = metalVar / bulkMetalConcentration * exchangeCurrentDensity depositionRateVariable = currentDensity * atomicVolume / charge / faradaysConstant extensionVelocityVariable = CellVariable(name='extension velocity', mesh=mesh, value=depositionRateVariable) kAccelerator = rateConstant * numerix.exp(-alphaAdsorption * etaPrime) kAcceleratorConsumption = Bd + A / (numerix.exp(Ba * (overpotential + Vd)) + numerix.exp(Bb * (overpotential + Vd))) q = m * overpotential + b levelerSurfactantEquation = AdsorbingSurfactantEquation( levelerVar, distanceVar=distanceVar, bulkVar=bulkLevelerVar, rateConstant=kLeveler, consumptionCoeff=kLevelerConsumption * depositionRateVariable) accVar1 = acceleratorVar.interfaceVar accVar2 = (accVar1 > 0) * accVar1 accConsumptionCoeff = kAcceleratorConsumption * (accVar2**(q - 1)) acceleratorSurfactantEquation = AdsorbingSurfactantEquation( acceleratorVar, distanceVar=distanceVar, bulkVar=bulkAcceleratorVar, rateConstant=kAccelerator, otherVar=levelerVar, otherBulkVar=bulkLevelerVar, otherRateConstant=kLeveler, consumptionCoeff=accConsumptionCoeff) advectionEquation = TransientTerm() + FirstOrderAdvectionTerm( extensionVelocityVariable) metalEquation = buildMetalIonDiffusionEquation( ionVar=metalVar, distanceVar=distanceVar, depositionRate=depositionRateVariable, diffusionCoeff=metalDiffusionCoefficient, metalIonMolarVolume=atomicVolume) metalVar.constrain(bulkMetalConcentration, mesh.facesTop) bulkAcceleratorEquation = buildSurfactantBulkDiffusionEquation( bulkVar=bulkAcceleratorVar, distanceVar=distanceVar, surfactantVar=acceleratorVar, otherSurfactantVar=levelerVar, diffusionCoeff=acceleratorDiffusionCoefficient, rateConstant=kAccelerator * siteDensity) bulkAcceleratorVar.constrain(bulkAcceleratorConcentration, mesh.facesTop) bulkLevelerEquation = buildSurfactantBulkDiffusionEquation( bulkVar=bulkLevelerVar, distanceVar=distanceVar, surfactantVar=levelerVar, diffusionCoeff=levelerDiffusionCoefficient, rateConstant=kLeveler * siteDensity) bulkLevelerVar.constrain(bulkLevelerConcentration, mesh.facesTop) eqnTuple = ((advectionEquation, distanceVar, (), None), (levelerSurfactantEquation, levelerVar, (), None), (acceleratorSurfactantEquation, acceleratorVar, (), None), (metalEquation, metalVar, (), None), (bulkAcceleratorEquation, bulkAcceleratorVar, (), GeneralSolver()), (bulkLevelerEquation, bulkLevelerVar, (), GeneralSolver())) narrowBandWidth = 20 * cellSize levelSetUpdateFrequency = int(0.7 * narrowBandWidth / cellSize / cflNumber / 2) totalTime = 0.0 if displayViewers: try: raise Exception from mayaviSurfactantViewer import MayaviSurfactantViewer viewers = (MayaviSurfactantViewer(distanceVar, acceleratorVar.interfaceVar, zoomFactor=1e6, datamax=0.5, datamin=0.0, smooth=1, title='accelerator coverage'), MayaviSurfactantViewer(distanceVar, levelerVar.interfaceVar, zoomFactor=1e6, datamax=0.5, datamin=0.0, smooth=1, title='leveler coverage')) except: class PlotVariable(CellVariable): def __init__(self, var=None, name=''): CellVariable.__init__(self, mesh=mesh.fineMesh, name=name) self.var = self._requires(var) def _calcValue(self): return numerix.array(self.var(self.mesh.cellCenters)) viewers = (Viewer(PlotVariable(var=acceleratorVar.interfaceVar)), Viewer(PlotVariable(var=levelerVar.interfaceVar))) for step in range(numberOfSteps): if displayViewers: if step % displayRate == 0: for viewer in viewers: viewer.plot() if step % levelSetUpdateFrequency == 0: distanceVar.calcDistanceFunction() extensionVelocityVariable.setValue(depositionRateVariable) extOnInt = numerix.where( distanceVar.globalValue > 0, numerix.where(distanceVar.globalValue < 2 * cellSize, extensionVelocityVariable.globalValue, 0), 0) dt = cflNumber * cellSize / extOnInt.max() distanceVar.extendVariable(extensionVelocityVariable) for eqn, var, BCs, solver in eqnTuple: eqn.solve(var, boundaryConditions=BCs, dt=dt, solver=solver) totalTime += dt point = ((1.25e-08, ), (3.125e-07, )) value = 2.02815779e-08 return abs(float(distanceVar(point, order=1)) - value) < cellSize / 10.0
__docformat__ = 'restructuredtext' from fipy import Grid2D, DistanceVariable, Viewer from fipy.tools import numerix, serialComm dx = 1. dy = 1. nx = 5 ny = 5 Lx = nx * dx Ly = ny * dy mesh = Grid2D(dx=dx, dy=dy, nx=nx, ny=ny, communicator=serialComm) var = DistanceVariable(name='level set variable', mesh=mesh, value=-1., hasOld=1) x, y = mesh.cellCenters var.setValue(1, where=((x < dx) | (x > (Lx - dx)) | (y < dy) | (y > (Ly - dy)))) if __name__ == '__main__': var.calcDistanceFunction(order=1) viewer = Viewer(vars=var, datamin=-5., datamax=5.) viewer.plot() input('finished')
# analytical_solution_transient = 0.5 + x - 100*t analytical_solution_steady = 1.0 - x # analytical_transient = CellVariable(mesh=mesh, name="Full Analytical Solution", value = analytical_solution_transient, hasOld=1) analytical_steady = CellVariable(mesh=mesh, name="Steady State Solution", value = analytical_solution_steady) # Set up the time stepping # First we got to initialise the viewer: if __name__ == "__main__": viewer = Viewer(vars=(c, analytical_steady, analytical_solution_transient), datamin=0., datamax=1., legend="upper right") viewer.axes.set_ylabel("Concentration") viewer.axes.set_xlabel("Distance") while t < run_time: t.value = t.value + dt timestep += 1 eq.solve(var=c, dt=dt) if (timestep % time_stride ==0): print ("Beep") if __name__ == '__main__': viewer.plot() if __name__ == '__main__': input("Press <return> to proceed...")
""" from __future__ import unicode_literals __docformat__ = 'restructuredtext' from fipy import input from fipy import CellVariable, Grid2D, DiffusionTerm, Viewer nx = 50 ny = 50 dx = 1. valueLeft = 0. valueRight = 1. mesh = Grid2D(dx=dx, nx=nx, ny=ny) var = CellVariable(name="solution variable", mesh=mesh, value=valueLeft) var.constrain(valueLeft, mesh.facesLeft) var.constrain(valueRight, mesh.facesRight) if __name__ == '__main__': DiffusionTerm().solve(var) viewer = Viewer(vars=var, datamin=0., datamax=1.) viewer.plot() input("finished")
distanceVariable = DistanceVariable(mesh=mesh, value=1., hasOld=1) x, y = mesh.cellCenters distanceVariable.setValue(-1, 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()
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
C_ani.remove() mesh = self.phase.mesh shape = mesh.shape x, y = mesh.cellCenters z = self.phase.value x, y, z = [a.reshape(shape, order='F') for a in (x, y, z)] # self.contour = self.axes.contour(X, Y, Z, (0.5,)) viewer = DendriteViewer(phase=phase, D_temp=D_temp, title=r'%s & %s' % (phase.name, D_temp.name), datamin=-0.1, datamax=0.05) except ImportError: viewer = DendriteViewer(viewers=(Viewer( vars=phase), Viewer(vars=D_temp, datamin=-0.5, datamax=0.5))) if __name__ == "__main__": steps = 500 else: steps = 10 from builtins import range for i in range(steps): phase.updateOld() D_temp.updateOld() phase_EQ.solve(phase, dt=D_time) heatEQ.solve(D_temp, dt=D_time) if __name__ == "__main__" and (i % 10 == 0): viewer.plot()
# Coupling the equations eq = eq1 & eq2 # Setting up the solver solver = LinearLUSolver(tolerance=1e-9, iterations=50, precon="ilu") # Set up time stepping dt = 10.0 duration = 20000 time_stride = 100 timestep = 0 elapsed = 0 # Initialising the viewer if __name__ == "__main__": viewer = Viewer(vars=(a), datamin=0., datamax=1.) # start the time start = time.time() # Time stepping while elapsed < duration: elapsed += dt timestep += 1 a.updateOld() mu_AB.updateOld() res = 1e4 while res > 1e-10: res = eq.sweep(dt=dt, solver=solver) print("sweep") print(res)
q = CellVariable(mesh=m, rank=1, elementshape=(2, )) q[0, :] = numerix.exp(-50 * (x - 0.3)**2) * numerix.cos(20 * (x - 0.3)) q[0, x > 0.3] = 0. Ax = FaceVariable(mesh=m, rank=3, value=[((0, K), (1 / rho, 0))], elementshape=(1, 2, 2)) eqn = TransientTerm() + CentralDifferenceConvectionTerm(Ax) == 0 if __name__ == '__main__': from fipy import MatplotlibViewer as Viewer vi = Viewer((q[0], q[1])) vi.plot() input('press key') for step in range(500): eqn.solve(q, dt=cfl * dx) if step % 10 == 0 and __name__ == '__main__': print('step', step) vi.plot() if __name__ == '__main__': import fipy.tests.doctestPlus exec(fipy.tests.doctestPlus._getScript()) input('finished')
"onlySolutionData.phr", -1) nSpecies = phreeqc_rm_toCalculateActivityCoef.RM_GetSpeciesCount() #================================================== #lets set up the transport model C = [] for i in range(ncomps): C.append( CellVariable(name=components[i].encode(), mesh=mesh, value=c[i * nxyz:(i + 1) * nxyz])) C[i].constrain(bc_conc[i], mesh.facesLeft) C[i].faceGrad.constrain(0, mesh.facesRight) if __name__ == '__main__': viewer = Viewer(vars=(C[4]), datamin=0., datamax=1e-4) viewer.plot() #=================================================== D = 0.0 # assume there is no diffusion except numerical diffusion hahahaha u = (1.5 / 432000, ) # m/s equivalent to 1 dt/day eqX = [] for i in range(ncomps): if (i != 4): eqX.append(TransientTerm() == DiffusionTerm(coeff=D) - UpwindConvectionTerm(coeff=u)) else: # I am assuming that microbes are attached #eqX.append(TransientTerm() == DiffusionTerm(coeff=D)) eqX.append(TransientTerm() == DiffusionTerm(coeff=D) - UpwindConvectionTerm(coeff=u)) #timeStepDuration = 0.9 * dx**2 / (2 * D) # the maximum time step
'''.format(cellSize, l1, l2, math.tan(beta) * (l2 - l1), l3, math.tan(alpha) * l3) mesh = Gmsh3D(geometryTemplate) # Enthaelt die Temperatur phi = CellVariable(name="Temperature", mesh=mesh, value=T0) # boundry conditions ---------------------------------------------------------- phi.constrain(Ti, where=mesh.physicalFaces["inner"]) phi.constrain(Te, where=mesh.physicalFaces["outer"]) # calculation ----------------------------------------------------------------- viewer = Viewer(vars=phi, datamin=200., datamax=Te * 1.01) print "Calculation started" started = time.clock() # Loest die Stationaere Waermegleichung DiffusionTerm(coeff=D).solve(var=phi) print "Calculation finished, took {} seconds".format(time.clock() - started) viewer.plot() raw_input("Press enter to close ...")
P2Eq = TransientTerm() - DiffusionTerm( params['diffusionCoeff']) - P2scCoeff + ImplicitSourceTerm(P2spCoeff) KCscCoeff = params['alphaKstar'] * params['lambdaK'] * ( KMVar / (1 + PN / params['kappaK'])).cellVolumeAverage KCspCoeff = params['lambdaKstar'] / (params['kappaKstar'] + KCVar) KCEq = TransientTerm() - KCscCoeff + ImplicitSourceTerm(KCspCoeff) eqs = ((KMVar, KMEq), (TMVar, TMEq), (TCVar, TCEq), (P3Var, P3Eq), (P2Var, P2Eq), (KCVar, KCEq)) if __name__ == '__main__': PNView = PN / PN.cellVolumeAverage PNView.setName('PN') PNViewer = Viewer(PNView, datamax=2., datamin=0., title='') 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.)
Jn.value = -mu_n * Nion * potential.arithmeticFaceValue.divergence + Dn * Pion.arithmeticFaceValue.divergence Pion.equation = TransientTerm( coeff=1, var=Pion) == -k_rec * Pion * Nion + (Jp.arithmeticFaceValue).divergence Nion.equation = TransientTerm( coeff=1, var=Nion) == -k_rec * Pion * Nion - (Jn.arithmeticFaceValue).divergence potential.equation = DiffusionTerm(coeff=epsilon, var=potential) == Pion - Nion Pion.constrain(0., where=mesh.facesLeft) Pion.constrain(0., where=mesh.facesRight) Nion.constrain(0., where=mesh.facesLeft) Nion.constrain(0., where=mesh.facesRight) potential.constrain(0., where=mesh.facesLeft) potential.constrain(0., where=mesh.facesRight) eq = Pion.equation & Nion.equation & potential.equation steps = 253 dt = 6 if __name__ == "__main__": viewer = Viewer(vars=(Nion, ), datamin=-1e15, datamax=1e15) for steps in range(steps): eq.solve(dt=dt) if __name__ == '__main__': viewer.plot() plt.pause(1)
initialSurfactantValue = 1. surfactantVariable = SurfactantVariable( 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.)
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')
from fipy import Grid2D, DistanceVariable, Viewer from fipy.tools import numerix dx = 0.5 dy = 2. nx = 5 ny = 5 Lx = nx * dx Ly = ny * dy mesh = Grid2D(dx = dx, dy = dy, nx = nx, ny = ny) var = DistanceVariable( name = 'level set variable', mesh = mesh, value = -1., hasOld = 1 ) x, y = mesh.cellCenters var.setValue(1, where=((Lx / 3. < x) & (x < 2. * Lx / 3.)) & ((Ly / 3. < y) & (y < 2. * Ly / 3))) if __name__ == '__main__': var.calcDistanceFunction(order=1) viewer = Viewer(vars=var, maxval=-5., minval=5.) viewer.plot() input('finished')
startingArray = numerix.zeros(nx, 'd') 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]
def runSimpleTrenchSystem(faradaysConstant=9.6e4, gasConstant=8.314, transferCoefficient=0.5, rateConstant0=1.76, rateConstant3=-245e-6, catalystDiffusion=1e-9, siteDensity=9.8e-6, molarVolume=7.1e-6, charge=2, metalDiffusion=5.6e-10, temperature=298., overpotential=-0.3, metalConcentration=250., catalystConcentration=5e-3, catalystCoverage=0., currentDensity0=0.26, currentDensity1=45., cellSize=0.1e-7, trenchDepth=0.5e-6, aspectRatio=2., trenchSpacing=0.6e-6, boundaryLayerDepth=0.3e-6, numberOfSteps=5, displayViewers=True): cflNumber = 0.2 numberOfCellsInNarrowBand = 10 cellsBelowTrench = 10 yCells = cellsBelowTrench \ + int((trenchDepth + boundaryLayerDepth) / cellSize) xCells = int(trenchSpacing / 2 / cellSize) from fipy.tools import serialComm mesh = Grid2D(dx=cellSize, dy=cellSize, nx=xCells, ny=yCells, communicator=serialComm) narrowBandWidth = numberOfCellsInNarrowBand * cellSize distanceVar = DistanceVariable(name='distance variable', mesh=mesh, value=-1., hasOld=1) bottomHeight = cellsBelowTrench * cellSize trenchHeight = bottomHeight + trenchDepth trenchWidth = trenchDepth / aspectRatio sideWidth = (trenchSpacing - trenchWidth) / 2 x, y = mesh.cellCenters distanceVar.setValue(1., where=(y > trenchHeight) | ((y > bottomHeight) & (x < xCells * cellSize - sideWidth))) distanceVar.calcDistanceFunction(order=2) catalystVar = SurfactantVariable(name="catalyst variable", value=catalystCoverage, distanceVar=distanceVar) bulkCatalystVar = CellVariable(name='bulk catalyst variable', mesh=mesh, value=catalystConcentration) metalVar = CellVariable(name='metal variable', mesh=mesh, value=metalConcentration) expoConstant = -transferCoefficient * faradaysConstant \ / (gasConstant * temperature) tmp = currentDensity1 * catalystVar.interfaceVar exchangeCurrentDensity = currentDensity0 + tmp expo = numerix.exp(expoConstant * overpotential) currentDensity = expo * exchangeCurrentDensity * metalVar \ / metalConcentration depositionRateVariable = currentDensity * molarVolume \ / (charge * faradaysConstant) extensionVelocityVariable = CellVariable(name='extension velocity', mesh=mesh, value=depositionRateVariable) surfactantEquation = AdsorbingSurfactantEquation( surfactantVar=catalystVar, distanceVar=distanceVar, bulkVar=bulkCatalystVar, rateConstant=rateConstant0 + rateConstant3 * overpotential**3) advectionEquation = TransientTerm() + AdvectionTerm( extensionVelocityVariable) metalEquation = buildMetalIonDiffusionEquation( ionVar=metalVar, distanceVar=distanceVar, depositionRate=depositionRateVariable, diffusionCoeff=metalDiffusion, metalIonMolarVolume=molarVolume, ) metalVar.constrain(metalConcentration, mesh.facesTop) from surfactantBulkDiffusionEquation import buildSurfactantBulkDiffusionEquation bulkCatalystEquation = buildSurfactantBulkDiffusionEquation( bulkVar=bulkCatalystVar, distanceVar=distanceVar, surfactantVar=catalystVar, diffusionCoeff=catalystDiffusion, rateConstant=rateConstant0 * siteDensity) bulkCatalystVar.constrain(catalystConcentration, mesh.facesTop) if displayViewers: try: from mayaviSurfactantViewer import MayaviSurfactantViewer viewer = MayaviSurfactantViewer(distanceVar, catalystVar.interfaceVar, zoomFactor=1e6, datamax=0.5, datamin=0.0, smooth=1, title='catalyst coverage') except: viewer = MultiViewer( viewers=(Viewer(distanceVar, datamin=-1e-9, datamax=1e-9), Viewer(catalystVar.interfaceVar))) else: viewer = None levelSetUpdateFrequency = int(0.8 * narrowBandWidth \ / (cellSize * cflNumber * 2)) for step in range(numberOfSteps): if step > 5 and step % 5 == 0 and viewer is not None: viewer.plot() if step % levelSetUpdateFrequency == 0: distanceVar.calcDistanceFunction(order=2) extensionVelocityVariable.setValue(depositionRateVariable()) distanceVar.updateOld() distanceVar.extendVariable(extensionVelocityVariable, order=2) dt = cflNumber * cellSize / extensionVelocityVariable.max() advectionEquation.solve(distanceVar, dt=dt) surfactantEquation.solve(catalystVar, dt=dt) metalEquation.solve(metalVar, dt=dt) bulkCatalystEquation.solve(bulkCatalystVar, dt=dt, solver=GeneralSolver(tolerance=1e-15, iterations=2000)) try: import os filepath = os.path.splitext(__file__)[0] + '.gz' print catalystVar.allclose(numerix.loadtxt(filepath), rtol=1e-4) except: return 0