Core

In the Core module you can find all basic classes and functions which form the backbone of the toolbox.

class Domain(bounds=None, num=None, step=None, points=None)[source]

Bases: object

Helper class that manages ranges for data evaluation, containing parameters.

Parameters:
  • bounds (tuple) – Interval bounds.
  • num (int) – Number of points in interval.
  • step (numbers.Number) – Distance between points (if homogeneous).
  • points (array_like) – Points themselves.

Note

If num and step are given, num will take precedence.

bounds
ndim
points
step
class EvalData(input_data, output_data, input_labels=None, input_units=None, enable_extrapolation=False, fill_axes=False, name=None)[source]

Bases: object

This class helps managing any kind of result data.

The data gained by evaluation of a function is stored together with the corresponding points of its evaluation. This way all data needed for plotting or other postprocessing is stored in one place. Next to the points of the evaluation the names and units of the included axes can be stored. After initialization an interpolator is set up, so that one can interpolate in the result data by using the overloaded __call__() method.

Parameters:
  • input_data – (List of) array(s) holding the axes of a regular grid on which the evaluation took place.
  • output_data – The result of the evaluation.
Keyword Arguments:
 
  • input_labels – (List of) labels for the input axes.
  • input_units – (List of) units for the input axes.
  • name – Name of the generated data set.
  • fill_axes – If the dimension of output_data is higher than the length of the given input_data list, dummy entries will be appended until the required dimension is reached.
  • enable_extrapolation (bool) – If True, internal interpolators will allow extrapolation. Otherwise, the last giben value will be repeated for 1D cases and the result will be padded with zeros for cases > 1D.

Examples

When instantiating 1d EvalData objects, the list can be omitted

>>> axis = Domain((0, 10), 5)
>>> data = np.random.rand(5,)
>>> e_1d = EvalData(axis, data)

For other cases, input_data has to be a list

>>> axis1 = Domain((0, 0.5), 5)
>>> axis2 = Domain((0, 1), 11)
>>> data = np.random.rand(5, 11)
>>> e_2d = EvalData([axis1, axis2], data)

Adding two Instances (if the boundaries fit, the data will be interpolated on the more coarse grid.) Same goes for subtraction and multiplication.

>>> e_1 = EvalData(Domain((0, 10), 5), np.random.rand(5,))
>>> e_2 = EvalData(Domain((0, 10), 10), 100*np.random.rand(5,))
>>> e_3 = e_1 + e_2
>>> e_3.output_data.shape
(5,)

Interpolate in the output data by calling the object

>>> e_4 = EvalData(np.array(range(5)), 2*np.array(range(5))))
>>> e_4.output_data
array([0, 2, 4, 6, 8])
>>> e_5 = e_4([2, 5])
>>> e_5.output_data
array([4, 8])
>>> e_5.output_data.size
2

one may also give a slice

>>> e_6 = e_4(slice(1, 5, 2))
>>> e_6.output_data
array([2., 6.])
>>> e_5.output_data.size
2

For multi-dimensional interpolation a list has to be provided

>>> e_7 = e_2d([[.1, .5], [.3, .4, .7)])
>>> e_7.output_data.shape
(2, 3)
abs()[source]

Get the absolute value of the elements form self.output_data .

Returns:EvalData with self.input_data and output_data as result of absolute value calculation.
add(other, from_left=True)[source]

Perform the element-wise addition of the output_data arrays from self and other

This method is used to support addition by implementing __add__ (fromLeft=True) and __radd__(fromLeft=False)). If other** is a EvalData, the input_data lists of self and other are adjusted using adjust_input_vectors() The summation operation is performed on the interpolated output_data. If other is a numbers.Number it is added according to numpy’s broadcasting rules.

Parameters:
  • other (numbers.Number or EvalData) – Number or EvalData object to add to self.
  • from_left (bool) – Perform the addition from left if True or from right if False.
Returns:

EvalData with adapted input_data and output_data as result of the addition.

adjust_input_vectors(other)[source]

Check the the inputs vectors of self and other for compatibility (equivalence) and harmonize them if they are compatible.

The compatibility check is performed for every input_vector in particular and examines whether they share the same boundaries. and equalize to the minimal discretized axis. If the amount of discretization steps between the two instances differs, the more precise discretization is interpolated down onto the less precise one.

Parameters:other (EvalData) – Other EvalData class.
Returns:
  • (list) - New common input vectors.
  • (numpy.ndarray) - Interpolated self output_data array.
  • (numpy.ndarray) - Interpolated other output_data array.
