Exemplo n.º 1
0
    def _calcValue(self):
        """

        Test case added because `and` was being used instead of bitwise `&`.

            >>> from fipy.meshes import Grid1D
            >>> mesh = Grid1D(nx = 3)
            >>> from fipy.variables.faceVariable import FaceVariable
            >>> P = FaceVariable(mesh = mesh, value = (1e-3, 1e+71, 1e-3, 1e-3))
            >>> alpha = ExponentialConvectionTerm([1])._alpha(P)
            >>> print alpha
            [ 0.5  1.   0.5  0.5]

        """
        eps = 1e-3
        largeValue = 101.0
        P = self.P.numericValue

        P = numerix.where(abs(P) < eps, eps, P)
        alpha = numerix.where(P > largeValue, (P - 1) / P, 0.5)
        Pmin = numerix.where(P > largeValue + 1, largeValue + 1, P)
        alpha = numerix.where((abs(Pmin) > eps) & (Pmin <= largeValue),
                              ((Pmin - 1) * numerix.exp(Pmin) + 1) /
                              (Pmin * (numerix.exp(Pmin) - 1)), alpha)

        return alpha
Exemplo n.º 2
0
    def dif_fp(u):
        b = -4.
        D = (numerix.exp(t1) / t2 *
             (numerix.power(s2 * numerix.exp(-s1) * u + numerix.exp(s2 * b),
                            t2 / s2) - numerix.exp(t2 * b))) / (
                                s2 * u + numerix.exp(s1 + s2 * b))

        return D
Exemplo n.º 3
0
    def _calcValue_(self, alpha, id1, id2):
        cell1 = take(self.var, id1)
        cell2 = take(self.var, id2)
        delta = cell1 - cell2

        eps = 1e-14
        value = where(abs(delta) < eps, 1.0 / exp(delta), 0.0)
        delta = where(abs(delta) < eps, eps, delta)
        value = where((abs(delta) > eps) & (delta < 100), delta / (exp(delta) - 1), value)

        value *= exp(cell1)

        for bc in self.bcs:
            if isinstance(bc, FixedValue):
                value[bc.faces.value] = bc._value

        return value
Exemplo n.º 4
0
    def _calcValue_(self, alpha, id1, id2):
        cell1 = take(self.var,id1)
        cell2 = take(self.var,id2)
        delta = cell1 - cell2

        eps = 1e-14
        value = where(abs(delta) < eps, 1. / exp(delta), 0.)
        delta = where(abs(delta) < eps, eps, delta)
        value = where((abs(delta) > eps) & (delta < 100),
                      delta / (exp(delta) - 1), value)

        value *= exp(cell1)

        for bc in self.bcs:
            if isinstance(bc, FixedValue):
                value[bc.faces.value] = bc._value

        return value
Exemplo n.º 5
0
    def attenuation_profile(self):
        """
        Calculates the attenuation profile for this channel

        This returns the cumulative product of attenuation factors in each cell of the domain,
        allowing this to be multiplied by a surface value to get the irradiance intensity profile.
        """
        if not self.is_setup:
            self.logger.warning('Attenuation definition may be incomplete!')
        return numerix.cumprod(
            numerix.exp(-1 * self.k_var * self.domain.distances))
Exemplo n.º 6
0
    def buildThetaEquation(phase, theta):

        phaseMod = phase + ( phase < thetaSmallValue ) * thetaSmallValue
        phaseModSq = phaseMod * phaseMod
        expo = epsilon * beta * theta.getGrad().getMag()
        expo = (expo < 100.) * (expo - 100.) + 100.
        pFunc = 1. + numerix.exp(-expo) * (mu / epsilon - 1.)

        phaseFace = phase.getArithmeticFaceValue()
        phaseSq = phaseFace * phaseFace
        gradMag = theta.getFaceGrad().getMag()
        eps = 1. / gamma / 10.
        gradMag += (gradMag < eps) * eps
        IGamma = (gradMag > 1. / gamma) * (1 / gradMag - gamma) + gamma
        diffusionCoeff = phaseSq * (s * IGamma + epsilon**2)

        thetaGradDiff = theta.getFaceGrad() - theta.getFaceGradNoMod()
        sourceCoeff = (diffusionCoeff * thetaGradDiff).getDivergence()

        from fipy.terms.implicitDiffusionTerm import ImplicitDiffusionTerm
        return TransientTerm(thetaTransientCoeff * phaseModSq * pFunc) == \
                   ImplicitDiffusionTerm(diffusionCoeff) \
                   + sourceCoeff
Exemplo n.º 7
0
    def buildThetaEquation(phase, theta):

        phaseMod = phase + (phase < thetaSmallValue) * thetaSmallValue
        phaseModSq = phaseMod * phaseMod
        expo = epsilon * beta * theta.getGrad().getMag()
        expo = (expo < 100.) * (expo - 100.) + 100.
        pFunc = 1. + numerix.exp(-expo) * (mu / epsilon - 1.)

        phaseFace = phase.getArithmeticFaceValue()
        phaseSq = phaseFace * phaseFace
        gradMag = theta.getFaceGrad().getMag()
        eps = 1. / gamma / 10.
        gradMag += (gradMag < eps) * eps
        IGamma = (gradMag > 1. / gamma) * (1 / gradMag - gamma) + gamma
        diffusionCoeff = phaseSq * (s * IGamma + epsilon**2)

        thetaGradDiff = theta.getFaceGrad() - theta.getFaceGradNoMod()
        sourceCoeff = (diffusionCoeff * thetaGradDiff).getDivergence()

        from fipy.terms.implicitDiffusionTerm import ImplicitDiffusionTerm
        return TransientTerm(thetaTransientCoeff * phaseModSq * pFunc) == \
                   ImplicitDiffusionTerm(diffusionCoeff) \
                   + sourceCoeff
Exemplo n.º 8
0
from fipy.tools import numerix

L = 2.
X0 = -1.
nx = 800
cfl = 0.1
K = 4.
rho = 1.

