# evaluable¶

The function module defines the Evaluable class and derived objects, commonly referred to as nutils functions. They represent mappings from a nutils.topology onto Python space. The notabe class of Array objects map onto the space of Numpy arrays of predefined dimension and shape. Most functions used in nutils applicatons are of this latter type, including the geometry and function bases for analysis.

Nutils functions are essentially postponed python functions, stored in a tree structure of input/output dependencies. Many Array objects have directly recognizable numpy equivalents, such as Sin or Inverse. By not evaluating directly but merely stacking operations, complex operations can be defined prior to entering a quadrature loop, allowing for a higher level style programming. It also allows for automatic differentiation and code optimization.

It is important to realize that nutils functions do not map for a physical xy-domain but from a topology, where a point is characterized by the combination of an element and its local coordinate. This is a natural fit for typical finite element operations such as quadrature. Evaluation from physical coordinates is possible only via inverting of the geometry function, which is a fundamentally expensive and currently unsupported operation.

nutils.evaluable.equalshape(N, M)

Compare two array shapes.

Returns True if all indices are certainly equal, False if any indices are certainly not equal, or None if equality cannot be determined at compile time.

nutils.evaluable.replace(func=None, depthfirst=False, recursive=False, lru=4)

decorator for deep object replacement

Generates a deep replacement method for general objects based on a callable that is applied (recursively) on individual constructor arguments.

Parameters: func – Callable which maps an object onto a new object, or None if no replacement is made. It must have one positional argument for the object, and may have any number of additional positional and/or keyword arguments. depthfirst (bool) – If True, decompose each object as far a possible, then apply func to all arguments as the objects are reconstructed. Otherwise apply func directly on each new object that is encountered in the decomposition, proceding only if the return value is None. recursive (bool) – If True, repeat replacement for any object returned by func until it returns None. Otherwise perform a single, non-recursive sweep. lru (int) – Maximum size of the least-recently-used cache. A persistent weak-key dictionary is maintained for every unique set of function arguments. When the size of lru is reached, the least recently used cache is dropped. The method that searches the object to perform the replacements. callable
class nutils.evaluable.Evaluable(args)

Base class

asciitree(self, richoutput=False)

string representation

eval(self, **evalargs)

Evaluate function on a specified element, point set.

eval_withtimes(self, times, **evalargs)

Evaluate function on a specified element, point set while measure time of each step.

class nutils.evaluable.EvaluableConstant(value)

Evaluate to the given constant value.

Parameters: value – The return value of eval.
nutils.evaluable.sum(arg, axis=None)

Sum array elements over a given axis.

nutils.evaluable.dot(a, b, axes)

Contract a and b along axes.

nutils.evaluable.align(arg, where, shape)

Align array to target shape.

The align operation can be considered the opposite of transpose: instead of specifying for each axis of the return value the original position in the argument, align specifies for each axis of the argument the new position in the return value. In addition, the return value may be of higher dimension, with new axes being inserted according to the shape argument.

Parameters: arg (Array) – Original array. where (tuple of integers) – New axis positions. shape (tuple) – Shape of the aligned array. The aligned array. Array
nutils.evaluable.unalign(*args, naxes=None)

Remove (joint) inserted axes.

Given one or more array arguments, return the shortest common axis vector along with function arguments such that the original arrays can be recovered by align(). Axes beyond the first naxes are not considered for removal, keep their position (as seen from the right), and are not part of the common axis vector. Those axes should be added to the axis vector before calling align().

If naxes is None (the default), all arguments must have the same number of axes and naxes is set to this number.

class nutils.evaluable.AsEvaluableArray

Bases: object

Protocol for conversion into an Array.

as_evaluable_array

Lower this object to a nutils.evaluable.Array.

__weakref__

list of weak references to the object (if defined)

class nutils.evaluable.Array(args, shape, dtype)

Base class for array valued functions.

shape

The shape of this array function.

Type: tuple of ints
ndim

The number of dimensions of this array array function. Equal to len(shape).

Type: int
dtype

The dtype of the array elements.

Type: int, float
sum(arg, axis=None)

Sum array elements over a given axis.