Return type:tuple
interpolate(interp_axis)[source]

Main interpolation method for output_data.

If one of the output dimensions is to be interpolated at one single point, the dimension of the output will decrease by one.

Parameters:
  • interp_axis (list(list)) – axis positions in the form
  • 1D (-) – axis with axis=[1,2,3]
  • 2D (-) – [axis1, axis2] with axis1=[1,2,3] and axis2=[0,1,2,3,4]
Returns:

EvalData with interp_axis as new input_data and interpolated output_data.

matmul(other, from_left=True)[source]

Perform the matrix multiplication of the output_data arrays from self and other .

This method is used to support matrix multiplication (@) by implementing __matmul__ (from_left=True) and __rmatmul__(from_left=False)). If other** is a EvalData, the input_data lists of self and other are adjusted using adjust_input_vectors(). The matrix multiplication operation is performed on the interpolated output_data. If other is a numbers.Number it is handled according to numpy’s broadcasting rules.

Parameters:
  • other (EvalData) – Object to multiply with.
  • from_left (boolean) – Matrix multiplication from left if True or from right if False.
Returns:

EvalData with adapted input_data and output_data as result of matrix multiplication.

mul(other, from_left=True)[source]

Perform the element-wise multiplication of the output_data arrays from self and other .

This method is used to support multiplication by implementing __mul__ (from_left=True) and __rmul__(from_left=False)). If other** is a EvalData, the input_data lists of self and other are adjusted using adjust_input_vectors(). The multiplication operation is performed on the interpolated output_data. If other is a numbers.Number it is handled according to numpy’s broadcasting rules.

Parameters:
  • other (numbers.Number or EvalData) – Factor to multiply with.
  • boolean (from_left) – Multiplication from left if True or from right if False.
Returns:

EvalData with adapted input_data and output_data as result of multiplication.

sqrt()[source]

Radicate the elements form self.output_data element-wise.

Returns:EvalData with self.input_data and output_data as result of root calculation.
sub(other, from_left=True)[source]

Perform the element-wise subtraction of the output_data arrays from self and other .

This method is used to support subtraction by implementing __sub__ (from_left=True) and __rsub__(from_left=False)). If other** is a EvalData, the input_data lists of self and other are adjusted using adjust_input_vectors(). The subtraction operation is performed on the interpolated output_data. If other is a numbers.Number it is handled according to numpy’s broadcasting rules.

Parameters:
  • other (numbers.Number or EvalData) – Number or EvalData object to subtract.
  • from_left (boolean) – Perform subtraction from left if True or from right if False.
Returns:

EvalData with adapted input_data and output_data as result of subtraction.

class Parameters(**kwargs)[source]

Bases: object

Handy class to collect system parameters. This class can be instantiated with a dict, whose keys will the become attributes of the object. (Bunch approach)

Parameters:kwargs – parameters
find_roots(function, grid, n_roots=None, rtol=1e-05, atol=1e-08, cmplx=False, sort_mode='norm')[source]

Searches n_roots roots of the function f(\boldsymbol{x}) on the given grid and checks them for uniqueness with aid of rtol.

In Detail scipy.optimize.root() is used to find initial candidates for roots of f(\boldsymbol{x}) . If a root satisfies the criteria given by atol and rtol it is added. If it is already in the list, a comprehension between the already present entries’ error and the current error is performed. If the newly calculated root comes with a smaller error it supersedes the present entry.

Raises:

ValueError – If the demanded amount of roots can’t be found.

Parameters:
  • function (callable) – Function handle for math:f(boldsymbol{x}) whose roots shall be found.
  • grid (list) – Grid to use as starting point for root detection. The i th element of this list provides sample points for the i th parameter of \boldsymbol{x} .
  • n_roots (int) – Number of roots to find. If none is given, return all roots that could be found in the given area.
  • rtol – Tolerance to be exceeded for the difference of two roots to be unique: f(r1) - f(r2) > \textrm{rtol} .
  • atol – Absolute tolerance to zero: f(x^0) < \textrm{atol} .
  • cmplx (bool) – Set to True if the given function is complex valued.
  • sort_mode (str) – Specify tho order in which the extracted roots shall be sorted. Default “norm” sorts entries by their l_2 norm, while “component” will sort them in increasing order by every component.
Returns:

numpy.ndarray of roots; sorted in the order they are returned by f(\boldsymbol{x}) .

sanitize_input(input_object, allowed_type)[source]