dx = L / nx
m = Grid1D(nx=nx, dx=dx) + X0
x, = m.cellCenters

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()

for step in range(500):
    eqn.solve(q, dt=cfl * dx)
    if step % 10 ==  0 and  __name__ == '__main__':
        vi.plot()
Exemplo n.º 9
0
def one_fourier (n):
    mode = (-2.0/(n*pi))*numerix.sin(n*pi*x)*numerix.exp(-t*(pi**2)*(n**2))
    return mode
Exemplo n.º 10
0
def hydro_1d_fipy(theta_ini, nx, dx, dt, params, ndays, sensor_loc,
                  boundary_values_left, boundary_values_right, precip,
                  evapotra, ele_interp, peat_depth):
    def zeta_from_theta(x, b):
        return np.log(np.exp(s2 * b) + s2 * np.exp(-s1) * x) / s2

    mesh = fp.Grid1D(nx=nx, dx=dx)

    ele = ele_interp(mesh.cellCenters.value[0])
    b = peat_depth + ele.min() - ele

    s1 = params[0]
    s2 = params[1]
    t1 = params[2]
    t2 = params[3]

    source = precip[0] - evapotra[0]

    theta = fp.CellVariable(name="theta",
                            mesh=mesh,
                            value=theta_ini,
                            hasOld=True)

    # Choice of parameterization
    # This is the underlying conductivity: K = exp(t1 + t2*zeta). The
    # transmissivity is derived from this and written in terms of theta
    # This is the underlying storage coeff: S = exp(s1 + s2*zeta)
    # S is hidden in change from theta to h
    # D = (numerix.exp(t1)/t2 * (numerix.power(s2 * numerix.exp(-s1) * theta + numerix.exp(s2*b), t2/s2) - numerix.exp(t2*b))) * np.power(s2 * (theta + numerix.exp(s1 + s2*b)/s2), -1)

    # Boussinesq eq. for theta
    eq = fp.TransientTerm() == fp.DiffusionTerm(coeff=(
        numerix.exp(t1) / t2 *
        (numerix.power(s2 * numerix.exp(-s1) * theta +
                       numerix.exp(s2 * b), t2 / s2) - numerix.exp(t2 * b))
    ) * np.power(s2 * (theta + numerix.exp(s1 + s2 * b) / s2), -1)) + source

    theta_sol_list = []  # returned quantity

    MAX_SWEEPS = 10000

    for day in range(ndays):

        theta.updateOld()

        # BC and Source/sink update
        theta_left = boundary_values_left[day]  # left BC is always Dirichlet
        theta.constrain(theta_left, where=mesh.facesLeft)
        if boundary_values_right == None:  # Pxx sensors. Neuman BC on the right
            theta.faceGrad.constrain(0. * mesh.faceNormals,
                                     where=mesh.facesRight)
        else:
            theta_right = boundary_values_right[day]
            theta.constrain(theta_right, where=mesh.facesRight)

        source = precip[day] - evapotra[day]

        res = 0.0
        for r in range(MAX_SWEEPS):
            resOld = res
            res = eq.sweep(var=theta, dt=dt)
            if abs(res - resOld) < 1e-7:
                break  # it has reached the solution of the linear system

        if r == MAX_SWEEPS:
            raise ValueError(
                'Solution not converging after maximum number of sweeps')

        # Append to list
        theta_sol = theta.value
        theta_sol_sensors = np.array(
            [theta_sol[sl] for sl in sensor_loc[1:]]
        )  # canal sensor is part of the model; cannot be part of the fitness estimation

        theta_sol_list.append(theta_sol_sensors[0])

    b_sensors = np.array([b[sl] for sl in sensor_loc[1:]])
    zeta_from_theta_sol_sensors = zeta_from_theta(np.array(theta_sol_list),
                                                  b_sensors)
    # print(zeta_from_theta_sol_sensors)

    return zeta_from_theta_sol_sensors
Exemplo n.º 11
0
U = 100.0
peclet = (U * L / D)
# This is the syntax needed to specify U
convCoeff = (1.0, )

# intial condition width (standard deviation)
sigma = 0.05 * L

#Defining the variable
c = CellVariable(mesh=mesh, name=r"$c$")

# Setting initial conditions
x = mesh.cellCenters[0]
c.value = 0.0
c.setValue(0.05 * (1.0 / (sigma * numerix.sqrt(2 * numerix.pi))) *
           numerix.exp(-0.5 * ((x - 1.0) / (sigma))**2.0))

# defining the equation
# We write three equations: pure convection, pure diffusion and convection-diffusion
# eq = TransientTerm() + VanLeerConvectionTerm(coeff=convCoeff) == 0
# eq = TransientTerm() - DiffusionTerm(coeff=(1/peclet)) == 0
eq = TransientTerm() + VanLeerConvectionTerm(coeff=convCoeff) - DiffusionTerm(
    coeff=(1.0 / peclet)) == 0

# The choice of dt and dx in a convection problem is a bit more complicated
dt = 0.001

# We might not want to see the output from every single timestep, so we define a stride parameter
time_stride = 10
timestep = 0
run_time = 2.0
Exemplo n.º 12
0
 def depositionCoeff(alpha, i0):
     expo = numerix.exp(-alpha * etaPrime)
     return 2 * i0 * (expo - expo * numerix.exp(etaPrime))
Exemplo n.º 13
0
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
Exemplo n.º 14
0
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
Exemplo n.º 15
0
    def _calcValue(self):
        """

        Test case added because `and` was being used instead of bitwise `&`.

            >>> from fipy.meshes import Grid1D
            >>> mesh = Grid1D(nx = 3)
            >>> from fipy.variables.faceVariable import FaceVariable
            >>> P = FaceVariable(mesh = mesh, value = (1e-3, 1e+71, 1e-3, 1e-3))
            >>> alpha = ExponentialConvectionTerm([1])._alpha(P)
            >>> print(alpha)
            [ 0.5  1.   0.5  0.5]

        """
        eps = 1e-3
        largeValue = 101.0
        P  = self.P.numericValue

        P = numerix.where(abs(P) < eps, eps, P)
        alpha = numerix.where(P > largeValue, (P - 1) / P, 0.5)
        Pmin = numerix.where(P > largeValue + 1, largeValue + 1, P)
        alpha = numerix.where((abs(Pmin) > eps) & (Pmin <= largeValue), ((Pmin - 1) * numerix.exp(Pmin) + 1) / (Pmin * (numerix.exp(Pmin) - 1)), alpha)

        return alpha