dot(a, b, axes)

Contract a and b along axes.

as_evaluable_array

return self

class nutils.evaluable.NPoints

The length of the points axis.

class nutils.evaluable.Orthonormal(basis, vector)

make a vector orthonormal to a subspace

class nutils.evaluable.Inverse(func)

Matrix inverse of func over the last two axes. All other axes are treated element-wise.

static evalf(A)

Matrix inverse.

Fully equivalent to numpy.linalg.inv(), with the exception that upon singular systems inv() does not raise a LinAlgError, but rather issues a RuntimeWarning and returns NaN (not a number) values. For arguments of dimension >2 the return array contains NaN values only for those entries that correspond to singular matrices.

class nutils.evaluable.Pointwise(*args, **params)

Abstract base class for pointwise array functions.

classmethod outer(*args)

Alternative constructor that outer-aligns the arguments.

The output shape of this pointwise function is the sum of all shapes of its arguments. When called with multiple arguments, the first argument will be appended with singleton axes to match the output shape, the second argument will be prepended with as many singleton axes as the dimension of the original first argument and appended to match the output shape, and so forth and so on.

class nutils.evaluable.Cos(*args, **params)

Cosine, element-wise.

evalf = <ufunc 'cos'>
class nutils.evaluable.Sin(*args, **params)

Sine, element-wise.

evalf = <ufunc 'sin'>
class nutils.evaluable.Tan(*args, **params)

Tangent, element-wise.

evalf = <ufunc 'tan'>
class nutils.evaluable.ArcSin(*args, **params)

Inverse sine, element-wise.

evalf = <ufunc 'arcsin'>
class nutils.evaluable.ArcCos(*args, **params)

Inverse cosine, element-wise.

evalf = <ufunc 'arccos'>
class nutils.evaluable.ArcTan(*args, **params)

Inverse tangent, element-wise.

evalf = <ufunc 'arctan'>
class nutils.evaluable.CosH(*args, **params)

Hyperbolic cosine, element-wise.

evalf = <ufunc 'cosh'>
class nutils.evaluable.SinH(*args, **params)

Hyperbolic sine, element-wise.

evalf = <ufunc 'sinh'>
class nutils.evaluable.TanH(*args, **params)

Hyperbolic tangent, element-wise.

evalf = <ufunc 'tanh'>
class nutils.evaluable.ArcTanH(*args, **params)

Inverse hyperbolic tangent, element-wise.

evalf = <ufunc 'arctanh'>
class nutils.evaluable.Sampled(points, target, interpolation)

Basis-like identity operator.

Basis-like function that for every point evaluates to a partition of unity of a predefined set based on the selected interpolation scheme.

Parameters: points (2d Array) – Present point coordinates. target (2d Array) – Elementwise constant that evaluates to the target point coordinates. interpolation (str) – Interpolation scheme to map points to target: “none” or “nearest”.
class nutils.evaluable.Zeros(shape, dtype)

zero

class nutils.evaluable.Guard(fun)

bar all simplifications

class nutils.evaluable.Find(where)

indices of boolean index vector

class nutils.evaluable.DerivativeTargetBase(args, shape, dtype)

base class for derivative targets

class nutils.evaluable.WithDerivative(func, var, derivative)

Wrap the given function and define the derivative to a target.

The wrapper is typically used together with a virtual derivative target like IdentifierDerivativeTarget. The wrapper is removed in the simplified form.

Parameters: func (Array) – The function to wrap. var (DerivativeTargetBase) – The derivative target. derivative (Array) – The derivative with shape func.shape + var.shape.

IdentifierDerivativeTarget
a virtual derivative target
class nutils.evaluable.Argument(name, shape, dtype=<class 'float'>)

Array argument, to be substituted before evaluation.

The Argument is an Array with a known shape, but whose values are to be defined later, before evaluation, e.g. using replace_arguments().

It is possible to take the derivative of an Array to an Argument:

>>> from nutils import evaluable
>>> a = evaluable.Argument('x', ())
>>> b = evaluable.Argument('y', ())
>>> f = a**3 + b**2
>>> evaluable.derivative(f, b).simplified == 2.*b
True