Sanitizes input data by testing if input_object is an array of type allowed_type.

Parameters:
  • input_object – Object which is to be checked.
  • allowed_type – desired type
Returns:

input_object

real(data)[source]

Check if the imaginary part of data vanishes and return its real part if it does.

Parameters:data (numbers.Number or array_like) – Possibly complex data to check.
Raises:ValueError – If provided data can’t be converted within the given tolerance limit.
Returns:Real part of data.
Return type:numbers.Number or array_like
class Base(fractions)[source]

Bases: object

Base class for approximation bases.

In general, a Base is formed by a certain amount of BaseFractions and therefore forms finite-dimensional subspace of the distributed problem’s domain. Most of the time, the user does not need to interact with this class.

Parameters:fractions (iterable of BaseFraction) – List, array or dict of BaseFraction’s
derive(order)[source]

Basic implementation of derive function. Empty implementation, overwrite to use this functionality.

Parameters:order (numbers.Number) – derivative order
Returns:derived object
Return type:Base
get_attribute(attr)[source]

Retrieve an attribute from the fractions of the base.

Parameters:attr (str) – Attribute to query the fractions for.
Returns:Array of len(fractions) holding the attributes. With None entries if the attribute is missing.
Return type:np.ndarray
raise_to(power)[source]

Factory method to obtain instances of this base, raised by the given power.

Parameters:power – power to raise the basis onto.
scalar_product_hint()[source]

Hint that returns steps for scalar product calculation with elements of this base.

Note

Overwrite to implement custom functionality.

scale(factor)[source]

Factory method to obtain instances of this base, scaled by the given factor.

Parameters:factor – factor or function to scale this base with.
transformation_hint(info)[source]

Method that provides a information about how to transform weights from one BaseFraction into another.

In Detail this function has to return a callable, which will take the weights of the source- and return the weights of the target system. It may have keyword arguments for other data which is required to perform the transformation. Information about these extra keyword arguments should be provided in form of a dictionary whose keys are keyword arguments of the returned transformation handle.

Note

This implementation covers the most basic case, where the two BaseFraction’s are of same type. For any other case it will raise an exception. Overwrite this Method in your implementation to support conversion between bases that differ from yours.

Parameters:infoTransformationInfo
Raises:NotImplementedError
Returns:Transformation handle
class BaseFraction(members)[source]

Bases: object

Abstract base class representing a basis that can be used to describe functions of several variables.

derive(order)[source]

Basic implementation of derive function.

Empty implementation, overwrite to use this functionality. For an example implementation see Function

Parameters:order (numbers.Number) – derivative order
Returns:derived object
Return type:BaseFraction
get_member(idx)[source]

Getter function to access members. Empty function, overwrite to implement custom functionality. For an example implementation see Function

Note

Empty function, overwrite to implement custom functionality.

Parameters:idx – member index
raise_to(power)[source]

Raises this fraction to the given power.

Parameters:power (numbers.Number) – power to raise the fraction onto
Returns:raised fraction
scalar_product_hint()[source]

Empty Hint that can return steps for scalar product calculation.

In detail this means a list object containing function calls to fill with (first, second) parameters that will calculate the scalar product when summed up.

Note

Overwrite to implement custom functionality. For an example implementation see Function

scale(factor)[source]

Factory method to obtain instances of this base fraction, scaled by the given factor. Empty function, overwrite to implement custom functionality. For an example implementation see Function.

Parameters:factor – Factor to scale the vector.
class StackedBase(fractions, base_info)[source]

Bases: pyinduct.core.Base

Implementation of a basis vector that is obtained by stacking different bases onto each other.
This typically occurs when the bases of coupled systems are joined to create a unified system.
Parameters:fractions (dict) – Dictionary with base_label and corresponding function
get_member(idx)[source]
scalar_product_hint()[source]

Hint that returns steps for scalar product calculation with elements of this base.

Note

Overwrite to implement custom functionality.

scale(factor)[source]

Factory method to obtain instances of this base, scaled by the given factor.

Parameters:factor – factor or function to scale this base with.
transformation_hint(info)[source]

If info.src_lbl is a member, just return it, using to correct derivative transformation, otherwise return None

Parameters:info (TransformationInfo) – Information about the requested transformation.
Returns:transformation handle
class Function(eval_handle, domain=(-inf, inf), nonzero=(-inf, inf), derivative_handles=None)[source]

Bases: pyinduct.core.BaseFraction

