fipy.tools package

Subpackages

Submodules

fipy.tools.debug module

fipy.tools.debug.PRINT(label, arg='', stall=True)

fipy.tools.decorators module

fipy.tools.decorators.deprecate(*args, **kwargs)

Issues a generic DeprecationWarning.

This function may also be used as a decorator.

Parameters:
  • func (function) – The function to be deprecated.

  • old_name (str, optional) – The name of the function to be deprecated. Default is None, in which case the name of func is used.

  • new_name (str, optional) – The new name for the function. Default is None, in which case the deprecation message is that old_name is deprecated. If given, the deprecation message is that old_name is deprecated and new_name should be used instead.

  • message (str, optional) – Additional explanation of the deprecation. Displayed in the docstring after the warning.

Returns:

old_func – The deprecated function.

Return type:

function

fipy.tools.dump module

fipy.tools.dump.read(filename, fileobject=None, communicator=SerialPETScCommWrapper(), mesh_unmangle=False)

Read a pickled object from a file. Returns the unpickled object. Wrapper for cPickle.load().

Parameters:
  • filename (str) – Name of the file to unpickle the object from. If the filename extension is .gz, the file is first decompressed.

  • fileobject (file) – Used to remove temporary files

  • communicator (CommWrapper) – A duck-typed object with procID and Nproc attributes is sufficient

  • mesh_unmangle (bool) – Whether to correct improper pickling of non-uniform meshes (ticket:243)

fipy.tools.dump.write(data, filename=None, extension='', communicator=SerialPETScCommWrapper())

Pickle an object and write it to a file. Wrapper for cPickle.dump().

Test to check pickling and unpickling.

>>> from fipy.meshes import Grid1D
>>> old = Grid1D(nx = 2)
>>> f, tempfile = write(old)
>>> new = read(tempfile, f)
>>> print(old.numberOfCells == new.numberOfCells)
True
Parameters:
  • data – Object to be pickled.

  • filename (str) – Name of the file to place the pickled object. If filename is None then a temporary file will be used and the file object and file name will be returned as a tuple. If the filename ends in .gz, the file is automatically saved in compressed gzip format.

  • extension (str) – File extension to append if filename is not given. If set to .gz, the file is automatically saved in compressed gzip format.

  • communicator (CommWrapper) – A duck-typed object with procID and Nproc attributes is sufficient

fipy.tools.inline module

fipy.tools.numerix module

Replacement module for NumPy

Attention

This module should be the only place in the code where numpy is explicitly imported and you should always import this module and not numpy in your own code. The documentation for numpy remains canonical for all functions and classes not explicitly documented here.

The functions provided in this module replace and augment the NumPy module. The functions work with Variables, arrays or numbers. For example, create a Variable.

>>> from fipy.variables.variable import Variable
>>> var = Variable(value=0)

Take the tangent of such a variable. The returned value is itself a Variable.

>>> v = tan(var)
>>> v
tan(Variable(value=array(0)))
>>> print(float(v))
0.0

Take the tangent of a int.

>>> tan(0)
0.0

Take the tangent of an array.

>>> print(tan(array((0, 0, 0))))
[ 0.  0.  0.]
fipy.tools.numerix.L1norm(arr)

Taxicab or Manhattan norm of arr

\|\mathtt{arr}\|_1 = \sum_{j=1}^{n} |\mathtt{arr}_j| is the L^1 norm of \mathtt{arr}.

Parameters:

arr (ndarray) –

fipy.tools.numerix.L2norm(arr)

Euclidean norm of arr

\|\mathtt{arr}\|_2 = \sqrt{\sum_{j=1}^{n} |\mathtt{arr}_j|^2} is the L^2 norm of \mathtt{arr}.

Parameters:

arr (ndarray) –

fipy.tools.numerix.LINFnorm(arr)

Infinity norm of arr

\|\mathtt{arr}\|_\infty = [\sum_{j=1}^{n}
|\mathtt{arr}_j|^\infty]^\infty = \underset{j}{\max} |\mathtt{arr}_j| is the L^\infty norm of \mathtt{arr}.

Parameters:

arr (ndarray) –

fipy.tools.numerix.all(a, axis=None, out=None)

Test whether all array elements along a given axis evaluate to True.

Parameters:
  • a (array_like) – Input array or object that can be converted to an array.

  • axis (int, optional) – Axis along which an logical AND is performed. The default (axis = None) is to perform a logical AND over a flattened input array. axis may be negative, in which case it counts from the last to the first axis.

  • out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape as the expected output and the type is preserved.

fipy.tools.numerix.allclose(first, second, rtol=1e-05, atol=1e-08)

Tests whether or not first and second are equal, subject to the given relative and absolute tolerances, such that:

|first - second| < atol + rtol * |second|

This means essentially that both elements are small compared to atol or their difference divided by second’s value is small compared to rtol.

fipy.tools.numerix.allequal(first, second)

Returns true if every element of first is equal to the corresponding element of second.

fipy.tools.numerix.dot(a1, a2, axis=0)

return array of vector dot-products of v1 and v2 for arrays a1 and a2 of vectors v1 and v2

We can’t use numpy.dot() on an array of vectors

Test that Variables are returned as Variables.

>>> from fipy.meshes import Grid2D
>>> mesh = Grid2D(nx=2, ny=1)
>>> from fipy.variables.cellVariable import CellVariable
>>> v1 = CellVariable(mesh=mesh, value=((0, 1), (2, 3)), rank=1)
>>> v2 = CellVariable(mesh=mesh, value=((0, 1), (2, 3)), rank=1)
>>> dot(v1, v2)._variableClass
<class 'fipy.variables.cellVariable.CellVariable'>
>>> dot(v2, v1)._variableClass
<class 'fipy.variables.cellVariable.CellVariable'>
>>> print(rank(dot(v2, v1)))
0
>>> print(dot(v1, v2))
[ 4 10]
>>> dot(v1, v1)._variableClass
<class 'fipy.variables.cellVariable.CellVariable'>
>>> print(dot(v1, v1))
[ 4 10]
>>> v3 = array(((0, 1), (2, 3)))
>>> print(isinstance(dot(v3, v3), type(array(1))))
1
>>> print(dot(v3, v3))
[ 4 10]
class fipy.tools.numerix.dtype(dtype, align=False, copy=False)

Bases: object

Create a data type object.

A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be constructed from different combinations of fundamental numeric types.

Parameters:
  • dtype – Object to be converted to a data type object.

  • align (bool, optional) – Add padding to the fields to match what a C compiler would output for a similar C-struct. Can be True only if obj is a dictionary or a comma-separated string. If a struct dtype is being created, this also sets a sticky alignment flag isalignedstruct.

  • copy (bool, optional) – Make a new copy of the data-type object. If False, the result may just be a reference to a built-in data-type object.

See also

result_type

Examples

Using array-scalar type:

>>> np.dtype(np.int16)
dtype('int16')

Structured type, one field name ‘f1’, containing int16:

