def GetAz(Bx, By, Jz, Nc, dl): mesh = Grid2D(dx=dl[0], dy=dl[1], nx=Nc[0], ny=Nc[1]) _Az = CellVariable(mesh=mesh, value=0.0) _Bx = CellVariable(mesh=mesh) _Bx.value = np.reshape(Bx, Nc[0] * Nc[1], order='F') _By = CellVariable(mesh=mesh) _By.value = np.reshape(By, Nc[0] * Nc[1], order='F') _Jz = CellVariable(mesh=mesh) _Jz.value = np.reshape(Jz, Nc[0] * Nc[1], order='F') _Az.equation = (DiffusionTerm(coeff=1.0) + _Jz == 0) # beware of the sign of the flux : always consider outward direction BCs = [ FixedFlux(value=_By.getFaceValue(), faces=mesh.getFacesLeft()), FixedFlux(value=-_By.getFaceValue(), faces=mesh.getFacesRight()), FixedFlux(value=-_Bx.getFaceValue(), faces=mesh.getFacesBottom()), FixedFlux(value=_Bx.getFaceValue(), faces=mesh.getFacesTop()) ] _Az.equation.solve(var=_Az, boundaryConditions=BCs) Az = np.reshape(_Az.value, Nc, order='F') return Az
def icir_rect(self): # step 1: Mesh mesh = Grid2D(dx=self.gsize, dy=self.gsize, nx=self.xy_n[0], ny=self.xy_n[1]) # step 2: Equation phi = CellVariable(mesh=mesh, name='potential phi', value=0.) eqn = (DiffusionTerm(coeff = 1.) == 0.) # step 3: Boundary conditions # compute flow of 4 vertexes # one vertex has 2 components of wind vector, (x, y) vertexWindVec = np.array([ [0.0 for i in range(2)] for i in range(4)]) for i in range(4): # 4 vertexes for j in range(2): # 2 components vertexWindVec[i, j] = self.mean_flow[j] \ + self.colored_noise(self.vertexWindVecRanInc[i][j]) # interpolate flow vector on sim area edges, and set neumann boundary # conditions, because /grad /phi = V(x,y) # get all points which lie on the center of edges of cells X, Y = mesh.faceCenters # /grad /phi array, of points of mesh face centers # grad_phi_bc[0, :] /grad/phi_x # grad_phi_bc[1, :] /grad/phi_y grad_phi_bc = np.zeros_like(mesh.faceCenters()) # p: points on one edge to interpolate, 1 dimension # vx, vy: x&y components of interpolated wind vectors of points list p # vertex index, for interpolate bc on 4 edges # vertexIndex[0] = [1,2], down boundary, 0<x<nx*dx, y=0 # vertexIndex[1] = [1,0], left boundary, x=0, 0<y<ny*dy # vertexIndex[2] = [0,3], up boundary, 0<x<nx*dx, y=ny*dy # vertexIndex[3] = [2,3], right boundary, x=nx*dx, 0<y<ny*dy vertexIndex = np.array([ [1,2], [1,0], [0,3], [2,3] ]) for i in range(4): # 4 edges for 2D rect area p = np.arange(self.gsize/2, self.gsize*self.xy_n[i%2], self.gsize) vx = np.interp(p, [0.0, self.gsize*self.xy_n[i%2]], \ [vertexWindVec[vertexIndex[0,0], 0], \ vertexWindVec[vertexIndex[0,1], 0]]).T.reshape(1,-1)[0] vy = np.interp(p, [0.0, self.gsize*self.xy_n[i%2]], \ [vertexWindVec[vertexIndex[0,0], 1], \ vertexWindVec[vertexIndex[0,1], 1]]).T.reshape(1,-1)[0] print 'vx = ' + str(vx) if i == 0: # down boundary grad_phi_bc[:, mesh.facesDown()] = np.array([vx, vy]) elif i == 1: # left boundary grad_phi_bc[:, mesh.facesLeft()] = np.array([vx, vy]) elif i == 2: # up boundary grad_phi_bc[:, mesh.facesUp()] = np.array([vx, vy]) elif i == 3: # right boundary grad_phi_bc[:, mesh.facesRight()] = np.array([vx, vy]) # set neumann boundary condition phi.faceGrad.constrain(((grad_phi_bc[0]),(grad_phi_bc[1])), where=mesh.exteriorFaces) # step 4: Solve eqn.solve(var=phi) #print str(phi) #print str(type(np.array(phi))) self.wind_phi_field = np.array(phi) self.wind_mesh_centers = mesh.cellCenters()
def define_uniform_comp_domain_rad( self, shells_per_particle, normalised_particle_radius ): # Uniform radial domain, electrode particles self.nr = int(shells_per_particle) self.Rs_normalised = normalised_particle_radius self.dr = self.Rs_normalised / self.nr self.p2d_mesh = Grid2D(nx=self.nx, ny=self.nr, Lx=self.L_normalised, Ly=self.Rs_normalised) self.dummy, self.radial_faces = self.p2d_mesh.faceCenters # Create a shorthand name for accessing y-axis faces in the particle mesh
def __init__(self, X=None, T=None, time_steps=5, max_time=0.4, num_cells=25, L=1.): """Initialize the objet. Keyword Arguments: X --- The sensor locations. T --- The sensor measurment times. time_steps --- How many timesteps do you want to measure. max_time --- The maximum solution time. num_cells --- The number of cells per dimension. L --- The size of the computational domain. """ assert isinstance(num_cells, int) self._num_cells = num_cells assert isinstance(L, float) and L > 0. self._dx = L / self.num_cells self._mesh = Grid2D(dx=self.dx, dy=self.dx, nx=self.num_cells, ny=self.num_cells) self._phi = CellVariable(name='solution variable', mesh=self.mesh) self._source = CellVariable(name='source term', mesh=self.mesh, hasOld=True) self._eqX = TransientTerm() == ExplicitDiffusionTerm( coeff=1.) + self.source self._eqI = TransientTerm() == DiffusionTerm(coeff=1.) + self.source self._eq = self._eqX + self._eqI assert isinstance(max_time, float) and max_time > 0. self._max_time = max_time #self.max_time / time_steps #. if X is None: idx = range(self.num_cells**2) else: idx = [] x1, x2 = self.mesh.cellCenters for x in X: dist = (x1 - x[0])**2 + (x2 - x[1])**2 idx.append(np.argmin(dist)) self._idx = idx if T is None: T = np.linspace(0, self.max_time, time_steps)[1:] self._max_time = T[-1] self._T = T self._dt = self.T[0] / time_steps super(Diffusion, self).__init__(5, len(self.T) * len(self.idx), name='Diffusion Solver')
def define_non_uniform_comp_domain_rad( self, shells_per_particle, normalised_particle_radius ): # Non-uniform radial domain, electrode particles self.nr = int(shells_per_particle) self.Rs_normalised = normalised_particle_radius self.dr = numerix.diff( numerix.log(1 - numerix.linspace( 0, 1.0 - numerix.exp(self.Rs_normalised), self.nr + 1))) self.p2d_mesh = Grid2D(dx=self.dx, dy=self.dr, Lx=self.L_normalised, Ly=self.Rs_normalised) self.dummy, self.radial_faces = self.p2d_mesh.faceCenters # Create a shorthand name for accessing y-axis faces in the particle mesh
def GetAz(Bx, By, Jz, Nc, dl): mesh = Grid2D(dx=dl[0], dy=dl[1], nx=Nc[0], ny=Nc[1]) _Az = CellVariable(mesh=mesh, value=0.0) _Bx = CellVariable(mesh=mesh) _Bx.value = np.reshape(Bx, Nc[0] * Nc[1], order='F') _By = CellVariable(mesh=mesh) _By.value = np.reshape(By, Nc[0] * Nc[1], order='F') _Jz = CellVariable(mesh=mesh) _Jz.value = np.reshape(Jz, Nc[0] * Nc[1], order='F') _Az.equation = (DiffusionTerm(coeff=1.0) + _Jz == 0) #diffcoeff = CellVariable(mesh=mesh, value = 1.0) #diffTerm = DiffusionTerm(coeff = diffcoeff) #diffTerm = DiffusionTerm(coeff = 1.0) #diffcoeff.constrain(0., mesh.exteriorFaces) # beware of the sign of the flux : always consider outward direction _Az.faceGrad.constrain(_By.arithmeticFaceValue, where=mesh.facesLeft) _Az.faceGrad.constrain(-_By.arithmeticFaceValue, where=mesh.facesRight) _Az.faceGrad.constrain(-_Bx.arithmeticFaceValue, where=mesh.facesBottom) _Az.faceGrad.constrain(_Bx.arithmeticFaceValue, where=mesh.facesTop) #_Az.faceGrad.constrain( _By.arithmeticFaceValue[mesh.facesLeft] , where=mesh.facesLeft) #_Az.faceGrad.constrain(-_By.arithmeticFaceValue[mesh.facesRight] , where=mesh.facesRight) #_Az.faceGrad.constrain(-_Bx.arithmeticFaceValue[mesh.facesBottom] , where=mesh.facesBottom) #_Az.faceGrad.constrain( _Bx.arithmeticFaceValue[mesh.facesTop] , where=mesh.facesTop) #_Az.equation = (diffTerm+_Jz == 0) #_Az.equation = (DiffusionTerm(diffcoeff)+ (mesh.exteriorFaces*exteriorFlux).divergence + _Jz== 0) #_Az.equation = (diffTerm + _Jz == 0) #BCs = [FixedFlux(value= _By.getFaceValue(), faces=mesh.getFacesLeft()), # FixedFlux(value=-_By.getFaceValue(), faces=mesh.getFacesRight()), # FixedFlux(value=-_Bx.getFaceValue(), faces=mesh.getFacesBottom()), # FixedFlux(value= _Bx.getFaceValue(), faces=mesh.getFacesTop())] #_Az.equation.solve(var=_Az, boundaryConditions=BCs) _Az.equation.solve(var=_Az) Az = np.reshape(_Az.value, Nc, order='F') return Az
steps = 10 timeStepDuration = 0.02 L = 1.5 nx = 100 ny = 100 temperature = 1. phaseTransientCoeff = 0.1 epsilon = 0.008 s = 0.01 alpha = 0.015 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) \
import numpy as np import matplotlib.pyplot as plt import pandas as pd from fipy import Variable, CellVariable, Grid2D, TransientTerm, DiffusionTerm from fipy import ImplicitSourceTerm, Viewer, Matplotlib2DGridViewer from fipy import MultiViewer, MatplotlibViewer from fipy.tools import numerix #%% Initial grid set up if __name__ == '__main__': NX = NY = 300 else: NX = NY = 30 X_SIZE = Y_SIZE = 9 DX = X_SIZE / NX DY = Y_SIZE / NY mesh = Grid2D(dx=DX, dy=DY, nx=NX, ny=NY) D_time = 0.0005 #%% Constants and Other Parameters TAU = 0.0003 # Tau CONSTANT ALPHA = 0.9 # Constant GAMMA = 10.0 # Nondimensionalized A_noise = 0.01 # Amplitude of the Noise EPSILON_BAR = 0.01 # Compute Param, Thickness of layer at interface #%% Anisotropy Functions def m_temp(alpha, gamma, temp_eq, temp): """ Parameters
L = 1. dx = 0.1 velocity = 1. cfl = 0.1 distanceToTravel = L / 5. boxSize = .2 nx = int(L / dx) ny = int(L / dx) steps = int(distanceToTravel / dx / cfl) timeStepDuration = cfl * dx / velocity mesh = Grid2D(dx=dx, dy=dx, nx=nx, ny=ny) x0 = (L - boxSize) / 2 x1 = (L + boxSize) / 2 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))
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
from __future__ import division from __future__ import unicode_literals from builtins import range from examples.chemotaxis.parameters import parameters from fipy import input from fipy import CellVariable, Grid2D, TransientTerm, DiffusionTerm, ImplicitSourceTerm, Viewer params = parameters['case 2'] nx = 50 ny = 50 dx = 1. L = nx * dx mesh = Grid2D(nx=nx, ny=ny, dx=dx, dy=1.) shift = 1. KMVar = CellVariable(mesh=mesh, value=params['KM'] * shift, hasOld=1) KCVar = CellVariable(mesh=mesh, value=params['KC'] * shift, hasOld=1) TMVar = CellVariable(mesh=mesh, value=params['TM'] * shift, hasOld=1) TCVar = CellVariable(mesh=mesh, value=params['TC'] * shift, hasOld=1) P3Var = CellVariable(mesh=mesh, value=params['P3'] * shift, hasOld=1) P2Var = CellVariable(mesh=mesh, value=params['P2'] * shift, hasOld=1) RVar = CellVariable(mesh=mesh, value=params['R'], hasOld=1) PN = P3Var + P2Var KMscCoeff = params['chiK'] * (RVar + 1) * (1 - KCVar - KMVar.cellVolumeAverage) KMspCoeff = params['lambdaK'] / (1 + PN / params['kappaK'])
from fipy import CellVariable, Grid2D, GaussianNoiseVariable, DiffusionTerm, TransientTerm, ImplicitSourceTerm, VTKCellViewer, LinearLUSolver, parallelComm from fipy.tools import numerix import time from params_fipy import (A_RAW, NOISE_MAGNITUDE, TIME_MAX, DT, N_CELLS, DOMAIN_LENGTH, TIME_STRIDE, chi_AB, N_A, N_B, GIBBS, DESIRED_RESIDUAL) print("Yay") # # Define mesh # mesh = Grid2D(dx=dx, dy=dx, nx=N_CELLS, ny=N_CELLS) mesh = Grid2D(nx=10.0, ny=10.0, dx=1.0, dy=1.0) print("mesh loaded") # We need to define the relevant variables: a = CellVariable(name=r"a", mesh=mesh, hasOld=1) exp_a = CellVariable(name=r"exp_a", mesh=mesh, hasOld=1) mu_AB = CellVariable(name=r"mu_AB", mesh=mesh, hasOld=1) # We need to introduce the noise noise = GaussianNoiseVariable(mesh=mesh, mean=numerix.log(A_RAW), variance=abs(numerix.log(NOISE_MAGNITUDE))).value a[:] = noise if GIBBS == "FH": dgda = (1 + a) * (numerix.exp(a) / N_A) - (numerix.exp(a) / N_B) * ( 1 + numerix.log(1.0 - numerix.exp(a)) ) + chi_AB * numerix.exp(a) - 2.0 * chi_AB * numerix.exp(2.0 * a)
from __future__ import unicode_literals from builtins import input __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()
value = valueBottomTop) var.constrain(valueLeftRight, mesh.facesLeft) var.constrain(valueLeftRight, mesh.facesRight) 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)
##### The first type of functions###### # y01 = np.zeros(nx) # y01[0:500] = 0.5e21 # # y02 = np.zeros(nx) # y02[0:500] = 0.5e21 # # y03 = np.zeros(nx) s=(nx, ny) B01=np.full(s, 0.5e21) B02=np.full(s, 0.5e21) B03=np.full(s, 0) # print(np.shape(B01)) mesh = Grid2D(dx=dx,dy=dy,nx=nx,ny=ny) # Establish mesh in how many dimensions necessary mesh_2D = Grid2D(dx=dx,dy=dy,nx=nx,ny=ny) Pion = CellVariable(mesh=mesh_2D, name='Positive ion Charge Density', value= B01) Nion = CellVariable(mesh=mesh_2D, name='Negative ion Charge Density', value= B02) potential = CellVariable(mesh=mesh_2D, name='Potential', value=0.) # # print(Pion.value.shape) # print(Nion.value.shape) # print(potential.value.shape) # plt.imshow(Pion.value, vmin=0, vmax = 1e22) # plt.colorbar() # plt.show()