fipy package

Subpackages

Submodules

fipy.testFiPy module

Module contents

FiPy is an object oriented, partial differential equation (PDE) solver, written in Python, based on a standard finite volume (FV) approach. The framework has been developed in the Materials Science and Engineering Division (MSED) and Center for Theoretical and Computational Materials Science (CTCMS), in the Material Measurement Laboratory (MML) at the National Institute of Standards and Technology (NIST).

The solution of coupled sets of PDEs is ubiquitous to the numerical simulation of science problems. Numerous PDE solvers exist, using a variety of languages and numerical approaches. Many are proprietary, expensive and difficult to customize. As a result, scientists spend considerable resources repeatedly developing limited tools for specific problems. Our approach, combining the FV method and Python, provides a tool that is extensible, powerful and freely available. A significant advantage to Python is the existing suite of tools for array calculations, sparse matrices and data rendering.

The FiPy framework includes terms for transient diffusion, convection and standard sources, enabling the solution of arbitrary combinations of coupled elliptic, hyperbolic and parabolic PDEs. Currently implemented models include phase field [1] [2] [3] treatments of polycrystalline, dendritic, and electrochemical phase transformations, as well as drug eluting stents [4], reactive wetting [5], photovoltaics [6] and a level set treatment of the electrodeposition process [7].

exception fipy.AbstractBaseClassError(s="can't instantiate abstract base class")

Bases: NotImplementedError

__cause__

exception cause

__context__

exception context

__delattr__(name, /)

Implement delattr(self, name).

__getattribute__(name, /)

Return getattr(self, name).

__reduce__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__setstate__()
__str__()

Return str(self).

__suppress_context__
__traceback__
args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class fipy.AdvectionTerm(coeff=None)

Bases: FirstOrderAdvectionTerm

The AdvectionTerm object constructs the b vector contribution for the advection term given by

u \abs{\nabla \phi}

from the advection equation given by:

\frac{\partial \phi}{\partial t} + u \abs{\nabla \phi} = 0

The construction of the gradient magnitude term requires upwinding as in the standard FirstOrderAdvectionTerm. The higher order terms are incorporated as follows. The formula used here is given by:

u_P \abs{\nabla \phi}_P = \max \left( u_P , 0 \right) \left[  \sum_A \min \left( D_{AP}, 0 \right)^2 \right]^{1/2} +  \min \left( u_P , 0 \right) \left[  \sum_A \max \left( D_{AP}, 0 \right)^2 \right]^{1/2}

where,

D_{AP} = \frac{ \phi_A - \phi_P } { d_{AP}} - \frac{ d_{AP} } {2} m \left(L_A, L_P \right)

and

m\left(x, y\right) &= x \qquad \text{if $\abs{x} \le \abs{y} \forall xy \ge 0$} \\
m\left(x, y\right) &= y \qquad \text{if $\abs{x} > \abs{y} \forall xy \ge 0$} \\
m\left(x, y\right) &= 0 \qquad \text{if $xy < 0$}

also,

L_A &= \frac{\phi_{AA} + \phi_P - 2 \phi_A}{d_{AP}^2} \\
L_P &= \frac{\phi_{A} + \phi_{PP} - 2 \phi_P}{d_{AP}^2}

Here are some simple test cases for this problem:

>>> from fipy.meshes import Grid1D
>>> from fipy.solvers import *
>>> SparseMatrix = LinearPCGSolver()._matrixClass
>>> mesh = Grid1D(dx = 1., nx = 3)

Trivial test:

>>> from fipy.variables.cellVariable import CellVariable
>>> coeff = CellVariable(mesh = mesh, value = numerix.zeros(3, 'd'))
>>> v, L, b = AdvectionTerm(0.)._buildMatrix(coeff, SparseMatrix)
>>> print(numerix.allclose(b, numerix.zeros(3, 'd'), atol = 1e-10)) 
True

Less trivial test:

>>> coeff = CellVariable(mesh = mesh, value = numerix.arange(3))
>>> v, L, b = AdvectionTerm(1.)._buildMatrix(coeff, SparseMatrix)
>>> print(numerix.allclose(b, numerix.array((0., -1., -1.)), atol = 1e-10)) 
True

Even less trivial

>>> coeff = CellVariable(mesh = mesh, value = numerix.arange(3))
>>> v, L, b = AdvectionTerm(-1.)._buildMatrix(coeff, SparseMatrix)
>>> print(numerix.allclose(b, numerix.array((1., 1., 0.)), atol = 1e-10)) 
True

Another trivial test case (more trivial than a trivial test case standing on a harpsichord singing “trivial test cases are here again”)

>>> vel = numerix.array((-1, 2, -3))
>>> coeff = CellVariable(mesh = mesh, value = numerix.array((4, 6, 1)))
>>> v, L, b = AdvectionTerm(vel)._buildMatrix(coeff, SparseMatrix)
>>> print(numerix.allclose(b, -vel * numerix.array((2, numerix.sqrt(5**2 + 2**2), 5)), atol = 1e-10)) 
True

Somewhat less trivial test case:

>>> from fipy.meshes import Grid2D
>>> mesh = Grid2D(dx = 1., dy = 1., nx = 2, ny = 2)
>>> vel = numerix.array((3, -5, -6, -3))
>>> coeff = CellVariable(mesh = mesh, value = numerix.array((3, 1, 6, 7)))
>>> v, L, b = AdvectionTerm(vel)._buildMatrix(coeff, SparseMatrix)
>>> answer = -vel * numerix.array((2, numerix.sqrt(2**2 + 6**2), 1, 0))
>>> print(numerix.allclose(b, answer, atol = 1e-10)) 
True

For the above test cases the AdvectionTerm gives the same result as the AdvectionTerm. The following test imposes a quadratic field. The higher order term can resolve this field correctly.

\phi = x^2

The returned vector b should have the value:

-\abs{\nabla \phi} = -\left|\frac{\partial \phi}{\partial x}\right| = - 2 \abs{x}

Build the test case in the following way,

>>> mesh = Grid1D(dx = 1., nx = 5)
>>> vel = 1.
>>> coeff = CellVariable(mesh = mesh, value = mesh.cellCenters[0]**2)
>>> v, L, b = __AdvectionTerm(vel)._buildMatrix(coeff, SparseMatrix)

The first order term is not accurate. The first and last element are ignored because they don’t have any neighbors for higher order evaluation

>>> print(numerix.allclose(CellVariable(mesh=mesh,
... value=b).globalValue[1:-1], -2 * mesh.cellCenters.globalValue[0][1:-1]))
False

The higher order term is spot on.

>>> v, L, b = AdvectionTerm(vel)._buildMatrix(coeff, SparseMatrix)
>>> print(numerix.allclose(CellVariable(mesh=mesh,
... value=b).globalValue[1:-1], -2 * mesh.cellCenters.globalValue[0][1:-1]))
True

The AdvectionTerm will also resolve a circular field with more accuracy,

\phi = \left( x^2 + y^2 \right)^{1/2}

Build the test case in the following way,

>>> mesh = Grid2D(dx = 1., dy = 1., nx = 10, ny = 10)
>>> vel = 1.
>>> x, y = mesh.cellCenters
>>> r = numerix.sqrt(x**2 + y**2)
>>> coeff = CellVariable(mesh = mesh, value = r)
>>> v, L, b = __AdvectionTerm(1.)._buildMatrix(coeff, SparseMatrix)
>>> error = CellVariable(mesh=mesh, value=b + 1)
>>> ans = CellVariable(mesh=mesh, value=b + 1)
>>> ans[(x > 2) & (x < 8) & (y > 2) & (y < 8)] = 0.123105625618
>>> print((error <= ans).all())
True

The maximum error is large (about 12 %) for the first order advection.

>>> v, L, b = AdvectionTerm(1.)._buildMatrix(coeff, SparseMatrix)
>>> error = CellVariable(mesh=mesh, value=b + 1)
>>> ans = CellVariable(mesh=mesh, value=b + 1)
>>> ans[(x > 2) & (x < 8) & (y > 2) & (y < 8)] = 0.0201715476598
>>> print((error <= ans).all())
True

The maximum error is 2 % when using a higher order contribution.

Create a Term.

Parameters:

coeff (float or CellVariable or FaceVariable) – Coefficient for the term. FaceVariable objects are only acceptable for diffusion or convection terms.

property RHSvector

Return the RHS vector calculated in solve() or sweep(). The cacheRHSvector() method should be called before solve() or sweep() to cache the vector.

__add__(other)
__and__(other)
__div__(other)
__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__mul__(other)

Multiply a term

>>> 2. * __NonDiffusionTerm(coeff=0.5)
__NonDiffusionTerm(coeff=1.0)

Test for ticket:291.

>>> from fipy import PowerLawConvectionTerm
>>> PowerLawConvectionTerm(coeff=[[1], [0]]) * 1.0
PowerLawConvectionTerm(coeff=array([[ 1.],
       [ 0.]]))
__neg__()

Negate a Term.

>>> -__NonDiffusionTerm(coeff=1.)
__NonDiffusionTerm(coeff=-1.0)
__pos__()
__radd__(other)
__rand__(other)
__repr__()

The representation of a Term object is given by,

>>> print(__UnaryTerm(123.456))
__UnaryTerm(coeff=123.456)
__rmul__(other)

Multiply a term

>>> 2. * __NonDiffusionTerm(coeff=0.5)
__NonDiffusionTerm(coeff=1.0)

Test for ticket:291.

>>> from fipy import PowerLawConvectionTerm
>>> PowerLawConvectionTerm(coeff=[[1], [0]]) * 1.0
PowerLawConvectionTerm(coeff=array([[ 1.],
       [ 0.]]))
__rsub__(other)
__sub__(other)
__truediv__(other)
cacheMatrix()

Informs solve() and sweep() to cache their matrix so that matrix can return the matrix.

cacheRHSvector()

Informs solve() and sweep() to cache their right hand side vector so that getRHSvector() can return it.

copy()
getDefaultSolver(var=None, solver=None, *args, **kwargs)
justErrorVector(var=None, solver=None, boundaryConditions=(), dt=1.0, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the error as well as applying under-relaxation.

justErrorVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy.solvers import DummySolver
>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(DiffusionTerm().justErrorVector(v, solver=DummySolver())) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

error – The residual vector \vec{e}=\mathsf{L}\vec{x}_\text{old} - \vec{b}

Return type:

CellVariable

justResidualVector(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

justResidualVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(numerix.asarray(DiffusionTerm().justResidualVector(v))) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

property matrix

Return the matrix calculated in solve() or sweep(). The cacheMatrix() method should be called before solve() or sweep() to cache the matrix.

residualVectorAndNorm(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

  • residual (~fipy.variables.cellVariable.CellVariable) – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

  • norm (float) – The L2 norm of residual, \|\vec{r}\|_2

solve(var=None, solver=None, boundaryConditions=(), dt=None)

Builds and solves the Term’s linear system once. This method does not return the residual. It should be used when the residual is not required.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

sweep(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None, cacheResidual=False, cacheError=False)

Builds and solves the Term’s linear system once. This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

  • cacheResidual (bool) – If True, calculate and store the residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b} in the residualVector member of Term

  • cacheError (bool) – If True, use the residual vector \vec{r} to solve \mathsf{L}\vec{e}=\vec{r} for the error vector \vec{e} and store it in the errorVector member of Term

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

class fipy.BetaNoiseVariable(*args, **kwds)

Bases: NoiseVariable

Represents a beta distribution of random numbers with the probability distribution

x^{\alpha - 1}\frac{\beta^\alpha e^{-\beta x}}{\Gamma(\alpha)}

with a shape parameter \alpha, a rate parameter \beta, and \Gamma(z) = \int_0^\infty t^{z - 1}e^{-t}\,dt.

Seed the random module for the sake of deterministic test results.

>>> from fipy import numerix
>>> numerix.random.seed(1)

We generate noise on a uniform Cartesian mesh

>>> from fipy.variables.variable import Variable
>>> alpha = Variable()
>>> beta = Variable()
>>> from fipy.meshes import Grid2D
>>> noise = BetaNoiseVariable(mesh = Grid2D(nx = 100, ny = 100), alpha = alpha, beta = beta)

We histogram the root-volume-weighted noise distribution

>>> from fipy.variables.histogramVariable import HistogramVariable
>>> histogram = HistogramVariable(distribution = noise, dx = 0.01, nx = 100)

and compare to a Gaussian distribution

>>> from fipy.variables.cellVariable import CellVariable
>>> betadist = CellVariable(mesh = histogram.mesh)
>>> x = CellVariable(mesh=histogram.mesh, value=histogram.mesh.cellCenters[0])
>>> from scipy.special import gamma as Gamma 
>>> betadist = ((Gamma(alpha + beta) / (Gamma(alpha) * Gamma(beta)))
...             * x**(alpha - 1) * (1 - x)**(beta - 1)) 
>>> if __name__ == '__main__':
...     from fipy import Viewer
...     viewer = Viewer(vars=noise, datamin=0, datamax=1)
...     histoplot = Viewer(vars=(histogram, betadist),
...                        datamin=0, datamax=1.5)
>>> from fipy.tools.numerix import arange
>>> for a in arange(0.5, 5, 0.5):
...     alpha.value = a
...     for b in arange(0.5, 5, 0.5):
...         beta.value = b
...         if __name__ == '__main__':
...             import sys
...             print("alpha: %g, beta: %g" % (alpha, beta), file=sys.stderr)
...             viewer.plot()
...             histoplot.plot()
>>> print(abs(noise.faceGrad.divergence.cellVolumeAverage) < 5e-15)
1
random values with a beta distribution histogram of random values with a beta distribution
Parameters:
  • mesh (Mesh) – The mesh on which to define the noise.

  • alpha (float) – The parameter \alpha.

  • beta (float) – The parameter \beta.

__abs__()

Following test it to fix a bug with C inline string using abs() instead of fabs()

>>> print(abs(Variable(2.3) - Variable(1.2)))
1.1

Check representation works with different versions of numpy

>>> print(repr(abs(Variable(2.3))))
numerix.fabs(Variable(value=array(2.3)))
__add__(other)
__and__(other)

This test case has been added due to a weird bug that was appearing.

>>> a = Variable(value=(0, 0, 1, 1))
>>> b = Variable(value=(0, 1, 0, 1))
>>> print(numerix.equal((a == 0) & (b == 1), [False,  True, False, False]).all())
True
>>> print(a & b)
[0 0 0 1]
>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx=4)
>>> from fipy.variables.cellVariable import CellVariable
>>> a = CellVariable(value=(0, 0, 1, 1), mesh=mesh)
>>> b = CellVariable(value=(0, 1, 0, 1), mesh=mesh)
>>> print(numerix.allequal((a == 0) & (b == 1), [False,  True, False, False]))
True
>>> print(a & b)
[0 0 0 1]
__array__(t=None)

Attempt to convert the Variable to a numerix array object

>>> v = Variable(value=[2, 3])
>>> print(numerix.array(v))
[2 3]

A dimensional Variable will convert to the numeric value in its base units

>>> v = Variable(value=[2, 3], unit="mm")
>>> numerix.array(v)
array([ 0.002,  0.003])
__array_priority__ = 100.0
__array_wrap__(arr, context=None)

Required to prevent numpy not calling the reverse binary operations. Both the following tests are examples ufuncs.

>>> print(type(numerix.array([1.0, 2.0]) * Variable([1.0, 2.0]))) 
<class 'fipy.variables.binaryOperatorVariable...binOp'>
>>> from scipy.special import gamma as Gamma 
>>> print(type(Gamma(Variable([1.0, 2.0])))) 
<class 'fipy.variables.unaryOperatorVariable...unOp'>
__bool__()
>>> print(bool(Variable(value=0)))
0
>>> print(bool(Variable(value=(0, 0, 1, 1))))
Traceback (most recent call last):
    ...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
__call__(points=None, order=0, nearestCellIDs=None)

Interpolates the CellVariable to a set of points using a method that has a memory requirement on the order of Ncells by Npoints in general, but uses only Ncells when the CellVariable’s mesh is a UniformGrid object.

Tests

>>> from fipy import *
>>> m = Grid2D(nx=3, ny=2)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> print(v(((0., 1.1, 1.2), (0., 1., 1.))))
[ 0.5  1.5  1.5]
>>> print(v(((0., 1.1, 1.2), (0., 1., 1.)), order=1))
[ 0.25  1.1   1.2 ]
>>> m0 = Grid2D(nx=2, ny=2, dx=1., dy=1.)
>>> m1 = Grid2D(nx=4, ny=4, dx=.5, dy=.5)
>>> x, y = m0.cellCenters
>>> v0 = CellVariable(mesh=m0, value=x * y)
>>> print(v0(m1.cellCenters.globalValue))
[ 0.25  0.25  0.75  0.75  0.25  0.25  0.75  0.75  0.75  0.75  2.25  2.25
  0.75  0.75  2.25  2.25]
>>> print(v0(m1.cellCenters.globalValue, order=1))
[ 0.125  0.25   0.5    0.625  0.25   0.375  0.875  1.     0.5    0.875
  1.875  2.25   0.625  1.     2.25   2.625]
Parameters:
  • points (tuple or list of tuple) – A point or set of points in the format (X, Y, Z)

  • order ({0, 1}) – The order of interpolation, default is 0

  • nearestCellIDs (array_like) – Optional argument if user can calculate own nearest cell IDs array, shape should be same as points

__div__(other)
__eq__(other)

Test if a Variable is equal to another quantity

>>> a = Variable(value=3)
>>> b = (a == 4)
>>> b
(Variable(value=array(3)) == 4)
>>> b()
0
__float__()
__ge__(other)

Test if a Variable is greater than or equal to another quantity

>>> a = Variable(value=3)
>>> b = (a >= 4)
>>> b
(Variable(value=array(3)) >= 4)
>>> b()
0
>>> a.value = 4
>>> print(b())
1
>>> a.value = 5
>>> print(b())
1
__getitem__(index)

“Evaluate” the Variable and return the specified element

>>> a = Variable(value=((3., 4.), (5., 6.)), unit="m") + "4 m"
>>> print(a[1, 1])
10.0 m

It is an error to slice a Variable whose value is not sliceable

>>> Variable(value=3)[2]
Traceback (most recent call last):
      ...
IndexError: 0-d arrays can't be indexed
__getstate__()

Used internally to collect the necessary information to pickle the CellVariable to persistent storage.

__gt__(other)

Test if a Variable is greater than another quantity

>>> a = Variable(value=3)
>>> b = (a > 4)
>>> b
(Variable(value=array(3)) > 4)
>>> print(b())
0
>>> a.value = 5
>>> print(b())
1
__hash__()

Return hash(self).

__int__()
__invert__()

Returns logical “not” of the Variable

>>> a = Variable(value=True)
>>> print(~a)
False
__iter__()
__le__(other)

Test if a Variable is less than or equal to another quantity

>>> a = Variable(value=3)
>>> b = (a <= 4)
>>> b
(Variable(value=array(3)) <= 4)
>>> b()
1
>>> a.value = 4
>>> print(b())
1
>>> a.value = 5
>>> print(b())
0
__len__()
__lt__(other)

Test if a Variable is less than another quantity

>>> a = Variable(value=3)
>>> b = (a < 4)
>>> b
(Variable(value=array(3)) < 4)
>>> b()
1
>>> a.value = 4
>>> print(b())
0
>>> print(1000000000000000000 * Variable(1) < 1.)
0
>>> print(1000 * Variable(1) < 1.)
0

Python automatically reverses the arguments when necessary

>>> 4 > Variable(value=3)
(Variable(value=array(3)) < 4)
__mod__(other)
__mul__(other)
__ne__(other)

Test if a Variable is not equal to another quantity

>>> a = Variable(value=3)
>>> b = (a != 4)
>>> b
(Variable(value=array(3)) != 4)
>>> b()
1
__neg__()
static __new__(cls, *args, **kwds)
__nonzero__()
>>> print(bool(Variable(value=0)))
0
>>> print(bool(Variable(value=(0, 0, 1, 1))))
Traceback (most recent call last):
    ...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
__or__(other)

This test case has been added due to a weird bug that was appearing.

>>> a = Variable(value=(0, 0, 1, 1))
>>> b = Variable(value=(0, 1, 0, 1))
>>> print(numerix.equal((a == 0) | (b == 1), [True,  True, False, True]).all())
True
>>> print(a | b)
[0 1 1 1]
>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx=4)
>>> from fipy.variables.cellVariable import CellVariable
>>> a = CellVariable(value=(0, 0, 1, 1), mesh=mesh)
>>> b = CellVariable(value=(0, 1, 0, 1), mesh=mesh)
>>> print(numerix.allequal((a == 0) | (b == 1), [True,  True, False, True]))
True
>>> print(a | b)
[0 1 1 1]
__pos__()
__pow__(other)