>>> np.dtype([('f1', np.int16)])
dtype([('f1', '<i2')])

Structured type, one field named ‘f1’, in itself containing a structured type with one field:

>>> np.dtype([('f1', [('f1', np.int16)])])
dtype([('f1', [('f1', '<i2')])])

Structured type, two fields: the first field contains an unsigned int, the second an int32:

>>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
dtype([('f1', '<u8'), ('f2', '<i4')])

Using array-protocol type strings:

>>> np.dtype([('a','f8'),('b','S10')])
dtype([('a', '<f8'), ('b', 'S10')])

Using comma-separated field formats. The shape is (2,3):

>>> np.dtype("i4, (2,3)f8")
dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])

Using tuples. int is a fixed type, 3 the field’s shape. void is a flexible type, here of size 10:

>>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
dtype([('hello', '<i8', (3,)), ('world', 'V10')])

Subdivide int16 into 2 int8’s, called x and y. 0 and 1 are the offsets in bytes:

>>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))

Using dictionaries. Two fields named ‘gender’ and ‘age’:

>>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
dtype([('gender', 'S1'), ('age', 'u1')])

Offsets in bytes, here 0 and 25:

>>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
dtype([('surname', 'S25'), ('age', 'u1')])
__bool__()

True if self else False

__eq__(value, /)

Return self==value.

__ge__(value, /)

Return self>=value.

__getitem__(key, /)

Return self[key].

__gt__(value, /)

Return self>value.

__hash__()

Return hash(self).

__le__(value, /)

Return self<=value.

__len__()

Return len(self).

__lt__(value, /)

Return self<value.

__mul__(value, /)

Return self*value.

__ne__(value, /)

Return self!=value.

__reduce__()

Helper for pickle.

__repr__()

Return repr(self).

__rmul__(value, /)

Return value*self.

__setstate__()
__str__()

Return str(self).

alignment

The required alignment (bytes) of this data-type according to the compiler.

More information is available in the C-API section of the manual.

Examples

>>> x = np.dtype('i4')
>>> x.alignment
4
>>> x = np.dtype(float)
>>> x.alignment
8
base

Returns dtype for the base element of the subarrays, regardless of their dimension or shape.

See also

dtype.subdtype

Examples

>>> x = numpy.dtype('8f')
>>> x.base
dtype('float32')
>>> x =  numpy.dtype('i2')
>>> x.base
dtype('int16')
byteorder

A character indicating the byte-order of this data-type object.

One of:

‘=’

native

‘<’

little-endian

‘>’

big-endian

‘|’

not applicable

All built-in data-type objects have byteorder either ‘=’ or ‘|’.

Examples

>>> dt = np.dtype('i2')
>>> dt.byteorder
'='
>>> # endian is not relevant for 8 bit numbers
>>> np.dtype('i1').byteorder
'|'
>>> # or ASCII strings
>>> np.dtype('S2').byteorder
'|'
>>> # Even if specific code is given, and it is native
>>> # '=' is the byteorder
>>> import sys
>>> sys_is_le = sys.byteorder == 'little'
>>> native_code = sys_is_le and '<' or '>'
>>> swapped_code = sys_is_le and '>' or '<'
>>> dt = np.dtype(native_code + 'i2')
>>> dt.byteorder
'='
>>> # Swapped code shows up as itself
>>> dt = np.dtype(swapped_code + 'i2')
>>> dt.byteorder == swapped_code
True
char

A unique character code for each of the 21 different built-in types.

Examples

>>> x = np.dtype(float)
>>> x.char
'd'
descr

__array_interface__ description of the data-type.

The format is that required by the ‘descr’ key in the __array_interface__ attribute.

Warning: This attribute exists specifically for __array_interface__, and passing it directly to np.dtype will not accurately reconstruct some dtypes (e.g., scalar and subarray dtypes).

Examples

>>> x = np.dtype(float)
>>> x.descr
[('', '<f8')]
>>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
>>> dt.descr
[('name', '<U16'), ('grades', '<f8', (2,))]
fields

Dictionary of named fields defined for this data type, or None.

The dictionary is indexed by keys that are the names of the fields. Each entry in the dictionary is a tuple fully describing the field:

(dtype, offset[, title])

Offset is limited to C int, which is signed and usually 32 bits. If present, the optional title can be any object (if it is a string or unicode then it will also be a key in the fields dictionary, otherwise it’s meta-data). Notice also that the first two elements of the tuple can be passed directly as arguments to the ndarray.getfield and ndarray.setfield methods.

See also

ndarray.getfield, ndarray.setfield

Examples

