# DMDBase¶

Base module for the DMD: fit method must be implemented in inherited classes

 DMDBase._col_major_2darray Private method that takes as input the snapshots and stores them into a 2D matrix, by column. DMDBase._compute_amplitudes Compute the amplitude coefficients. DMDBase.atilde Get the reduced Koopman operator A, called A tilde. DMDBase.dmd_timesteps Get the timesteps of the reconstructed states. DMDBase.dynamics Get the time evolution of each mode. DMDBase.eigs Get the eigenvalues of A tilde. DMDBase.fit Abstract method to fit the snapshots matrices. DMDBase.modes Get the matrix containing the DMD modes, stored by column. DMDBase.original_timesteps Get the timesteps of the original snapshot. DMDBase.plot_eigs Plot the eigenvalues. DMDBase.plot_modes_2D Plot the DMD Modes. DMDBase.plot_snapshots_2D Plot the snapshots. DMDBase.reconstructed_data Get the reconstructed data. DMDBase.snapshots Get the original input data.
class DMDBase(svd_rank=0, tlsq_rank=0, exact=False, opt=False, rescale_mode=None, forward_backward=False, sorted_eigs=False, tikhonov_regularization=None)[source]

Bases: object

Dynamic Mode Decomposition base class.

Parameters
• svd_rank (int or float) – the rank for the truncation; If 0, the method computes the optimal rank and uses it for truncation; if positive interger, the method uses the argument for the truncation; if float between 0 and 1, the rank is the number of the biggest singular values that are needed to reach the ‘energy’ specified by svd_rank; if -1, the method does not compute truncation.

• tlsq_rank (int) – rank truncation computing Total Least Square. Default is 0, that means no truncation.

• exact (bool) – flag to compute either exact DMD or projected DMD. Default is False.

• opt (bool or int) – If True, amplitudes are computed like in optimized DMD (see _compute_amplitudes() for reference). If False, amplitudes are computed following the standard algorithm. If opt is an integer, it is used as the (temporal) index of the snapshot used to compute DMD modes amplitudes (following the standard algorithm). The reconstruction will generally be better in time instants near the chosen snapshot; however increasing opt may lead to wrong results when the system presents small eigenvalues. For this reason a manual selection of the number of eigenvalues considered for the analyisis may be needed (check svd_rank). Also setting svd_rank to a value between 0 and 1 may give better results. Default is False.

• rescale_mode ({'auto'} or None or numpy.ndarray) – Scale Atilde as shown in 10.1016/j.jneumeth.2015.10.010 (section 2.4) before computing its eigendecomposition. None means no rescaling, ‘auto’ means automatic rescaling using singular values, otherwise the scaling factors.