Exemplo n.º 16
0
from fipy import Grid1D, CellVariable, Viewer
from fipy.tools import numerix, dump

import numpy
from scipy.special import wofz


# ----------------- Mesh Generation -----------------------
L = 4.0
nx = 100
mesh = Grid1D(nx=nx, Lx=L)
x = mesh.cellCenters[0] # Cell position

plasma_disp_real = CellVariable(name=r"Re$(X(z))$", mesh=mesh)
plasma_disp_imag = CellVariable(name=r"Im$(X(z))$", mesh=mesh)

full_plasma_disp = numpy.array(1j*numerix.sqrt(numerix.pi)\
		* numerix.exp(-x**2)*wofz(x))
print full_plasma_disp

plasma_disp_real.setValue(full_plasma_disp.real)
plasma_disp_imag.setValue(full_plasma_disp.imag)

initial_viewer = Viewer((plasma_disp_real, plasma_disp_imag),\
		xmin=0.0, legend='best')
raw_input("Pause for Initial Conditions")

Exemplo n.º 17
0
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.meshes.grid2D import Grid2D
    mesh = Grid2D(dx = cellSize,
                  dy = cellSize,
                  nx = xCells,
                  ny = yCells)

    narrowBandWidth = numberOfCellsInNarrowBand * cellSize
    from fipy.models.levelSet.distanceFunction.distanceVariable import \
         DistanceVariable        

    distanceVar = DistanceVariable(
        name = 'distance variable',
        mesh = mesh,
        value = -1,
        narrowBandWidth = narrowBandWidth,
        hasOld = 1)

    bottomHeight = cellsBelowTrench * cellSize
    trenchHeight = bottomHeight + trenchDepth
    trenchWidth = trenchDepth / aspectRatio
    sideWidth = (trenchSpacing - trenchWidth) / 2

    x, y = mesh.getCellCenters()[...,0], mesh.getCellCenters()[...,1]
    distanceVar.setValue(1, where=(y > trenchHeight) | ((y > bottomHeight) & (x < xCells * cellSize - sideWidth)))

    distanceVar.calcDistanceFunction(narrowBandWidth = 1e10)

    from fipy.models.levelSet.surfactant.surfactantVariable import \
         SurfactantVariable
    
    catalystVar = SurfactantVariable(
        name = "catalyst variable",
        value = catalystCoverage,
        distanceVar = distanceVar)
    
    from fipy.variables.cellVariable import CellVariable

    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.getInterfaceVar()

    exchangeCurrentDensity = currentDensity0 + tmp

    import fipy.tools.numerix as numerix
    expo = numerix.exp(expoConstant * overpotential)
    currentDensity = expo * exchangeCurrentDensity * metalVar \
                     / metalConcentration

    depositionRateVariable = currentDensity * molarVolume \
                             / (charge * faradaysConstant)

    extensionVelocityVariable = CellVariable(
        name = 'extension velocity',
        mesh = mesh,
        value = depositionRateVariable)   

    from fipy.models.levelSet.surfactant.adsorbingSurfactantEquation \
                import AdsorbingSurfactantEquation

    surfactantEquation = AdsorbingSurfactantEquation(
        surfactantVar = catalystVar,
        distanceVar = distanceVar,
        bulkVar = bulkCatalystVar,
        rateConstant = rateConstant0 + rateConstant3 * overpotential**3)

    from fipy.models.levelSet.advection.higherOrderAdvectionEquation \
                   import buildHigherOrderAdvectionEquation

    advectionEquation = buildHigherOrderAdvectionEquation(
        advectionCoeff = extensionVelocityVariable)

    from fipy.boundaryConditions.fixedValue import FixedValue
    from fipy.models.levelSet.electroChem.metalIonDiffusionEquation \
                         import buildMetalIonDiffusionEquation

    metalEquation = buildMetalIonDiffusionEquation(
        ionVar = metalVar,
        distanceVar = distanceVar,
        depositionRate = depositionRateVariable,
        diffusionCoeff = metalDiffusion,
        metalIonMolarVolume = molarVolume,
    )

    metalEquationBCs = FixedValue(mesh.getFacesTop(), metalConcentration)

    from fipy.models.levelSet.surfactant.surfactantBulkDiffusionEquation \
                    import buildSurfactantBulkDiffusionEquation

    bulkCatalystEquation = buildSurfactantBulkDiffusionEquation(
        bulkVar = bulkCatalystVar,
        distanceVar = distanceVar,
        surfactantVar = catalystVar,
        diffusionCoeff = catalystDiffusion,
        rateConstant = rateConstant0 * siteDensity
    )

    catalystBCs = FixedValue(mesh.getFacesTop(), catalystConcentration)

    if displayViewers:
        try:
            from fipy.viewers.mayaviViewer.mayaviSurfactantViewer import MayaviSurfactantViewer
            viewers = (MayaviSurfactantViewer(distanceVar, catalystVar.getInterfaceVar(), zoomFactor = 1e6, limits = { 'datamax' : 0.5, 'datamin' : 0.0 }, smooth = 1, title = 'catalyst coverage'),)
        except:
            from fipy.viewers import make
            viewers = (
                make(distanceVar, limits = { 'datamin' :-1e-9 , 'datamax' : 1e-9 }),
                make(catalystVar.getInterfaceVar()))
    else:
        viewers = ()

    levelSetUpdateFrequency = int(0.8 * narrowBandWidth \
                                  / (cellSize * cflNumber * 2))

    for step in range(numberOfSteps):

        if step % 5 == 0:
            for viewer in viewers:
                viewer.plot()

        if step % levelSetUpdateFrequency == 0:
            distanceVar.calcDistanceFunction()
            
        extensionVelocityVariable.setValue(depositionRateVariable())

        distanceVar.updateOld()
        catalystVar.updateOld()
        metalVar.updateOld()
        bulkCatalystVar.updateOld()

        distanceVar.extendVariable(extensionVelocityVariable)
        dt = cflNumber * cellSize / numerix.max(extensionVelocityVariable)

        advectionEquation.solve(distanceVar, dt = dt) 
        surfactantEquation.solve(catalystVar, dt = dt)
        metalEquation.solve(metalVar, dt = dt, 
                            boundaryConditions = metalEquationBCs)
        bulkCatalystEquation.solve(bulkCatalystVar, dt = dt,
                                   boundaryConditions = catalystBCs)

    try:
        import os
        import examples.levelSet.electroChem
        filepath = os.path.join(examples.levelSet.electroChem.__path__[0], 'test.gz')
        
        from fipy.tools import dump
        from fipy.tools import numerix
        print catalystVar.allclose(numerix.array(dump.read(filepath)), rtol = 1e-4)
    except:
        return 0
