Visualization

Here are some frequently used plot types with the packages pyqtgraph and/or matplotlib implemented. The respective pyinduct.visualization plotting function get an EvalData object whose definition also placed in this module. A EvalData-object in turn can easily generated from simulation data. The function pyinduct.simulation.simulate_system() for example already provide the simulation result as EvalData object.

class DataPlot(data)

Base class for all plotting related classes.

class Domain(bounds=None, num=None, step=None, points=None)

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(self)
ndim(self)
points(self)
step(self)
class EvalData(input_data, output_data, input_labels=None, input_units=None, enable_extrapolation=False, fill_axes=False, fill_value=None, name=None)

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.

  • fill_value – If invalid data is encountered, it will be replaced with this value before interpolation is performed.

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(self)

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(self, other, from_left=True)

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(self, other)

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(self, interp_axis)

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(self, other, from_left=True)

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(self, other, from_left=True)

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(self)

Radicate the elements form self.output_data element-wise.

Returns

EvalData with self.input_data and output_data as result of root calculation.

sub(self, other, from_left=True)

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.

FORCE_MPL_ON_WINDOWS = True
class Function(eval_handle, domain=- np.inf, np.inf, nonzero=- np.inf, np.inf, derivative_handles=None)

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

  • output. Must be a subset of domain (nonzero) –

  • derivative_handles (list) – List of callable(s) that contain

  • of eval_handle (derivatives) –

add_neutral_element(self)

Return the neutral element of addition for this object.

In other words: self + ret_val == self.

derivative_handles(self)
derive(self, order=1)

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.

static from_data(x, y, **kwargs)

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(self)
function_space_hint(self)

Return the hint that this function is an element of the an scalar product space which is uniquely defined by the scalar product scalar_product_hint().

Note

If you are working on different function spaces, you have to overwrite this hint in order to provide more properties which characterize your specific function space. For example the domain of the functions.

get_member(self, idx)

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

mul_neutral_element(self)

Return the neutral element of multiplication for this object.

In other words: self * ret_val == self.

raise_to(self, power)

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(self)

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

scale(self, factor)

Factory method to scale a Function.

Parameters

factornumbers.Number or a callable.

class MplSlicePlot(eval_data_list, time_point=None, spatial_point=None, ylabel='', legend_label=None, legend_location=1, figure_size=10, 6)

Bases: pyinduct.visualization.PgDataPlot

Get list (eval_data_list) of ut.EvalData objects and plot the temporal/spatial slice, by spatial_point/time_point, from each ut.EvalData object, in one plot. For now: only ut.EvalData objects with len(input_data) == 2 supported

class MplSurfacePlot(data, keep_aspect=False, fig_size=12, 8, zlabel='$\\quad x(z,t)$', title='')

Bases: pyinduct.visualization.DataPlot

Plot as 3d surface.

class PgAnimatedPlot(data, title='', refresh_time=40, replay_gain=1, save_pics=False, create_video=False, labels=None)

Bases: pyinduct.visualization.PgDataPlot

Wrapper that shows an updating one dimensional plot of n-curves discretized in t time steps and z spatial steps. It is assumed that time propagates along axis 0 and and location along axis 1 of values. Values are therefore expected to be a array of shape (n, t, z).

Parameters
  • data ((iterable of) EvalData) – results to animate

  • title (basestring) – Window title.

  • refresh_time (int) – Time in msec to refresh the window must be greater than zero

  • replay_gain (float) – Values above 1 acc- and below 1 decelerate the playback process, must be greater than zero

  • save_pics (bool) – Export snapshots for animation purposes.

  • labels (dict) – Axis labels for the plot that are passed to pyqtgraph.PlotItem .

exported_files(self)
class PgDataPlot(data)

Bases: pyinduct.visualization.DataPlot, pyqtgraph.QtCore.QObject

Base class for all pyqtgraph plotting related classes.

class PgLinePlot3d(data, n=50, scale=1)

Bases: pyinduct.visualization.PgDataPlot

Ulots a series of n-lines of the systems state. Scaling in z-direction can be changed with the scale setting.

class PgSlicePlot(data, title=None)

Bases: pyinduct.visualization.PgDataPlot

Plot selected slice of given DataSets.

class PgSurfacePlot(data, scales=None, animation_axis=None, title='')

Bases: pyinduct.visualization.PgDataPlot

Plot 3 dimensional data as a surface using OpenGl.