>>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
>>> print(dt.fields)
{'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
flags

Bit-flags describing how this data type is to be interpreted.

Bit-masks are in numpy.core.multiarray as the constants ITEM_HASOBJECT, LIST_PICKLE, ITEM_IS_POINTER, NEEDS_INIT, NEEDS_PYAPI, USE_GETITEM, USE_SETITEM. A full explanation of these flags is in C-API documentation; they are largely useful for user-defined data-types.

The following example demonstrates that operations on this particular dtype requires Python C-API.

Examples

>>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
>>> x.flags
16
>>> np.core.multiarray.NEEDS_PYAPI
16
hasobject

Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes.

Recall that what is actually in the ndarray memory representing the Python object is the memory address of that object (a pointer). Special handling may be required, and this attribute is useful for distinguishing data types that may contain arbitrary Python objects and data-types that won’t.

isalignedstruct

Boolean indicating whether the dtype is a struct which maintains field alignment. This flag is sticky, so when combining multiple structs together, it is preserved and produces new dtypes which are also aligned.

isbuiltin

Integer indicating how this dtype relates to the built-in dtypes.

Read-only.

0

if this is a structured array type, with fields

1

if this is a dtype compiled into numpy (such as ints, floats etc)

2

if the dtype is for a user-defined numpy type A user-defined type uses the numpy C-API machinery to extend numpy to handle a new array type. See User-defined data-types in the NumPy manual.

Examples

>>> dt = np.dtype('i2')
>>> dt.isbuiltin
1
>>> dt = np.dtype('f8')
>>> dt.isbuiltin
1
>>> dt = np.dtype([('field1', 'f8')])
>>> dt.isbuiltin
0
isnative

Boolean indicating whether the byte order of this dtype is native to the platform.

itemsize

The element size of this data-type object.

For 18 of the 21 types this number is fixed by the data-type. For the flexible data-types, this number can be anything.

Examples

>>> arr = np.array([[1, 2], [3, 4]])
>>> arr.dtype
dtype('int64')
>>> arr.itemsize
8
>>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
>>> dt.itemsize
80
kind

A character code (one of ‘biufcmMOSUV’) identifying the general kind of data.

b

boolean

i

signed integer

u

unsigned integer

f

floating-point

c

complex floating-point

m

timedelta

M

datetime

O

object

S

(byte-)string

U

Unicode

V

void

Examples

>>> dt = np.dtype('i4')
>>> dt.kind
'i'
>>> dt = np.dtype('f8')
>>> dt.kind
'f'
>>> dt = np.dtype([('field1', 'f8')])
>>> dt.kind
'V'
metadata

Either None or a readonly dictionary of metadata (mappingproxy).

The metadata field can be set using any dictionary at data-type creation. NumPy currently has no uniform approach to propagating metadata; although some array operations preserve it, there is no guarantee that others will.

Warning

Although used in certain projects, this feature was long undocumented and is not well supported. Some aspects of metadata propagation are expected to change in the future.

Examples

>>> dt = np.dtype(float, metadata={"key": "value"})
>>> dt.metadata["key"]
'value'
>>> arr = np.array([1, 2, 3], dtype=dt)
>>> arr.dtype.metadata
mappingproxy({'key': 'value'})

Adding arrays with identical datatypes currently preserves the metadata:

>>> (arr + arr).dtype.metadata
mappingproxy({'key': 'value'})

But if the arrays have different dtype metadata, the metadata may be dropped:

>>> dt2 = np.dtype(float, metadata={"key2": "value2"})
>>> arr2 = np.array([3, 2, 1], dtype=dt2)
>>> (arr + arr2).dtype.metadata is None
True  # The metadata field is cleared so None is returned
name

A bit-width name for this data-type.

Un-sized flexible data-type objects do not have this attribute.

Examples

>>> x = np.dtype(float)
>>> x.name
'float64'
>>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
>>> x.name
'void640'
names

Ordered list of field names, or None if there are no fields.

The names are ordered according to increasing byte offset. This can be used, for example, to walk through all of the named fields in offset order.

Examples

>>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
>>> dt.names
('name', 'grades')
ndim

Number of dimensions of the sub-array if this data type describes a sub-array, and 0 otherwise.

New in version 1.13.0.

Examples

>>> x = np.dtype(float)
>>> x.ndim
0
>>> x = np.dtype((float, 8))
>>> x.ndim
1
>>> x = np.dtype(('i4', (3, 4)))
>>> x.ndim
2
newbyteorder(new_order='S', /)

Return a new dtype with a different byte order.

Changes are also made in all fields and sub-arrays of the data type.

Parameters:

new_order (string, optional) –

Byte order to force; a value from the byte order specifications below. The default value (‘S’) results in swapping the current byte order. new_order codes can be any of:

  • ’S’ - swap dtype from current to opposite endian

  • {‘<’, ‘little’} - little endian

  • {‘>’, ‘big’} - big endian

  • {‘=’, ‘native’} - native order

  • {‘|’, ‘I’} - ignore (no change to byte order)

Returns:

new_dtype – New dtype object with the given change to the byte order.

Return type:

dtype

Notes

Changes are also made in all fields and sub-arrays of the data type.

Examples

>>> import sys
>>> sys_is_le = sys.byteorder == 'little'
>>> native_code = sys_is_le and '<' or '>'
>>> swapped_code = sys_is_le and '>' or '<'
>>> native_dt = np.dtype(native_code+'i2')
>>> swapped_dt = np.dtype(swapped_code+'i2')
>>> native_dt.newbyteorder('S') == swapped_dt
True
>>> native_dt.newbyteorder() == swapped_dt
True
>>> native_dt == swapped_dt.newbyteorder('S')
True
>>> native_dt == swapped_dt.newbyteorder('=')
True
>>> native_dt == swapped_dt.newbyteorder('N')
True
>>> native_dt == native_dt.newbyteorder('|')
True
>>> np.dtype('<i2') == native_dt.newbyteorder('<')
True
>>> np.dtype('<i2') == native_dt.newbyteorder('L')
True
>>> np.dtype('>i2') == native_dt.newbyteorder('>')
True
>>> np.dtype('>i2') == native_dt.newbyteorder('B')
True
num

A unique number for each of the 21 different built-in types.

These are roughly ordered from least-to-most precision.

Examples

>>> dt = np.dtype(str)
>>> dt.num
19
>>> dt = np.dtype(float)
>>> dt.num
12
shape

Shape tuple of the sub-array if this data type describes a sub-array, and () otherwise.

Examples

>>> dt = np.dtype(('i4', 4))
>>> dt.shape
(4,)
>>> dt = np.dtype(('i4', (2, 3)))
>>> dt.shape
(2, 3)
str

The array-protocol typestring of this data-type object.

subdtype

Tuple (item_dtype, shape) if this dtype describes a sub-array, and None otherwise.

The shape is the fixed shape of the sub-array described by this data type, and item_dtype the data type of the array.

If a field whose dtype object has this attribute is retrieved, then the extra dimensions implied by shape are tacked on to the end of the retrieved array.

See also

dtype.base

Examples

>>> x = numpy.dtype('8f')
>>> x.subdtype
(dtype('float32'), (8,))
>>> x =  numpy.dtype('i2')
>>> x.subdtype
>>>
type = None
fipy.tools.numerix.getShape(arr)

Return the shape of arr

>>> getShape(1)
()
>>> getShape(1.)
()
>>> from fipy.variables.variable import Variable
>>> getShape(Variable(1))
()
>>> getShape(Variable(1.))
()
>>> getShape(Variable(1., unit="m"))
()
>>> getShape(Variable("1 m"))
()
fipy.tools.numerix.getUnit(arr)
fipy.tools.numerix.isFloat(arr)
fipy.tools.numerix.isInt(arr)
fipy.tools.numerix.isclose(first, second, rtol=1e-05, atol=1e-08)

Returns which elements of first and second are equal, subject to the given relative and absolute tolerances, such that:

|first - second| < atol + rtol * |second|

This means essentially that both elements are small compared to atol or their difference divided by second’s value is small compared to rtol.

fipy.tools.numerix.nearest(data, points, max_mem=100000000.0)

find the indices of data that are closest to points

>>> from fipy import *
>>> m0 = Grid2D(dx=(.1, 1., 10.), dy=(.1, 1., 10.))
>>> m1 = Grid2D(nx=2, ny=2, dx=5., dy=5.)
>>> print(nearest(m0.cellCenters.globalValue, m1.cellCenters.globalValue))
[4 5 7 8]
>>> print(nearest(m0.cellCenters.globalValue, m1.cellCenters.globalValue, max_mem=100))
[4 5 7 8]
>>> print(nearest(m0.cellCenters.globalValue, m1.cellCenters.globalValue, max_mem=10000))
[4 5 7 8]
fipy.tools.numerix.put(arr, ids, values)

The opposite of take. The values of arr at the locations specified by ids are set to the corresponding value of values.

The following is to test improvements to puts with masked arrays. Places in the code were assuming incorrect put behavior.

>>> maskValue = 999999
>>> arr = zeros(3, 'l')
>>> ids = MA.masked_values((2, maskValue), maskValue)
>>> values = MA.masked_values((4, maskValue), maskValue)
>>> put(arr, ids, values) ## this should work
>>> print(arr)
[0 0 4]
>>> arr = MA.masked_values((maskValue, 5, 10), maskValue)
>>> ids = MA.masked_values((2, maskValue), maskValue)
>>> values = MA.masked_values((4, maskValue), maskValue)
>>> put(arr, ids, values)
>>> print(arr) ## works as expected
[-- 5 4]
>>> arr = MA.masked_values((maskValue, 5, 10), maskValue)
>>> ids = MA.masked_values((maskValue, 2), maskValue)
>>> values = MA.masked_values((4, maskValue), maskValue)
>>> put(arr, ids, values)
>>> print(arr) ## should be [-- 5 --] maybe??
[-- 5 999999]
fipy.tools.numerix.rank(a)

Get the rank of sequence a (the number of dimensions, not a matrix rank) The rank of a scalar is zero.

Note

The rank of a MeshVariable is for any single element. E.g., A CellVariable containing scalars at each cell, and defined on a 9 element Grid1D, has rank 0. If it is defined on a 3x3 Grid2D, it is still rank 0.

fipy.tools.numerix.reshape(arr, shape)

Change the shape of arr to shape, as long as the product of all the lengths of all the axes is constant (the total number of elements does not change).

fipy.tools.numerix.sqrtDot(a1, a2)

Return array of square roots of vector dot-products for arrays a1 and a2 of vectors v1 and v2

Usually used with v1==v2 to return magnitude of v1.

fipy.tools.numerix.sum(arr, axis=0)

The sum of all the elements of arr along the specified axis.

fipy.tools.numerix.take(a, indices, axis=0, fill_value=None)

Selects the elements of a corresponding to indices.

fipy.tools.numerix.tostring(arr, max_line_width=75, precision=8, suppress_small=False, separator=' ', array_output=0)

Returns a textual representation of a number or field of numbers. Each dimension is indicated by a pair of matching square brackets ([]), within which each subset of the field is output. The orientation of the dimensions is as follows: the last (rightmost) dimension is always horizontal, so that the frequent rank-1 fields use a minimum of screen real-estate. The next-to-last dimension is displayed vertically if present and any earlier dimension is displayed with additional bracket divisions.

>>> from fipy import Variable
>>> print(tostring(Variable((1, 0, 11.2345)), precision=1))
[  1.    0.   11.2]
>>> print(tostring(array((1, 2)), precision=5))
[1 2]
>>> print(tostring(array((1.12345, 2.79)), precision=2))
[ 1.12  2.79]
>>> print(tostring(1))
1
>>> print(tostring(array(1)))
1
>>> print(tostring(array([1.23345]), precision=2))
[ 1.23]
>>> print(tostring(array([1]), precision=2))
[1]
>>> print(tostring(1.123456, precision=2))
1.12
>>> print(tostring(array(1.123456), precision=3))
1.123
Parameters:
  • max_line_width (int) – Maximum number of characters used in a single line. Default is sys.output_line_width or 77.

  • precision (int) – Number of digits after the decimal point. Default is sys.float_output_precision or 8.

  • suppress_small (bool) – Whether small values should be suppressed (and output as 0). Default is sys.float_output_suppress_small or False.

  • separator (str) – What character string to place between two numbers.

  • array_output (bool) – unused

fipy.tools.parser module

fipy.tools.parser.parse(larg, action=None, type=None, default=None)

This is a wrapper function for the python optparse module. Unfortunately optparse does not allow command line arguments to be ignored. See the documentation for optparse for more details. Returns the argument value.

Parameters:
  • larg (str) – Argument to be parsed.

  • action ({‘store’, ‘store_true’, ‘store_false’, ‘store_const’, ‘append’, ‘count’, ‘callback’}) – Basic type of action to be taken when this argument is encountered at the command line. See https://docs.python.org/2/library/argparse.html#action

  • type (type) – Type to which the command-line argument should be converted

  • default – Value produced if the argument is absent from the command line

fipy.tools.sharedtempfile module

This module provides a generic, high-level interface for creating shared temporary files. All of the interfaces provided by this module can be used without fear of race conditions.

fipy.tools.sharedtempfile.SharedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix='', prefix='tmp', dir=None, delete=True, communicator=SerialPETScCommWrapper())