Most common instance of a BaseFraction. This class handles all tasks concerning derivation and evaluation of functions. It is used broad across the toolbox and therefore incorporates some very specific attributes. For example, to ensure the accurateness of numerical handling functions may only evaluated in areas where they provide nonzero return values. Also their domain has to be taken into account. Therefore the attributes domain and nonzero are provided.

To save implementation time, ready to go version like LagrangeFirstOrder are provided in the pyinduct.simulation module.

For the implementation of new shape functions subclass this implementation or directly provide a callable eval_handle and callable derivative_handles if spatial derivatives are required for the application.

Parameters:
  • eval_handle (callable) – Callable object that can be evaluated.
  • domain ((list of) tuples) – Domain on which the eval_handle is defined.
  • nonzero (tuple) – Region in which the eval_handle will return nonzero output. Must be a subset of domain
  • derivative_handles (list) – List of callable(s) that contain derivatives of eval_handle
derivative_handles
derive(order=1)[source]

Spatially derive this Function.

This is done by neglecting order derivative handles and to select handle \text{order} - 1 as the new evaluation_handle.

Parameters:

order (int) – the amount of derivations to perform

Raises:
  • TypeError – If order is not of type int.
  • ValueError – If the requested derivative order is higher than the provided one.
Returns:

Function the derived function.

evaluation_hint(values)[source]

If evaluation can be accelerated by using special properties of a function, this function can be overwritten to performs that computation. It gets passed an array of places where the caller wants to evaluate the function and should return an array of the same length, containing the results.

Note

This implementation just calls the normal evaluation hook.

Parameters:values – places to be evaluated at
Returns:Evaluation results.
Return type:numpy.ndarray
static from_constant(constant, **kwargs)[source]

Create a Function that returns a constant value.

Parameters:
  • constant (number) – value to return
  • **kwargs – all kwargs get passed to Function
Returns:

A constant function

Return type:

Function

static from_data(x, y, **kwargs)[source]

Create a Function based on discrete data by interpolating.

The interpolation is done by using interp1d from scipy, the kwargs will be passed.

Parameters:
  • x (array-like) – Places where the function has been evaluated .
  • y (array-like) – Function values at x.
  • **kwargs – all kwargs get passed to Function .
Returns:

An interpolating function.

Return type:

Function

function_handle
get_member(idx)[source]

Implementation of the abstract parent method.

Since the Function has only one member (itself) the parameter idx is ignored and self is returned.

Parameters:idx – ignored.
Returns:self
raise_to(power)[source]

Raises the function to the given power.

Warning

Derivatives are lost after this action is performed.

Parameters:power (numbers.Number) – power to raise the function to
Returns:raised function
scalar_product_hint()[source]

Return the hint that the dot_product_l2() has to calculated to gain the scalar product.

scale(factor)[source]

Factory method to scale a Function.

Parameters:factornumbers.Number or a callable.
class ComposedFunctionVector(functions, scalars)[source]

Bases: pyinduct.core.BaseFraction

Implementation of composite function vector \boldsymbol{x}.

\boldsymbol{x} = \begin{pmatrix}
    x_1(z) \\
    \vdots \\
    x_n(z) \\
    \xi_1 \\
    \vdots \\
    \xi_m \\
\end{pmatrix}

get_member(idx)[source]

Getter function to access members. Empty function, overwrite to implement custom functionality. For an example implementation see Function

Note

Empty function, overwrite to implement custom functionality.

Parameters:idx – member index
scalar_product_hint()[source]

Empty Hint that can return steps for scalar product calculation.

In detail this means a list object containing function calls to fill with (first, second) parameters that will calculate the scalar product when summed up.

Note

Overwrite to implement custom functionality. For an example implementation see Function

scale(factor)[source]

Factory method to obtain instances of this base fraction, scaled by the given factor. Empty function, overwrite to implement custom functionality. For an example implementation see Function.

Parameters:factor – Factor to scale the vector.
normalize_base(b1, b2=None)[source]

Takes two Base’s \boldsymbol{b}_1 , \boldsymbol{b}_1 and normalizes them so that \langle\boldsymbol{b}_{1i}\,
,\:\boldsymbol{b}_{2i}\rangle = 1. If only one base is given, \boldsymbol{b}_2 defaults to \boldsymbol{b}_1.

Parameters:
Raises:

ValueError – If \boldsymbol{b}_1 and \boldsymbol{b}_2 are orthogonal.

Returns:

if b2 is None, otherwise: Tuple of 2 Base’s.

Return type:

Base

project_on_base(state, base)[source]