Exemplo n.º 18
0
        name = 'metal variable',
        mesh = mesh,
        value = bulkMetalConcentration)

    bench.stop('variables')

    bench.start()

    expoConstant = -transferCoefficient * faradaysConstant \
                   / (gasConstant * temperature)

    tmp = currentDensity1 \
          * catalystVar.getInterfaceVar()

    exchangeCurrentDensity = currentDensity0 + tmp
    expo = numerix.exp(expoConstant * overpotential)
    currentDensity = expo * exchangeCurrentDensity * metalVar \
                     / bulkMetalConcentration

    depositionRateVariable = currentDensity * molarVolume \
                             / (charge * faradaysConstant)

    extensionVelocityVariable = CellVariable(
        name = 'extension velocity',
        mesh = mesh,
        value = depositionRateVariable)   

    from fipy.models.levelSet.surfactant.adsorbingSurfactantEquation \
                import AdsorbingSurfactantEquation

    surfactantEquation = AdsorbingSurfactantEquation(
Exemplo n.º 19
0
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
Exemplo n.º 20
0
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
Exemplo n.º 21
0
Arquivo: input2D.py Projeto: ghorn/Eg
       NthOrderBoundaryCondition(mesh.getFacesRight(), 0, 3),
       NthOrderBoundaryCondition(mesh.getFacesTop(), 0, 3),
       NthOrderBoundaryCondition(mesh.getFacesBottom(), 0, 3))

if __name__ == '__main__':

    import fipy.viewers
    viewer = fipy.viewers.make(vars=var,
                               limits={
                                   'datamin': 0.,
                                   'datamax': 1.0
                               })
    viewer.plot()

dexp = -5

for step in range(steps):
    dt = numerix.exp(dexp)
    dt = min(100, dt)
    dexp += 0.01
    var.updateOld()
    eqch.solve(var, boundaryConditions=BCs, solver=solver, dt=dt)

    if __name__ == '__main__':
        viewer.plot()
        print 'step', step, 'dt', dt


def _run():
    pass
Exemplo n.º 22
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)
elif GIBBS != "FH":
    print("Implent more stuff you lazy f**k")

# Define the equations

# evaluating kappa
kappa = (1.0 / 6.0) * chi_AB

# # eqn 1 is the 2nd order transport equation
# eq1 = (TransientTerm(var=x_a)) == DiffusionTerm(coeff = x_a * (1 - x_a), var=mu_AB)