Create a temporary file shared by all MPI ranks.

The file is created as NamedTemporaryFile would do it. The name of the returned file-like object is accessible as its name attribute. The file will be automatically deleted when it is closed unless the delete argument is set to False.

>>> from fipy.tools import SharedTemporaryFile, parallelComm
>>> with SharedTemporaryFile(mode='w+', suffix=".tmp") as tmpFile:
...     # write on processor 0
...     if parallelComm.procID == 0:
...         _ = tmpFile.write("shared text")
...
...     parallelComm.Barrier()
...
...     # read on all processors
...     _ = tmpFile.seek(0)
...     txt = tmpFile.read()
>>> print(txt)
shared text
Parameters:
  • prefix (str) – As for mkstemp

  • suffix (str) – As for mkstemp

  • dir (str) – As for mkstemp

  • mode (str) – The mode argument to io.open (default “w+b”)

  • buffering (int) – The buffer size argument to io.open (default -1)

  • encoding (str or None) – The encoding argument to io.open (default None)

  • newline (str or None) – The newline argument to io.open (default None)

  • delete (bool) – Whether the file is deleted on close (default True)

  • communicator (CommWrapper) – MPI communicator describing ranks to share with. A duck-typed object with procID and Nproc attributes is sufficient.

Return type:

file-like object

fipy.tools.test module

fipy.tools.vector module

Vector utility functions that are inexplicably absent from Numeric

fipy.tools.vector.prune(array, shift, start=0, axis=0)

removes elements with indices i = start + shift * n where n = 0, 1, 2, …

>>> prune(numerix.arange(10), 3, 5)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> prune(numerix.arange(10), 3, 2)
array([0, 1, 3, 4, 6, 7, 9])
>>> prune(numerix.arange(10), 3)
array([1, 2, 4, 5, 7, 8])
>>> prune(numerix.arange(4, 7), 3)
array([5, 6])
fipy.tools.vector.putAdd(vector, ids, additionVector)

This is a temporary replacement for Numeric.put as it was not doing what we thought it was doing.

fipy.tools.version module

Shim for version checking

distutils.version is deprecated, but packaging.version is unavailable in Python 2.7

fipy.tools.vitals module

class fipy.tools.vitals.Vitals

Bases: Document

Returns XML formatted information about current FiPy environment

ATTRIBUTE_NODE = 2
CDATA_SECTION_NODE = 4
COMMENT_NODE = 8
DOCUMENT_FRAGMENT_NODE = 11
DOCUMENT_NODE = 9
DOCUMENT_TYPE_NODE = 10
ELEMENT_NODE = 1
ENTITY_NODE = 6
ENTITY_REFERENCE_NODE = 5
NOTATION_NODE = 12
PROCESSING_INSTRUCTION_NODE = 7
TEXT_NODE = 3
__slots__ = ('_elem_info', 'doctype', '_id_search_stack', 'childNodes', '_id_cache')
__str__()

Return str(self).

actualEncoding = None
appendChild(child)
appendInfo(name, svnpath=None, **kwargs)