Parameters
  • data (EvalData) – Data to display, if the the input-vector has length of 2, a 3d surface is plotted, if has length 3, this surface is animated. Hereby, the time axis is assumed to be the first entry of the input vector.

  • scales (tuple) – Factors to scale the displayed data, each entry corresponds to an axis in the input vector with one additional scale for the output_data. It therefore must be of the size: len(input_data) + 1 . If no scale is given, all axis are scaled uniformly.

  • animation_axis (int) – Index of the axis to use for animation. Not implemented, yet and therefore defaults to 0 by now.

  • title (str) – Window title to display.

Note

For animation this object spawns a QTimer which needs an running event loop. Therefore remember to store a reference to this object.

color_map = viridis
colors = ['g', 'c', 'm', 'b', 'y', 'k', 'w', 'r']
complex_wrapper(func)

Wraps complex valued functions into two-dimensional functions. This enables the root-finding routine to handle it as a vectorial function.

Parameters

func (callable) – Callable that returns a complex result.

Returns

function handle, taking x = (re(x), im(x) and returning [re(func(x), im(func(x)].

Return type

two-dimensional, callable

create_animation(input_file_mask='', input_file_names=None, target_format='.mp4')

Create an animation from the given files.

If no file names are given, a file selection dialog will appear.

Parameters
  • input_file_mask (basestring) – file name mask with c-style format string

  • input_file_names (iterable) – names of the files

Returns

animation file

create_colormap(cnt)

Create a colormap containing cnt values.

Parameters

cnt (int) – Number of colors in the map.

Returns

List of QColor instances.

create_dir(dir_name)

Create a directory with name dir_name relative to the current path if it doesn’t already exist and return its full path.

Parameters

dir_name (str) – Directory name.

Returns

Full absolute path of the created directory.

Return type

str

deregister_base(label)

Removes a set of initial functions from the packages registry.

Parameters

label (str) – String, label of functions that are to be removed.

Raises

ValueError – If label is not found in registry.

get_colors(cnt, scheme='tab10', samples=10)

Create a list of colors.

Parameters
  • cnt (int) – Number of colors in the list.

  • scheme (str) – Mpl color scheme to use.

  • samples (cnt) – Number of samples to take from the scheme before starting from the beginning.

Returns

List of np.Array holding the rgb values.

mpl_3d_remove_margins()

Remove thin margins in matplotlib 3d plots. The Solution is from Stackoverflow.

mpl_activate_latex()

Activate full (label, ticks, …) latex printing in matplotlib plots.

save_2d_pg_plot(plot, filename)

Save a given pyqtgraph plot in the folder <current path>.pictures_plot under the given filename filename.

Parameters
  • plot (pyqtgraph.plotItem) – Pyqtgraph plot.

  • filename (str) – Png picture filename.

Returns

Path with filename and path only.

Return type

tuple of 2 str’s

show(show_pg=True, show_mpl=True)

Shortcut to show all pyqtgraph and matplotlib plots / animations.

Parameters
  • show_pg (bool) – Show matplotlib plots? Default: True

  • show_mpl (bool) – Show pyqtgraph plots? Default: True

surface_plot(data, **kwargs)

Compatibility wrapper for PgSurfacePLot and MplSurfacePlot

Since OpenGL suffers under some problems in current windows versions, the matplotlib implementation is used there.

tear_down(labels, plots=None)

Deregister labels and delete plots.

Parameters
  • labels (array-like) – All labels to deregister.

  • plots (array-like) – All plots to delete.

visualize_functions(functions, points=100, return_window=False)

Visualizes a set of Function s on their domain.

Parameters
  • functions (iterable) – collection of Function s to display.

  • points (int) – Points to use for sampling the domain.

  • return_window (bool) – If True the graphics window is not shown directly. In this case, a reference to the plot window is returned.

Returns: A PgPlotWindow if delay_exec is True.

visualize_roots(roots, grid, func, cmplx=False, return_window=False)

Visualize a given set of roots by examining the output of the generating function.

Parameters
  • roots (array like) – Roots to display, if None is given, no roots will be displayed, this is useful to get a view of func and choosing an appropriate grid.

  • grid (list) – List of arrays that form the grid, used for the evaluation of the given func.

  • func (callable) – Possibly vectorial function handle that will take input of of the shape (‘len(grid)’, ).

  • cmplx (bool) – If True, the complex valued func is handled as a vectorial function returning [Re(func), Im(func)].

  • return_window (bool) – If True the graphics window is not shown directly. In this case, a reference to the plot window is returned.

Returns: A PgPlotWindow if delay_exec is True.