Projects a state on a basis given by base.

Parameters:
  • state (array_like) – List of functions to approximate.
  • base (Base) – Basis to project onto.
Returns:

Weight vector in the given base

Return type:

numpy.ndarray

change_projection_base(src_weights, src_base, dst_base)[source]

Converts given weights that form an approximation using src_base to the best possible fit using dst_base.

Parameters:
  • src_weights (numpy.ndarray) – Vector of numbers.
  • src_base (Base) – The source Basis.
  • dst_base (Base) – The destination Basis.
Returns:

target weights

Return type:

numpy.ndarray

back_project_from_base(weights, base)[source]

Build evaluation handle for a distributed variable that was approximated as a set of weights om a certain base.

Parameters:
  • weights (numpy.ndarray) – Weight vector.
  • base (Base) – Base to be used for the projection.
Returns:

evaluation handle

calculate_scalar_product_matrix(scalar_product_handle, base_a, base_b, optimize=True)[source]

Calculates a matrix A , whose elements are the scalar products of each element from base_a and base_b, so that a_{ij} = \langle \mathrm{a}_i\,,\: \mathrm{b}_j\rangle.

Parameters:
  • scalar_product_handle (callable) – function handle that is called to calculate the scalar product. This function has to be able to cope with (1d) vectorial input.
  • base_a (Base) – Basis a
  • base_b (Base) – Basis b
  • optimize (bool) – Switch to turn on the symmetry based speed up. For development purposes only.

Todo

making use of the commutable scalar product could save time, run some test on this

Returns:matrix A
Return type:numpy.ndarray
calculate_base_transformation_matrix(src_base, dst_base)[source]

Calculates the transformation matrix V , so that the a set of weights, describing a function in the src_base will express the same function in the dst_base, while minimizing the reprojection error. An quadratic error is used as the error-norm for this case.

Warning

This method assumes that all members of the given bases have the same type and that their BaseFraction s, define compatible scalar products.

Raises:

TypeError – If given bases do not provide an scalar_product_hint() method.

Parameters:
  • src_base (Base) – Current projection base.
  • dst_base (Base) – New projection base.
Returns:

Transformation matrix V .

Return type:

numpy.ndarray

calculate_expanded_base_transformation_matrix(src_base, dst_base, src_order, dst_order, use_eye=False)[source]

Constructs a transformation matrix \bar V from basis given by src_base to basis given by dst_base that also transforms all temporal derivatives of the given weights.

See:
calculate_base_transformation_matrix() for further details.
Parameters:
  • dst_base (Base) – New projection base.
  • src_base (Base) – Current projection base.
  • src_order – Temporal derivative order available in src_base.
  • dst_order – Temporal derivative order needed in dst_base.
  • use_eye (bool) – Use identity as base transformation matrix. (For easy selection of derivatives in the same base)
Raises:

ValueError – If destination needs a higher derivative order than source can provide.

Returns:

Transformation matrix

Return type:

numpy.ndarray

dot_product_l2(first, second)[source]

Vectorized version of the inner product on L2.

Given two vectors of functions

\boldsymbol{\varphi}(z)
= \left(\varphi_0(z), \dotsc, \varphi_N(z)\right)^T

and

\boldsymbol{\psi}(z) = \left(\psi_0(z), \dotsc, \psi_N(z)\right)^T` ,

this function computes \left< \boldsymbol{\varphi}(z) | \boldsymbol{\psi}(z) \right>_{L2} where

\left< \varphi_i(z) | \psi_j(z) \right>_{L2} =
\int\limits_{\Gamma_0}^{\Gamma_1}
\bar\varphi_i(\zeta) \psi_j(\zeta) \,\textup{d}\zeta \:.

Herein, \bar\varphi_i(\zeta) denotes the complex conjugate and \Gamma_0 as well as \Gamma_1 are derived by computing the intersection of the nonzero areas of the involved functions.

Parameters:
  • first (callable or numpy.ndarray) – (1d array of n) callable(s)
  • second (callable or numpy.ndarray) – (1d array of n) callable(s)
Raises:

ValueError, if the provided arrays are not equally long.

Returns:

Array of inner products

Return type:

numpy.ndarray

generic_scalar_product(b1, b2=None)[source]

Calculates the pairwise scalar product between the elements of the Base b1 and b2.

Parameters:
  • b1 (Base) – first basis
  • b2 (Base) – second basis, if omitted defaults to b1

Note

If b2 is omitted, the result can be used to normalize b1 in terms of its scalar product.