append some additional information, possibly about a project under a separate svn repository

async_ = False
attributes = None
childNodes
dictToXML(d, name)
doctype
property documentElement

Top-level element of this document.

documentURI = None
encoding = None
errorHandler = None
property firstChild

First child node, or None.

implementation = <xml.dom.minidom.DOMImplementation object>
property lastChild

Last child node, or None.

property localName

Namespace-local name of this node.

namespaceURI = None
nextSibling = None
nodeName = '#document'
nodeType = 9
nodeValue = None
ownerDocument = None
parentNode = None
prefix = None
previousSibling = None
save(fname)
standalone = None
strictErrorChecking = False
svn(*args)
svncmd(cmd, *args)
tupleToXML(t, name, keys=None)
version = None

Module contents

class fipy.tools.PhysicalField(value, unit=None, array=None)

Bases: object

Physical field or quantity with units

Physical Fields can be constructed in one of two ways:

  • PhysicalField(*value*, *unit*), where *value* is a number of arbitrary type and *unit* is a string containing the unit name

    >>> print(PhysicalField(value = 10., unit = 'm'))
    10.0 m
    
  • PhysicalField(*string*), where *string* contains both the value and the unit. This form is provided to make interactive use more convenient

    >>> print(PhysicalField(value = "10. m"))
    10.0 m
    

Dimensionless quantities, with a unit of 1, can be specified in several ways

>>> print(PhysicalField(value = "1"))
1.0 1
>>> print(PhysicalField(value = 2., unit = " "))
2.0 1
>>> print(PhysicalField(value = 2.))
2.0 1

Physical arrays are also possible (and are the reason this code was adapted from Konrad Hinsen’s original PhysicalQuantity). The value can be a Numeric array:

>>> a = numerix.array(((3., 4.), (5., 6.)))
>>> print(PhysicalField(value = a, unit = "m"))
[[ 3.  4.]
 [ 5.  6.]] m

or a tuple:

>>> print(PhysicalField(value = ((3., 4.), (5., 6.)), unit = "m"))
[[ 3.  4.]
 [ 5.  6.]] m

or as a single value to be applied to every element of a supplied array:

>>> print(PhysicalField(value = 2., unit = "m", array = a))
[[ 2.  2.]
 [ 2.  2.]] m

Every element in an array has the same unit, which is stored only once for the whole array.

__abs__()

Return the absolute value of the quantity. The unit is unchanged.

>>> print(abs(PhysicalField(((3., -2.), (-1., 4.)), 'm')))
[[ 3.  2.]
 [ 1.  4.]] m
__add__(other)

Add two physical quantities, so long as their units are compatible. The unit of the result is the unit of the first operand.

>>> print(PhysicalField(10., 'km') + PhysicalField(10., 'm'))
10.01 km
>>> print(PhysicalField(10., 'km') + PhysicalField(10., 'J'))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
__array__(t=None)

Return a dimensionless PhysicalField as a Numeric array.

>>> print(numerix.array(PhysicalField(((2., 3.), (4., 5.)), "m/m")))
[[ 2.  3.]
 [ 4.  5.]]

As a special case, fields with angular units are converted to base units (radians) and then assumed dimensionless.

>>> print(numerix.array(PhysicalField(((2., 3.), (4., 5.)), "deg")))
[[ 0.03490659  0.05235988]
 [ 0.06981317  0.08726646]]

If the array is not dimensionless, the numerical value in its base units is returned.

>>> numerix.array(PhysicalField(((2., 3.), (4., 5.)), "mm"))
array([[ 0.002,  0.003],
       [ 0.004,  0.005]])
__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.

>>> from fipy.tools.dimensions.physicalField import PhysicalField
>>> print(type(numerix.array([1.0, 2.0]) * PhysicalField([1.0, 2.0], unit="m")))
<class 'fipy.tools.dimensions.physicalField.PhysicalField'>
>>> print(type(numerix.array([1.0, 2.0]) * PhysicalField([1.0, 2.0])))
<class 'fipy.tools.dimensions.physicalField.PhysicalField'>
>>> from scipy.special import gamma as Gamma 
>>> print(isinstance(Gamma(PhysicalField([1.0, 2.0])), type(numerix.array(1)))) 
1
__bool__()

Test if the quantity is zero.

Should this only pass if the unit offset is zero?

__div__(other)

Divide two physical quantities. The unit of the result is the unit of the first operand divided by the unit of the second.

>>> print(PhysicalField(10., 'm') / PhysicalField(2., 's'))
5.0 m/s

As a special case, if the result is dimensionless, the value is returned without units, rather than with a dimensionless unit of 1. This facilitates passing physical quantities to packages such as Numeric that cannot use units, while ensuring the quantities have the desired units

>>> print((PhysicalField(1., 'inch')
...        / PhysicalField(1., 'mm')))
25.4
__eq__(other)

Return self==value.

__float__()

Return a dimensionless PhysicalField quantity as a float.

>>> float(PhysicalField("2. m/m"))
2.0

As a special case, quantities with angular units are converted to base units (radians) and then assumed dimensionless.

>>> print(numerix.round(float(PhysicalField("2. deg")), 6))
0.034907

If the quantity is not dimensionless, the conversion fails.

>>> float(PhysicalField("2. m"))
Traceback (most recent call last):
    ...
TypeError: Not possible to convert a PhysicalField with dimensions to float

Just as a Numeric array cannot be cast to float, neither can PhysicalField arrays

>>> float(PhysicalField(((2., 3.), (4., 5.)), "m/m")) 
Traceback (most recent call last):
    ...
TypeError: only ...-1 arrays can be converted to Python scalars
__ge__(other)

Return self>=value.

__getitem__(index)

Return the specified element of the array. The unit of the result will be the unit of the array.

>>> a = PhysicalField(((3., 4.), (5., 6.)), "m")
>>> print(a[1, 1])
6.0 m
__gt__(other)

Compare self to other, returning an array of Boolean values corresponding to the test against each element.

>>> a = PhysicalField(((3., 4.), (5., 6.)), "m")
>>> print(numerix.allclose(a > PhysicalField("13 ft"),
...                        [[False, True], [ True, True]]))
True

Appropriately formatted dimensional quantity strings can also be compared.

>>> print(numerix.allclose(a > "13 ft",
...                        [[False, True], [ True, True]]))
True

Arrays are compared element to element

>>> print(numerix.allclose(a > PhysicalField(((3., 13.), (17., 6.)), "ft"),
...                        [[ True, True], [False, True]]))
True

Units must be compatible

>>> print(a > PhysicalField("1 lb"))
Traceback (most recent call last):
    ...
TypeError: Incompatible units

And so must array dimensions

>>> print(a > PhysicalField(((3., 13., 4.), (17., 6., 2.)), "ft")) 
Traceback (most recent call last):
    ...
ValueError: shape mismatch: objects cannot be broadcast to a single shape
__hash__()

Return hash(self).

__le__(other)

Return self<=value.