return self**other, or self raised to power other

>>> print(Variable(1, "mol/l")**3)
1.0 mol**3/l**3
>>> print((Variable(1, "mol/l")**3).unit)
<PhysicalUnit mol**3/l**3>
__radd__(other)
__rdiv__(other)
__repr__()

Return repr(self).

__rmul__(other)
__rpow__(other)
__rsub__(other)
__rtruediv__(other)
__setitem__(index, value)
__setstate__(dict)

Used internally to create a new CellVariable from pickled persistent storage.

__str__()

Return str(self).

__sub__(other)
__truediv__(other)
all(axis=None)
>>> print(Variable(value=(0, 0, 1, 1)).all())
0
>>> print(Variable(value=(1, 1, 1, 1)).all())
1
allclose(other, rtol=1e-05, atol=1e-08)
>>> var = Variable((1, 1))
>>> print(var.allclose((1, 1)))
1
>>> print(var.allclose((1,)))
1

The following test is to check that the system does not run out of memory.

>>> from fipy.tools import numerix
>>> var = Variable(numerix.ones(10000))
>>> print(var.allclose(numerix.zeros(10000, 'l')))
False
allequal(other)
any(axis=None)
>>> print(Variable(value=0).any())
0
>>> print(Variable(value=(0, 0, 1, 1)).any())
1
property arithmeticFaceValue

Returns a FaceVariable whose value corresponds to the arithmetic interpolation of the adjacent cells:

\phi_f = (\phi_1 - \phi_2) \frac{d_{f2}}{d_{12}} + \phi_2

