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:
objectHelper 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:
objectThis 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: EvalDatawith 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 usingadjust_input_vectors()The summation operation is performed on the interpolated output_data. If other is anumbers.Numberit is added according to numpy’s broadcasting rules.Parameters: - other (
numbers.NumberorEvalData) – Number or EvalData object to add to self. - from_left (bool) – Perform the addition from left if True or from right if False.
Returns: EvalDatawith adapted input_data and output_data as result of the addition.- other (
-
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: EvalDatawith 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 usingadjust_input_vectors(). The matrix multiplication operation is performed on the interpolated output_data. If other is anumbers.Numberit 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: EvalDatawith adapted input_data and output_data as result of matrix multiplication.- other (
-
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 usingadjust_input_vectors(). The multiplication operation is performed on the interpolated output_data. If other is anumbers.Numberit is handled according to numpy’s broadcasting rules.Parameters: - other (
numbers.NumberorEvalData) – Factor to multiply with. - boolean (from_left) – Multiplication from left if True or from right if False.
Returns: EvalDatawith adapted input_data and output_data as result of multiplication.- other (
-
sqrt()[source]¶ Radicate the elements form self.output_data element-wise.
Returns: EvalDatawith 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 usingadjust_input_vectors(). The subtraction operation is performed on the interpolated output_data. If other is anumbers.Numberit is handled according to numpy’s broadcasting rules.Parameters: - other (
numbers.NumberorEvalData) – Number or EvalData object to subtract. - from_left (boolean) – Perform subtraction from left if True or from right if False.
Returns: EvalDatawith adapted input_data and output_data as result of subtraction.- other (
-
class
Parameters(**kwargs)[source]¶ Bases:
objectHandy 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
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
. 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
th element of this list provides sample points
for the
th parameter of
. - 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:
. - atol – Absolute tolerance to zero:
. - 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
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
.
-
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
datavanishes 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:
objectBase class for approximation bases.
In general, a
Baseis formed by a certain amount ofBaseFractionsand 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 ofBaseFraction’s-
derive(order)[source]¶ Basic implementation of derive function. Empty implementation, overwrite to use this functionality.
Parameters: order ( numbers.Number) – derivative orderReturns: 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
BaseFractioninto 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: info – TransformationInfoRaises: NotImplementedErrorReturns: Transformation handle
-
-
class
BaseFraction(members)[source]¶ Bases:
objectAbstract 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
FunctionParameters: order ( numbers.Number) – derivative orderReturns: 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
FunctionNote
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 ontoReturns: 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
-
-
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 -
scalar_product_hint()[source]¶ Hint that returns steps for scalar product calculation with elements of this base.
Note
Overwrite to implement custom functionality.
-
class
Function(eval_handle, domain=(-inf, inf), nonzero=(-inf, inf), derivative_handles=None)[source]¶ Bases:
pyinduct.core.BaseFractionMost 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
LagrangeFirstOrderare provided in thepyinduct.simulationmodule.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
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: Functionthe 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
Functionthat returns a constant value.Parameters: - constant (number) – value to return
- **kwargs – all kwargs get passed to
Function
Returns: A constant function
Return type:
-
static
from_data(x, y, **kwargs)[source]¶ Create a
Functionbased on discrete data by interpolating.The interpolation is done by using
interp1dfrom 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_handle¶
-
get_member(idx)[source]¶ Implementation of the abstract parent method.
Since the
Functionhas 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 toReturns: raised function
-
scalar_product_hint()[source]¶ Return the hint that the
dot_product_l2()has to calculated to gain the scalar product.
-
class
ComposedFunctionVector(functions, scalars)[source]¶ Bases:
pyinduct.core.BaseFractionImplementation of composite function vector
.
-
get_member(idx)[source]¶ Getter function to access members. Empty function, overwrite to implement custom functionality. For an example implementation see
FunctionNote
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
-
-
normalize_base(b1, b2=None)[source]¶ Takes two
Base’s
,
and normalizes them so that
.
If only one base is given,
defaults to
.Parameters: Raises: ValueError– If
and
are orthogonal.Returns: if b2 is None, otherwise: Tuple of 2
Base’s.Return type:
-
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: 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
, whose elements are the scalar products of
each element from base_a and base_b, so that
.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 
Return type: numpy.ndarray
-
calculate_base_transformation_matrix(src_base, dst_base)[source]¶ Calculates the transformation matrix
, 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
BaseFractions, define compatible scalar products.Raises: TypeError– If given bases do not provide anscalar_product_hint()method.Parameters: Returns: Transformation matrix
.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
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

and

this function computes
where
Herein,
denotes the complex conjugate and
as well as
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
- first (callable or