# # eqn 2 is the chemical potential definition
# eq2 = (ImplicitSourceTerm(coeff=1. , var=mu_AB)) == ImplicitSourceTerm(coeff=d2gdx_a2, var=x_a) - d2gdx_a2 * x_a + dgdx_a - DiffusionTerm(coeff=kappa, var=x_a)
Exemplo n.º 23
0
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
    numberOfCellsInNarrowBand = 20
    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

    from fipy import TrenchMesh
    from fipy.tools import numerix
    mesh = TrenchMesh(cellSize = cellSize,
                      trenchSpacing = trenchSpacing,
                      trenchDepth = trenchDepth,
                      boundaryLayerDepth = boundaryLayerDepth,
                      aspectRatio = aspectRatio,
                      angle = numerix.pi * 4. / 180.,
                      bowWidth = 0.,
                      overBumpRadius = 0.,
                      overBumpWidth = 0.)

    narrowBandWidth = numberOfCellsInNarrowBand * cellSize
    from fipy.models.levelSet.distanceFunction.distanceVariable import DistanceVariable
    distanceVar = DistanceVariable(
        name = 'distance variable',
        mesh = mesh,
        value = -1,
        narrowBandWidth = narrowBandWidth)

    distanceVar.setValue(1, where=mesh.getElectrolyteMask())
    
    distanceVar.calcDistanceFunction(narrowBandWidth = 1e10)
    from fipy.models.levelSet.surfactant.surfactantVariable import SurfactantVariable
    levelerVar = SurfactantVariable(
        name = "leveler variable",
        value = initialLevelerCoverage,
        distanceVar = distanceVar)

    acceleratorVar = SurfactantVariable(
        name = "accelerator variable",
        value = initialAcceleratorCoverage,
        distanceVar = distanceVar)

    from fipy.variables.cellVariable import CellVariable
    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.getInterfaceVar() * (coeffAccelerator - coeffSuppressor) + coeffSuppressor

    currentDensity = metalVar / bulkMetalConcentration * exchangeCurrentDensity

    depositionRateVariable = currentDensity * atomicVolume / charge / faradaysConstant

    extensionVelocityVariable = CellVariable(
        name = 'extension velocity',
        mesh = mesh,
        value = depositionRateVariable)   

    from fipy.models.levelSet.surfactant.adsorbingSurfactantEquation \
             import AdsorbingSurfactantEquation

    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.getInterfaceVar()
    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)

    from fipy.models.levelSet.advection.higherOrderAdvectionEquation \
         import buildHigherOrderAdvectionEquation

    advectionEquation = buildHigherOrderAdvectionEquation(
        advectionCoeff = extensionVelocityVariable)

    from fipy.boundaryConditions.fixedValue import FixedValue
    from fipy.models.levelSet.electroChem.metalIonDiffusionEquation \
         import buildMetalIonDiffusionEquation

    metalEquation = buildMetalIonDiffusionEquation(
        ionVar = metalVar,
        distanceVar = distanceVar,
        depositionRate = depositionRateVariable,
        diffusionCoeff = metalDiffusionCoefficient,
        metalIonMolarVolume = atomicVolume)

    metalEquationBCs = FixedValue(mesh.getTopFaces(), bulkMetalConcentration)

    from fipy.models.levelSet.surfactant.surfactantBulkDiffusionEquation \
         import buildSurfactantBulkDiffusionEquation

    bulkAcceleratorEquation = buildSurfactantBulkDiffusionEquation(
        bulkVar = bulkAcceleratorVar,
        distanceVar = distanceVar,
        surfactantVar = acceleratorVar,
        otherSurfactantVar = levelerVar,
        diffusionCoeff = acceleratorDiffusionCoefficient,
        rateConstant = kAccelerator * siteDensity)

    bulkAcceleratorEquationBCs = (FixedValue(
        mesh.getTopFaces(),
        bulkAcceleratorConcentration),)

    bulkLevelerEquation = buildSurfactantBulkDiffusionEquation(
        bulkVar = bulkLevelerVar,
        distanceVar = distanceVar,
        surfactantVar = levelerVar,
        diffusionCoeff = levelerDiffusionCoefficient,
        rateConstant = kLeveler * siteDensity)

    bulkLevelerEquationBCs =  (FixedValue(
        mesh.getTopFaces(),
        bulkLevelerConcentration),)

    eqnTuple = ( (advectionEquation, distanceVar, ()),
                 (levelerSurfactantEquation, levelerVar, ()),
                 (acceleratorSurfactantEquation, acceleratorVar, ()),
                 (metalEquation, metalVar,  metalEquationBCs),
                 (bulkAcceleratorEquation, bulkAcceleratorVar, bulkAcceleratorEquationBCs),
                 (bulkLevelerEquation, bulkLevelerVar, bulkLevelerEquationBCs))

    levelSetUpdateFrequency = int(0.7 * narrowBandWidth / cellSize / cflNumber / 2)

    totalTime = 0.0

    if displayViewers:
        from fipy.viewers.mayaviViewer.mayaviSurfactantViewer import MayaviSurfactantViewer
        viewers = (
            MayaviSurfactantViewer(distanceVar, acceleratorVar.getInterfaceVar(), zoomFactor = 1e6, limits = { 'datamax' : 0.5, 'datamin' : 0.0 }, smooth = 1, title = 'accelerator coverage'),
            MayaviSurfactantViewer(distanceVar, levelerVar.getInterfaceVar(), zoomFactor = 1e6, limits = { 'datamax' : 0.5, 'datamin' : 0.0 }, smooth = 1, title = 'leveler coverage'))
        
    for step in range(numberOfSteps):

        if displayViewers:
            if step % displayRate == 0:
                for viewer in viewers:
                    viewer.plot()
            
        if step % levelSetUpdateFrequency == 0:
            distanceVar.calcDistanceFunction(deleteIslands = True)

        extensionVelocityVariable.setValue(depositionRateVariable)

        extOnInt = numerix.where(distanceVar > 0,
                                 numerix.where(distanceVar < 2 * cellSize,
                                               extensionVelocityVariable,
                                               0),
                                 0)

        dt = cflNumber * cellSize / numerix.max(extOnInt)

        id = numerix.max(numerix.nonzero(distanceVar._getInterfaceFlag()))
        distanceVar.extendVariable(extensionVelocityVariable, deleteIslands = True)

        extensionVelocityVariable[mesh.getFineMesh().getNumberOfCells():] = 0.

        for eqn, var, BCs in eqnTuple:
            var.updateOld()

        for eqn, var, BCs in eqnTuple:
            eqn.solve(var, boundaryConditions = BCs, dt = dt)
            
        totalTime += dt

    try:
        testFile = 'testLeveler.gz'
        import os
        import examples.levelSet.electroChem
        from fipy.tools import dump
        data = dump.read(os.path.join(examples.levelSet.electroChem.__path__[0], testFile))
        N = mesh.getFineMesh().getNumberOfCells()
        print numerix.allclose(data[:N], levelerVar[:N], rtol = 1e-3)
    except:
        return 0
Exemplo n.º 24
0
from fipy.tools import numerix

L = 2.
X0 = -1.
nx = 800
cfl = 0.1
K = 4.
rho = 1.

dx = L / nx
m = Grid1D(nx=nx, dx=dx) + X0
x, = m.cellCenters

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()

for step in range(500):
Exemplo n.º 25
0
 def depositionCoeff(alpha, i0):
     expo = numerix.exp(-alpha * etaPrime)
     return 2 * i0 * (expo - expo * numerix.exp(etaPrime))