Parameters: name (str) – The Identifier of this argument. shape (tuple of ints) – The shape of this argument.
class nutils.evaluable.IdentifierDerivativeTarget(identifier, shape)

Virtual derivative target distinguished by an identifier.

Parameters: identifier (hashable object) – The identifier for this derivative target. shape (tuple of Array or int) – The shape of this derivative target.

WithDerivative
Array wrapper with additional derivative
class nutils.evaluable.Polyval(coeffs, points)

Evaluate a polynomial

The polynomials are of the form

$Σ_{k ∈ ℤ^n | Σ_i k_i ≤ p} c_k ∏_i x_i^(k_i)$

where $$c$$ is a vector of coefficients, $$x$$ a vector of $$n$$ variables and $$p$$ a nonnegative integer degree. The coefficients are assumed to be in reverse [lexicographic order]: the coefficient for powers $$j ∈ ℤ^n$$ comes before the coefficient for powers $$k ∈ ℤ^n / {j}$$ iff $$j_i > k_i$$, where $$i = max_l(j_l ≠ k_l)$$, the index of the last non-matching power.

Parameters: coeffs (Array) – Array of coefficients where the last axis is treated as the coefficients axes. All remaining axes are treated pointwise. points (Array) – Array of values where the last axis is treated as the variables axis. All remaining axes are treated pointwise.
static evalf(coeffs, coords)

Evaluates all pairs of polynomials and values.

The degree of the polynomial and the number of variables are automatically determined from the lengths of the last axes of the arguments.

Parameters: coeffs (numpy.ndarray) – The polynomial coefficients. The last axis constitutes the axis of coefficients. values (numpy.ndarray) – The values for the variables of the coefficients. The last axis constitutes the axis of variables. The evaluated polynomial. The leading axes of values come first, followed by the leading axes of coeffs. numpy.ndarray

eval()
Evaluates joined polynomials and values.
class nutils.evaluable.PolyDegree(ncoeffs, nvars)

Returns the degree of a polynomial given the number of coefficients and number of variables

Parameters: ncoeffs (Array) – The number of coefficients of the polynomial. nvars (int) – The number of variables of the polynomial.

Notes

See Polyval for a definition of the polynomial.

class nutils.evaluable.PolyNCoeffs(nvars, degree)

Returns the number of coefficients for a polynomial of given degree and number of variables

Parameters: nvars (int) – The number of variables of the polynomial. degree (Array) – The degree of the polynomial.

Notes

See Polyval for a definition of the polynomial.

class nutils.evaluable.PolyMul(coeffs_left, coeffs_right, vars)

Compute the coefficients for the product of two polynomials

Return the coefficients such that calling Polyval on this result is equal to the product of Polyval called on the individual arrays of coefficients (with the appropriate selection of the variables as described by parameter vars).

Parameters: coeffs_left (Array) – The coefficients for the left operand. The last axis is treated as the coefficients axis. coeffs_right (Array) – The coefficients for the right operand. The last axis is treated as the coefficients axis. vars (tuple of nutils_poly.MulVar) – For each variable of this product, var defines if the variable exists in the left polynomial, the right or both.

Notes

See Polyval for a definition of the polynomial.

class nutils.evaluable.PolyGrad(coeffs, nvars)

Compute the coefficients for the gradient of a polynomial

The last two axes of this array are the axis of variables and the axis of coefficients.

Parameters: coeffs (Array) – The coefficients of the polynomial to compute the gradient for. The last axis is treated as the coefficients axis. nvars (int) – The number of variables of the polynomial.

Notes

See Polyval for a definition of the polynomial.

class nutils.evaluable.Legendre(x, degree)

Series of Legendre polynomial up to and including the given degree.

Parameters: x (Array) – The coordinates to evaluate the series at. degree (int) – The degree of the last polynomial of the series.
class nutils.evaluable.Choose(index, *choices)

Function equivalent of numpy.choose().

class nutils.evaluable.TransformCoords(target, source, index, coords)

Transform coordinates from one coordinate system to another (spatial part)