__len__()
__lt__(other)

Return self<value.

__mod__(other)

Return the remainder of dividing two physical quantities. The unit of the result is the unit of the first operand divided by the unit of the second.

>>> print(PhysicalField(11., 'm') % PhysicalField(2., 's'))
1.0 m/s
__mul__(other)

Multiply two physical quantities. The unit of the result is the product of the units of the operands.

>>> print(PhysicalField(10., 'N') * PhysicalField(10., 'm') == PhysicalField(100., 'N*m'))
True

As a special case, if the result is dimensionless, the value is returned without units, rather than with a dimensionless unit of 1. This facilitates passing physical quantities to packages such as Numeric that cannot use units, while ensuring the quantities have the desired units.

>>> print((PhysicalField(10., 's') * PhysicalField(2., 'Hz')))
20.0
__ne__(other)

Return self!=value.

__neg__()

Return the negative of the quantity. The unit is unchanged.

>>> print(-PhysicalField(((3., -2.), (-1., 4.)), 'm'))
[[-3.  2.]
 [ 1. -4.]] m
__nonzero__()

Test if the quantity is zero.

Should this only pass if the unit offset is zero?

__pos__()
__pow__(other)

Raise a PhysicalField to a power. The unit is raised to the same power.

>>> print(PhysicalField(10., 'm')**2)
100.0 m**2
__radd__(other)

Add two physical quantities, so long as their units are compatible. The unit of the result is the unit of the first operand.

>>> print(PhysicalField(10., 'km') + PhysicalField(10., 'm'))
10.01 km
>>> print(PhysicalField(10., 'km') + PhysicalField(10., 'J'))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
__rdiv__(other)
__repr__()

Return representation of a physical quantity suitable for re-use

>>> PhysicalField(value = 3., unit = "eV")
PhysicalField(3.0,'eV')
__rmul__(other)

Multiply two physical quantities. The unit of the result is the product of the units of the operands.

>>> print(PhysicalField(10., 'N') * PhysicalField(10., 'm') == PhysicalField(100., 'N*m'))
True

As a special case, if the result is dimensionless, the value is returned without units, rather than with a dimensionless unit of 1. This facilitates passing physical quantities to packages such as Numeric that cannot use units, while ensuring the quantities have the desired units.

>>> print((PhysicalField(10., 's') * PhysicalField(2., 'Hz')))
20.0
__rpow__(other)
__rsub__(other)
__rtruediv__(other)
__setitem__(index, value)

Assign the specified element of the array, performing appropriate conversions.

>>> a = PhysicalField(((3., 4.), (5., 6.)), "m")
>>> a[0, 1] = PhysicalField("6 ft")
>>> print(a)
[[ 3.      1.8288]
 [ 5.      6.    ]] m
>>> a[1, 0] = PhysicalField("2 min")
Traceback (most recent call last):
    ...
TypeError: Incompatible units
__str__()

Return human-readable form of a physical quantity

>>> print(PhysicalField(value = 3., unit = "eV"))
3.0 eV
__sub__(other)

Subtract two physical quantities, so long as their units are compatible. The unit of the result is the unit of the first operand.

>>> print(PhysicalField(10., 'km') - PhysicalField(10., 'm'))
9.99 km
>>> print(PhysicalField(10., 'km') - PhysicalField(10., 'J'))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
__truediv__(other)

Divide two physical quantities. The unit of the result is the unit of the first operand divided by the unit of the second.

>>> print(PhysicalField(10., 'm') / PhysicalField(2., 's'))
5.0 m/s

As a special case, if the result is dimensionless, the value is returned without units, rather than with a dimensionless unit of 1. This facilitates passing physical quantities to packages such as Numeric that cannot use units, while ensuring the quantities have the desired units

>>> print((PhysicalField(1., 'inch')
...        / PhysicalField(1., 'mm')))
25.4
add(other)

Add two physical quantities, so long as their units are compatible. The unit of the result is the unit of the first operand.

>>> print(PhysicalField(10., 'km') + PhysicalField(10., 'm'))
10.01 km
>>> print(PhysicalField(10., 'km') + PhysicalField(10., 'J'))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
allclose(other, atol=None, rtol=1e-08)

This function tests whether or not self and other are equal subject to the given relative and absolute tolerances. The formula used is:

| self - other | < atol + rtol * | other |

This means essentially that both elements are small compared to atol or their difference divided by other’s value is small compared to rtol.

allequal(other)

This function tests whether or not self and other are exactly equal.

arccos()

Return the inverse cosine of the PhysicalField in radians

>>> print(PhysicalField(0).arccos().allclose("1.57079632679 rad"))
1

The input PhysicalField must be dimensionless

>>> print(numerix.round(PhysicalField("1 m").arccos(), 6))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
arccosh()

Return the inverse hyperbolic cosine of the PhysicalField

>>> print(numerix.allclose(PhysicalField(2).arccosh(),
...                        1.31695789692))
1

The input PhysicalField must be dimensionless

>>> print(numerix.round(PhysicalField("1. m").arccosh(), 6))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
arcsin()

Return the inverse sine of the PhysicalField in radians

>>> print(PhysicalField(1).arcsin().allclose("1.57079632679 rad"))
1

The input PhysicalField must be dimensionless

>>> print(numerix.round(PhysicalField("1 m").arcsin(), 6))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
arctan()

Return the arctangent of the PhysicalField in radians

>>> print(numerix.round(PhysicalField(1).arctan(), 6))
0.785398

The input PhysicalField must be dimensionless

>>> print(numerix.round(PhysicalField("1 m").arctan(), 6))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
arctan2(other)

Return the arctangent of self divided by other in radians

>>> print(numerix.round(PhysicalField(2.).arctan2(PhysicalField(5.)), 6))
0.380506

The input PhysicalField objects must be in the same dimensions

>>> print(numerix.round(PhysicalField(2.54, "cm").arctan2(PhysicalField(1., "inch")), 6))
0.785398
>>> print(numerix.round(PhysicalField(2.).arctan2(PhysicalField("5. m")), 6))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
arctanh()

Return the inverse hyperbolic tangent of the PhysicalField

>>> print(PhysicalField(0.5).arctanh())
0.549306144334

The input PhysicalField must be dimensionless

>>> print(numerix.round(PhysicalField("1 m").arctanh(), 6))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
ceil()

Return the smallest integer greater than or equal to the PhysicalField.

>>> print(PhysicalField(2.2, "m").ceil())
3.0 m
conjugate()

Return the complex conjugate of the PhysicalField.

>>> print(PhysicalField(2.2 - 3j, "ohm").conjugate() == PhysicalField(2.2 + 3j, "ohm"))
True
convertToUnit(unit)

Changes the unit to unit and adjusts the value such that the combination is equivalent. The new unit is by a string containing its name. The new unit must be compatible with the previous unit of the object.

>>> e = PhysicalField('2.7 Hartree*Nav')
>>> e.convertToUnit('kcal/mol')
>>> print(e)
1694.27557621 kcal/mol
copy()