Exemplo n.º 26
0
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
    numberOfCellsInNarrowBand = 20
    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

    from fipy import TrenchMesh
    from fipy.tools import numerix
    mesh = TrenchMesh(cellSize=cellSize,
                      trenchSpacing=trenchSpacing,
                      trenchDepth=trenchDepth,
                      boundaryLayerDepth=boundaryLayerDepth,
                      aspectRatio=aspectRatio,
                      angle=numerix.pi * 4. / 180.,
                      bowWidth=0.,
                      overBumpRadius=0.,
                      overBumpWidth=0.)

    narrowBandWidth = numberOfCellsInNarrowBand * cellSize
    from fipy.models.levelSet.distanceFunction.distanceVariable import DistanceVariable
    distanceVar = DistanceVariable(name='distance variable',
                                   mesh=mesh,
                                   value=-1,
                                   narrowBandWidth=narrowBandWidth)

    distanceVar.setValue(1, where=mesh.getElectrolyteMask())

    distanceVar.calcDistanceFunction(narrowBandWidth=1e10)
    from fipy.models.levelSet.surfactant.surfactantVariable import SurfactantVariable
    levelerVar = SurfactantVariable(name="leveler variable",
                                    value=initialLevelerCoverage,
                                    distanceVar=distanceVar)

    acceleratorVar = SurfactantVariable(name="accelerator variable",
                                        value=initialAcceleratorCoverage,
                                        distanceVar=distanceVar)

    from fipy.variables.cellVariable import CellVariable
    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.getInterfaceVar() * (
        coeffAccelerator - coeffSuppressor) + coeffSuppressor

    currentDensity = metalVar / bulkMetalConcentration * exchangeCurrentDensity

    depositionRateVariable = currentDensity * atomicVolume / charge / faradaysConstant

    extensionVelocityVariable = CellVariable(name='extension velocity',
                                             mesh=mesh,
                                             value=depositionRateVariable)

    from fipy.models.levelSet.surfactant.adsorbingSurfactantEquation \
             import AdsorbingSurfactantEquation

    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.getInterfaceVar()
    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)

    from fipy.models.levelSet.advection.higherOrderAdvectionEquation \
         import buildHigherOrderAdvectionEquation

    advectionEquation = buildHigherOrderAdvectionEquation(
        advectionCoeff=extensionVelocityVariable)

    from fipy.boundaryConditions.fixedValue import FixedValue
    from fipy.models.levelSet.electroChem.metalIonDiffusionEquation \
         import buildMetalIonDiffusionEquation

    metalEquation = buildMetalIonDiffusionEquation(
        ionVar=metalVar,
        distanceVar=distanceVar,
        depositionRate=depositionRateVariable,
        diffusionCoeff=metalDiffusionCoefficient,
        metalIonMolarVolume=atomicVolume)

    metalEquationBCs = FixedValue(mesh.getTopFaces(), bulkMetalConcentration)

    from fipy.models.levelSet.surfactant.surfactantBulkDiffusionEquation \
         import buildSurfactantBulkDiffusionEquation

    bulkAcceleratorEquation = buildSurfactantBulkDiffusionEquation(
        bulkVar=bulkAcceleratorVar,
        distanceVar=distanceVar,
        surfactantVar=acceleratorVar,
        otherSurfactantVar=levelerVar,
        diffusionCoeff=acceleratorDiffusionCoefficient,
        rateConstant=kAccelerator * siteDensity)

    bulkAcceleratorEquationBCs = (FixedValue(mesh.getTopFaces(),
                                             bulkAcceleratorConcentration), )

    bulkLevelerEquation = buildSurfactantBulkDiffusionEquation(
        bulkVar=bulkLevelerVar,
        distanceVar=distanceVar,
        surfactantVar=levelerVar,
        diffusionCoeff=levelerDiffusionCoefficient,
        rateConstant=kLeveler * siteDensity)

    bulkLevelerEquationBCs = (FixedValue(mesh.getTopFaces(),
                                         bulkLevelerConcentration), )

    eqnTuple = ((advectionEquation, distanceVar,
                 ()), (levelerSurfactantEquation, levelerVar,
                       ()), (acceleratorSurfactantEquation, acceleratorVar,
                             ()), (metalEquation, metalVar, metalEquationBCs),
                (bulkAcceleratorEquation, bulkAcceleratorVar,
                 bulkAcceleratorEquationBCs),
                (bulkLevelerEquation, bulkLevelerVar, bulkLevelerEquationBCs))

    levelSetUpdateFrequency = int(0.7 * narrowBandWidth / cellSize /
                                  cflNumber / 2)

    totalTime = 0.0

    if displayViewers:
        from fipy.viewers.mayaviViewer.mayaviSurfactantViewer import MayaviSurfactantViewer
        viewers = (MayaviSurfactantViewer(distanceVar,
                                          acceleratorVar.getInterfaceVar(),
                                          zoomFactor=1e6,
                                          limits={
                                              'datamax': 0.5,
                                              'datamin': 0.0
                                          },
                                          smooth=1,
                                          title='accelerator coverage'),
                   MayaviSurfactantViewer(distanceVar,
                                          levelerVar.getInterfaceVar(),
                                          zoomFactor=1e6,
                                          limits={
                                              'datamax': 0.5,
                                              'datamin': 0.0
                                          },
                                          smooth=1,
                                          title='leveler coverage'))

    for step in range(numberOfSteps):

        if displayViewers:
            if step % displayRate == 0:
                for viewer in viewers:
                    viewer.plot()

        if step % levelSetUpdateFrequency == 0:
            distanceVar.calcDistanceFunction(deleteIslands=True)

        extensionVelocityVariable.setValue(depositionRateVariable)

        extOnInt = numerix.where(
            distanceVar > 0,
            numerix.where(distanceVar < 2 * cellSize,
                          extensionVelocityVariable, 0), 0)

        dt = cflNumber * cellSize / numerix.max(extOnInt)

        id = numerix.max(numerix.nonzero(distanceVar._getInterfaceFlag()))
        distanceVar.extendVariable(extensionVelocityVariable,
                                   deleteIslands=True)

        extensionVelocityVariable[mesh.getFineMesh().getNumberOfCells():] = 0.

        for eqn, var, BCs in eqnTuple:
            var.updateOld()

        for eqn, var, BCs in eqnTuple:
            eqn.solve(var, boundaryConditions=BCs, dt=dt)

        totalTime += dt

    try:
        testFile = 'testLeveler.gz'
        import os
        import examples.levelSet.electroChem
        from fipy.tools import dump
        data = dump.read(
            os.path.join(examples.levelSet.electroChem.__path__[0], testFile))
        N = mesh.getFineMesh().getNumberOfCells()
        print numerix.allclose(data[:N], levelerVar[:N], rtol=1e-3)
    except:
        return 0