>>> from fipy.meshes import Grid1D
>>> from fipy import numerix
>>> mesh = Grid1D(dx = (1., 1.))
>>> L = 1
>>> R = 2
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (0.5 / 1.) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (2., 4.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (1.0 / 3.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (10., 100.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (5.0 / 55.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
cacheMe(recursive=False)
property cellVolumeAverage

Return the cell-volume-weighted average of the CellVariable:

<\phi>_\text{vol}
= \frac{\sum_\text{cells} \phi_\text{cell} V_\text{cell}}
    {\sum_\text{cells} V_\text{cell}}

>>> from fipy.meshes import Grid2D
>>> from fipy.variables.cellVariable import CellVariable
>>> mesh = Grid2D(nx = 3, ny = 1, dx = .5, dy = .1)
>>> var = CellVariable(value = (1, 2, 6), mesh = mesh)
>>> print(var.cellVolumeAverage)
3.0
constrain(value, where=None)

Constrains the CellVariable to value at a location specified by where.

>>> from fipy import *
>>> m = Grid1D(nx=3)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> v.constrain(0., where=m.facesLeft)
>>> v.faceGrad.constrain([1.], where=m.facesRight)
>>> print(v.faceGrad)
[[ 1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 0.   1.   2.   2.5]

Changing the constraint changes the dependencies

>>> v.constrain(1., where=m.facesLeft)
>>> print(v.faceGrad)
[[-1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 1.   1.   2.   2.5]

Constraints can be Variable

>>> c = Variable(0.)
>>> v.constrain(c, where=m.facesLeft)
>>> print(v.faceGrad)
[[ 1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 0.   1.   2.   2.5]
>>> c.value = 1.
>>> print(v.faceGrad)
[[-1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 1.   1.   2.   2.5]

Constraints can have a Variable mask.

>>> v = CellVariable(mesh=m)
>>> mask = FaceVariable(mesh=m, value=m.facesLeft)
>>> v.constrain(1., where=mask)
>>> print(v.faceValue)
[ 1.  0.  0.  0.]
>>> mask[:] = mask | m.facesRight
>>> print(v.faceValue)
[ 1.  0.  0.  1.]
property constraintMask

Test that constraintMask returns a Variable that updates itself whenever the constraints change.

>>> from fipy import *
>>> m = Grid2D(nx=2, ny=2)
>>> x, y = m.cellCenters
>>> v0 = CellVariable(mesh=m)
>>> v0.constrain(1., where=m.facesLeft)
>>> print(v0.faceValue.constraintMask)
[False False False False False False  True False False  True False False]
>>> print(v0.faceValue)
[ 0.  0.  0.  0.  0.  0.  1.  0.  0.  1.  0.  0.]
>>> v0.constrain(3., where=m.facesRight)
>>> print(v0.faceValue.constraintMask)
[False False False False False False  True False  True  True False  True]
>>> print(v0.faceValue)
[ 0.  0.  0.  0.  0.  0.  1.  0.  3.  1.  0.  3.]
>>> v1 = CellVariable(mesh=m)
>>> v1.constrain(1., where=(x < 1) & (y < 1))
>>> print(v1.constraintMask)
[ True False False False]
>>> print(v1)
[ 1.  0.  0.  0.]
>>> v1.constrain(3., where=(x > 1) & (y > 1))
>>> print(v1.constraintMask)
[ True False False  True]
>>> print(v1)
[ 1.  0.  0.  3.]
property constraints
copy()

Copy the value of the NoiseVariable to a static CellVariable.

dontCacheMe(recursive=False)
dot(other, opShape=None, operatorClass=None)

Return the mesh-element–by–mesh-element (cell-by-cell, face-by-face, etc.) scalar product

ext{self} \cdot         ext{other}

Both self and other can be of arbitrary rank, and other does not need to be a _MeshVariable.

property faceGrad

Return \nabla \phi as a rank-1 FaceVariable using differencing for the normal direction(second-order gradient).

property faceGradAverage

Deprecated since version 3.3: use grad.arithmeticFaceValue() instead

Return \nabla \phi as a rank-1 FaceVariable using averaging for the normal direction(second-order gradient)

property faceValue

Returns a FaceVariable whose value corresponds to the arithmetic interpolation of the adjacent cells:

\phi_f = (\phi_1 - \phi_2) \frac{d_{f2}}{d_{12}} + \phi_2

>>> from fipy.meshes import Grid1D
>>> from fipy import numerix
>>> mesh = Grid1D(dx = (1., 1.))
>>> L = 1
>>> R = 2
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (0.5 / 1.) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (2., 4.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (1.0 / 3.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (10., 100.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (5.0 / 55.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
property gaussGrad

Return \frac{1}{V_P} \sum_f \vec{n} \phi_f A_f as a rank-1 CellVariable (first-order gradient).

getsctype(default=None)

Returns the Numpy sctype of the underlying array.

>>> Variable(1).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1))
True
>>> Variable(1.).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1.))
True
>>> Variable((1, 1.)).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array((1., 1.)))
True
property globalValue

Concatenate and return values from all processors

When running on a single processor, the result is identical to value.

property grad

Return \nabla \phi as a rank-1 CellVariable (first-order gradient).

property harmonicFaceValue

Returns a FaceVariable whose value corresponds to the harmonic interpolation of the adjacent cells:

\phi_f = \frac{\phi_1 \phi_2}{(\phi_2 - \phi_1) \frac{d_{f2}}{d_{12}} + \phi_1}

>>> from fipy.meshes import Grid1D
>>> from fipy import numerix
>>> mesh = Grid1D(dx = (1., 1.))
>>> L = 1
>>> R = 2
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.harmonicFaceValue[mesh.interiorFaces.value]
>>> answer = L * R / ((R - L) * (0.5 / 1.) + L)
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (2., 4.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.harmonicFaceValue[mesh.interiorFaces.value]
>>> answer = L * R / ((R - L) * (1.0 / 3.0) + L)
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (10., 100.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.harmonicFaceValue[mesh.interiorFaces.value]
>>> answer = L * R / ((R - L) * (5.0 / 55.0) + L)
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
inBaseUnits()

Return the value of the Variable with all units reduced to their base SI elements.

>>> e = Variable(value="2.7 Hartree*Nav")
>>> print(e.inBaseUnits().allclose("7088849.01085 kg*m**2/s**2/mol"))
1
inUnitsOf(*units)

Returns one or more Variable objects that express the same physical quantity in different units. The units are specified by strings containing their names. The units must be compatible with the unit of the object. If one unit is specified, the return value is a single Variable.

>>> freeze = Variable('0 degC')
>>> print(freeze.inUnitsOf('degF').allclose("32.0 degF"))
1

If several units are specified, the return value is a tuple of Variable instances with with one element per unit such that the sum of all quantities in the tuple equals the the original quantity and all the values except for the last one are integers. This is used to convert to irregular unit systems like hour/minute/second. The original object will not be changed.

>>> t = Variable(value=314159., unit='s')
>>> from builtins import zip
>>> print(numerix.allclose([e.allclose(v) for (e, v) in zip(t.inUnitsOf('d', 'h', 'min', 's'),
...                                                         ['3.0 d', '15.0 h', '15.0 min', '59.0 s'])],
...                        True))
1
itemset(value)
property itemsize
property leastSquaresGrad

Return \nabla \phi, which is determined by solving for \nabla \phi in the following matrix equation,

\nabla \phi \cdot \sum_f d_{AP}^2 \vec{n}_{AP} \otimes \vec{n}_{AP} =
\sum_f d_{AP}^2 \left( \vec{n} \cdot \nabla \phi \right)_{AP}

The matrix equation is derived by minimizing the following least squares sum,

F \left( \phi_x, \phi_y \right) = \sqrt{\sum_f \left( d_{AP}
\vec{n}_{AP} \cdot \nabla \phi - d_{AP} \left( \vec{n}_{AP} \cdot
\nabla \phi \right)_{AP} \right)^2 }

Tests

>>> from fipy import Grid2D
>>> m = Grid2D(nx=2, ny=2, dx=0.1, dy=2.0)
>>> print(numerix.allclose(CellVariable(mesh=m, value=(0, 1, 3, 6)).leastSquaresGrad.globalValue, \
...                                     [[8.0, 8.0, 24.0, 24.0],
...                                      [1.2, 2.0, 1.2, 2.0]]))
True
>>> from fipy import Grid1D
>>> print(numerix.allclose(CellVariable(mesh=Grid1D(dx=(2.0, 1.0, 0.5)),
...                                     value=(0, 1, 2)).leastSquaresGrad.globalValue, [[0.461538461538, 0.8, 1.2]]))
True
property mag

The magnitude of the Variable, e.g., |\vec{\psi}| = \sqrt{\vec{\psi}\cdot\vec{\psi}}.

max(axis=None)
min(axis=None)
>>> from fipy import Grid2D, CellVariable
>>> mesh = Grid2D(nx=5, ny=5)
>>> x, y = mesh.cellCenters
>>> v = CellVariable(mesh=mesh, value=x*y)
>>> print(v.min())
0.25
property minmodFaceValue

Returns a FaceVariable with a value that is the minimum of the absolute values of the adjacent cells. If the values are of opposite sign then the result is zero:

\phi_f = \begin{cases}
               \phi_1& \text{when $|\phi_1| \le |\phi_2|$},\\
               \phi_2& \text{when $|\phi_2| < |\phi_1|$},\\
               0 & \text{when $\phi1 \phi2 < 0$}
         \end{cases}

>>> from fipy import *
>>> print(CellVariable(mesh=Grid1D(nx=2), value=(1, 2)).minmodFaceValue)
[1 1 2]
>>> print(CellVariable(mesh=Grid1D(nx=2), value=(-1, -2)).minmodFaceValue)
[-1 -1 -2]
>>> print(CellVariable(mesh=Grid1D(nx=2), value=(-1, 2)).minmodFaceValue)
[-1  0  2]
property name
property numericValue
property old

Return the values of the CellVariable from the previous solution sweep.

Combinations of CellVariable’s should also return old values.

>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx = 2)
>>> from fipy.variables.cellVariable import CellVariable
>>> var1 = CellVariable(mesh = mesh, value = (2, 3), hasOld = 1)
>>> var2 = CellVariable(mesh = mesh, value = (3, 4))
>>> v = var1 * var2
>>> print(v)
[ 6 12]
>>> var1.value = ((3, 2))
>>> print(v)
[9 8]
>>> print(v.old)
[ 6 12]

The following small test is to correct for a bug when the operator does not just use variables.

>>> v1 = var1 * 3
>>> print(v1)
[9 6]
>>> print(v1.old)
[6 9]
parallelRandom()
put(indices, value)
random()
property rank
ravel()
rdot(other, opShape=None, operatorClass=None)

Return the mesh-element–by–mesh-element (cell-by-cell, face-by-face, etc.) scalar product

ext{other} \cdot        ext{self}

Both self and other can be of arbitrary rank, and other does not need to be a _MeshVariable.

release(constraint)

Remove constraint from self

>>> from fipy import *
>>> m = Grid1D(nx=3)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> c = Constraint(0., where=m.facesLeft)
>>> v.constrain(c)
>>> print(v.faceValue)
[ 0.   1.   2.   2.5]
>>> v.release(constraint=c)
>>> print(v.faceValue)
[ 0.5  1.   2.   2.5]
scramble()

Generate a new random distribution.

setValue(value, unit=None, where=None)

Set the value of the Variable. Can take a masked array.

>>> a = Variable((1, 2, 3))
>>> a.setValue(5, where=(1, 0, 1))
>>> print(a)
[5 2 5]
>>> b = Variable((4, 5, 6))
>>> a.setValue(b, where=(1, 0, 1))
>>> print(a)
[4 2 6]
>>> print(b)
[4 5 6]
>>> a.value = 3
>>> print(a)
[3 3 3]
>>> b = numerix.array((3, 4, 5))
>>> a.value = b
>>> a[:] = 1
>>> print(b)
[3 4 5]
>>> a.setValue((4, 5, 6), where=(1, 0)) 
Traceback (most recent call last):
    ....
ValueError: shape mismatch: objects cannot be broadcast to a single shape
property shape
>>> from fipy.meshes import Grid2D
>>> from fipy.variables.cellVariable import CellVariable
>>> mesh = Grid2D(nx=2, ny=3)
>>> var = CellVariable(mesh=mesh)
>>> print(numerix.allequal(var.shape, (6,))) 
True
>>> print(numerix.allequal(var.arithmeticFaceValue.shape, (17,))) 
True
>>> print(numerix.allequal(var.grad.shape, (2, 6))) 
True
>>> print(numerix.allequal(var.faceGrad.shape, (2, 17))) 
True

Have to account for zero length arrays

>>> from fipy import Grid1D
>>> m = Grid1D(nx=0)
>>> v = CellVariable(mesh=m, elementshape=(2,))
>>> numerix.allequal((v * 1).shape, (2, 0))
True
std(axis=None, **kwargs)

Evaluate standard deviation of all the elements of a MeshVariable.

Adapted from http://mpitutorial.com/tutorials/mpi-reduce-and-allreduce/

>>> import fipy as fp
>>> mesh = fp.Grid2D(nx=2, ny=2, dx=2., dy=5.)
>>> var = fp.CellVariable(value=(1., 2., 3., 4.), mesh=mesh)
>>> print((var.std()**2).allclose(1.25))
True
property subscribedVariables
sum(axis=None)
take(ids, axis=0)
tostring(max_line_width=75, precision=8, suppress_small=False, separator=' ')
property unit

Return the unit object of self.

>>> Variable(value="1 m").unit
<PhysicalUnit m>
updateOld()

Set the values of the previous solution sweep to the current values.

>>> from fipy import *
>>> v = CellVariable(mesh=Grid1D(), hasOld=False)
>>> v.updateOld()
Traceback (most recent call last):
   ...
AssertionError: The updateOld method requires the CellVariable to have an old value. Set hasOld to True when instantiating the CellVariable.
property value

“Evaluate” the Variable and return its value (longhand)

>>> a = Variable(value=3)
>>> print(a.value)
3
>>> b = a + 4
>>> b
(Variable(value=array(3)) + 4)
>>> b.value
7
class fipy.CellVariable(*args, **kwds)

Bases: _MeshVariable

Represents the field of values of a variable on a Mesh.

A CellVariable can be pickled to persistent storage (disk) for later use:

>>> from fipy.meshes import Grid2D
>>> mesh = Grid2D(dx = 1., dy = 1., nx = 10, ny = 10)
>>> var = CellVariable(mesh = mesh, value = 1., hasOld = 1, name = 'test')
>>> x, y = mesh.cellCenters
>>> var.value = (x * y)
>>> from fipy.tools import dump
>>> (f, filename) = dump.write(var, extension = '.gz')
>>> unPickledVar = dump.read(filename, f)
>>> print(var.allclose(unPickledVar, atol = 1e-10, rtol = 1e-10))
1
Parameters:
  • mesh (Mesh) – the mesh that defines the geometry of this Variable

  • name (str) – the user-readable name of the Variable

  • value (float or array_like) – the initial value

  • rank (int) – the rank (number of dimensions) of each element of this Variable. Default: 0

  • elementshape (tuple of int) – the shape of each element of this variable Default: rank * (mesh.dim,)

  • unit (str or PhysicalUnit) – The physical units of the variable

__abs__()

Following test it to fix a bug with C inline string using abs() instead of fabs()

>>> print(abs(Variable(2.3) - Variable(1.2)))
1.1

Check representation works with different versions of numpy

>>> print(repr(abs(Variable(2.3))))
numerix.fabs(Variable(value=array(2.3)))
__add__(other)
__and__(other)

This test case has been added due to a weird bug that was appearing.

>>> a = Variable(value=(0, 0, 1, 1))
>>> b = Variable(value=(0, 1, 0, 1))
>>> print(numerix.equal((a == 0) & (b == 1), [False,  True, False, False]).all())
True
>>> print(a & b)
[0 0 0 1]
>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx=4)
>>> from fipy.variables.cellVariable import CellVariable
>>> a = CellVariable(value=(0, 0, 1, 1), mesh=mesh)
>>> b = CellVariable(value=(0, 1, 0, 1), mesh=mesh)
>>> print(numerix.allequal((a == 0) & (b == 1), [False,  True, False, False]))
True
>>> print(a & b)
[0 0 0 1]
__array__(t=None)

Attempt to convert the Variable to a numerix array object

>>> v = Variable(value=[2, 3])
>>> print(numerix.array(v))
[2 3]

A dimensional Variable will convert to the numeric value in its base units

>>> v = Variable(value=[2, 3], unit="mm")
>>> numerix.array(v)
array([ 0.002,  0.003])
__array_priority__ = 100.0
__array_wrap__(arr, context=None)

Required to prevent numpy not calling the reverse binary operations. Both the following tests are examples ufuncs.

>>> print(type(numerix.array([1.0, 2.0]) * Variable([1.0, 2.0]))) 
<class 'fipy.variables.binaryOperatorVariable...binOp'>
>>> from scipy.special import gamma as Gamma 
>>> print(type(Gamma(Variable([1.0, 2.0])))) 
<class 'fipy.variables.unaryOperatorVariable...unOp'>
__bool__()
>>> print(bool(Variable(value=0)))
0
>>> print(bool(Variable(value=(0, 0, 1, 1))))
Traceback (most recent call last):
    ...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
__call__(points=None, order=0, nearestCellIDs=None)

Interpolates the CellVariable to a set of points using a method that has a memory requirement on the order of Ncells by Npoints in general, but uses only Ncells when the CellVariable’s mesh is a UniformGrid object.

Tests

>>> from fipy import *
>>> m = Grid2D(nx=3, ny=2)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> print(v(((0., 1.1, 1.2), (0., 1., 1.))))
[ 0.5  1.5  1.5]
>>> print(v(((0., 1.1, 1.2), (0., 1., 1.)), order=1))
[ 0.25  1.1   1.2 ]
>>> m0 = Grid2D(nx=2, ny=2, dx=1., dy=1.)
>>> m1 = Grid2D(nx=4, ny=4, dx=.5, dy=.5)
>>> x, y = m0.cellCenters
>>> v0 = CellVariable(mesh=m0, value=x * y)
>>> print(v0(m1.cellCenters.globalValue))
[ 0.25  0.25  0.75  0.75  0.25  0.25  0.75  0.75  0.75  0.75  2.25  2.25
  0.75  0.75  2.25  2.25]
>>> print(v0(m1.cellCenters.globalValue, order=1))
[ 0.125  0.25   0.5    0.625  0.25   0.375  0.875  1.     0.5    0.875
  1.875  2.25   0.625  1.     2.25   2.625]
Parameters:
  • points (tuple or list of tuple) – A point or set of points in the format (X, Y, Z)

  • order ({0, 1}) – The order of interpolation, default is 0

  • nearestCellIDs (array_like) – Optional argument if user can calculate own nearest cell IDs array, shape should be same as points

__div__(other)
__eq__(other)

Test if a Variable is equal to another quantity

>>> a = Variable(value=3)
>>> b = (a == 4)
>>> b
(Variable(value=array(3)) == 4)
>>> b()
0
__float__()
__ge__(other)

Test if a Variable is greater than or equal to another quantity

>>> a = Variable(value=3)
>>> b = (a >= 4)
>>> b
(Variable(value=array(3)) >= 4)
>>> b()
0
>>> a.value = 4
>>> print(b())
1
>>> a.value = 5
>>> print(b())
1
__getitem__(index)

“Evaluate” the Variable and return the specified element

>>> a = Variable(value=((3., 4.), (5., 6.)), unit="m") + "4 m"
>>> print(a[1, 1])
10.0 m

It is an error to slice a Variable whose value is not sliceable

>>> Variable(value=3)[2]
Traceback (most recent call last):
      ...
IndexError: 0-d arrays can't be indexed
__getstate__()

Used internally to collect the necessary information to pickle the CellVariable to persistent storage.

__gt__(other)

Test if a Variable is greater than another quantity

>>> a = Variable(value=3)
>>> b = (a > 4)
>>> b
(Variable(value=array(3)) > 4)
>>> print(b())
0
>>> a.value = 5
>>> print(b())
1
__hash__()

Return hash(self).

__int__()
__invert__()

Returns logical “not” of the Variable

>>> a = Variable(value=True)
>>> print(~a)
False
__iter__()
__le__(other)

Test if a Variable is less than or equal to another quantity

>>> a = Variable(value=3)
>>> b = (a <= 4)
>>> b
(Variable(value=array(3)) <= 4)
>>> b()
1
>>> a.value = 4
>>> print(b())
1
>>> a.value = 5
>>> print(b())
0
__len__()
__lt__(other)

Test if a Variable is less than another quantity

>>> a = Variable(value=3)
>>> b = (a < 4)
>>> b
(Variable(value=array(3)) < 4)
>>> b()
1
>>> a.value = 4
>>> print(b())
0
>>> print(1000000000000000000 * Variable(1) < 1.)
0
>>> print(1000 * Variable(1) < 1.)
0

Python automatically reverses the arguments when necessary

>>> 4 > Variable(value=3)
(Variable(value=array(3)) < 4)
__mod__(other)
__mul__(other)
__ne__(other)

Test if a Variable is not equal to another quantity

>>> a = Variable(value=3)
>>> b = (a != 4)
>>> b
(Variable(value=array(3)) != 4)
>>> b()
1
__neg__()
static __new__(cls, *args, **kwds)
__nonzero__()
>>> print(bool(Variable(value=0)))
0
>>> print(bool(Variable(value=(0, 0, 1, 1))))
Traceback (most recent call last):
    ...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
__or__(other)

This test case has been added due to a weird bug that was appearing.

>>> a = Variable(value=(0, 0, 1, 1))
>>> b = Variable(value=(0, 1, 0, 1))
>>> print(numerix.equal((a == 0) | (b == 1), [True,  True, False, True]).all())
True
>>> print(a | b)
[0 1 1 1]
>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx=4)
>>> from fipy.variables.cellVariable import CellVariable
>>> a = CellVariable(value=(0, 0, 1, 1), mesh=mesh)
>>> b = CellVariable(value=(0, 1, 0, 1), mesh=mesh)
>>> print(numerix.allequal((a == 0) | (b == 1), [True,  True, False, True]))
True
>>> print(a | b)
[0 1 1 1]
__pos__()
__pow__(other)

return self**other, or self raised to power other

>>> print(Variable(1, "mol/l")**3)
1.0 mol**3/l**3
>>> print((Variable(1, "mol/l")**3).unit)
<PhysicalUnit mol**3/l**3>
__radd__(other)
__rdiv__(other)
__repr__()

Return repr(self).

__rmul__(other)
__rpow__(other)
__rsub__(other)
__rtruediv__(other)
__setitem__(index, value)
__setstate__(dict)

Used internally to create a new CellVariable from pickled persistent storage.

__str__()

Return str(self).

__sub__(other)
__truediv__(other)
all(axis=None)
>>> print(Variable(value=(0, 0, 1, 1)).all())
0
>>> print(Variable(value=(1, 1, 1, 1)).all())
1
allclose(other, rtol=1e-05, atol=1e-08)
>>> var = Variable((1, 1))
>>> print(var.allclose((1, 1)))
1
>>> print(var.allclose((1,)))
1

The following test is to check that the system does not run out of memory.

>>> from fipy.tools import numerix
>>> var = Variable(numerix.ones(10000))
>>> print(var.allclose(numerix.zeros(10000, 'l')))
False
allequal(other)
any(axis=None)
>>> print(Variable(value=0).any())
0
>>> print(Variable(value=(0, 0, 1, 1)).any())
1
property arithmeticFaceValue

Returns a FaceVariable whose value corresponds to the arithmetic interpolation of the adjacent cells:

\phi_f = (\phi_1 - \phi_2) \frac{d_{f2}}{d_{12}} + \phi_2

>>> from fipy.meshes import Grid1D
>>> from fipy import numerix
>>> mesh = Grid1D(dx = (1., 1.))
>>> L = 1
>>> R = 2
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (0.5 / 1.) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (2., 4.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (1.0 / 3.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (10., 100.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (5.0 / 55.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
cacheMe(recursive=False)
property cellVolumeAverage

Return the cell-volume-weighted average of the CellVariable:

<\phi>_\text{vol}
= \frac{\sum_\text{cells} \phi_\text{cell} V_\text{cell}}
    {\sum_\text{cells} V_\text{cell}}

>>> from fipy.meshes import Grid2D
>>> from fipy.variables.cellVariable import CellVariable
>>> mesh = Grid2D(nx = 3, ny = 1, dx = .5, dy = .1)
>>> var = CellVariable(value = (1, 2, 6), mesh = mesh)
>>> print(var.cellVolumeAverage)
3.0
constrain(value, where=None)

Constrains the CellVariable to value at a location specified by where.

>>> from fipy import *
>>> m = Grid1D(nx=3)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> v.constrain(0., where=m.facesLeft)
>>> v.faceGrad.constrain([1.], where=m.facesRight)
>>> print(v.faceGrad)
[[ 1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 0.   1.   2.   2.5]

Changing the constraint changes the dependencies

>>> v.constrain(1., where=m.facesLeft)
>>> print(v.faceGrad)
[[-1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 1.   1.   2.   2.5]

Constraints can be Variable

>>> c = Variable(0.)
>>> v.constrain(c, where=m.facesLeft)
>>> print(v.faceGrad)
[[ 1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 0.   1.   2.   2.5]
>>> c.value = 1.
>>> print(v.faceGrad)
[[-1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 1.   1.   2.   2.5]

Constraints can have a Variable mask.

>>> v = CellVariable(mesh=m)
>>> mask = FaceVariable(mesh=m, value=m.facesLeft)
>>> v.constrain(1., where=mask)
>>> print(v.faceValue)
[ 1.  0.  0.  0.]
>>> mask[:] = mask | m.facesRight
>>> print(v.faceValue)
[ 1.  0.  0.  1.]
property constraintMask

Test that constraintMask returns a Variable that updates itself whenever the constraints change.

>>> from fipy import *
>>> m = Grid2D(nx=2, ny=2)
>>> x, y = m.cellCenters
>>> v0 = CellVariable(mesh=m)
>>> v0.constrain(1., where=m.facesLeft)
>>> print(v0.faceValue.constraintMask)
[False False False False False False  True False False  True False False]
>>> print(v0.faceValue)
[ 0.  0.  0.  0.  0.  0.  1.  0.  0.  1.  0.  0.]
>>> v0.constrain(3., where=m.facesRight)
>>> print(v0.faceValue.constraintMask)
[False False False False False False  True False  True  True False  True]
>>> print(v0.faceValue)
[ 0.  0.  0.  0.  0.  0.  1.  0.  3.  1.  0.  3.]
>>> v1 = CellVariable(mesh=m)
>>> v1.constrain(1., where=(x < 1) & (y < 1))
>>> print(v1.constraintMask)
[ True False False False]
>>> print(v1)
[ 1.  0.  0.  0.]
>>> v1.constrain(3., where=(x > 1) & (y > 1))
>>> print(v1.constraintMask)
[ True False False  True]
>>> print(v1)
[ 1.  0.  0.  3.]
property constraints
copy()

Make an duplicate of the Variable

>>> a = Variable(value=3)
>>> b = a.copy()
>>> b
Variable(value=array(3))

The duplicate will not reflect changes made to the original

>>> a.setValue(5)
>>> b
Variable(value=array(3))

Check that this works for arrays.

>>> a = Variable(value=numerix.array((0, 1, 2)))
>>> b = a.copy()
>>> b
Variable(value=array([0, 1, 2]))
>>> a[1] = 3
>>> b
Variable(value=array([0, 1, 2]))
dontCacheMe(recursive=False)
dot(other, opShape=None, operatorClass=None)

Return the mesh-element–by–mesh-element (cell-by-cell, face-by-face, etc.) scalar product

ext{self} \cdot         ext{other}

Both self and other can be of arbitrary rank, and other does not need to be a _MeshVariable.

property faceGrad

Return \nabla \phi as a rank-1 FaceVariable using differencing for the normal direction(second-order gradient).

property faceGradAverage

Deprecated since version 3.3: use grad.arithmeticFaceValue() instead

Return \nabla \phi as a rank-1 FaceVariable using averaging for the normal direction(second-order gradient)

property faceValue

Returns a FaceVariable whose value corresponds to the arithmetic interpolation of the adjacent cells:

\phi_f = (\phi_1 - \phi_2) \frac{d_{f2}}{d_{12}} + \phi_2

>>> from fipy.meshes import Grid1D
>>> from fipy import numerix
>>> mesh = Grid1D(dx = (1., 1.))
>>> L = 1
>>> R = 2
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (0.5 / 1.) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (2., 4.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (1.0 / 3.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (10., 100.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (5.0 / 55.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
property gaussGrad

Return \frac{1}{V_P} \sum_f \vec{n} \phi_f A_f as a rank-1 CellVariable (first-order gradient).

getsctype(default=None)

Returns the Numpy sctype of the underlying array.

>>> Variable(1).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1))
True
>>> Variable(1.).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1.))
True
>>> Variable((1, 1.)).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array((1., 1.)))
True
property globalValue

Concatenate and return values from all processors

When running on a single processor, the result is identical to value.

property grad

Return \nabla \phi as a rank-1 CellVariable (first-order gradient).

property harmonicFaceValue

Returns a FaceVariable whose value corresponds to the harmonic interpolation of the adjacent cells:

\phi_f = \frac{\phi_1 \phi_2}{(\phi_2 - \phi_1) \frac{d_{f2}}{d_{12}} + \phi_1}

>>> from fipy.meshes import Grid1D
>>> from fipy import numerix
>>> mesh = Grid1D(dx = (1., 1.))
>>> L = 1
>>> R = 2
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.harmonicFaceValue[mesh.interiorFaces.value]
>>> answer = L * R / ((R - L) * (0.5 / 1.) + L)
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (2., 4.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.harmonicFaceValue[mesh.interiorFaces.value]
>>> answer = L * R / ((R - L) * (1.0 / 3.0) + L)
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (10., 100.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.harmonicFaceValue[mesh.interiorFaces.value]
>>> answer = L * R / ((R - L) * (5.0 / 55.0) + L)
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
inBaseUnits()

Return the value of the Variable with all units reduced to their base SI elements.

>>> e = Variable(value="2.7 Hartree*Nav")
>>> print(e.inBaseUnits().allclose("7088849.01085 kg*m**2/s**2/mol"))
1
inUnitsOf(*units)

Returns one or more Variable objects that express the same physical quantity in different units. The units are specified by strings containing their names. The units must be compatible with the unit of the object. If one unit is specified, the return value is a single Variable.

>>> freeze = Variable('0 degC')
>>> print(freeze.inUnitsOf('degF').allclose("32.0 degF"))
1

If several units are specified, the return value is a tuple of Variable instances with with one element per unit such that the sum of all quantities in the tuple equals the the original quantity and all the values except for the last one are integers. This is used to convert to irregular unit systems like hour/minute/second. The original object will not be changed.

>>> t = Variable(value=314159., unit='s')
>>> from builtins import zip
>>> print(numerix.allclose([e.allclose(v) for (e, v) in zip(t.inUnitsOf('d', 'h', 'min', 's'),
...                                                         ['3.0 d', '15.0 h', '15.0 min', '59.0 s'])],
...                        True))
1
itemset(value)
property itemsize
property leastSquaresGrad

Return \nabla \phi, which is determined by solving for \nabla \phi in the following matrix equation,

\nabla \phi \cdot \sum_f d_{AP}^2 \vec{n}_{AP} \otimes \vec{n}_{AP} =
\sum_f d_{AP}^2 \left( \vec{n} \cdot \nabla \phi \right)_{AP}

The matrix equation is derived by minimizing the following least squares sum,

F \left( \phi_x, \phi_y \right) = \sqrt{\sum_f \left( d_{AP}
\vec{n}_{AP} \cdot \nabla \phi - d_{AP} \left( \vec{n}_{AP} \cdot
\nabla \phi \right)_{AP} \right)^2 }

Tests

>>> from fipy import Grid2D
>>> m = Grid2D(nx=2, ny=2, dx=0.1, dy=2.0)
>>> print(numerix.allclose(CellVariable(mesh=m, value=(0, 1, 3, 6)).leastSquaresGrad.globalValue, \
...                                     [[8.0, 8.0, 24.0, 24.0],
...                                      [1.2, 2.0, 1.2, 2.0]]))
True
>>> from fipy import Grid1D
>>> print(numerix.allclose(CellVariable(mesh=Grid1D(dx=(2.0, 1.0, 0.5)),
...                                     value=(0, 1, 2)).leastSquaresGrad.globalValue, [[0.461538461538, 0.8, 1.2]]))
True
property mag

The magnitude of the Variable, e.g., |\vec{\psi}| = \sqrt{\vec{\psi}\cdot\vec{\psi}}.

max(axis=None)
min(axis=None)
>>> from fipy import Grid2D, CellVariable
>>> mesh = Grid2D(nx=5, ny=5)
>>> x, y = mesh.cellCenters
>>> v = CellVariable(mesh=mesh, value=x*y)
>>> print(v.min())
0.25
property minmodFaceValue

Returns a FaceVariable with a value that is the minimum of the absolute values of the adjacent cells. If the values are of opposite sign then the result is zero:

\phi_f = \begin{cases}
               \phi_1& \text{when $|\phi_1| \le |\phi_2|$},\\
               \phi_2& \text{when $|\phi_2| < |\phi_1|$},\\
               0 & \text{when $\phi1 \phi2 < 0$}
         \end{cases}

>>> from fipy import *
>>> print(CellVariable(mesh=Grid1D(nx=2), value=(1, 2)).minmodFaceValue)
[1 1 2]
>>> print(CellVariable(mesh=Grid1D(nx=2), value=(-1, -2)).minmodFaceValue)
[-1 -1 -2]
>>> print(CellVariable(mesh=Grid1D(nx=2), value=(-1, 2)).minmodFaceValue)
[-1  0  2]
property name
property numericValue
property old

Return the values of the CellVariable from the previous solution sweep.

Combinations of CellVariable’s should also return old values.

>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx = 2)
>>> from fipy.variables.cellVariable import CellVariable
>>> var1 = CellVariable(mesh = mesh, value = (2, 3), hasOld = 1)
>>> var2 = CellVariable(mesh = mesh, value = (3, 4))
>>> v = var1 * var2
>>> print(v)
[ 6 12]
>>> var1.value = ((3, 2))
>>> print(v)
[9 8]
>>> print(v.old)
[ 6 12]

The following small test is to correct for a bug when the operator does not just use variables.

>>> v1 = var1 * 3
>>> print(v1)
[9 6]
>>> print(v1.old)
[6 9]
put(indices, value)
property rank
ravel()
rdot(other, opShape=None, operatorClass=None)

Return the mesh-element–by–mesh-element (cell-by-cell, face-by-face, etc.) scalar product

ext{other} \cdot        ext{self}

Both self and other can be of arbitrary rank, and other does not need to be a _MeshVariable.

release(constraint)

Remove constraint from self

>>> from fipy import *
>>> m = Grid1D(nx=3)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> c = Constraint(0., where=m.facesLeft)
>>> v.constrain(c)
>>> print(v.faceValue)
[ 0.   1.   2.   2.5]
>>> v.release(constraint=c)
>>> print(v.faceValue)
[ 0.5  1.   2.   2.5]
setValue(value, unit=None, where=None)

Set the value of the Variable. Can take a masked array.

>>> a = Variable((1, 2, 3))
>>> a.setValue(5, where=(1, 0, 1))
>>> print(a)
[5 2 5]
>>> b = Variable((4, 5, 6))
>>> a.setValue(b, where=(1, 0, 1))
>>> print(a)
[4 2 6]
>>> print(b)
[4 5 6]
>>> a.value = 3
>>> print(a)
[3 3 3]
>>> b = numerix.array((3, 4, 5))
>>> a.value = b
>>> a[:] = 1
>>> print(b)
[3 4 5]
>>> a.setValue((4, 5, 6), where=(1, 0)) 
Traceback (most recent call last):
    ....
ValueError: shape mismatch: objects cannot be broadcast to a single shape
property shape
>>> from fipy.meshes import Grid2D
>>> from fipy.variables.cellVariable import CellVariable
>>> mesh = Grid2D(nx=2, ny=3)
>>> var = CellVariable(mesh=mesh)
>>> print(numerix.allequal(var.shape, (6,))) 
True
>>> print(numerix.allequal(var.arithmeticFaceValue.shape, (17,))) 
True
>>> print(numerix.allequal(var.grad.shape, (2, 6))) 
True
>>> print(numerix.allequal(var.faceGrad.shape, (2, 17))) 
True

Have to account for zero length arrays

>>> from fipy import Grid1D
>>> m = Grid1D(nx=0)
>>> v = CellVariable(mesh=m, elementshape=(2,))
>>> numerix.allequal((v * 1).shape, (2, 0))
True
std(axis=None, **kwargs)

Evaluate standard deviation of all the elements of a MeshVariable.

Adapted from http://mpitutorial.com/tutorials/mpi-reduce-and-allreduce/

>>> import fipy as fp
>>> mesh = fp.Grid2D(nx=2, ny=2, dx=2., dy=5.)
>>> var = fp.CellVariable(value=(1., 2., 3., 4.), mesh=mesh)
>>> print((var.std()**2).allclose(1.25))
True
property subscribedVariables
sum(axis=None)
take(ids, axis=0)
tostring(max_line_width=75, precision=8, suppress_small=False, separator=' ')
property unit

Return the unit object of self.

>>> Variable(value="1 m").unit
<PhysicalUnit m>
updateOld()

Set the values of the previous solution sweep to the current values.

>>> from fipy import *
>>> v = CellVariable(mesh=Grid1D(), hasOld=False)
>>> v.updateOld()
Traceback (most recent call last):
   ...
AssertionError: The updateOld method requires the CellVariable to have an old value. Set hasOld to True when instantiating the CellVariable.
property value

“Evaluate” the Variable and return its value (longhand)

>>> a = Variable(value=3)
>>> print(a.value)
3
>>> b = a + 4
>>> b
(Variable(value=array(3)) + 4)
>>> b.value
7
class fipy.CentralDifferenceConvectionTerm(coeff=1.0, var=None)

Bases: _AbstractConvectionTerm

This Term represents

\int_V \nabla \cdot (\vec{u} \phi)\,dV \simeq \sum_{f} (\vec{n}
\cdot \vec{u})_f \phi_f A_f

where \phi_f=\alpha_f \phi_P +(1-\alpha_f)\phi_A and \alpha_f is calculated using the central differencing scheme. For further details see Numerical Schemes.

Create a _AbstractConvectionTerm object.

>>> from fipy import *
>>> m = Grid1D(nx = 2)
>>> cv = CellVariable(mesh = m)
>>> fv = FaceVariable(mesh = m)
>>> vcv = CellVariable(mesh=m, rank=1)
>>> vfv = FaceVariable(mesh=m, rank=1)
>>> __ConvectionTerm(coeff = cv) 
Traceback (most recent call last):
    ...
VectorCoeffError: The coefficient must be a vector value.
>>> __ConvectionTerm(coeff = fv) 
Traceback (most recent call last):
    ...
VectorCoeffError: The coefficient must be a vector value.
>>> __ConvectionTerm(coeff = vcv)
__ConvectionTerm(coeff=_ArithmeticCellToFaceVariable(value=array([[ 0.,  0.,  0.]]), mesh=UniformGrid1D(dx=1.0, nx=2)))
>>> __ConvectionTerm(coeff = vfv)
__ConvectionTerm(coeff=FaceVariable(value=array([[ 0.,  0.,  0.]]), mesh=UniformGrid1D(dx=1.0, nx=2)))
>>> __ConvectionTerm(coeff = (1,))
__ConvectionTerm(coeff=(1,))
>>> ExplicitUpwindConvectionTerm(coeff = (0,)).solve(var=cv, solver=DummySolver()) 
Traceback (most recent call last):
    ...
TransientTermError: The equation requires a TransientTerm with explicit convection.
>>> (TransientTerm(0.) - ExplicitUpwindConvectionTerm(coeff = (0,))).solve(var=cv, solver=DummySolver(), dt=1.)
>>> (TransientTerm() - ExplicitUpwindConvectionTerm(coeff = 1)).solve(var=cv, solver=DummySolver(), dt=1.) 
Traceback (most recent call last):
    ...
VectorCoeffError: The coefficient must be a vector value.
>>> m2 = Grid2D(nx=2, ny=1)
>>> cv2 = CellVariable(mesh=m2)
>>> vcv2 = CellVariable(mesh=m2, rank=1)
>>> vfv2 = FaceVariable(mesh=m2, rank=1)
>>> __ConvectionTerm(coeff=vcv2)
__ConvectionTerm(coeff=_ArithmeticCellToFaceVariable(value=array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]]), mesh=UniformGrid2D(dx=1.0, nx=2, dy=1.0, ny=1)))
>>> __ConvectionTerm(coeff=vfv2)
__ConvectionTerm(coeff=FaceVariable(value=array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]]), mesh=UniformGrid2D(dx=1.0, nx=2, dy=1.0, ny=1)))
>>> (TransientTerm() - ExplicitUpwindConvectionTerm(coeff = ((0,), (0,)))).solve(var=cv2, solver=DummySolver(), dt=1.)
>>> (TransientTerm() - ExplicitUpwindConvectionTerm(coeff = (0, 0))).solve(var=cv2, solver=DummySolver(), dt=1.)
Parameters:

coeff (The Term’s coefficient value.) –

property RHSvector

Return the RHS vector calculated in solve() or sweep(). The cacheRHSvector() method should be called before solve() or sweep() to cache the vector.

__add__(other)
__and__(other)
__div__(other)
__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__mul__(other)

Multiply a term

>>> 2. * __NonDiffusionTerm(coeff=0.5)
__NonDiffusionTerm(coeff=1.0)

Test for ticket:291.

>>> from fipy import PowerLawConvectionTerm
>>> PowerLawConvectionTerm(coeff=[[1], [0]]) * 1.0
PowerLawConvectionTerm(coeff=array([[ 1.],
       [ 0.]]))
__neg__()

Negate a Term.

>>> -__NonDiffusionTerm(coeff=1.)
__NonDiffusionTerm(coeff=-1.0)
__pos__()
__radd__(other)
__rand__(other)
__repr__()

The representation of a Term object is given by,

>>> print(__UnaryTerm(123.456))
__UnaryTerm(coeff=123.456)
__rmul__(other)

Multiply a term

>>> 2. * __NonDiffusionTerm(coeff=0.5)
__NonDiffusionTerm(coeff=1.0)

Test for ticket:291.

>>> from fipy import PowerLawConvectionTerm
>>> PowerLawConvectionTerm(coeff=[[1], [0]]) * 1.0
PowerLawConvectionTerm(coeff=array([[ 1.],
       [ 0.]]))
__rsub__(other)
__sub__(other)
__truediv__(other)
cacheMatrix()

Informs solve() and sweep() to cache their matrix so that matrix can return the matrix.

cacheRHSvector()

Informs solve() and sweep() to cache their right hand side vector so that getRHSvector() can return it.

copy()
getDefaultSolver(var=None, solver=None, *args, **kwargs)
justErrorVector(var=None, solver=None, boundaryConditions=(), dt=1.0, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the error as well as applying under-relaxation.

justErrorVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy.solvers import DummySolver
>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(DiffusionTerm().justErrorVector(v, solver=DummySolver())) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

error – The residual vector \vec{e}=\mathsf{L}\vec{x}_\text{old} - \vec{b}

Return type:

CellVariable

justResidualVector(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

justResidualVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(numerix.asarray(DiffusionTerm().justResidualVector(v))) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

property matrix

Return the matrix calculated in solve() or sweep(). The cacheMatrix() method should be called before solve() or sweep() to cache the matrix.

residualVectorAndNorm(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

  • residual (~fipy.variables.cellVariable.CellVariable) – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

  • norm (float) – The L2 norm of residual, \|\vec{r}\|_2

solve(var=None, solver=None, boundaryConditions=(), dt=None)

Builds and solves the Term’s linear system once. This method does not return the residual. It should be used when the residual is not required.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

sweep(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None, cacheResidual=False, cacheError=False)

Builds and solves the Term’s linear system once. This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

  • cacheResidual (bool) – If True, calculate and store the residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b} in the residualVector member of Term

  • cacheError (bool) – If True, use the residual vector \vec{r} to solve \mathsf{L}\vec{e}=\vec{r} for the error vector \vec{e} and store it in the errorVector member of Term

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

class fipy.Constraint(value, where=None)

Bases: object

Object to hold a Variable to value at where

see constrain()

__repr__()

Return repr(self).

fipy.ConvectionTerm

alias of PowerLawConvectionTerm

fipy.CylindricalGrid1D(dr=None, nr=None, Lr=None, dx=1.0, nx=None, Lx=None, origin=(0,), overlap=2, communicator=SerialPETScCommWrapper())

Create a 2D cylindrical mesh

Factory function to select between CylindricalUniformGrid1D and CylindricalNonUniformGrid1D. If Lr is specified the length of the domain is always Lr regardless of dr, unless dr is a list of spacings, in which case Lr will be the sum of dr.

Parameters:
  • dr (float) – Grid spacing in the radial direction. Alternative: dx.

  • nr (int) – Number of cells in the radial direction. Alternative: nx.

  • Lr (float) – Domain length in the radial direction. Alternative: Lx.

  • overlap (int) – the number of overlapping cells for parallel simulations. Generally 2 is adequate. Higher order equations or discretizations require more.

  • communicator (CommWrapper) – MPI communicator to use. Select serialComm to create a serial mesh when running in parallel; mostly used for test purposes. (default: parallelComm).

fipy.CylindricalGrid2D(dr=None, dz=None, nr=None, nz=None, Lr=None, Lz=None, dx=1.0, dy=1.0, nx=None, ny=None, Lx=None, Ly=None, origin=((0,), (0,)), overlap=2, communicator=SerialPETScCommWrapper())

Create a 2D cylindrical mesh

Factory function to select between CylindricalUniformGrid2D and CylindricalNonUniformGrid2D. If Lr is specified the length of the domain is always Lr regardless of dr, unless dr is a list of spacings, in which case Lr will be the sum of dr.

Parameters:
  • dr (float) – Grid spacing in the radial direction. Alternative: dx.

  • dz (float) – grid spacing in the vertical direction. Alternative: dy.

  • nr (int) – Number of cells in the radial direction. Alternative: nx.

  • nz (int) – Number of cells in the vertical direction. Alternative: ny.

  • Lr (float) – Domain length in the radial direction. Alternative: Lx.

  • Lz (float) – Domain length in the vertical direction. Alternative: Ly.

  • overlap (int) – the number of overlapping cells for parallel simulations. Generally 2 is adequate. Higher order equations or discretizations require more.

  • communicator (CommWrapper) – MPI communicator to use. Select serialComm to create a serial mesh when running in parallel; mostly used for test purposes. (default: parallelComm).

fipy.DefaultAsymmetricSolver

alias of LinearGMRESSolver

fipy.DefaultSolver

alias of LinearGMRESSolver

class fipy.DiffusionTerm(coeff=(1.0,), var=None)

Bases: DiffusionTermNoCorrection

This term represents a higher order diffusion term. The order of the term is determined by the number of coeffs, such that:

DiffusionTerm(D1)

represents a typical 2nd-order diffusion term of the form

\nabla\cdot\left(D_1 \nabla \phi\right)

and:

DiffusionTerm((D1,D2))

represents a 4th-order Cahn-Hilliard term of the form

\nabla \cdot \left\{ D_1 \nabla \left[ \nabla\cdot\left( D_2 \nabla \phi\right) \right] \right\}

and so on.

Create a Term.

Parameters:

coeff (float or CellVariable or FaceVariable) – Coefficient for the term. FaceVariable objects are only acceptable for diffusion or convection terms.

property RHSvector

Return the RHS vector calculated in solve() or sweep(). The cacheRHSvector() method should be called before solve() or sweep() to cache the vector.

__add__(other)
__and__(other)
__div__(other)
__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__mul__(other)
__neg__()
__pos__()
__radd__(other)
__rand__(other)
__repr__()

The representation of a Term object is given by,

>>> print(__UnaryTerm(123.456))
__UnaryTerm(coeff=123.456)
__rmul__(other)
__rsub__(other)
__sub__(other)
__truediv__(other)
cacheMatrix()

Informs solve() and sweep() to cache their matrix so that matrix can return the matrix.

cacheRHSvector()

Informs solve() and sweep() to cache their right hand side vector so that getRHSvector() can return it.

copy()
getDefaultSolver(var=None, solver=None, *args, **kwargs)
justErrorVector(var=None, solver=None, boundaryConditions=(), dt=1.0, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the error as well as applying under-relaxation.

justErrorVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy.solvers import DummySolver
>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(DiffusionTerm().justErrorVector(v, solver=DummySolver())) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

error – The residual vector \vec{e}=\mathsf{L}\vec{x}_\text{old} - \vec{b}

Return type:

CellVariable

justResidualVector(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

justResidualVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(numerix.asarray(DiffusionTerm().justResidualVector(v))) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

property matrix

Return the matrix calculated in solve() or sweep(). The cacheMatrix() method should be called before solve() or sweep() to cache the matrix.

residualVectorAndNorm(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

  • residual (~fipy.variables.cellVariable.CellVariable) – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

  • norm (float) – The L2 norm of residual, \|\vec{r}\|_2

solve(var=None, solver=None, boundaryConditions=(), dt=None)

Builds and solves the Term’s linear system once. This method does not return the residual. It should be used when the residual is not required.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

sweep(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None, cacheResidual=False, cacheError=False)

Builds and solves the Term’s linear system once. This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

  • cacheResidual (bool) – If True, calculate and store the residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b} in the residualVector member of Term

  • cacheError (bool) – If True, use the residual vector \vec{r} to solve \mathsf{L}\vec{e}=\vec{r} for the error vector \vec{e} and store it in the errorVector member of Term

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

class fipy.DiffusionTermCorrection(coeff=(1.0,), var=None)

Bases: _AbstractDiffusionTerm

Create a Term.

Parameters:

coeff (float or CellVariable or FaceVariable) – Coefficient for the term. FaceVariable objects are only acceptable for diffusion or convection terms.

property RHSvector

Return the RHS vector calculated in solve() or sweep(). The cacheRHSvector() method should be called before solve() or sweep() to cache the vector.

__add__(other)
__and__(other)
__div__(other)
__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__mul__(other)
__neg__()
__pos__()
__radd__(other)
__rand__(other)
__repr__()

The representation of a Term object is given by,

>>> print(__UnaryTerm(123.456))
__UnaryTerm(coeff=123.456)
__rmul__(other)
__rsub__(other)
__sub__(other)
__truediv__(other)
cacheMatrix()

Informs solve() and sweep() to cache their matrix so that matrix can return the matrix.

cacheRHSvector()

Informs solve() and sweep() to cache their right hand side vector so that getRHSvector() can return it.

copy()
getDefaultSolver(var=None, solver=None, *args, **kwargs)
justErrorVector(var=None, solver=None, boundaryConditions=(), dt=1.0, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the error as well as applying under-relaxation.

justErrorVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy.solvers import DummySolver
>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(DiffusionTerm().justErrorVector(v, solver=DummySolver())) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

error – The residual vector \vec{e}=\mathsf{L}\vec{x}_\text{old} - \vec{b}

Return type:

CellVariable

justResidualVector(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

justResidualVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(numerix.asarray(DiffusionTerm().justResidualVector(v))) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

property matrix

Return the matrix calculated in solve() or sweep(). The cacheMatrix() method should be called before solve() or sweep() to cache the matrix.

residualVectorAndNorm(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

  • residual (~fipy.variables.cellVariable.CellVariable) – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

  • norm (float) – The L2 norm of residual, \|\vec{r}\|_2

solve(var=None, solver=None, boundaryConditions=(), dt=None)

Builds and solves the Term’s linear system once. This method does not return the residual. It should be used when the residual is not required.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

sweep(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None, cacheResidual=False, cacheError=False)

Builds and solves the Term’s linear system once. This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

  • cacheResidual (bool) – If True, calculate and store the residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b} in the residualVector member of Term

  • cacheError (bool) – If True, use the residual vector \vec{r} to solve \mathsf{L}\vec{e}=\vec{r} for the error vector \vec{e} and store it in the errorVector member of Term

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

class fipy.DiffusionTermNoCorrection(coeff=(1.0,), var=None)

Bases: _AbstractDiffusionTerm

Create a Term.

Parameters:

coeff (float or CellVariable or FaceVariable) – Coefficient for the term. FaceVariable objects are only acceptable for diffusion or convection terms.

property RHSvector

Return the RHS vector calculated in solve() or sweep(). The cacheRHSvector() method should be called before solve() or sweep() to cache the vector.

__add__(other)
__and__(other)
__div__(other)
__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__mul__(other)
__neg__()
__pos__()
__radd__(other)
__rand__(other)
__repr__()

The representation of a Term object is given by,

>>> print(__UnaryTerm(123.456))
__UnaryTerm(coeff=123.456)
__rmul__(other)
__rsub__(other)
__sub__(other)
__truediv__(other)
cacheMatrix()

Informs solve() and sweep() to cache their matrix so that matrix can return the matrix.

cacheRHSvector()

Informs solve() and sweep() to cache their right hand side vector so that getRHSvector() can return it.

copy()
getDefaultSolver(var=None, solver=None, *args, **kwargs)
justErrorVector(var=None, solver=None, boundaryConditions=(), dt=1.0, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the error as well as applying under-relaxation.

justErrorVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy.solvers import DummySolver
>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(DiffusionTerm().justErrorVector(v, solver=DummySolver())) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

error – The residual vector \vec{e}=\mathsf{L}\vec{x}_\text{old} - \vec{b}

Return type:

CellVariable

justResidualVector(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

justResidualVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(numerix.asarray(DiffusionTerm().justResidualVector(v))) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

property matrix

Return the matrix calculated in solve() or sweep(). The cacheMatrix() method should be called before solve() or sweep() to cache the matrix.

residualVectorAndNorm(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

  • residual (~fipy.variables.cellVariable.CellVariable) – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

  • norm (float) – The L2 norm of residual, \|\vec{r}\|_2

solve(var=None, solver=None, boundaryConditions=(), dt=None)

Builds and solves the Term’s linear system once. This method does not return the residual. It should be used when the residual is not required.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

sweep(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None, cacheResidual=False, cacheError=False)

Builds and solves the Term’s linear system once. This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

  • cacheResidual (bool) – If True, calculate and store the residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b} in the residualVector member of Term

  • cacheError (bool) – If True, use the residual vector \vec{r} to solve \mathsf{L}\vec{e}=\vec{r} for the error vector \vec{e} and store it in the errorVector member of Term

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

class fipy.DistanceVariable(*args, **kwds)

Bases: CellVariable

A DistanceVariable object calculates \phi so it satisfies,

\abs{\nabla \phi} = 1

using the fast marching method with an initial condition defined by the zero level set. The solution can either be first or second order.

Here we will define a few test cases. Firstly a 1D test case

>>> from fipy.meshes import Grid1D
>>> from fipy.tools import serialComm
>>> mesh = Grid1D(dx = .5, nx = 8, communicator=serialComm)
>>> from .distanceVariable import DistanceVariable
>>> var = DistanceVariable(mesh = mesh, value = (-1., -1., -1., -1., 1., 1., 1., 1.))
>>> var.calcDistanceFunction() 
>>> answer = (-1.75, -1.25, -.75, -0.25, 0.25, 0.75, 1.25, 1.75)
>>> print(var.allclose(answer)) 
1

A 1D test case with very small dimensions.

>>> dx = 1e-10
>>> mesh = Grid1D(dx = dx, nx = 8, communicator=serialComm)
>>> var = DistanceVariable(mesh = mesh, value = (-1., -1., -1., -1., 1., 1., 1., 1.))
>>> var.calcDistanceFunction() 
>>> answer = numerix.arange(8) * dx - 3.5 * dx
>>> print(var.allclose(answer)) 
1

A 2D test case to test _calcTrialValue for a pathological case.

>>> dx = 1.
>>> dy = 2.
>>> from fipy.meshes import Grid2D
>>> mesh = Grid2D(dx = dx, dy = dy, nx = 2, ny = 3, communicator=serialComm)
>>> var = DistanceVariable(mesh = mesh, value = (-1., 1., 1., 1., -1., 1.))
>>> var.calcDistanceFunction() 
>>> vbl = -dx * dy / numerix.sqrt(dx**2 + dy**2) / 2.
>>> vbr = dx / 2
>>> vml = dy / 2.
>>> crossProd = dx * dy
>>> dsq = dx**2 + dy**2
>>> top = vbr * dx**2 + vml * dy**2
>>> sqrt = crossProd**2 *(dsq - (vbr - vml)**2)
>>> sqrt = numerix.sqrt(max(sqrt, 0))
>>> vmr = (top + sqrt) / dsq
>>> answer = (vbl, vbr, vml, vmr, vbl, vbr)
>>> print(var.allclose(answer)) 
1

The extendVariable method solves the following equation for a given extensionVariable.

\nabla u \cdot \nabla \phi = 0

using the fast marching method with an initial condition defined at the zero level set.

>>> from fipy.variables.cellVariable import CellVariable
>>> mesh = Grid2D(dx = 1., dy = 1., nx = 2, ny = 2, communicator=serialComm)
>>> var = DistanceVariable(mesh = mesh, value = (-1., 1., 1., 1.))
>>> var.calcDistanceFunction() 
>>> extensionVar = CellVariable(mesh = mesh, value = (-1, .5, 2, -1))
>>> tmp = 1 / numerix.sqrt(2)
>>> print(var.allclose((-tmp / 2, 0.5, 0.5, 0.5 + tmp))) 
1
>>> var.extendVariable(extensionVar, order=1) 
>>> print(extensionVar.allclose((1.25, .5, 2, 1.25))) 
1
>>> mesh = Grid2D(dx = 1., dy = 1., nx = 3, ny = 3, communicator=serialComm)
>>> var = DistanceVariable(mesh = mesh, value = (-1., 1., 1.,
...                                               1., 1., 1.,
...                                               1., 1., 1.))
>>> var.calcDistanceFunction(order=1) 
>>> extensionVar = CellVariable(mesh = mesh, value = (-1., .5, -1.,
...                                                    2., -1., -1.,
...                                                   -1., -1., -1.))
>>> v1 = 0.5 + tmp
>>> v2 = 1.5
>>> tmp1 = (v1 + v2) / 2 + numerix.sqrt(2. - (v1 - v2)**2) / 2
>>> tmp2 = tmp1 + 1 / numerix.sqrt(2)
>>> print(var.allclose((-tmp / 2, 0.5, 1.5, 0.5, 0.5 + tmp,
...                      tmp1, 1.5, tmp1, tmp2))) 
1
>>> answer = (1.25, .5, .5, 2, 1.25, 0.9544, 2, 1.5456, 1.25)
>>> var.extendVariable(extensionVar, order=1) 
>>> print(extensionVar.allclose(answer, rtol = 1e-4)) 
1

Test case for a bug that occurs when initializing the distance variable at the interface. Currently it is assumed that adjacent cells that are opposite sign neighbors have perpendicular normal vectors. In fact the two closest cells could have opposite normals.

>>> mesh = Grid1D(dx = 1., nx = 3, communicator=serialComm)
>>> var = DistanceVariable(mesh = mesh, value = (-1., 1., -1.))
>>> var.calcDistanceFunction() 
>>> print(var.allclose((-0.5, 0.5, -0.5))) 
1

Testing second order. This example failed with Scikit-fmm.

>>> mesh = Grid2D(dx = 1., dy = 1., nx = 4, ny = 4, communicator=serialComm)
>>> var = DistanceVariable(mesh = mesh, value = (-1., -1., 1., 1.,
...                                               -1., -1., 1., 1.,
...                                               1., 1., 1., 1.,
...                                               1, 1, 1, 1))
>>> var.calcDistanceFunction(order=2) 
>>> answer = [-1.30473785, -0.5, 0.5, 1.49923009,
...           -0.5, -0.35355339, 0.5, 1.45118446,
...            0.5, 0.5, 0.97140452, 1.76215286,
...            1.49923009, 1.45118446, 1.76215286, 2.33721352]
>>> print(numerix.allclose(var, answer, rtol=1e-9)) 
True

** A test for a bug in both LSMLIB and Scikit-fmm **

The following test gives different result depending on whether LSMLIB or Scikit-fmm is used. There is a deeper problem that is related to this issue. When a value becomes “known” after previously being a “trial” value it updates its neighbors’ values. In a second order scheme the neighbors one step away also need to be updated (if the in between cell is “known” and the far cell is a “trial” cell), but are not in either package. By luck (due to trial values having the same value), the values calculated in Scikit-fmm for the following example are correct although an example that didn’t work for Scikit-fmm could also be constructed.

>>> mesh = Grid2D(dx = 1., dy = 1., nx = 4, ny = 4, communicator=serialComm)
>>> var = DistanceVariable(mesh = mesh, value = (-1., -1., -1., -1.,
...                                               1.,  1., -1., -1.,
...                                               1.,  1., -1., -1.,
...                                               1.,  1., -1., -1.))
>>> var.calcDistanceFunction(order=2) 
>>> var.calcDistanceFunction(order=2) 
>>> answer = [-0.5,        -0.58578644, -1.08578644, -1.85136395,
...            0.5,         0.29289322, -0.58578644, -1.54389939,
...            1.30473785,  0.5,        -0.5,        -1.5,
...            1.49547948,  0.5,        -0.5,        -1.5]

The 3rd and 7th element are different for LSMLIB. This is because the 15th element is not “known” when the “trial” value for the 7th element is calculated. Scikit-fmm calculates the values in a slightly different order so gets a seemingly better answer, but this is just chance.

>>> print(numerix.allclose(var, answer, rtol=1e-9)) 
True

Creates a distanceVariable object.

Parameters:
  • mesh (Mesh) – The mesh that defines the geometry of this variable.

  • name (str) – The name of the variable.

  • value (float or array_like) – The initial value.

  • unit (str or PhysicalUnit) – The physical units of the variable

  • hasOld (bool) – Whether the variable maintains an old value.

__abs__()

Following test it to fix a bug with C inline string using abs() instead of fabs()

>>> print(abs(Variable(2.3) - Variable(1.2)))
1.1

Check representation works with different versions of numpy

>>> print(repr(abs(Variable(2.3))))
numerix.fabs(Variable(value=array(2.3)))
__add__(other)
__and__(other)

This test case has been added due to a weird bug that was appearing.

>>> a = Variable(value=(0, 0, 1, 1))
>>> b = Variable(value=(0, 1, 0, 1))
>>> print(numerix.equal((a == 0) & (b == 1), [False,  True, False, False]).all())
True
>>> print(a & b)
[0 0 0 1]
>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx=4)
>>> from fipy.variables.cellVariable import CellVariable
>>> a = CellVariable(value=(0, 0, 1, 1), mesh=mesh)
>>> b = CellVariable(value=(0, 1, 0, 1), mesh=mesh)
>>> print(numerix.allequal((a == 0) & (b == 1), [False,  True, False, False]))
True
>>> print(a & b)
[0 0 0 1]
__array__(t=None)

Attempt to convert the Variable to a numerix array object

>>> v = Variable(value=[2, 3])
>>> print(numerix.array(v))
[2 3]

A dimensional Variable will convert to the numeric value in its base units

>>> v = Variable(value=[2, 3], unit="mm")
>>> numerix.array(v)
array([ 0.002,  0.003])
__array_priority__ = 100.0
__array_wrap__(arr, context=None)

Required to prevent numpy not calling the reverse binary operations. Both the following tests are examples ufuncs.

>>> print(type(numerix.array([1.0, 2.0]) * Variable([1.0, 2.0]))) 
<class 'fipy.variables.binaryOperatorVariable...binOp'>
>>> from scipy.special import gamma as Gamma 
>>> print(type(Gamma(Variable([1.0, 2.0])))) 
<class 'fipy.variables.unaryOperatorVariable...unOp'>
__bool__()
>>> print(bool(Variable(value=0)))
0
>>> print(bool(Variable(value=(0, 0, 1, 1))))
Traceback (most recent call last):
    ...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
__call__(points=None, order=0, nearestCellIDs=None)

Interpolates the CellVariable to a set of points using a method that has a memory requirement on the order of Ncells by Npoints in general, but uses only Ncells when the CellVariable’s mesh is a UniformGrid object.

Tests

>>> from fipy import *
>>> m = Grid2D(nx=3, ny=2)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> print(v(((0., 1.1, 1.2), (0., 1., 1.))))
[ 0.5  1.5  1.5]
>>> print(v(((0., 1.1, 1.2), (0., 1., 1.)), order=1))
[ 0.25  1.1   1.2 ]
>>> m0 = Grid2D(nx=2, ny=2, dx=1., dy=1.)
>>> m1 = Grid2D(nx=4, ny=4, dx=.5, dy=.5)
>>> x, y = m0.cellCenters
>>> v0 = CellVariable(mesh=m0, value=x * y)
>>> print(v0(m1.cellCenters.globalValue))
[ 0.25  0.25  0.75  0.75  0.25  0.25  0.75  0.75  0.75  0.75  2.25  2.25
  0.75  0.75  2.25  2.25]
>>> print(v0(m1.cellCenters.globalValue, order=1))
[ 0.125  0.25   0.5    0.625  0.25   0.375  0.875  1.     0.5    0.875
  1.875  2.25   0.625  1.     2.25   2.625]
Parameters:
  • points (tuple or list of tuple) – A point or set of points in the format (X, Y, Z)

  • order ({0, 1}) – The order of interpolation, default is 0

  • nearestCellIDs (array_like) – Optional argument if user can calculate own nearest cell IDs array, shape should be same as points

__div__(other)
__eq__(other)

Test if a Variable is equal to another quantity

>>> a = Variable(value=3)
>>> b = (a == 4)
>>> b
(Variable(value=array(3)) == 4)
>>> b()
0
__float__()
__ge__(other)

Test if a Variable is greater than or equal to another quantity

>>> a = Variable(value=3)
>>> b = (a >= 4)
>>> b
(Variable(value=array(3)) >= 4)
>>> b()
0
>>> a.value = 4
>>> print(b())
1
>>> a.value = 5
>>> print(b())
1
__getitem__(index)

“Evaluate” the Variable and return the specified element

>>> a = Variable(value=((3., 4.), (5., 6.)), unit="m") + "4 m"
>>> print(a[1, 1])
10.0 m

It is an error to slice a Variable whose value is not sliceable

>>> Variable(value=3)[2]
Traceback (most recent call last):
      ...
IndexError: 0-d arrays can't be indexed
__getstate__()

Used internally to collect the necessary information to pickle the CellVariable to persistent storage.

__gt__(other)

Test if a Variable is greater than another quantity

>>> a = Variable(value=3)
>>> b = (a > 4)
>>> b
(Variable(value=array(3)) > 4)
>>> print(b())
0
>>> a.value = 5
>>> print(b())
1
__hash__()

Return hash(self).

__int__()
__invert__()

Returns logical “not” of the Variable

>>> a = Variable(value=True)
>>> print(~a)
False
__iter__()
__le__(other)

Test if a Variable is less than or equal to another quantity

>>> a = Variable(value=3)
>>> b = (a <= 4)
>>> b
(Variable(value=array(3)) <= 4)
>>> b()
1
>>> a.value = 4
>>> print(b())
1
>>> a.value = 5
>>> print(b())
0
__len__()
__lt__(other)

Test if a Variable is less than another quantity

>>> a = Variable(value=3)
>>> b = (a < 4)
>>> b
(Variable(value=array(3)) < 4)
>>> b()
1
>>> a.value = 4
>>> print(b())
0
>>> print(1000000000000000000 * Variable(1) < 1.)
0
>>> print(1000 * Variable(1) < 1.)
0

Python automatically reverses the arguments when necessary

>>> 4 > Variable(value=3)
(Variable(value=array(3)) < 4)
__mod__(other)
__mul__(other)
__ne__(other)

Test if a Variable is not equal to another quantity

>>> a = Variable(value=3)
>>> b = (a != 4)
>>> b
(Variable(value=array(3)) != 4)
>>> b()
1
__neg__()
static __new__(cls, *args, **kwds)
__nonzero__()
>>> print(bool(Variable(value=0)))
0
>>> print(bool(Variable(value=(0, 0, 1, 1))))
Traceback (most recent call last):
    ...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
__or__(other)

This test case has been added due to a weird bug that was appearing.

>>> a = Variable(value=(0, 0, 1, 1))
>>> b = Variable(value=(0, 1, 0, 1))
>>> print(numerix.equal((a == 0) | (b == 1), [True,  True, False, True]).all())
True
>>> print(a | b)
[0 1 1 1]
>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx=4)
>>> from fipy.variables.cellVariable import CellVariable
>>> a = CellVariable(value=(0, 0, 1, 1), mesh=mesh)
>>> b = CellVariable(value=(0, 1, 0, 1), mesh=mesh)
>>> print(numerix.allequal((a == 0) | (b == 1), [True,  True, False, True]))
True
>>> print(a | b)
[0 1 1 1]
__pos__()
__pow__(other)

return self**other, or self raised to power other

>>> print(Variable(1, "mol/l")**3)
1.0 mol**3/l**3
>>> print((Variable(1, "mol/l")**3).unit)
<PhysicalUnit mol**3/l**3>
__radd__(other)
__rdiv__(other)
__repr__()

Return repr(self).

__rmul__(other)
__rpow__(other)
__rsub__(other)
__rtruediv__(other)
__setitem__(index, value)
__setstate__(dict)

Used internally to create a new CellVariable from pickled persistent storage.

__str__()

Return str(self).

__sub__(other)
__truediv__(other)
all(axis=None)
>>> print(Variable(value=(0, 0, 1, 1)).all())
0
>>> print(Variable(value=(1, 1, 1, 1)).all())
1
allclose(other, rtol=1e-05, atol=1e-08)
>>> var = Variable((1, 1))
>>> print(var.allclose((1, 1)))
1
>>> print(var.allclose((1,)))
1

The following test is to check that the system does not run out of memory.

>>> from fipy.tools import numerix
>>> var = Variable(numerix.ones(10000))
>>> print(var.allclose(numerix.zeros(10000, 'l')))
False
allequal(other)
any(axis=None)
>>> print(Variable(value=0).any())
0
>>> print(Variable(value=(0, 0, 1, 1)).any())
1
property arithmeticFaceValue

Returns a FaceVariable whose value corresponds to the arithmetic interpolation of the adjacent cells:

\phi_f = (\phi_1 - \phi_2) \frac{d_{f2}}{d_{12}} + \phi_2

>>> from fipy.meshes import Grid1D
>>> from fipy import numerix
>>> mesh = Grid1D(dx = (1., 1.))
>>> L = 1
>>> R = 2
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (0.5 / 1.) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (2., 4.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (1.0 / 3.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (10., 100.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (5.0 / 55.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
cacheMe(recursive=False)
calcDistanceFunction(order=2)

Calculates the distanceVariable as a distance function.

Parameters:

order ({1, 2}) – The order of accuracy for the distance function calculation

property cellInterfaceAreas

Returns the length of the interface that crosses the cell

A simple 1D test:

>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(dx = 1., nx = 4)
>>> distanceVariable = DistanceVariable(mesh = mesh,
...                                     value = (-1.5, -0.5, 0.5, 1.5))
>>> answer = CellVariable(mesh=mesh, value=(0, 0., 1., 0))
>>> print(numerix.allclose(distanceVariable.cellInterfaceAreas,
...                        answer))
True

A 2D test case:

>>> from fipy.meshes import Grid2D
>>> from fipy.variables.cellVariable import CellVariable
>>> mesh = Grid2D(dx = 1., dy = 1., nx = 3, ny = 3)
>>> distanceVariable = DistanceVariable(mesh = mesh,
...                                     value = (1.5, 0.5, 1.5,
...                                              0.5, -0.5, 0.5,
...                                              1.5, 0.5, 1.5))
>>> answer = CellVariable(mesh=mesh,
...                       value=(0, 1, 0, 1, 0, 1, 0, 1, 0))
>>> print(numerix.allclose(distanceVariable.cellInterfaceAreas, answer))
True

Another 2D test case:

>>> mesh = Grid2D(dx = .5, dy = .5, nx = 2, ny = 2)
>>> from fipy.variables.cellVariable import CellVariable
>>> distanceVariable = DistanceVariable(mesh = mesh,
...                                     value = (-0.5, 0.5, 0.5, 1.5))
>>> answer = CellVariable(mesh=mesh,
...                       value=(0, numerix.sqrt(2) / 4,  numerix.sqrt(2) / 4, 0))
>>> print(numerix.allclose(distanceVariable.cellInterfaceAreas,
...                        answer))
True

Test to check that the circumference of a circle is, in fact, 2\pi r.

>>> mesh = Grid2D(dx = 0.05, dy = 0.05, nx = 20, ny = 20)
>>> r = 0.25
>>> x, y = mesh.cellCenters
>>> rad = numerix.sqrt((x - .5)**2 + (y - .5)**2) - r
>>> distanceVariable = DistanceVariable(mesh = mesh, value = rad)
>>> print(numerix.allclose(distanceVariable.cellInterfaceAreas.sum(), 1.57984690073))
1
property cellVolumeAverage

Return the cell-volume-weighted average of the CellVariable:

<\phi>_\text{vol}
= \frac{\sum_\text{cells} \phi_\text{cell} V_\text{cell}}
    {\sum_\text{cells} V_\text{cell}}

>>> from fipy.meshes import Grid2D
>>> from fipy.variables.cellVariable import CellVariable
>>> mesh = Grid2D(nx = 3, ny = 1, dx = .5, dy = .1)
>>> var = CellVariable(value = (1, 2, 6), mesh = mesh)
>>> print(var.cellVolumeAverage)
3.0
constrain(value, where=None)

Constrains the CellVariable to value at a location specified by where.

>>> from fipy import *
>>> m = Grid1D(nx=3)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> v.constrain(0., where=m.facesLeft)
>>> v.faceGrad.constrain([1.], where=m.facesRight)
>>> print(v.faceGrad)
[[ 1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 0.   1.   2.   2.5]

Changing the constraint changes the dependencies

>>> v.constrain(1., where=m.facesLeft)
>>> print(v.faceGrad)
[[-1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 1.   1.   2.   2.5]

Constraints can be Variable

>>> c = Variable(0.)
>>> v.constrain(c, where=m.facesLeft)
>>> print(v.faceGrad)
[[ 1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 0.   1.   2.   2.5]
>>> c.value = 1.
>>> print(v.faceGrad)
[[-1.  1.  1.  1.]]
>>> print(v.faceValue)
[ 1.   1.   2.   2.5]

Constraints can have a Variable mask.

>>> v = CellVariable(mesh=m)
>>> mask = FaceVariable(mesh=m, value=m.facesLeft)
>>> v.constrain(1., where=mask)
>>> print(v.faceValue)
[ 1.  0.  0.  0.]
>>> mask[:] = mask | m.facesRight
>>> print(v.faceValue)
[ 1.  0.  0.  1.]
property constraintMask

Test that constraintMask returns a Variable that updates itself whenever the constraints change.

>>> from fipy import *
>>> m = Grid2D(nx=2, ny=2)
>>> x, y = m.cellCenters
>>> v0 = CellVariable(mesh=m)
>>> v0.constrain(1., where=m.facesLeft)
>>> print(v0.faceValue.constraintMask)
[False False False False False False  True False False  True False False]
>>> print(v0.faceValue)
[ 0.  0.  0.  0.  0.  0.  1.  0.  0.  1.  0.  0.]
>>> v0.constrain(3., where=m.facesRight)
>>> print(v0.faceValue.constraintMask)
[False False False False False False  True False  True  True False  True]
>>> print(v0.faceValue)
[ 0.  0.  0.  0.  0.  0.  1.  0.  3.  1.  0.  3.]
>>> v1 = CellVariable(mesh=m)
>>> v1.constrain(1., where=(x < 1) & (y < 1))
>>> print(v1.constraintMask)
[ True False False False]
>>> print(v1)
[ 1.  0.  0.  0.]
>>> v1.constrain(3., where=(x > 1) & (y > 1))
>>> print(v1.constraintMask)
[ True False False  True]
>>> print(v1)
[ 1.  0.  0.  3.]
property constraints
copy()

Make an duplicate of the Variable

>>> a = Variable(value=3)
>>> b = a.copy()
>>> b
Variable(value=array(3))

The duplicate will not reflect changes made to the original

>>> a.setValue(5)
>>> b
Variable(value=array(3))

Check that this works for arrays.

>>> a = Variable(value=numerix.array((0, 1, 2)))
>>> b = a.copy()
>>> b
Variable(value=array([0, 1, 2]))
>>> a[1] = 3
>>> b
Variable(value=array([0, 1, 2]))
dontCacheMe(recursive=False)
dot(other, opShape=None, operatorClass=None)

Return the mesh-element–by–mesh-element (cell-by-cell, face-by-face, etc.) scalar product

ext{self} \cdot         ext{other}

Both self and other can be of arbitrary rank, and other does not need to be a _MeshVariable.

extendVariable(extensionVariable, order=2)

Calculates the extension of extensionVariable from the zero level set.

Parameters:

extensionVariable (CellVariable) – The variable to extend from the zero level set.

property faceGrad

Return \nabla \phi as a rank-1 FaceVariable using differencing for the normal direction(second-order gradient).

property faceGradAverage

Deprecated since version 3.3: use grad.arithmeticFaceValue() instead

Return \nabla \phi as a rank-1 FaceVariable using averaging for the normal direction(second-order gradient)

property faceValue

Returns a FaceVariable whose value corresponds to the arithmetic interpolation of the adjacent cells:

\phi_f = (\phi_1 - \phi_2) \frac{d_{f2}}{d_{12}} + \phi_2

>>> from fipy.meshes import Grid1D
>>> from fipy import numerix
>>> mesh = Grid1D(dx = (1., 1.))
>>> L = 1
>>> R = 2
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (0.5 / 1.) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (2., 4.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (1.0 / 3.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (10., 100.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.arithmeticFaceValue[mesh.interiorFaces.value]
>>> answer = (R - L) * (5.0 / 55.0) + L
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
property gaussGrad

Return \frac{1}{V_P} \sum_f \vec{n} \phi_f A_f as a rank-1 CellVariable (first-order gradient).

getLSMshape()
getsctype(default=None)

Returns the Numpy sctype of the underlying array.

>>> Variable(1).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1))
True
>>> Variable(1.).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1.))
True
>>> Variable((1, 1.)).getsctype() == numerix.NUMERIX.obj2sctype(numerix.array((1., 1.)))
True
property globalValue

Concatenate and return values from all processors

When running on a single processor, the result is identical to value.

property grad

Return \nabla \phi as a rank-1 CellVariable (first-order gradient).

property harmonicFaceValue

Returns a FaceVariable whose value corresponds to the harmonic interpolation of the adjacent cells:

\phi_f = \frac{\phi_1 \phi_2}{(\phi_2 - \phi_1) \frac{d_{f2}}{d_{12}} + \phi_1}

>>> from fipy.meshes import Grid1D
>>> from fipy import numerix
>>> mesh = Grid1D(dx = (1., 1.))
>>> L = 1
>>> R = 2
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.harmonicFaceValue[mesh.interiorFaces.value]
>>> answer = L * R / ((R - L) * (0.5 / 1.) + L)
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (2., 4.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.harmonicFaceValue[mesh.interiorFaces.value]
>>> answer = L * R / ((R - L) * (1.0 / 3.0) + L)
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
>>> mesh = Grid1D(dx = (10., 100.))
>>> var = CellVariable(mesh = mesh, value = (L, R))
>>> faceValue = var.harmonicFaceValue[mesh.interiorFaces.value]
>>> answer = L * R / ((R - L) * (5.0 / 55.0) + L)
>>> print(numerix.allclose(faceValue, answer, atol = 1e-10, rtol = 1e-10))
True
inBaseUnits()

Return the value of the Variable with all units reduced to their base SI elements.

>>> e = Variable(value="2.7 Hartree*Nav")
>>> print(e.inBaseUnits().allclose("7088849.01085 kg*m**2/s**2/mol"))
1
inUnitsOf(*units)

Returns one or more Variable objects that express the same physical quantity in different units. The units are specified by strings containing their names. The units must be compatible with the unit of the object. If one unit is specified, the return value is a single Variable.

>>> freeze = Variable('0 degC')
>>> print(freeze.inUnitsOf('degF').allclose("32.0 degF"))
1

If several units are specified, the return value is a tuple of Variable instances with with one element per unit such that the sum of all quantities in the tuple equals the the original quantity and all the values except for the last one are integers. This is used to convert to irregular unit systems like hour/minute/second. The original object will not be changed.

>>> t = Variable(value=314159., unit='s')
>>> from builtins import zip
>>> print(numerix.allclose([e.allclose(v) for (e, v) in zip(t.inUnitsOf('d', 'h', 'min', 's'),
...                                                         ['3.0 d', '15.0 h', '15.0 min', '59.0 s'])],
...                        True))
1
itemset(value)
property itemsize
property leastSquaresGrad

Return \nabla \phi, which is determined by solving for \nabla \phi in the following matrix equation,

\nabla \phi \cdot \sum_f d_{AP}^2 \vec{n}_{AP} \otimes \vec{n}_{AP} =
\sum_f d_{AP}^2 \left( \vec{n} \cdot \nabla \phi \right)_{AP}

The matrix equation is derived by minimizing the following least squares sum,

F \left( \phi_x, \phi_y \right) = \sqrt{\sum_f \left( d_{AP}
\vec{n}_{AP} \cdot \nabla \phi - d_{AP} \left( \vec{n}_{AP} \cdot
\nabla \phi \right)_{AP} \right)^2 }

Tests

>>> from fipy import Grid2D
>>> m = Grid2D(nx=2, ny=2, dx=0.1, dy=2.0)
>>> print(numerix.allclose(CellVariable(mesh=m, value=(0, 1, 3, 6)).leastSquaresGrad.globalValue, \
...                                     [[8.0, 8.0, 24.0, 24.0],
...                                      [1.2, 2.0, 1.2, 2.0]]))
True
>>> from fipy import Grid1D
>>> print(numerix.allclose(CellVariable(mesh=Grid1D(dx=(2.0, 1.0, 0.5)),
...                                     value=(0, 1, 2)).leastSquaresGrad.globalValue, [[0.461538461538, 0.8, 1.2]]))
True
property mag

The magnitude of the Variable, e.g., |\vec{\psi}| = \sqrt{\vec{\psi}\cdot\vec{\psi}}.

max(axis=None)
min(axis=None)
>>> from fipy import Grid2D, CellVariable
>>> mesh = Grid2D(nx=5, ny=5)
>>> x, y = mesh.cellCenters
>>> v = CellVariable(mesh=mesh, value=x*y)
>>> print(v.min())
0.25
property minmodFaceValue

Returns a FaceVariable with a value that is the minimum of the absolute values of the adjacent cells. If the values are of opposite sign then the result is zero:

\phi_f = \begin{cases}
               \phi_1& \text{when $|\phi_1| \le |\phi_2|$},\\
               \phi_2& \text{when $|\phi_2| < |\phi_1|$},\\
               0 & \text{when $\phi1 \phi2 < 0$}
         \end{cases}

>>> from fipy import *
>>> print(CellVariable(mesh=Grid1D(nx=2), value=(1, 2)).minmodFaceValue)
[1 1 2]
>>> print(CellVariable(mesh=Grid1D(nx=2), value=(-1, -2)).minmodFaceValue)
[-1 -1 -2]
>>> print(CellVariable(mesh=Grid1D(nx=2), value=(-1, 2)).minmodFaceValue)
[-1  0  2]
property name
property numericValue
property old

Return the values of the CellVariable from the previous solution sweep.

Combinations of CellVariable’s should also return old values.

>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx = 2)
>>> from fipy.variables.cellVariable import CellVariable
>>> var1 = CellVariable(mesh = mesh, value = (2, 3), hasOld = 1)
>>> var2 = CellVariable(mesh = mesh, value = (3, 4))
>>> v = var1 * var2
>>> print(v)
[ 6 12]
>>> var1.value = ((3, 2))
>>> print(v)
[9 8]
>>> print(v.old)
[ 6 12]

The following small test is to correct for a bug when the operator does not just use variables.

>>> v1 = var1 * 3
>>> print(v1)
[9 6]
>>> print(v1.old)
[6 9]
put(indices, value)
property rank
ravel()
rdot(other, opShape=None, operatorClass=None)

Return the mesh-element–by–mesh-element (cell-by-cell, face-by-face, etc.) scalar product

ext{other} \cdot        ext{self}

Both self and other can be of arbitrary rank, and other does not need to be a _MeshVariable.

release(constraint)

Remove constraint from self

>>> from fipy import *
>>> m = Grid1D(nx=3)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> c = Constraint(0., where=m.facesLeft)
>>> v.constrain(c)
>>> print(v.faceValue)
[ 0.   1.   2.   2.5]
>>> v.release(constraint=c)
>>> print(v.faceValue)
[ 0.5  1.   2.   2.5]
setValue(value, unit=None, where=None)

Set the value of the Variable. Can take a masked array.

>>> a = Variable((1, 2, 3))
>>> a.setValue(5, where=(1, 0, 1))
>>> print(a)
[5 2 5]
>>> b = Variable((4, 5, 6))
>>> a.setValue(b, where=(1, 0, 1))
>>> print(a)
[4 2 6]
>>> print(b)
[4 5 6]
>>> a.value = 3
>>> print(a)
[3 3 3]
>>> b = numerix.array((3, 4, 5))
>>> a.value = b
>>> a[:] = 1
>>> print(b)
[3 4 5]
>>> a.setValue((4, 5, 6), where=(1, 0)) 
Traceback (most recent call last):
    ....
ValueError: shape mismatch: objects cannot be broadcast to a single shape
property shape
>>> from fipy.meshes import Grid2D
>>> from fipy.variables.cellVariable import CellVariable
>>> mesh = Grid2D(nx=2, ny=3)
>>> var = CellVariable(mesh=mesh)
>>> print(numerix.allequal(var.shape, (6,))) 
True
>>> print(numerix.allequal(var.arithmeticFaceValue.shape, (17,))) 
True
>>> print(numerix.allequal(var.grad.shape, (2, 6))) 
True
>>> print(numerix.allequal(var.faceGrad.shape, (2, 17))) 
True

Have to account for zero length arrays

>>> from fipy import Grid1D
>>> m = Grid1D(nx=0)
>>> v = CellVariable(mesh=m, elementshape=(2,))
>>> numerix.allequal((v * 1).shape, (2, 0))
True
std(axis=None, **kwargs)

Evaluate standard deviation of all the elements of a MeshVariable.

Adapted from http://mpitutorial.com/tutorials/mpi-reduce-and-allreduce/

>>> import fipy as fp
>>> mesh = fp.Grid2D(nx=2, ny=2, dx=2., dy=5.)
>>> var = fp.CellVariable(value=(1., 2., 3., 4.), mesh=mesh)
>>> print((var.std()**2).allclose(1.25))
True
property subscribedVariables
sum(axis=None)
take(ids, axis=0)
tostring(max_line_width=75, precision=8, suppress_small=False, separator=' ')
property unit

Return the unit object of self.

>>> Variable(value="1 m").unit
<PhysicalUnit m>
updateOld()

Set the values of the previous solution sweep to the current values.

>>> from fipy import *
>>> v = CellVariable(mesh=Grid1D(), hasOld=False)
>>> v.updateOld()
Traceback (most recent call last):
   ...
AssertionError: The updateOld method requires the CellVariable to have an old value. Set hasOld to True when instantiating the CellVariable.
property value

“Evaluate” the Variable and return its value (longhand)

>>> a = Variable(value=3)
>>> print(a.value)
3
>>> b = a + 4
>>> b
(Variable(value=array(3)) + 4)
>>> b.value
7
class fipy.DummySolver(*args, **kwargs)

Bases: PETScSolver

Solver that doesn’t do anything.

PETSc is intolerant of having zeros on the diagonal

Create a Solver object.

Parameters:
  • tolerance (float) – Required error tolerance.

  • iterations (int) – Maximum number of iterative steps to perform.

  • precon – Preconditioner to use. Not all solver suites support preconditioners.

__del__()
__enter__()
__exit__(exc_type, exc_value, traceback)
__repr__()

Return repr(self).

class fipy.DummyViewer(vars, title=None, **kwlimits)

Bases: AbstractViewer

Substitute viewer that doesn’t do anything

Create a AbstractViewer object.

Parameters:
  • vars (CellVariable or list) – the CellVariable objects to display.

  • title (str, optional) – displayed at the top of the Viewer window

  • xmin (float, optional) – displayed range of data. Any limit set to a (default) value of None will autoscale.

  • xmax (float, optional) – displayed range of data. Any limit set to a (default) value of None will autoscale.

  • ymin (float, optional) – displayed range of data. Any limit set to a (default) value of None will autoscale.

  • ymax (float, optional) – displayed range of data. Any limit set to a (default) value of None will autoscale.

  • zmin (float, optional) – displayed range of data. Any limit set to a (default) value of None will autoscale.

  • zmax (float, optional) – displayed range of data. Any limit set to a (default) value of None will autoscale.

  • datamin (float, optional) – displayed range of data. Any limit set to a (default) value of None will autoscale.

  • datamax (float, optional) – displayed range of data. Any limit set to a (default) value of None will autoscale.

property limits
plot(filename=None)

Update the display of the viewed variables.

Parameters:

filename (str) – If not None, the name of a file to save the image into.

plotMesh(filename=None)

Display a representation of the mesh

Parameters:

filename (str) – If not None, the name of a file to save the image into.

setLimits(limits={}, **kwlimits)

Update the limits.

Parameters:
  • limits (dict, optional) – a (deprecated) alternative to limit keyword arguments

  • xmin (float, optional) – displayed range of data. A 1D Viewer will only use xmin and xmax, a 2D viewer will also use ymin and ymax, and so on. All viewers will use datamin and datamax. Any limit set to a (default) value of None will autoscale.

  • xmax (float, optional) – displayed range of data. A 1D Viewer will only use xmin and xmax, a 2D viewer will also use ymin and ymax, and so on. All viewers will use datamin and datamax. Any limit set to a (default) value of None will autoscale.

  • ymin (float, optional) – displayed range of data. A 1D Viewer will only use xmin and xmax, a 2D viewer will also use ymin and ymax, and so on. All viewers will use datamin and datamax. Any limit set to a (default) value of None will autoscale.

  • ymax (float, optional) – displayed range of data. A 1D Viewer will only use xmin and xmax, a 2D viewer will also use ymin and ymax, and so on. All viewers will use datamin and datamax. Any limit set to a (default) value of None will autoscale.

  • zmin (float, optional) – displayed range of data. A 1D Viewer will only use xmin and xmax, a 2D viewer will also use ymin and ymax, and so on. All viewers will use datamin and datamax. Any limit set to a (default) value of None will autoscale.

  • zmax (float, optional) – displayed range of data. A 1D Viewer will only use xmin and xmax, a 2D viewer will also use ymin and ymax, and so on. All viewers will use datamin and datamax. Any limit set to a (default) value of None will autoscale.

  • datamin (float, optional) – displayed range of data. A 1D Viewer will only use xmin and xmax, a 2D viewer will also use ymin and ymax, and so on. All viewers will use datamin and datamax. Any limit set to a (default) value of None will autoscale.

  • datamax (float, optional) – displayed range of data. A 1D Viewer will only use xmin and xmax, a 2D viewer will also use ymin and ymax, and so on. All viewers will use datamin and datamax. Any limit set to a (default) value of None will autoscale.

property title

The text appearing at the top center.

(default: if len(self.vars) == 1, the name of self.vars[0], otherwise "".)

property vars

The Variable or list of Variable objects to display.

class fipy.ExplicitDiffusionTerm(coeff=(1.0,), var=None)

Bases: _AbstractDiffusionTerm

The discretization for the ExplicitDiffusionTerm is given by

\int_V \nabla \cdot (\Gamma\nabla\phi) dV \simeq \sum_f \Gamma_f
\frac{\phi_A^\text{old}-\phi_P^\text{old}}{d_{AP}} A_f

where \phi_A^\text{old} and \phi_P^\text{old} are the old values of the variable. The term is added to the RHS vector and makes no contribution to the solution matrix.

Create a Term.

Parameters:

coeff (float or CellVariable or FaceVariable) – Coefficient for the term. FaceVariable objects are only acceptable for diffusion or convection terms.

property RHSvector

Return the RHS vector calculated in solve() or sweep(). The cacheRHSvector() method should be called before solve() or sweep() to cache the vector.

__add__(other)
__and__(other)
__div__(other)
__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__mul__(other)
__neg__()
__pos__()
__radd__(other)
__rand__(other)
__repr__()

The representation of a Term object is given by,

>>> print(__UnaryTerm(123.456))
__UnaryTerm(coeff=123.456)
__rmul__(other)
__rsub__(other)
__sub__(other)
__truediv__(other)
cacheMatrix()

Informs solve() and sweep() to cache their matrix so that matrix can return the matrix.

cacheRHSvector()

Informs solve() and sweep() to cache their right hand side vector so that getRHSvector() can return it.

copy()
getDefaultSolver(var=None, solver=None, *args, **kwargs)
justErrorVector(var=None, solver=None, boundaryConditions=(), dt=1.0, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the error as well as applying under-relaxation.

justErrorVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy.solvers import DummySolver
>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(DiffusionTerm().justErrorVector(v, solver=DummySolver())) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

error – The residual vector \vec{e}=\mathsf{L}\vec{x}_\text{old} - \vec{b}

Return type:

CellVariable

justResidualVector(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

justResidualVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(numerix.asarray(DiffusionTerm().justResidualVector(v))) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

property matrix

Return the matrix calculated in solve() or sweep(). The cacheMatrix() method should be called before solve() or sweep() to cache the matrix.

residualVectorAndNorm(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

  • residual (~fipy.variables.cellVariable.CellVariable) – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

  • norm (float) – The L2 norm of residual, \|\vec{r}\|_2

solve(var=None, solver=None, boundaryConditions=(), dt=None)

Builds and solves the Term’s linear system once. This method does not return the residual. It should be used when the residual is not required.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

sweep(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None, cacheResidual=False, cacheError=False)

Builds and solves the Term’s linear system once. This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

  • cacheResidual (bool) – If True, calculate and store the residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b} in the residualVector member of Term

  • cacheError (bool) – If True, use the residual vector \vec{r} to solve \mathsf{L}\vec{e}=\vec{r} for the error vector \vec{e} and store it in the errorVector member of Term

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

class fipy.ExplicitUpwindConvectionTerm(coeff=1.0, var=None)

Bases: _AbstractUpwindConvectionTerm

The discretization for this Term is given by

\int_V \nabla \cdot (\vec{u} \phi)\,dV \simeq \sum_{f} (\vec{n}
\cdot \vec{u})_f \phi_f A_f

where \phi_f=\alpha_f \phi_P^\text{old} +(1-\alpha_f)\phi_A^\text{old} and \alpha_f is calculated using the upwind scheme. For further details see Numerical Schemes.

Create a _AbstractConvectionTerm object.

>>> from fipy import *
>>> m = Grid1D(nx = 2)
>>> cv = CellVariable(mesh = m)
>>> fv = FaceVariable(mesh = m)
>>> vcv = CellVariable(mesh=m, rank=1)
>>> vfv = FaceVariable(mesh=m, rank=1)
>>> __ConvectionTerm(coeff = cv) 
Traceback (most recent call last):
    ...
VectorCoeffError: The coefficient must be a vector value.
>>> __ConvectionTerm(coeff = fv) 
Traceback (most recent call last):
    ...
VectorCoeffError: The coefficient must be a vector value.
>>> __ConvectionTerm(coeff = vcv)
__ConvectionTerm(coeff=_ArithmeticCellToFaceVariable(value=array([[ 0.,  0.,  0.]]), mesh=UniformGrid1D(dx=1.0, nx=2)))
>>> __ConvectionTerm(coeff = vfv)
__ConvectionTerm(coeff=FaceVariable(value=array([[ 0.,  0.,  0.]]), mesh=UniformGrid1D(dx=1.0, nx=2)))
>>> __ConvectionTerm(coeff = (1,))
__ConvectionTerm(coeff=(1,))
>>> ExplicitUpwindConvectionTerm(coeff = (0,)).solve(var=cv, solver=DummySolver()) 
Traceback (most recent call last):
    ...
TransientTermError: The equation requires a TransientTerm with explicit convection.
>>> (TransientTerm(0.) - ExplicitUpwindConvectionTerm(coeff = (0,))).solve(var=cv, solver=DummySolver(), dt=1.)
>>> (TransientTerm() - ExplicitUpwindConvectionTerm(coeff = 1)).solve(var=cv, solver=DummySolver(), dt=1.) 
Traceback (most recent call last):
    ...
VectorCoeffError: The coefficient must be a vector value.
>>> m2 = Grid2D(nx=2, ny=1)
>>> cv2 = CellVariable(mesh=m2)
>>> vcv2 = CellVariable(mesh=m2, rank=1)
>>> vfv2 = FaceVariable(mesh=m2, rank=1)
>>> __ConvectionTerm(coeff=vcv2)
__ConvectionTerm(coeff=_ArithmeticCellToFaceVariable(value=array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]]), mesh=UniformGrid2D(dx=1.0, nx=2, dy=1.0, ny=1)))
>>> __ConvectionTerm(coeff=vfv2)
__ConvectionTerm(coeff=FaceVariable(value=array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]]), mesh=UniformGrid2D(dx=1.0, nx=2, dy=1.0, ny=1)))
>>> (TransientTerm() - ExplicitUpwindConvectionTerm(coeff = ((0,), (0,)))).solve(var=cv2, solver=DummySolver(), dt=1.)
>>> (TransientTerm() - ExplicitUpwindConvectionTerm(coeff = (0, 0))).solve(var=cv2, solver=DummySolver(), dt=1.)
Parameters:

coeff (The Term’s coefficient value.) –

property RHSvector

Return the RHS vector calculated in solve() or sweep(). The cacheRHSvector() method should be called before solve() or sweep() to cache the vector.

__add__(other)
__and__(other)
__div__(other)
__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__mul__(other)

Multiply a term

>>> 2. * __NonDiffusionTerm(coeff=0.5)
__NonDiffusionTerm(coeff=1.0)

Test for ticket:291.

>>> from fipy import PowerLawConvectionTerm
>>> PowerLawConvectionTerm(coeff=[[1], [0]]) * 1.0
PowerLawConvectionTerm(coeff=array([[ 1.],
       [ 0.]]))
__neg__()

Negate a Term.

>>> -__NonDiffusionTerm(coeff=1.)
__NonDiffusionTerm(coeff=-1.0)
__pos__()
__radd__(other)
__rand__(other)
__repr__()

The representation of a Term object is given by,

>>> print(__UnaryTerm(123.456))
__UnaryTerm(coeff=123.456)
__rmul__(other)

Multiply a term

>>> 2. * __NonDiffusionTerm(coeff=0.5)
__NonDiffusionTerm(coeff=1.0)

Test for ticket:291.

>>> from fipy import PowerLawConvectionTerm
>>> PowerLawConvectionTerm(coeff=[[1], [0]]) * 1.0
PowerLawConvectionTerm(coeff=array([[ 1.],
       [ 0.]]))
__rsub__(other)
__sub__(other)
__truediv__(other)
cacheMatrix()

Informs solve() and sweep() to cache their matrix so that matrix can return the matrix.

cacheRHSvector()

Informs solve() and sweep() to cache their right hand side vector so that getRHSvector() can return it.

copy()
getDefaultSolver(var=None, solver=None, *args, **kwargs)
justErrorVector(var=None, solver=None, boundaryConditions=(), dt=1.0, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the error as well as applying under-relaxation.

justErrorVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy.solvers import DummySolver
>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(DiffusionTerm().justErrorVector(v, solver=DummySolver())) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

error – The residual vector \vec{e}=\mathsf{L}\vec{x}_\text{old} - \vec{b}

Return type:

CellVariable

justResidualVector(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

justResidualVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(numerix.asarray(DiffusionTerm().justResidualVector(v))) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

property matrix

Return the matrix calculated in solve() or sweep(). The cacheMatrix() method should be called before solve() or sweep() to cache the matrix.

residualVectorAndNorm(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

  • residual (~fipy.variables.cellVariable.CellVariable) – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

  • norm (float) – The L2 norm of residual, \|\vec{r}\|_2

solve(var=None, solver=None, boundaryConditions=(), dt=None)

Builds and solves the Term’s linear system once. This method does not return the residual. It should be used when the residual is not required.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

sweep(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None, cacheResidual=False, cacheError=False)

Builds and solves the Term’s linear system once. This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

  • cacheResidual (bool) – If True, calculate and store the residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b} in the residualVector member of Term

  • cacheError (bool) – If True, use the residual vector \vec{r} to solve \mathsf{L}\vec{e}=\vec{r} for the error vector \vec{e} and store it in the errorVector member of Term

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

exception fipy.ExplicitVariableError(s='Terms with explicit Variables cannot mix with Terms with implicit Variables.')

Bases: Exception

__cause__

exception cause

__context__

exception context

__delattr__(name, /)

Implement delattr(self, name).

__getattribute__(name, /)

Return getattr(self, name).

__reduce__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__setstate__()
__str__()

Return str(self).

__suppress_context__
__traceback__
args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class fipy.ExponentialConvectionTerm(coeff=1.0, var=None)

Bases: _AsymmetricConvectionTerm

The discretization for this Term is given by

\int_V \nabla \cdot (\vec{u} \phi)\,dV \simeq \sum_{f} (\vec{n}
\cdot \vec{u})_f \phi_f A_f

where \phi_f=\alpha_f \phi_P +(1-\alpha_f)\phi_A and \alpha_f is calculated using the exponential scheme. For further details see Numerical Schemes.

Create a _AbstractConvectionTerm object.

>>> from fipy import *
>>> m = Grid1D(nx = 2)
>>> cv = CellVariable(mesh = m)
>>> fv = FaceVariable(mesh = m)
>>> vcv = CellVariable(mesh=m, rank=1)
>>> vfv = FaceVariable(mesh=m, rank=1)
>>> __ConvectionTerm(coeff = cv) 
Traceback (most recent call last):
    ...
VectorCoeffError: The coefficient must be a vector value.
>>> __ConvectionTerm(coeff = fv) 
Traceback (most recent call last):
    ...
VectorCoeffError: The coefficient must be a vector value.
>>> __ConvectionTerm(coeff = vcv)
__ConvectionTerm(coeff=_ArithmeticCellToFaceVariable(value=array([[ 0.,  0.,  0.]]), mesh=UniformGrid1D(dx=1.0, nx=2)))
>>> __ConvectionTerm(coeff = vfv)
__ConvectionTerm(coeff=FaceVariable(value=array([[ 0.,  0.,  0.]]), mesh=UniformGrid1D(dx=1.0, nx=2)))
>>> __ConvectionTerm(coeff = (1,))
__ConvectionTerm(coeff=(1,))
>>> ExplicitUpwindConvectionTerm(coeff = (0,)).solve(var=cv, solver=DummySolver()) 
Traceback (most recent call last):
    ...
TransientTermError: The equation requires a TransientTerm with explicit convection.
>>> (TransientTerm(0.) - ExplicitUpwindConvectionTerm(coeff = (0,))).solve(var=cv, solver=DummySolver(), dt=1.)
>>> (TransientTerm() - ExplicitUpwindConvectionTerm(coeff = 1)).solve(var=cv, solver=DummySolver(), dt=1.) 
Traceback (most recent call last):
    ...
VectorCoeffError: The coefficient must be a vector value.
>>> m2 = Grid2D(nx=2, ny=1)
>>> cv2 = CellVariable(mesh=m2)
>>> vcv2 = CellVariable(mesh=m2, rank=1)
>>> vfv2 = FaceVariable(mesh=m2, rank=1)
>>> __ConvectionTerm(coeff=vcv2)
__ConvectionTerm(coeff=_ArithmeticCellToFaceVariable(value=array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]]), mesh=UniformGrid2D(dx=1.0, nx=2, dy=1.0, ny=1)))
>>> __ConvectionTerm(coeff=vfv2)
__ConvectionTerm(coeff=FaceVariable(value=array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]]), mesh=UniformGrid2D(dx=1.0, nx=2, dy=1.0, ny=1)))
>>> (TransientTerm() - ExplicitUpwindConvectionTerm(coeff = ((0,), (0,)))).solve(var=cv2, solver=DummySolver(), dt=1.)
>>> (TransientTerm() - ExplicitUpwindConvectionTerm(coeff = (0, 0))).solve(var=cv2, solver=DummySolver(), dt=1.)
Parameters:

coeff (The Term’s coefficient value.) –

property RHSvector

Return the RHS vector calculated in solve() or sweep(). The cacheRHSvector() method should be called before solve() or sweep() to cache the vector.

__add__(other)
__and__(other)
__div__(other)
__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__mul__(other)

Multiply a term

>>> 2. * __NonDiffusionTerm(coeff=0.5)
__NonDiffusionTerm(coeff=1.0)

Test for ticket:291.

>>> from fipy import PowerLawConvectionTerm
>>> PowerLawConvectionTerm(coeff=[[1], [0]]) * 1.0
PowerLawConvectionTerm(coeff=array([[ 1.],
       [ 0.]]))
__neg__()

Negate a Term.

>>> -__NonDiffusionTerm(coeff=1.)
__NonDiffusionTerm(coeff=-1.0)
__pos__()
__radd__(other)
__rand__(other)
__repr__()

The representation of a Term object is given by,

>>> print(__UnaryTerm(123.456))
__UnaryTerm(coeff=123.456)
__rmul__(other)

Multiply a term

>>> 2. * __NonDiffusionTerm(coeff=0.5)
__NonDiffusionTerm(coeff=1.0)

Test for ticket:291.

>>> from fipy import PowerLawConvectionTerm
>>> PowerLawConvectionTerm(coeff=[[1], [0]]) * 1.0
PowerLawConvectionTerm(coeff=array([[ 1.],
       [ 0.]]))
__rsub__(other)
__sub__(other)
__truediv__(other)
cacheMatrix()

Informs solve() and sweep() to cache their matrix so that matrix can return the matrix.

cacheRHSvector()

Informs solve() and sweep() to cache their right hand side vector so that getRHSvector() can return it.

copy()
getDefaultSolver(var=None, solver=None, *args, **kwargs)
justErrorVector(var=None, solver=None, boundaryConditions=(), dt=1.0, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the error as well as applying under-relaxation.

justErrorVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy.solvers import DummySolver
>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(DiffusionTerm().justErrorVector(v, solver=DummySolver())) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

error – The residual vector \vec{e}=\mathsf{L}\vec{x}_\text{old} - \vec{b}

Return type:

CellVariable

justResidualVector(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

justResidualVector returns the overlapping local value in parallel (not the non-overlapping value).

>>> from fipy import *
>>> m = Grid1D(nx=10)
>>> v = CellVariable(mesh=m)
>>> len(numerix.asarray(DiffusionTerm().justResidualVector(v))) == m.numberOfCells
True
Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

property matrix

Return the matrix calculated in solve() or sweep(). The cacheMatrix() method should be called before solve() or sweep() to cache the matrix.

residualVectorAndNorm(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None)

Builds the Term’s linear system once.

This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

Returns:

  • residual (~fipy.variables.cellVariable.CellVariable) – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

  • norm (float) – The L2 norm of residual, \|\vec{r}\|_2

solve(var=None, solver=None, boundaryConditions=(), dt=None)

Builds and solves the Term’s linear system once. This method does not return the residual. It should be used when the residual is not required.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

sweep(var=None, solver=None, boundaryConditions=(), dt=None, underRelaxation=None, residualFn=None, cacheResidual=False, cacheError=False)

Builds and solves the Term’s linear system once. This method also recalculates and returns the residual as well as applying under-relaxation.

Parameters:
  • var (CellVariable) – Variable to be solved for. Provides the initial condition, the old value and holds the solution on completion.

  • solver (Solver) – Iterative solver to be used to solve the linear system of equations. The default sovler depends on the solver package selected.

  • boundaryConditions (tuple of BoundaryCondition) –

  • dt (float) – Timestep size.

  • underRelaxation (float) – Usually a value between 0 and 1 or None in the case of no under-relaxation

  • residualFn (function) – Takes var, matrix, and RHSvector arguments, used to customize the residual calculation.

  • cacheResidual (bool) – If True, calculate and store the residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b} in the residualVector member of Term

  • cacheError (bool) – If True, use the residual vector \vec{r} to solve \mathsf{L}\vec{e}=\vec{r} for the error vector \vec{e} and store it in the errorVector member of Term

Returns:

residual – The residual vector \vec{r}=\mathsf{L}\vec{x} - \vec{b}

Return type:

CellVariable

class fipy.ExponentialNoiseVariable(*args, **kwds)

Bases: NoiseVariable

Represents an exponential distribution of random numbers with the probability distribution

\mu^{-1} e^{-\frac{x}{\mu}}

with a mean parameter \mu.

Seed the random module for the sake of deterministic test results.

>>> from fipy import numerix
>>> numerix.random.seed(1)

We generate noise on a uniform Cartesian mesh

>>> from fipy.variables.variable import Variable
>>> mean = Variable()
>>> from fipy.meshes import Grid2D
>>> noise = ExponentialNoiseVariable(mesh = Grid2D(nx = 100, ny = 100), mean = mean)

We histogram the root-volume-weighted noise distribution

>>> from fipy.variables.histogramVariable import HistogramVariable
>>> histogram = HistogramVariable(distribution = noise, dx = 0.1, nx = 100)

and compare to a Gaussian distribution

>>> from fipy.variables.cellVariable import CellVariable
>>> expdist = CellVariable(mesh = histogram.mesh)
>>> x = histogram.mesh.cellCenters[0]
>>> if __name__ == '__main__':
...     from fipy import Viewer
...     viewer = Viewer(vars=noise, datamin=0, datamax=5)
...     histoplot = Viewer(vars=(histogram, expdist),
...                        datamin=0, datamax=1.5)
>>> from fipy.tools.numerix import arange, exp
>>> for mu in arange(0.5, 3, 0.5):
...     mean.value = (mu)
...     expdist.value = ((1/mean)*exp(-x/mean))
...     if __name__ == '__main__':
...         import sys
...         print("mean: %g" % mean, file=sys.stderr)
...         viewer.plot()
...         histoplot.plot()
>>> print(abs(noise.faceGrad.divergence.cellVolumeAverage) < 5e-15)
1
random values with an exponential distribution histogram of random values with an exponential distribution
Parameters:
  • mesh (Mesh) – The mesh on which to define the noise.

  • mean (float) – The mean of the distribution \mu.

__abs__()

Following test it to fix a bug with C inline string using abs() instead of fabs()

>>> print(abs(Variable(2.3) - Variable(1.2)))
1.1

Check representation works with different versions of numpy

>>> print(repr(abs(Variable(2.3))))
numerix.fabs(Variable(value=array(2.3)))
__add__(other)
__and__(other)

This test case has been added due to a weird bug that was appearing.

>>> a = Variable(value=(0, 0, 1, 1))
>>> b = Variable(value=(0, 1, 0, 1))
>>> print(numerix.equal((a == 0) & (b == 1), [False,  True, False, False]).all())
True
>>> print(a & b)
[0 0 0 1]
>>> from fipy.meshes import Grid1D
>>> mesh = Grid1D(nx=4)
>>> from fipy.variables.cellVariable import CellVariable
>>> a = CellVariable(value=(0, 0, 1, 1), mesh=mesh)
>>> b = CellVariable(value=(0, 1, 0, 1), mesh=mesh)
>>> print(numerix.allequal((a == 0) & (b == 1), [False,  True, False, False]))
True
>>> print(a & b)
[0 0 0 1]
__array__(t=None)

Attempt to convert the Variable to a numerix array object

>>> v = Variable(value=[2, 3])
>>> print(numerix.array(v))
[2 3]

A dimensional Variable will convert to the numeric value in its base units

>>> v = Variable(value=[2, 3], unit="mm")
>>> numerix.array(v)
array([ 0.002,  0.003])
__array_priority__ = 100.0
__array_wrap__(arr, context=None)

Required to prevent numpy not calling the reverse binary operations. Both the following tests are examples ufuncs.

>>> print(type(numerix.array([1.0, 2.0]) * Variable([1.0, 2.0]))) 
<class 'fipy.variables.binaryOperatorVariable...binOp'>
>>> from scipy.special import gamma as Gamma 
>>> print(type(Gamma(Variable([1.0, 2.0])))) 
<class 'fipy.variables.unaryOperatorVariable...unOp'>
__bool__()
>>> print(bool(Variable(value=0)))
0
>>> print(bool(Variable(value=(0, 0, 1, 1))))
Traceback (most recent call last):
    ...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
__call__(points=None, order=0, nearestCellIDs=None)

Interpolates the CellVariable to a set of points using a method that has a memory requirement on the order of Ncells by Npoints in general, but uses only Ncells when the CellVariable’s mesh is a UniformGrid object.

Tests

>>> from fipy import *
>>> m = Grid2D(nx=3, ny=2)
>>> v = CellVariable(mesh=m, value=m.cellCenters[0])
>>> print(v(((0., 1.1, 1.2), (0., 1., 1.))))
[