Make a duplicate.

>>> a = PhysicalField(1, unit = 'inch')
>>> b = a.copy()

The duplicate will not reflect changes made to the original

>>> a.convertToUnit('cm')
>>> print(a)
2.54 cm
>>> print(b)
1 inch

Likewise for arrays

>>> a = PhysicalField(numerix.array((0, 1, 2)), unit  = 'm')
>>> b = a.copy()
>>> a[0] = 3
>>> print(a)
[3 1 2] m
>>> print(b)
[0 1 2] m
cos()

Return the cosine of the PhysicalField

>>> print(numerix.round(PhysicalField(2*numerix.pi/6, "rad").cos(), 6))
0.5
>>> print(numerix.round(PhysicalField(60., "deg").cos(), 6))
0.5

The units of the PhysicalField must be an angle

>>> PhysicalField(60., "m").cos()
Traceback (most recent call last):
    ...
TypeError: Incompatible units
cosh()

Return the hyperbolic cosine of the PhysicalField

>>> PhysicalField(0.).cosh()
1.0

The units of the PhysicalField must be dimensionless

>>> PhysicalField(60., "m").cosh()
Traceback (most recent call last):
    ...
TypeError: Incompatible units
divide(other)

Divide two physical quantities. The unit of the result is the unit of the first operand divided by the unit of the second.

>>> print(PhysicalField(10., 'm') / PhysicalField(2., 's'))
5.0 m/s

As a special case, if the result is dimensionless, the value is returned without units, rather than with a dimensionless unit of 1. This facilitates passing physical quantities to packages such as Numeric that cannot use units, while ensuring the quantities have the desired units

>>> print((PhysicalField(1., 'inch')
...        / PhysicalField(1., 'mm')))
25.4
dot(other)

Return the dot product of self with other. The resulting unit is the product of the units of self and other.

>>> v = PhysicalField(((5., 6.), (7., 8.)), "m")
>>> print(PhysicalField(((1., 2.), (3., 4.)), "m").dot(v))
[ 26.  44.] m**2
floor()

Return the largest integer less than or equal to the PhysicalField.

>>> print(PhysicalField(2.2, "m").floor())
2.0 m
getsctype(default=None)

Returns the NumPy sctype of the underlying array.

>>> PhysicalField(1, 'm').getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1))
True
>>> PhysicalField(1., 'm').getsctype() == numerix.NUMERIX.obj2sctype(numerix.array(1.))
True
>>> PhysicalField((1, 1.), 'm').getsctype() == numerix.NUMERIX.obj2sctype(numerix.array((1., 1.)))
True
inBaseUnits()

Return the quantity with all units reduced to their base SI elements.

>>> e = PhysicalField('2.7 Hartree*Nav')
>>> print(e.inBaseUnits().allclose("7088849.01085 kg*m**2/s**2/mol"))
1
inDimensionless()

Returns the numerical value of a dimensionless quantity.

>>> print(PhysicalField(((2., 3.), (4., 5.))).inDimensionless())
[[ 2.  3.]
 [ 4.  5.]]

It’s an error to convert a quantity with units

>>> print(PhysicalField(((2., 3.), (4., 5.)), "m").inDimensionless())
Traceback (most recent call last):
    ...
TypeError: Incompatible units
inRadians()

Converts an angular quantity to radians and returns the numerical value.

>>> print(PhysicalField(((2., 3.), (4., 5.)), "rad").inRadians())
[[ 2.  3.]
 [ 4.  5.]]
>>> print(PhysicalField(((2., 3.), (4., 5.)), "deg").inRadians())
[[ 0.03490659  0.05235988]
 [ 0.06981317  0.08726646]]

As a special case, assumes a dimensionless quantity is already in radians.

>>> print(PhysicalField(((2., 3.), (4., 5.))).inRadians())
[[ 2.  3.]
 [ 4.  5.]]

It’s an error to convert a quantity with non-angular units

>>> print(PhysicalField(((2., 3.), (4., 5.)), "m").inRadians())
Traceback (most recent call last):
    ...
TypeError: Incompatible units
inSIUnits()

Return the quantity with all units reduced to SI-compatible elements.

>>> e = PhysicalField('2.7 Hartree*Nav')
>>> print(e.inSIUnits().allclose("7088849.01085 kg*m**2/s**2/mol"))
1
inUnitsOf(*units)

Returns one or more PhysicalField 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 PhysicalField.

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