Exemplo n.º 27
0
    metalVar = CellVariable(name='metal variable',
                            mesh=mesh,
                            value=bulkMetalConcentration)

    bench.stop('variables')

    bench.start()

    expoConstant = -transferCoefficient * faradaysConstant \
                   / (gasConstant * temperature)

    tmp = currentDensity1 \
          * catalystVar.getInterfaceVar()

    exchangeCurrentDensity = currentDensity0 + tmp
    expo = numerix.exp(expoConstant * overpotential)
    currentDensity = expo * exchangeCurrentDensity * metalVar \
                     / bulkMetalConcentration

    depositionRateVariable = currentDensity * molarVolume \
                             / (charge * faradaysConstant)

    extensionVelocityVariable = CellVariable(name='extension velocity',
                                             mesh=mesh,
                                             value=depositionRateVariable)

    from fipy.models.levelSet.surfactant.adsorbingSurfactantEquation \
                import AdsorbingSurfactantEquation

    surfactantEquation = AdsorbingSurfactantEquation(
        surfactantVar = catalystVar,
Exemplo n.º 28
0
 def exp(self):
     return self._UnaryOperatorVariable(lambda a: numerix.exp(a))
Exemplo n.º 29
0
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.meshes.grid2D import Grid2D
    mesh = Grid2D(dx=cellSize, dy=cellSize, nx=xCells, ny=yCells)

    narrowBandWidth = numberOfCellsInNarrowBand * cellSize
    from fipy.models.levelSet.distanceFunction.distanceVariable import \
         DistanceVariable

    distanceVar = DistanceVariable(name='distance variable',
                                   mesh=mesh,
                                   value=-1,
                                   narrowBandWidth=narrowBandWidth,
                                   hasOld=1)

    bottomHeight = cellsBelowTrench * cellSize
    trenchHeight = bottomHeight + trenchDepth
    trenchWidth = trenchDepth / aspectRatio
    sideWidth = (trenchSpacing - trenchWidth) / 2

    x, y = mesh.getCellCenters()[..., 0], mesh.getCellCenters()[..., 1]
    distanceVar.setValue(1,
                         where=(y > trenchHeight) |
                         ((y > bottomHeight) &
                          (x < xCells * cellSize - sideWidth)))

    distanceVar.calcDistanceFunction(narrowBandWidth=1e10)

    from fipy.models.levelSet.surfactant.surfactantVariable import \
         SurfactantVariable

    catalystVar = SurfactantVariable(name="catalyst variable",
                                     value=catalystCoverage,
                                     distanceVar=distanceVar)

    from fipy.variables.cellVariable import CellVariable

    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.getInterfaceVar()

    exchangeCurrentDensity = currentDensity0 + tmp

    import fipy.tools.numerix as numerix
    expo = numerix.exp(expoConstant * overpotential)
    currentDensity = expo * exchangeCurrentDensity * metalVar \
                     / metalConcentration

    depositionRateVariable = currentDensity * molarVolume \
                             / (charge * faradaysConstant)

    extensionVelocityVariable = CellVariable(name='extension velocity',
                                             mesh=mesh,
                                             value=depositionRateVariable)

    from fipy.models.levelSet.surfactant.adsorbingSurfactantEquation \
                import AdsorbingSurfactantEquation

    surfactantEquation = AdsorbingSurfactantEquation(
        surfactantVar=catalystVar,
        distanceVar=distanceVar,
        bulkVar=bulkCatalystVar,
        rateConstant=rateConstant0 + rateConstant3 * overpotential**3)

    from fipy.models.levelSet.advection.higherOrderAdvectionEquation \
                   import buildHigherOrderAdvectionEquation

    advectionEquation = buildHigherOrderAdvectionEquation(
        advectionCoeff=extensionVelocityVariable)

    from fipy.boundaryConditions.fixedValue import FixedValue
    from fipy.models.levelSet.electroChem.metalIonDiffusionEquation \
                         import buildMetalIonDiffusionEquation

    metalEquation = buildMetalIonDiffusionEquation(
        ionVar=metalVar,
        distanceVar=distanceVar,
        depositionRate=depositionRateVariable,
        diffusionCoeff=metalDiffusion,
        metalIonMolarVolume=molarVolume,
    )

    metalEquationBCs = FixedValue(mesh.getFacesTop(), metalConcentration)

    from fipy.models.levelSet.surfactant.surfactantBulkDiffusionEquation \
                    import buildSurfactantBulkDiffusionEquation

    bulkCatalystEquation = buildSurfactantBulkDiffusionEquation(
        bulkVar=bulkCatalystVar,
        distanceVar=distanceVar,
        surfactantVar=catalystVar,
        diffusionCoeff=catalystDiffusion,
        rateConstant=rateConstant0 * siteDensity)

    catalystBCs = FixedValue(mesh.getFacesTop(), catalystConcentration)

    if displayViewers:
        try:
            from fipy.viewers.mayaviViewer.mayaviSurfactantViewer import MayaviSurfactantViewer
            viewers = (MayaviSurfactantViewer(distanceVar,
                                              catalystVar.getInterfaceVar(),
                                              zoomFactor=1e6,
                                              limits={
                                                  'datamax': 0.5,
                                                  'datamin': 0.0
                                              },
                                              smooth=1,
                                              title='catalyst coverage'), )
        except:
            from fipy.viewers import make
            viewers = (make(distanceVar,
                            limits={
                                'datamin': -1e-9,
                                'datamax': 1e-9
                            }), make(catalystVar.getInterfaceVar()))
    else:
        viewers = ()

    levelSetUpdateFrequency = int(0.8 * narrowBandWidth \
                                  / (cellSize * cflNumber * 2))

    for step in range(numberOfSteps):

        if step % 5 == 0:
            for viewer in viewers:
                viewer.plot()

        if step % levelSetUpdateFrequency == 0:
            distanceVar.calcDistanceFunction()

        extensionVelocityVariable.setValue(depositionRateVariable())

        distanceVar.updateOld()
        catalystVar.updateOld()
        metalVar.updateOld()
        bulkCatalystVar.updateOld()

        distanceVar.extendVariable(extensionVelocityVariable)
        dt = cflNumber * cellSize / numerix.max(extensionVelocityVariable)

        advectionEquation.solve(distanceVar, dt=dt)
        surfactantEquation.solve(catalystVar, dt=dt)
        metalEquation.solve(metalVar,
                            dt=dt,
                            boundaryConditions=metalEquationBCs)
        bulkCatalystEquation.solve(bulkCatalystVar,
                                   dt=dt,
                                   boundaryConditions=catalystBCs)

    try:
        import os
        import examples.levelSet.electroChem
        filepath = os.path.join(examples.levelSet.electroChem.__path__[0],
                                'test.gz')

        from fipy.tools import dump
        from fipy.tools import numerix
        print catalystVar.allclose(numerix.array(dump.read(filepath)),
                                   rtol=1e-4)
    except:
        return 0
Exemplo n.º 30
0
D = 1.0
U = 100.0
peclet = (U*L/D)
# This is the syntax needed to specify u_x
convCoeff= (1.0,)

# intial condition width (standard deviation)
sigma = 0.05*L

#Defining the variable
c = CellVariable(mesh=mesh, name=r"$c$")

# Setting initial conditions
x = mesh.cellCenters[0]
c.value=0.0
c.setValue(0.05*(1.0/(sigma*numerix.sqrt(2*numerix.pi)))*numerix.exp(-0.5*((x-1.0)/(sigma))**2.0))

# defining the equation
# We write three equations: pure convection, pure diffusion and convection-diffusion
eq = TransientTerm() + VanLeerConvectionTerm(coeff=convCoeff) == 0
# eq = TransientTerm() + ExponentialConvectionTerm(coeff=convCoeff) == 0
# eq = TransientTerm() - DiffusionTerm(coeff=(1/peclet)) == 0
# eq = TransientTerm() + VanLeerConvectionTerm(coeff=convCoeff) - DiffusionTerm(coeff=(1.0/peclet)) == 0


# The choice of dt and dx in a convection problem is a bit more complicated 
dt = 0.0001

# We might not want to see the output from every single timestep, so we define a stride parameter
time_stride = 200
timestep = 0
Exemplo n.º 31
0
dmdt = CellVariable(mesh=mesh, value=dmdt_val)
Dval = CellVariable(mesh=mesh, value=D)

# ### Fipy Calculation loop starts
time_per_loop = numerix.zeros(number_of_steps)
loop = numerix.zeros(number_of_steps)
while t_i <= number_of_steps:
    start_import = time.time()
    print('*************************************************************')
    percentage = float(float(t_i) / (float(number_of_steps))) * 100.0
    percentage_val[t_i] = percentage
    print('Completed = ' + str(percentage) + '%')

    print('dexp=' + str(dexp))
    #timestep=min(1e-3, numerix.exp(dexp))
    timestep = numerix.exp(dexp)
    print('timestep=' + str(timestep))

    eqI = (TransientTerm() == DiffusionTerm(coeff=Dval) -
           ExponentialConvectionTerm(coeff=dmdt))
    eqI.solve(var=phi, dt=timestep)
    print('Max phi=' + str(max(phi)))
    max_val_phi[t_i] = max(phi)
    if __name__ == "__main__":  #Parameters to be changed are in the seciton below.
        viewer.plot(
            filename="trial.vtk"
        )  #It will only save the final vtk file. You can change the name
    if not t_i == 0:
        filename = str(t_i).zfill(5)
        dest_name = './with_axis_0_VTK_files/with_axis_0_img_' + str(
            filename
Exemplo n.º 32
0
Arquivo: input2D.py Projeto: ghorn/Eg
from fipy.boundaryConditions.nthOrderBoundaryCondition import NthOrderBoundaryCondition
BCs = (FixedFlux(mesh.getFacesRight(), 0),
       FixedFlux(mesh.getFacesLeft(), 0),
       NthOrderBoundaryCondition(mesh.getFacesLeft(), 0, 3),
       NthOrderBoundaryCondition(mesh.getFacesRight(), 0, 3),
       NthOrderBoundaryCondition(mesh.getFacesTop(), 0, 3),
       NthOrderBoundaryCondition(mesh.getFacesBottom(), 0, 3))

if __name__ == '__main__':

    import fipy.viewers
    viewer = fipy.viewers.make(vars = var, limits = {'datamin': 0., 'datamax': 1.0})
    viewer.plot()
    
dexp=-5

for step in range(steps):
    dt = numerix.exp(dexp)
    dt = min(100, dt)
    dexp += 0.01
    var.updateOld()
    eqch.solve(var, boundaryConditions = BCs, solver = solver, dt = dt)

    if __name__ == '__main__':
        viewer.plot()
        print 'step',step,'dt',dt
	
def _run():
    pass
            
Exemplo n.º 33
0
nx = 300
dx = 1
dt = 10.

mesh = fp.Grid1D(nx=nx, dx=dx)

s0 = 0.1; s1 = 0.2
t0 = 1.; t1 = 0.01; t2 = 1.1

# IC
hini = 1.

h = fp.CellVariable(name="head", mesh=mesh, value=hini, hasOld=True)
h_implicit_source = fp.CellVariable(name="head_implicit_source", mesh=mesh, value=hini, hasOld=True)
h_convection = fp.CellVariable(name="head_convection", mesh=mesh, value=hini, hasOld=True)
theta = fp.CellVariable(name="theta", mesh=mesh, value=numerix.exp(s0 + s1*h.value), hasOld=True)

T = t0 * numerix.exp(t1 * h**t2)
S = s1 * numerix.exp(s0 + s1 * h) # and S_theta = s1 * theta
D = t0/s1 * numerix.exp(t1* ((numerix.log(theta) -s0)/s1)**t2)/ theta

# Plots
plotOpt = True
if plotOpt:
    fig, ax = plt.subplots(2,2)
    x = mesh.cellCenters.value[0]
    
    head = np.arange(0,10,0.1)
    th = np.exp(s0 + s1*head)
    trans = t0 * np.exp(t1 * head**t2)
    sto = s1 * np.exp(s0 + s1*head)