• forward_backward (bool) – If True, the low-rank operator is computed like in fbDMD (reference: https://arxiv.org/abs/1507.02264). Default is False.

• sorted_eigs ({'real', 'abs'} or False) – Sort eigenvalues (and modes/dynamics accordingly) by magnitude if sorted_eigs=’abs’, by real part (and then by imaginary part to break ties) if sorted_eigs=’real’. Default: False.

• tikhonov_regularization (int or float) – Tikhonov parameter for the regularization. If None, no regularization is applied, if float, it is used as the \lambda tikhonov parameter.

Variables
• original_time (dict) –

dictionary that contains information about the time window where the system is sampled:

• t0 is the time of the first input snapshot;

• tend is the time of the last input snapshot;

• dt is the delta time between the snapshots.

• dmd_time (dict) –

dictionary that contains information about the time window where the system is reconstructed:

• t0 is the time of the first approximated solution;

• tend is the time of the last approximated solution;

• dt is the delta time between the approximated solutions.

static _col_major_2darray(X)[source]

Private method that takes as input the snapshots and stores them into a 2D matrix, by column. If the input data is already formatted as 2D array, the method saves it, otherwise it also saves the original snapshots shape and reshapes the snapshots.

Parameters

X (int or numpy.ndarray) – the input snapshots.

Returns

the 2D matrix that contains the flatten snapshots, the shape of original snapshots.

Return type

numpy.ndarray, tuple

_compute_amplitudes()[source]

Compute the amplitude coefficients. If self.opt is False the amplitudes are computed by minimizing the error between the modes and the first snapshot; if self.opt is True the amplitudes are computed by minimizing the error between the modes and all the snapshots, at the expense of bigger computational cost.

This method uses the class variables self._snapshots (for the snapshots), self.modes and self.eigs.

Returns

the amplitudes array

Return type

numpy.ndarray

References for optimal amplitudes: Jovanovic et al. 2014, Sparsity-promoting dynamic mode decomposition, https://hal-polytechnique.archives-ouvertes.fr/hal-00995141/document

_enforce_ratio(goal_ratio, supx, infx, supy, infy)[source]

Computes the right value of supx,infx,supy,infy to obtain the desired ratio in plot_eigs(). Ratio is defined as

dx = supx - infx
dy = supy - infy
max(dx,dy) / min(dx,dy)

Parameters
• goal_ratio (float) – the desired ratio.

• supx (float) – the old value of supx, to be adjusted.

• infx (float) – the old value of infx, to be adjusted.

• supy (float) – the old value of supy, to be adjusted.

• infy (float) – the old value of infy, to be adjusted.

Return tuple

a tuple which contains the updated values of supx,infx,supy,infy in this order.

_optimal_dmd_matrices()[source]
_plot_limits(narrow_view)[source]
_set_initial_time_dictionary(time_dict)[source]

Set the initial values for the class fields time_dict and original_time. This is usually called in fit() and never again.

Parameters

time_dict (dict) – Initial time dictionary for this DMD instance.

_translate_eigs_exponent(tpow)[source]

Transforms the exponent of the eigenvalues in the dynamics formula according to the selected value of self.opt (check the documentation for opt in __init__).

Parameters

tpow (int or np.ndarray) – the exponent(s) of Sigma in the original DMD formula.

Returns

the exponent(s) adjusted according to self.opt

Return type

int or np.ndarray

allocate_proxy()[source]
property amplitudes

Get the coefficients that minimize the error between the original system and the reconstructed one. For futher information, see dmdbase._compute_amplitudes.

Returns

the array that contains the amplitudes coefficient.

Return type

numpy.ndarray

property atilde

Get the reduced Koopman operator A, called A tilde.

Returns

the reduced Koopman operator A.

Return type

numpy.ndarray

property dmd_time

A dictionary which contains information about the time window used to reconstruct/predict using this DMD instance. By default this is equal to original_time().

Inside the dictionary:

Key

Value

t0

Time of the first output snapshot.

tend

Time of the last output snapshot.

dt

Timestep between two snapshots.

Returns

A dict which contains info about the input time frame.

Return type

dict

property dmd_timesteps

Get the timesteps of the reconstructed states.

Returns

the time intervals of the original snapshots.

Return type

numpy.ndarray

property dynamics

Get the time evolution of each mode.

\mathbf{x}(t) \approx \sum_{k=1}^{r} \boldsymbol{\phi}_{k} \exp \left( \omega_{k} t \right) b_{k} = \sum_{k=1}^{r} \boldsymbol{\phi}_{k} \left( \lambda_{k} \right)^{\left( t / \Delta t \right)} b_{k}

Returns

the matrix that contains all the time evolution, stored by row.

Return type

numpy.ndarray

property eigs

Get the eigenvalues of A tilde.

Returns

the eigenvalues from the eigendecomposition of atilde.

Return type

numpy.ndarray

property exact
fit(X)[source]

Abstract method to fit the snapshots matrices.

Not implemented, it has to be implemented in subclasses.

property fitted

Check whether this DMD instance has been fitted.

Returns

True is the instance has been fitted, False otherwise.

Return type

bool

property forward_backward
property frequency

Get the amplitude spectrum.

Returns

the array that contains the frequencies of the eigenvalues.

Return type

numpy.ndarray

property growth_rate

Get the growth rate values relative to the modes.

Returns

the Floquet values

Return type

numpy.ndarray

static load(fname)[source]

Load the object from fname using the pickle module.

Returns

Example:

>>> from pydmd import DMD
>>> print(dmd.reconstructed_data)

property modes

Get the matrix containing the DMD modes, stored by column.

Returns

the matrix containing the DMD modes.

Return type

numpy.ndarray

property modes_activation_bitmask

Get the bitmask which controls which DMD modes are enabled at the moment in this DMD instance.

The DMD instance must be fitted before this property becomes valid. After fit() is called, the defalt value of modes_activation_bitmask is an array of True values of the same shape of amplitudes().

The array returned is read-only (this allow us to react appropriately to changes in the bitmask). In order to modify the bitmask you need to set the field to a brand-new value (see example below).

Example:

>>> # this is an error
>>> tmp[[1,2]] = False

Returns

Return type

numpy.ndarray

property operator

Get the instance of DMDOperator.

Returns

the instance of DMDOperator

Return type

DMDOperator

property opt
property original_time

A dictionary which contains information about the time window used to fit this DMD instance.

Inside the dictionary:

Key

Value

t0

Time of the first input snapshot (0 by default).

tend

Time of the last input snapshot (usually corresponds to the number of snapshots).

dt

Timestep between two snapshots (1 by default).

Returns

A dict which contains info about the input time frame.

Return type

dict

property original_timesteps

Get the timesteps of the original snapshot.

Returns

the time intervals of the original snapshots.

Return type

numpy.ndarray

plot_eigs(show_axes=True, show_unit_circle=True, figsize=(8, 8), title='', narrow_view=False, dpi=None, filename=None)[source]

Plot the eigenvalues. :param bool show_axes: if True, the axes will be showed in the plot.

Default is True.

Parameters
• show_unit_circle (bool) – if True, the circle with unitary radius and center in the origin will be showed. Default is True.

• figsize (tuple(int,int)) – tuple in inches defining the figure size. Default is (8, 8).

• title (str) – title of the plot.

• bool (narrow_view) – if True, the plot will show only the smallest rectangular area which contains all the eigenvalues, with a padding of 0.05. Not compatible with show_axes=True. Default is False.

• int (dpi) – If not None, the given value is passed to plt.figure.

• filename (str) – if specified, the plot is saved at filename.

plot_modes_2D(index_mode=None, filename=None, x=None, y=None, order='C', figsize=(8, 8))[source]

Plot the DMD Modes.

Parameters
• index_mode (int or sequence(int)) – the index of the modes to plot. By default, all the modes are plotted.

• filename (str) – if specified, the plot is saved at filename.

• x (numpy.ndarray) – domain abscissa.

• y (numpy.ndarray) – domain ordinate

• order ({'C', 'F', 'A'}, default 'C'.) – read the elements of snapshots using this index order, and place the elements into the reshaped array using this index order. It has to be the same used to store the snapshot. ‘C’ means to read/ write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of indexing. ‘A’ means to read / write the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.

• figsize (tuple(int,int)) – tuple in inches defining the figure size. Default is (8, 8).

plot_snapshots_2D(index_snap=None, filename=None, x=None, y=None, order='C', figsize=(8, 8))[source]

Plot the snapshots.

Parameters
• index_snap (int or sequence(int)) – the index of the snapshots to plot. By default, all the snapshots are plotted.

• filename (str) – if specified, the plot is saved at filename.

• x (numpy.ndarray) – domain abscissa.

• y (numpy.ndarray) – domain ordinate

• order ({'C', 'F', 'A'}, default 'C'.) – read the elements of snapshots using this index order, and place the elements into the reshaped array using this index order. It has to be the same used to store the snapshot. ‘C’ means to read/ write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of indexing. ‘A’ means to read / write the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.

• figsize (tuple(int,int)) – tuple in inches defining the figure size. Default is (8, 8).

property reconstructed_data

Get the reconstructed data.

Returns

the matrix that contains the reconstructed snapshots.

Return type

numpy.ndarray

property rescale_mode
save(fname)[source]

Save the object to fname using the pickle module.

Parameters

fname (str) – the name of file where the reduced order model will be saved.

Example:

>>> from pydmd import DMD
>>> dmd = DMD(...) #  Construct here the rom
>>> dmd.fit(...)
>>> dmd.save('pydmd.dmd')

property snapshots

Get the original input data.

Returns

the matrix that contains the original snapshots.

Return type

numpy.ndarray

property svd_rank
property tlsq_rank