If several units are specified, the return value is a tuple of PhysicalField 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 = PhysicalField(314159., '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
isCompatible(unit)
itemset(value)

Assign the value of a scalar array, performing appropriate conversions.

>>> a = PhysicalField(4., "m")
>>> a.itemset(PhysicalField("6 ft"))
>>> print(a.allclose("1.8288 m"))
1
>>> a = PhysicalField(((3., 4.), (5., 6.)), "m")
>>> try: 
...     a.itemset(PhysicalField("6 ft"))
... except IndexError:
...     # NumPy 1.7 has changed the exception type
...     raise ValueError("can only place a scalar for an  array of size 1")
Traceback (most recent call last):
    ...
ValueError: can only convert an array of size 1 to a Python scalar
>>> a.itemset(PhysicalField("2 min"))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
property itemsize
log()

Return the natural logarithm of the PhysicalField

>>> print(numerix.round(PhysicalField(10).log(), 6))
2.302585

The input PhysicalField must be dimensionless

>>> print(numerix.round(PhysicalField("1. m").log(), 6))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
log10()

Return the base-10 logarithm of the PhysicalField

>>> print(numerix.round(PhysicalField(10.).log10(), 6))
1.0

The input PhysicalField must be dimensionless

>>> print(numerix.round(PhysicalField("1. m").log10(), 6))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
multiply(other)

Multiply two physical quantities. The unit of the result is the product of the units of the operands.

>>> print(PhysicalField(10., 'N') * PhysicalField(10., 'm') == PhysicalField(100., 'N*m'))
True

As a special case, if the result is dimensionless, the value is returned without units, rather than with a dimensionless unit of 1. This facilitates passing physical quantities to packages such as Numeric that cannot use units, while ensuring the quantities have the desired units.

>>> print((PhysicalField(10., 's') * PhysicalField(2., 'Hz')))
20.0
property numericValue

Return the PhysicalField without units, after conversion to base SI units.

>>> print(numerix.round(PhysicalField("1 inch").numericValue, 6))
0.0254
put(indices, values)

put is the opposite of take. The values of self at the locations specified in indices are set to the corresponding value of values.

The indices can be any integer sequence object with values suitable for indexing into the flat form of self. The values must be any sequence of values that can be converted to the typecode of self.

>>> f = PhysicalField((1., 2., 3.), "m")
>>> f.put((2, 0), PhysicalField((2., 3.), "inch"))
>>> print(f)
[ 0.0762  2.      0.0508] m

The units of values must be compatible with self.

>>> f.put(1, PhysicalField(3, "kg"))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
ravel()
reshape(shape)

Changes the shape of self to that specified in shape

>>> print(PhysicalField((1., 2., 3., 4.), "m").reshape((2, 2)))
[[ 1.  2.]
 [ 3.  4.]] m

The new shape must have the same size as the existing one.

>>> print(PhysicalField((1., 2., 3., 4.), "m").reshape((2, 3))) 
Traceback (most recent call last):
    ...
ValueError: total size of new array must be unchanged
property shape

Tuple of array dimensions.

sign()

Return the sign of the quantity. The unit is unchanged.

>>> from fipy.tools.numerix import sign
>>> print(sign(PhysicalField(((3., -2.), (-1., 4.)), 'm')))
[[ 1. -1.]
 [-1.  1.]]
sin()

Return the sine of the PhysicalField

>>> print(PhysicalField(numerix.pi/6, "rad").sin())
0.5
>>> print(PhysicalField(30., "deg").sin())
0.5

The units of the PhysicalField must be an angle

>>> PhysicalField(30., "m").sin()
Traceback (most recent call last):
    ...
TypeError: Incompatible units
sinh()

Return the hyperbolic sine of the PhysicalField

>>> PhysicalField(0.).sinh()
0.0

The units of the PhysicalField must be dimensionless

>>> PhysicalField(60., "m").sinh()
Traceback (most recent call last):
    ...
TypeError: Incompatible units
sqrt()

Return the square root of the PhysicalField

>>> print(PhysicalField("100. m**2").sqrt())
10.0 m

The resulting unit must be integral

>>> print(PhysicalField("100. m").sqrt())
Traceback (most recent call last):
    ...
TypeError: Illegal exponent
subtract(other)

Subtract two physical quantities, so long as their units are compatible. The unit of the result is the unit of the first operand.

>>> print(PhysicalField(10., 'km') - PhysicalField(10., 'm'))
9.99 km
>>> print(PhysicalField(10., 'km') - PhysicalField(10., 'J'))
Traceback (most recent call last):
    ...
TypeError: Incompatible units
sum(index=0)

Returns the sum of all of the elements in self along the specified axis (first axis by default).

>>> print(PhysicalField(((1., 2.), (3., 4.)), "m").sum())
[ 4.  6.] m
>>> print(PhysicalField(((1., 2.), (3., 4.)), "m").sum(1))
[ 3.  7.] m
take(indices, axis=0)

Return the elements of self specified by the elements of indices. The resulting PhysicalField array has the same units as the original.

>>> print(PhysicalField((1., 2., 3.), "m").take((2, 0)))
[ 3.  1.] m

The optional third argument specifies the axis along which the selection occurs, and the default value (as in the example above) is 0, the first axis.

>>> print(PhysicalField(((1., 2., 3.), (4., 5., 6.)), "m").take((2, 0), axis = 1))
[[ 3.  1.]
 [ 6.  4.]] m
tan()

Return the tangent of the PhysicalField

>>> numerix.round(PhysicalField(numerix.pi/4, "rad").tan(), 6)
1.0
>>> numerix.round(PhysicalField(45, "deg").tan(), 6)
1.0

The units of the PhysicalField must be an angle

>>> PhysicalField(45., "m").tan()
Traceback (most recent call last):
    ...
TypeError: Incompatible units
tanh()

Return the hyperbolic tangent of the PhysicalField

>>> print(numerix.allclose(PhysicalField(1.).tanh(), 0.761594155956))
True

The units of the PhysicalField must be dimensionless

>>> PhysicalField(60., "m").tanh()
Traceback (most recent call last):
    ...
TypeError: Incompatible units
tostring(max_line_width=75, precision=8, suppress_small=False, separator=' ')

Return human-readable form of a physical quantity

>>> p = PhysicalField(value = (3., 3.14159), unit = "eV")
>>> print(p.tostring(precision = 3, separator = '|'))
[ 3.   | 3.142] eV
property unit

Return the unit object of self.

>>> PhysicalField("1 m").unit
<PhysicalUnit m>
fipy.tools.SharedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix='', prefix='tmp', dir=None, delete=True, communicator=SerialPETScCommWrapper())

Create a temporary file shared by all MPI ranks.

The file is created as NamedTemporaryFile would do it. The name of the returned file-like object is accessible as its name attribute. The file will be automatically deleted when it is closed unless the delete argument is set to False.

>>> from fipy.tools import SharedTemporaryFile, parallelComm
>>> with SharedTemporaryFile(mode='w+', suffix=".tmp") as tmpFile:
...     # write on processor 0
...     if parallelComm.procID == 0:
...         _ = tmpFile.write("shared text")
...
...     parallelComm.Barrier()
...
...     # read on all processors
...     _ = tmpFile.seek(0)
...     txt = tmpFile.read()
>>> print(txt)
shared text
Parameters:
  • prefix (str) – As for mkstemp

  • suffix (str) – As for mkstemp

  • dir (str) – As for mkstemp

  • mode (str) – The mode argument to io.open (default “w+b”)

  • buffering (int) – The buffer size argument to io.open (default -1)

  • encoding (str or None) – The encoding argument to io.open (default None)

  • newline (str or None) – The newline argument to io.open (default None)

  • delete (bool) – Whether the file is deleted on close (default True)

  • communicator (CommWrapper) – MPI communicator describing ranks to share with. A duck-typed object with procID and Nproc attributes is sufficient.

Return type:

file-like object

class fipy.tools.Vitals

Bases: Document

Returns XML formatted information about current FiPy environment

ATTRIBUTE_NODE = 2
CDATA_SECTION_NODE = 4
COMMENT_NODE = 8
DOCUMENT_FRAGMENT_NODE = 11
DOCUMENT_NODE = 9
DOCUMENT_TYPE_NODE = 10
ELEMENT_NODE = 1
ENTITY_NODE = 6
ENTITY_REFERENCE_NODE = 5
NOTATION_NODE = 12
PROCESSING_INSTRUCTION_NODE = 7
TEXT_NODE = 3
__slots__ = ('_elem_info', 'doctype', '_id_search_stack', 'childNodes', '_id_cache')
__str__()

Return str(self).

actualEncoding = None
appendChild(child)
appendInfo(name, svnpath=None, **kwargs)

append some additional information, possibly about a project under a separate svn repository

async_ = False
attributes = None
childNodes
dictToXML(d, name)
doctype
property documentElement

Top-level element of this document.

documentURI = None
encoding = None
errorHandler = None
property firstChild

First child node, or None.

implementation = <xml.dom.minidom.DOMImplementation object>
property lastChild

Last child node, or None.

property localName

Namespace-local name of this node.

namespaceURI = None
nextSibling = None
nodeName = '#document'
nodeType = 9
nodeValue = None
ownerDocument = None
parentNode = None
prefix = None
previousSibling = None
save(fname)
standalone = None
strictErrorChecking = False
svn(*args)
svncmd(cmd, *args)
tupleToXML(t, name, keys=None)
version = None
Last updated on Jun 27, 2023. Created using Sphinx 6.2.1.