Parameters: target (nutils.transformseq.Transforms, optional) – The target coordinate system. If None the target is root coordinate system. source (nutils.transformseq.Transforms) – The source coordinate system. index (scalar, integer Array) – The index part of the source coordinates. coords (Array) – The spatial part of the source coordinates.
class nutils.evaluable.TransformIndex(target, source, index)

Transform coordinates from one coordinate system to another (index part)

Parameters: target (nutils.transformseq.Transforms, optional) – The target coordinate system. If None the target is the root coordinate system. source (nutils.transformseq.Transforms) – The source coordinate system. index (scalar, integer Array) – The index part of the source coordinates.
class nutils.evaluable.TransformLinear(target, source, index)

Linear part of a coordinate transformation

Parameters: target (nutils.transformseq.Transforms, optional) – The target coordinate system. If None the target is the root coordinate system. source (nutils.transformseq.Transforms) – The source coordinate system. index (scalar, integer Array) – The index part of the source coordinates.
class nutils.evaluable.TransformBasis(source, index)

Vector basis for the root and a source coordinate system

The columns of this matrix form a vector basis for the space of root coordinates. The first n vectors also span the space of source coordinates mapped to the root, where n is the dimension of the source coordinate system. The remainder is not a span of the complement space in general.

No additional properties are guaranteed beyond the above. In particular, if the source coordinate system has the same dimension as the root, the basis is not necessarily the same as TransformLinear(None, source, index).

Parameters: source (nutils.transformseq.Transforms) – The source coordinate system. index (scalar, integer Array) – The index part of the source coordinates.
class nutils.evaluable.SearchSorted(arg, *, array, side, sorter)

Find index of evaluable array into sorted numpy array.

nutils.evaluable.derivative(func, var, seen=None)
nutils.evaluable.prependaxes(func, shape)

Prepend axes with specified shape to func.

nutils.evaluable.appendaxes(func, shape)

Append axes with specified shape to func.

nutils.evaluable.replace_arguments(value, arguments)

Replace Argument objects in value.

Replace Argument objects in value according to the arguments map, taking into account derivatives to the local coordinates.

Parameters: value (Array) – Array to be edited. arguments (collections.abc.Mapping with Arrays as values) – Arguments replacements. The key correspond to the name passed to an Argument and the value is the replacement. The edited value. Array
nutils.evaluable.einsum(fmt, *args, **dims)

Multiply and/or contract arrays via format string.

The format string consists of a comma separated list of axis labels, followed by -> and the axis labels of the return value. For example, the following swaps the axes of a matrix:

>>> a45 = ones(tuple(map(constant, [4,5]))) # 4x5 matrix
>>> einsum('ij->ji', a45)
nutils.evaluable.Transpose<f:(5),(4)>


Axis labels that do not occur in the return value are summed. For example, the following performs a matrix-vector product:

>>> a5 = ones(tuple(map(constant, ))) # vector with length 5
>>> einsum('ij,j->i', a45, a5)
nutils.evaluable.Sum<f:4>


The following contracts a third order tensor, a matrix, and a vector, and transposes the result:

>>> a234 = ones(tuple(map(constant, [2,3,4]))) # 2x3x4 tensor
>>> einsum('ijk,kl,l->ji', a234, a45, a5)
nutils.evaluable.Sum<f:3,2>


In case the dimension of the input and output arrays may vary, a variable length axes group can be denoted by a capital. Its length is automatically established based on the dimension of the input arrays. The following example performs a tensor product of an array and a vector:

>>> einsum('A,i->Ai', a234, a5)
nutils.evaluable.Multiply<f:2,3,4,5>


The format string may contain multiple variable length axes groups, but their lengths must be resolvable from left to right. In case this is not possible, lengths may be specified as keyword arguments.

>>> einsum('AjB,i->AijB', a234, a5, B=1)
nutils.evaluable.Multiply<f:2,5,3,4>

nutils.evaluable.eval_sparse

Evaluate one or several Array objects as sparse data.

Parameters: funcs (tuple of Array objects) – Arrays to be evaluated. arguments (dict (default: None)) – Optional arguments for function evaluation. results tuple of sparse data arrays