pymor.algorithms package¶
Submodules¶
adaptivegreedy module¶
-
class
pymor.algorithms.adaptivegreedy.AdaptiveSampleSet(parameter_space)[source]¶ Bases:
pymor.core.base.BasicObjectAn adaptive parameter sample set.
Used by
adaptive_weak_greedy.Methods
map_vertex_to_mu,refine,visualizeAttributes
Element
-
pymor.algorithms.adaptivegreedy.adaptive_weak_greedy(surrogate, parameter_space, target_error=None, max_extensions=None, validation_mus=0, rho=1.1, gamma=0.2, theta=0.0, visualize=False, visualize_vertex_size=80, pool=None)[source]¶ Weak greedy basis generation algorithm with adaptively refined training set.
This method extends pyMOR’s default
weak_greedygreedy basis generation algorithm by adaptive refinement of the parameter training set according to [HDO11] to prevent overfitting of the approximation basis to the training set. This is achieved by estimating the approximation error on an additional validation set of parameters. If the ratio between the estimated errors on the validation set and the validation set is larger thanrho, the training set is refined using standard grid refinement techniques.Parameters
- surrogate
See
weak_greedy.- parameter_space
The
ParameterSpacefor which to compute the approximation basis.- target_error
See
weak_greedy.- max_extensions
See
weak_greedy.- validation_mus
- One of the following:
a list of
Parametersto use as validation set,a positive number indicating the number of random parameters to use as validation set,
a non-positive number, indicating the negative number of random parameters to use as validation set in addition to the centers of the elements of the adaptive training set.
- rho
Maximum allowed ratio between maximum estimated error on validation set vs. maximum estimated error on training set. If the ratio is larger, the training set is refined.
- gamma
Weight of the age penalty term in the training set refinement indicators.
- theta
Ratio of training set elements to select for refinement. (One element is always refined.)
- visualize
If
True, visualize the refinement indicators. (Only available for 2 and 3 dimensional parameter spaces.)- visualize_vertex_size
Size of the vertices in the visualization.
- pool
See
weak_greedy.
Returns
Dict with the following fields
- extensions
Number of greedy iterations.
- max_errs
Sequence of maximum errors during the greedy run.
- max_err_mus
The parameters corresponding to
max_errs.- max_val_errs
Sequence of maximum errors on the validation set.
- max_val_err_mus
The parameters corresponding to
max_val_errs.- refinements
Number of refinements made in each extension step.
- training_set_sizes
The final size of the training set in each extension step.
- time
Duration of the algorithm.
-
pymor.algorithms.adaptivegreedy.rb_adaptive_greedy(fom, reductor, parameter_space, use_error_estimator=True, error_norm=None, target_error=None, max_extensions=None, validation_mus=0, rho=1.1, gamma=0.2, theta=0.0, extension_params=None, visualize=False, visualize_vertex_size=80, pool=None)[source]¶ Reduced basis greedy basis generation with adaptively refined training set.
This method extends pyMOR’s default
rb_greedygreedy reduced basis generation algorithm by adaptive refinement of the parameter training set [HDO11] to prevent overfitting of the reduced basis to the training set as implemented inadaptive_weak_greedy.Parameters
- fom
See
rb_greedy.- reductor
See
rb_greedy.- parameter_space
The
ParameterSpacefor which to compute the reduced model.- use_error_estimator
See
rb_greedy.- error_norm
See
rb_greedy.- target_error
See
weak_greedy.- max_extensions
See
weak_greedy.- validation_mus
See
adaptive_weak_greedy.- rho
See
adaptive_weak_greedy.- gamma
See
adaptive_weak_greedy.- theta
See
adaptive_weak_greedy.- extension_params
See
rb_greedy.- visualize
See
adaptive_weak_greedy.- visualize_vertex_size
See
adaptive_weak_greedy.- pool
See
weak_greedy.
Returns
Dict with the following fields
- rom
The reduced
Modelobtained for the computed basis.- extensions
Number of greedy iterations.
- max_errs
Sequence of maximum errors during the greedy run.
- max_err_mus
The parameters corresponding to
max_errs.- max_val_errs
Sequence of maximum errors on the validation set.
- max_val_err_mus
The parameters corresponding to
max_val_errs.- refinements
Number of refinements made in each extension step.
- training_set_sizes
The final size of the training set in each extension step.
- time
Duration of the algorithm.
basic module¶
Module containing some basic but generic linear algebra algorithms.
-
pymor.algorithms.basic.almost_equal(U, V, product=None, sup_norm=False, rtol=1e-14, atol=1e-14)[source]¶ Compare U and V for almost equality.
The vectors of
UandVare compared in pairs for almost equality. Two vectorsuandvare considered almost equal iff||u - v|| <= atol + ||v|| * rtol.
The norm to be used can be specified via the
productorsup_normparameters.If the length of
Uresp.Vis 1, the single specified vector is compared to all vectors of the other array. Otherwise, the lengths of both indexed arrays have to agree.Parameters
- U, V
VectorArraysto be compared.- product
If specified, use this inner product
Operatorto compute the norm. Otherwise, the Euclidean norm is used.- sup_norm
If
True, use the sup norm to compute the error.- rtol
The relative tolerance.
- atol
The absolute tolerance.
Defaults
rtol, atol (see
pymor.core.defaults)
-
pymor.algorithms.basic.contains_zero_vector(vector_array, rtol=None, atol=None)[source]¶ returns
Trueiff any vector in the array float_compares to 0s of the same dimParameters
- vector_array
a
VectorArrayimplementation- rtol
relative tolerance for float_cmp
- atol
absolute tolerance for float_cmp
-
pymor.algorithms.basic.project_array(U, basis, product=None, orthonormal=True)[source]¶ Orthogonal projection of
VectorArrayonto subspace.Parameters
- U
The
VectorArrayto project.- basis
VectorArrayof basis vectors for the subspace onto which to project.- product
Inner product
Operatorw.r.t. which to project.- orthonormal
If
True, the vectors inbasisare assumed to be orthonormal w.r.t.product.
Returns
The projected
VectorArray.
-
pymor.algorithms.basic.relative_error(U, V, product=None)[source]¶ Compute error between U and V relative to norm of U.
ei module¶
This module contains algorithms for the empirical interpolation of Operators.
The main work for generating the necessary interpolation data is handled by
the ei_greedy method. The objects returned by this method can be used
to instantiate an EmpiricalInterpolatedOperator.
As a convenience, the interpolate_operators method allows to perform
the empirical interpolation of the Operators of a given model with
a single function call.
-
pymor.algorithms.ei.deim(U, modes=None, pod=True, atol=None, rtol=None, product=None, pod_options={})[source]¶ Generate data for empirical interpolation using DEIM algorithm.
Given a
VectorArrayU, this method generates a collateral basis and interpolation DOFs for empirical interpolation of the vectors contained inU. The returned objects can be used to instantiate anEmpiricalInterpolatedOperator(withtriangular=False).The collateral basis is determined by the first
podmodes ofU.Parameters
- U
A
VectorArrayof vectors to interpolate.- modes
Dimension of the collateral basis i.e. number of POD modes of the vectors in
U.- pod
If
True, perform a POD ofUto obtain the collateral basis. IfFalse,Uis used as collateral basis.- atol
Absolute POD tolerance.
- rtol
Relative POD tolerance.
- product
Inner product
Operatorused for the POD.- pod_options
Dictionary of additional options to pass to the
podalgorithm.
Returns
- interpolation_dofs
NumPy arrayof the DOFs at which the vectors are interpolated.- collateral_basis
VectorArraycontaining the generated collateral basis.- data
Dict containing the following fields:
- svals
POD singular values.
-
pymor.algorithms.ei.ei_greedy(U, error_norm=None, atol=None, rtol=None, max_interpolation_dofs=None, copy=True, pool=DummyPool('??', '??'))[source]¶ Generate data for empirical interpolation using EI-Greedy algorithm.
Given a
VectorArrayU, this method generates a collateral basis and interpolation DOFs for empirical interpolation of the vectors contained inU. The returned objects can be used to instantiate anEmpiricalInterpolatedOperator(withtriangular=True).The interpolation data is generated by a greedy search algorithm, where in each loop iteration the worst approximated vector in
Uis added to the collateral basis.Parameters
- U
A
VectorArrayof vectors to interpolate.- error_norm
Norm w.r.t. which to calculate the interpolation error. If
None, the Euclidean norm is used.- atol
Stop the greedy search if the largest approximation error is below this threshold.
- rtol
Stop the greedy search if the largest relative approximation error is below this threshold.
- max_interpolation_dofs
Stop the greedy search if the number of interpolation DOF (= dimension of the collateral basis) reaches this value.
- copy
If
False,Uwill be modified during executing of the algorithm.- pool
If not
None, theWorkerPoolto use for parallelization.
Returns
- interpolation_dofs
NumPy arrayof the DOFs at which the vectors are evaluated.- collateral_basis
VectorArraycontaining the generated collateral basis.- data
Dict containing the following fields:
- errors
Sequence of maximum approximation errors during greedy search.
- triangularity_errors
Sequence of maximum absolute values of interoplation matrix coefficients in the upper triangle (should be near zero).
-
pymor.algorithms.ei.interpolate_operators(fom, operator_names, parameter_sample, error_norm=None, product=None, atol=None, rtol=None, max_interpolation_dofs=None, pod_options={}, alg='ei_greedy', pool=DummyPool('??', '??'))[source]¶ Empirical operator interpolation using the EI-Greedy/DEIM algorithm.
This is a convenience method to facilitate the use of
ei_greedyordeim. Given aModel, names ofOperators, and a sample ofParameters, first the operators are evaluated on the solution snapshots of the model for the provided parameters. These evaluations are then used as input forei_greedy/deim. Finally the resulting interpolation data is used to createEmpiricalInterpolatedOperatorsand a new model with the interpolated operators is returned.Note that this implementation creates one common collateral basis for all specified operators, which might not be what you want.
Parameters
- fom
- operator_names
List of keys in the
operatorsdict of the model. The correspondingOperatorswill be interpolated.- parameter_sample
A list of
Parametersfor which solution snapshots are calculated.- error_norm
See
ei_greedy. Has no effect ifalg == 'deim'.- product
Inner product for POD computation in
deim. Has no effect ifalg == 'ei_greedy'.- atol
See
ei_greedy.- rtol
See
ei_greedy.- max_interpolation_dofs
See
ei_greedy.- pod_options
Further options for
podalgorithm. Has no effect ifalg == 'ei_greedy'.- alg
Either
ei_greedyordeim.- pool
If not
None, theWorkerPoolto use for parallelization.
Returns
- eim
ModelwithOperatorsgiven byoperator_namesreplaced byEmpiricalInterpolatedOperators.- data
Dict containing the following fields:
- dofs
NumPy arrayof the DOFs at which theOperatorshave to be evaluated.- basis
VectorArraycontaining the generated collateral basis.
In addition,
datacontains the fields of thedatadictreturned byei_greedy/deim.
eigs module¶
-
pymor.algorithms.eigs._extend_arnoldi(A, E, V, H, f, p)[source]¶ Extend an existing Arnoldi factorization.
-
pymor.algorithms.eigs.eigs(A, E=None, k=3, which='LM', b=None, l=None, maxiter=1000, tol=1e-13, imag_tol=1e-12, complex_pair_tol=1e-12, seed=0)[source]¶ Approximate a few eigenvalues of a linear
Operator.Computes
keigenvalueswwith corresponding eigenvectorsvwhich solve the eigenvalue problem\[A v_i = w_i v_i\]or the generalized eigenvalue problem
\[A v_i = w_i E v_i\]if
Eis notNone.The implementation is based on Algorithm 4.2 in [RL95].
Parameters
- A
The real linear
Operatorfor which the eigenvalues are to be computed.- E
The real linear
Operatorwhich defines the generalized eigenvalue problem.- k
The number of eigenvalues and eigenvectors which are to be computed.
- which
A string specifying which
keigenvalues and eigenvectors to compute:'LM': select eigenvalues with largest magnitude'SM': select eigenvalues with smallest magnitude'LR': select eigenvalues with largest real part'SR': select eigenvalues with smallest real part'LI': select eigenvalues with largest imaginary part'SI': select eigenvalues with smallest imaginary part
- b
Initial vector for Arnoldi iteration. Default is a random vector.
- l
The size of the Arnoldi factorization. Default is
min(n - 1, max(2*k + 1, 20)).- maxiter
The maximum number of iterations.
- tol
The relative error tolerance for the Ritz estimates.
- imag_tol
Relative imaginary parts below this tolerance are set to 0.
- complex_pair_tol
Tolerance for detecting pairs of complex conjugate eigenvalues.
- seed
Random seed which is used for computing the initial vector for the Arnoldi iteration.
Returns
- w
A 1D
NumPy arraywhich contains the computed eigenvalues.- v
A
VectorArraywhich contains the computed eigenvectors.
error module¶
-
pymor.algorithms.error.reduction_error_analysis(rom, fom, reductor, test_mus, basis_sizes=0, error_estimator=True, condition=False, error_norms=(), error_norm_names=None, error_estimator_norm_index=0, custom=(), plot=False, plot_custom_logarithmic=True, pool=DummyPool('??', '??'))[source]¶ Analyze the model reduction error.
The maximum model reduction error is estimated by solving the reduced
Modelfor given randomParameters.Parameters
- rom
The reduced
Model.- fom
The high-dimensional
Model.- reductor
The reductor which has created
rom.- test_mus
List of
Parametersto compute the errors for.- basis_sizes
Either a list of reduced basis dimensions to consider, or the number of dimensions (which are then selected equidistantly, always including the maximum reduced space dimension). The dimensions are input for the
dim-Parameter ofreductor.reduce().- error_estimator
If
Trueevaluate the error estimator ofromon the testParameters.- condition
If
True, compute the condition of the reduced system matrix for the given testParameters(can only be specified ifromis an instance ofStationaryModelandrom.operatoris linear).- error_norms
List of norms in which to compute the model reduction error.
- error_norm_names
Names of the norms given by
error_norms. IfNone, thenameattributes of the given norms are used.- error_estimator_norm_index
When
error_estimatorisTrueanderror_normsare specified, this is the index of the norm inerror_normsw.r.t. which to compute the effectivity of the error estimator.- custom
List of custom functions which are evaluated for each test
parameter valuesand basis size. The functions must have the signaturedef custom_value(rom, fom, reductor, mu, dim): pass
- plot
If
True, generate a plot of the computed quantities w.r.t. the basis size.- plot_custom_logarithmic
If
True, use a logarithmic y-axis to plot the computed custom values.- pool
If not
None, theWorkerPoolto use for parallelization.
Returns
Dict with the following fields
- mus
The test
Parameterswhich have been considered.- basis_sizes
The reduced basis dimensions which have been considered.
- norms
NumPy arrayof the norms of the high-dimensional solutions w.r.t. all given testParameters, reduced basis dimensions and norms inerror_norms. (Only present whenerror_normshas been specified.)- max_norms
Maxima of
normsover the given testParameters.- max_norm_mus
Parameterscorresponding tomax_norms.- errors
NumPy arrayof the norms of the model reduction errors w.r.t. all given testParameters, reduced basis dimensions and norms inerror_norms. (Only present whenerror_normshas been specified.)- max_errors
Maxima of
errorsover the given testParameters.- max_error_mus
Parameterscorresponding tomax_errors.- rel_errors
errorsdivided bynorms. (Only present whenerror_normshas been specified.)- max_rel_errors
Maxima of
rel_errorsover the given testParameters.- max_rel_error_mus
Parameterscorresponding tomax_rel_errors.- error_norm_names
Names of the given
error_norms. (Only present whenerror_normshas been specified.)- error_estimates
NumPy arrayof the model reduction error estimates w.r.t. all given testParametersand reduced basis dimensions. (Only present whenerror_estimatorisTrue.)- max_error_estimate
Maxima of
error_estimatesover the given testParameters.- max_error_estimate_mus
Parameterscorresponding tomax_error_estimates.- effectivities
errorsdivided byerror_estimates. (Only present whenerror_estimatorisTrueanderror_normshas been specified.)- min_effectivities
Minima of
effectivitiesover the given testParameters.- min_effectivity_mus
Parameterscorresponding tomin_effectivities.- max_effectivities
Maxima of
effectivitiesover the given testParameters.- max_effectivity_mus
Parameterscorresponding tomax_effectivities.- errors
NumPy arrayof the reduced system matrix conditions w.r.t. all given testParametersand reduced basis dimensions. (Only present whenconditionsisTrue.)- max_conditions
Maxima of
conditionsover the given testParameters.- max_condition_mus
Parameterscorresponding tomax_conditions.- custom_values
NumPy arrayof custom function evaluations w.r.t. all given testParameters, reduced basis dimensions and functions incustom. (Only present whencustomhas been specified.)- max_custom_values
Maxima of
custom_valuesover the given testParameters.- max_custom_values_mus
Parameterscorresponding tomax_custom_values.- time
Time (in seconds) needed for the error analysis.
- summary
String containing a summary of all computed quantities for the largest (last) considered basis size.
- figure
The figure containing the generated plots. (Only present when
plotisTrue.)
genericsolvers module¶
This module contains some iterative linear solvers which only use the Operator interface
-
pymor.algorithms.genericsolvers.apply_inverse(op, V, initial_guess=None, options=None, least_squares=False, check_finite=True, default_solver='generic_lgmres', default_least_squares_solver='generic_least_squares_lsmr')[source]¶ Solve linear equation system.
Applies the inverse of
opto the vectors inVusing a generic iterative solver.Parameters
- op
The linear, non-parametric
Operatorto invert.- V
VectorArrayof right-hand sides for the equation system.- initial_guess
VectorArraywith the same length asVcontaining initial guesses for the solution. Some implementations ofapply_inversemay ignore this parameter. IfNonea solver-dependent default is used.- options
The
solver_optionsto use (seesolver_options).- least_squares
If
True, return least squares solution.- check_finite
Test if solution only contains finite values.
- default_solver
Default solver to use (generic_lgmres, generic_least_squares_lsmr, generic_least_squares_lsqr).
- default_least_squares_solver
Default solver to use for least squares problems (generic_least_squares_lsmr, generic_least_squares_lsqr).
Returns
VectorArrayof the solution vectors.Defaults
check_finite, default_solver, default_least_squares_solver (see
pymor.core.defaults)
-
pymor.algorithms.genericsolvers.lgmres(A, b, x0=None, tol=1e-05, maxiter=1000, M=None, callback=None, inner_m=30, outer_k=3, outer_v=None, store_outer_Av=True)[source]¶
-
pymor.algorithms.genericsolvers.lsmr(A, b, damp=0.0, atol=1e-06, btol=1e-06, conlim=100000000.0, maxiter=None, show=False)[source]¶
-
pymor.algorithms.genericsolvers.lsqr(A, b, damp=0.0, atol=1e-08, btol=1e-08, conlim=100000000.0, iter_lim=None, show=False)[source]¶
-
pymor.algorithms.genericsolvers.solver_options(lgmres_tol=1e-05, lgmres_maxiter=1000, lgmres_inner_m=39, lgmres_outer_k=3, least_squares_lsmr_damp=0.0, least_squares_lsmr_atol=1e-06, least_squares_lsmr_btol=1e-06, least_squares_lsmr_conlim=100000000.0, least_squares_lsmr_maxiter=None, least_squares_lsmr_show=False, least_squares_lsqr_damp=0.0, least_squares_lsqr_atol=1e-06, least_squares_lsqr_btol=1e-06, least_squares_lsqr_conlim=100000000.0, least_squares_lsqr_iter_lim=None, least_squares_lsqr_show=False)[source]¶ Returns available solvers with default
solver_options.Parameters
- lgmres_tol
- lgmres_maxiter
- lgmres_inner_m
- lgmres_outer_k
- least_squares_lsmr_damp
- least_squares_lsmr_atol
- least_squares_lsmr_btol
- least_squares_lsmr_conlim
- least_squares_lsmr_maxiter
- least_squares_lsmr_show
- least_squares_lsqr_damp
- least_squares_lsqr_atol
- least_squares_lsqr_btol
- least_squares_lsqr_conlim
- least_squares_lsqr_iter_lim
- least_squares_lsqr_show
Returns
A dict of available solvers with default
solver_options.Defaults
lgmres_tol, lgmres_maxiter, lgmres_inner_m, lgmres_outer_k, least_squares_lsmr_damp, least_squares_lsmr_atol, least_squares_lsmr_btol, least_squares_lsmr_conlim, least_squares_lsmr_maxiter, least_squares_lsmr_show, least_squares_lsqr_atol, least_squares_lsqr_btol, least_squares_lsqr_conlim, least_squares_lsqr_iter_lim, least_squares_lsqr_show (see
pymor.core.defaults)
gram_schmidt module¶
-
pymor.algorithms.gram_schmidt.gram_schmidt(A, product=None, return_R=False, atol=1e-13, rtol=1e-13, offset=0, reiterate=True, reiteration_threshold=0.9, check=True, check_tol=0.001, copy=True)[source]¶ Orthonormalize a
VectorArrayusing the modified Gram-Schmidt algorithm.Parameters
- A
The
VectorArraywhich is to be orthonormalized.- product
The inner product
Operatorw.r.t. which to orthonormalize. IfNone, the Euclidean product is used.- return_R
If
True, the R matrix from QR decomposition is returned.- atol
Vectors of norm smaller than
atolare removed from the array.- rtol
Relative tolerance used to detect linear dependent vectors (which are then removed from the array).
- offset
Assume that the first
offsetvectors are already orthonormal and start the algorithm at theoffset + 1-th vector.- reiterate
If
True, orthonormalize again if the norm of the orthogonalized vector is much smaller than the norm of the original vector.- reiteration_threshold
If
reiterateisTrue, re-orthonormalize if the ratio between the norms of the orthogonalized vector and the original vector is smaller than this value.- check
If
True, check if the resultingVectorArrayis really orthonormal.- check_tol
Tolerance for the check.
- copy
If
True, create a copy ofAinstead of modifyingAin-place.
Returns
- Q
The orthonormalized
VectorArray.- R
The upper-triangular/trapezoidal matrix (if
compute_RisTrue).
Defaults
atol, rtol, reiterate, reiteration_threshold, check, check_tol (see
pymor.core.defaults)
-
pymor.algorithms.gram_schmidt.gram_schmidt_biorth(V, W, product=None, reiterate=True, reiteration_threshold=0.1, check=True, check_tol=0.001, copy=True)[source]¶ Biorthonormalize a pair of
VectorArraysusing the biorthonormal Gram-Schmidt process.See Algorithm 1 in [BKS11].
Parameters
- V, W
The
VectorArrayswhich are to be biorthonormalized.- product
The inner product
Operatorw.r.t. which to biorthonormalize. IfNone, the Euclidean product is used.- reiterate
If
True, orthonormalize again if the norm of the orthogonalized vector is much smaller than the norm of the original vector.- reiteration_threshold
If
reiterateisTrue, re-orthonormalize if the ratio between the norms of the orthogonalized vector and the original vector is smaller than this value.- check
If
True, check if the resultingVectorArrayis really orthonormal.- check_tol
Tolerance for the check.
- copy
If
True, create a copy ofVandWinstead of modifyingVandWin-place.
Returns
The biorthonormalized
VectorArrays.
greedy module¶
-
class
pymor.algorithms.greedy.RBSurrogate(fom, reductor, use_error_estimator, error_norm, extension_params, pool)[source]¶ Bases:
pymor.algorithms.greedy.WeakGreedySurrogateSurrogate for the
weak_greedyerror used inrb_greedy.Not intended to be used directly.
Methods
evaluate,extendAttributes
-
evaluate(mus, return_all_values=False)[source]¶ Evaluate the surrogate for given parameters.
Parameters
- mus
List of parameters for which to estimate the approximation error. When parallelization is used,
muscan be aRemoteObject.- return_all_values
See below.
Returns
If
return_all_valuesisTrue, anNumPy arrayof the estimated errors. Ifreturn_all_valuesisFalse, the maximum estimated error as first return value and the corresponding parameter as second return value.
-
-
class
pymor.algorithms.greedy.WeakGreedySurrogate[source]¶ Bases:
pymor.core.base.BasicObjectSurrogate for the approximation error in
weak_greedy.Methods
evaluate,extendAttributes
-
abstract
evaluate(mus, return_all_values=False)[source]¶ Evaluate the surrogate for given parameters.
Parameters
- mus
List of parameters for which to estimate the approximation error. When parallelization is used,
muscan be aRemoteObject.- return_all_values
See below.
Returns
If
return_all_valuesisTrue, anNumPy arrayof the estimated errors. Ifreturn_all_valuesisFalse, the maximum estimated error as first return value and the corresponding parameter as second return value.
-
abstract
-
pymor.algorithms.greedy.rb_greedy(fom, reductor, training_set, use_error_estimator=True, error_norm=None, atol=None, rtol=None, max_extensions=None, extension_params=None, pool=None)[source]¶ Weak Greedy basis generation using the RB approximation error as surrogate.
This algorithm generates a reduced basis using the
weak greedyalgorithm [BCDDPW11], where the approximation error is estimated from computing solutions of the reduced order model for the current reduced basis and then estimating the model reduction error.Parameters
- fom
The
Modelto reduce.- reductor
Reductor for reducing the given
Model. This has to be an object with areducemethod, such thatreductor.reduce()yields the reduced model, and anexted_basismethod, such thatreductor.extend_basis(U, copy_U=False, **extension_params)extends the current reduced basis by the vectors contained inU. For an example seeCoerciveRBReductor.- training_set
The training set of
Parameterson which to perform the greedy search.- use_error_estimator
If
False, exactly compute the model reduction error by also computing the solution offomfor allparameter valuesof the training set. This is mainly useful when no estimator for the model reduction error is available.- error_norm
If
use_error_estimatorisFalse, use this function to calculate the norm of the error. IfNone, the Euclidean norm is used.- atol
See
weak_greedy.- rtol
See
weak_greedy.- max_extensions
See
weak_greedy.- extension_params
dictof parameters passed to thereductor.extend_basismethod. IfNone,'gram_schmidt'basis extension will be used as a default for stationary problems (fom.solvereturnsVectorArraysof length 1) and'pod'basis extension (adding a single POD mode) for instationary problems.- pool
See
weak_greedy.
Returns
Dict with the following fields
- rom
The reduced
Modelobtained for the computed basis.- max_errs
Sequence of maximum errors during the greedy run.
- max_err_mus
The parameters corresponding to
max_errs.- extensions
Number of performed basis extensions.
- time
Total runtime of the algorithm.
-
pymor.algorithms.greedy.weak_greedy(surrogate, training_set, atol=None, rtol=None, max_extensions=None, pool=None)[source]¶ Weak greedy basis generation algorithm [BCDDPW11].
This algorithm generates an approximation basis for a given set of vectors associated with a training set of parameters by iteratively evaluating a
surrogatefor the approximation error on the training set and adding the worst approximated vector (according to the surrogate) to the basis.The constructed basis is extracted from the surrogate after termination of the algorithm.
Parameters
- surrogate
An instance of
WeakGreedySurrogaterepresenting the surrogate for the approximation error.- training_set
The set of parameter samples on which to perform the greedy search.
- atol
If not
None, stop the algorithm if the maximum (estimated) error on the training set drops below this value.- rtol
If not
None, stop the algorithm if the maximum (estimated) relative error on the training set drops below this value.- max_extensions
If not
None, stop the algorithm aftermax_extensionsextension steps.- pool
If not
None, aWorkerPoolto use for parallelization. Parallelization needs to be supported bysurrogate.
Returns
Dict with the following fields
- max_errs
Sequence of maximum estimated errors during the greedy run.
- max_err_mus
The parameters corresponding to
max_errs.- extensions
Number of performed basis extensions.
- time
Total runtime of the algorithm.
hapod module¶
-
class
pymor.algorithms.hapod.DistHAPODTree(slices)[source]¶ Bases:
pymor.algorithms.hapod.TreeMethods
childrenis_leafAttributes
depth,root
-
class
pymor.algorithms.hapod.IncHAPODTree(steps)[source]¶ Bases:
pymor.algorithms.hapod.TreeMethods
childrenis_leafAttributes
depth,root
-
class
pymor.algorithms.hapod.LifoExecutor(executor, max_workers=None)[source]¶ Bases:
objectMethods
done_callback,run_task,submit
-
class
pymor.algorithms.hapod.Tree[source]¶ Bases:
pymor.core.base.BasicObjectA rooted tree.
Methods
children,is_leafAttributes
depth,root
-
pymor.algorithms.hapod.dist_hapod(num_slices, snapshots, eps, omega, product=None, executor=None, eval_snapshots_in_executor=False)[source]¶ Distributed Hierarchical Approximate POD.
This computes the distributed HAPOD from [HLR18].
Parameters
- num_slices
The number of snapshot vector slices.
- snapshots
A mapping
snapshots(slice)returning for each slice number the associated snapshot vectors.- eps
Desired l2-mean approximation error.
- omega
Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
- product
Inner product
Operatorw.r.t. which to compute the POD.- executor
If not
None, aconcurrent.futures.Executorobject to use for parallelization.- eval_snapshots_in_executor
If
Truealso parallelize the evaluation of the snapshot map.
Returns
- modes
The computed POD modes.
- svals
The associated singular values.
- snap_count
The total number of input snapshot vectors.
-
pymor.algorithms.hapod.dist_vectorarray_hapod(num_slices, U, eps, omega, product=None, executor=None)[source]¶ Distributed Hierarchical Approximate POD.
This computes the distributed HAPOD from [HLR18] of a given
VectorArray.Parameters
- num_slices
The number of snapshot vector slices.
- U
The
VectorArrayof which to compute the HAPOD.- eps
Desired l2-mean approximation error.
- omega
Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
- product
Inner product
Operatorw.r.t. which to compute the POD.- executor
If not
None, aconcurrent.futures.Executorobject to use for parallelization.
Returns
- modes
The computed POD modes.
- svals
The associated singular values.
- snap_count
The total number of input snapshot vectors.
-
pymor.algorithms.hapod.hapod(tree, snapshots, local_eps, product=None, pod_method=<function default_pod_method>, executor=None, eval_snapshots_in_executor=False)[source]¶ Compute the Hierarchical Approximate POD.
This is an implementation of the HAPOD algorithm from [HLR18].
Parameters
- tree
A
Treedefining the worker topology.- snapshots
A mapping
snapshots(node)returning for each leaf node the associated snapshot vectors.- local_eps
A mapping
local_eps(node, snap_count, num_vecs)assigning to each tree nodenodean l2 truncation error tolerance for the local pod based on the number of input vectorsnum_vecsand the total number of snapshot vectors below the given nodesnap_count.- product
Inner product
Operatorw.r.t. which to compute the POD.- pod_method
A function
pod_method(U, eps, root_node, product)for computing the POD of theVectorArrayUw.r.t. the given inner productproductand the l2 error toleranceeps.root_nodeis set toTruewhen the POD is computed at the root of the tree.- executor
If not
None, aconcurrent.futures.Executorobject to use for parallelization.- eval_snapshots_in_executor
If
Truealso parallelize the evaluation of the snapshot map.
Returns
- modes
The computed POD modes.
- svals
The associated singular values.
- snap_count
The total number of input snapshot vectors.
-
pymor.algorithms.hapod.inc_hapod(steps, snapshots, eps, omega, product=None, executor=None, eval_snapshots_in_executor=False)[source]¶ Incremental Hierarchical Approximate POD.
This computes the incremental HAPOD from [HLR18].
Parameters
- steps
The number of incremental POD updates.
- snapshots
A mapping
snapshots(step)returning for each incremental POD step the associated snapshot vectors.- eps
Desired l2-mean approximation error.
- omega
Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
- product
Inner product
Operatorw.r.t. which to compute the POD.- executor
If not
None, aconcurrent.futures.Executorobject to use for parallelization.- eval_snapshots_in_executor
If
Truealso parallelize the evaluation of the snapshot map.
Returns
- modes
The computed POD modes.
- svals
The associated singular values.
- snap_count
The total number of input snapshot vectors.
-
pymor.algorithms.hapod.inc_vectorarray_hapod(steps, U, eps, omega, product=None, executor=None)[source]¶ Incremental Hierarchical Approximate POD.
This computes the incremental HAPOD from [HLR18] for a given
VectorArray.Parameters
- steps
The number of incremental POD updates.
- U
The
VectorArrayof which to compute the HAPOD.- eps
Desired l2-mean approximation error.
- omega
Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
- product
Inner product
Operatorw.r.t. which to compute the POD.- executor
If not
None, aconcurrent.futures.Executorobject to use for parallelization.- eval_snapshots_in_executor
If
Truealso parallelize the evaluation of the snapshot map.
Returns
- modes
The computed POD modes.
- svals
The associated singular values.
- snap_count
The total number of input snapshot vectors.
image module¶
-
class
pymor.algorithms.image.CollectOperatorRangeRules(source, image, extends)[source]¶ Bases:
pymor.algorithms.rules.RuleTableRuleTablefor theestimate_imagealgorithm.Methods
append_rule,apply,apply_children,breakpoint_for_name,breakpoint_for_obj,get_children,insert_rule,replace_childrenAttributes
action_apply_operator,action_ConcatenationOperator,action_EmpiricalInterpolatedOperator,action_recurse,rules
-
class
pymor.algorithms.image.CollectVectorRangeRules(image)[source]¶ Bases:
pymor.algorithms.rules.RuleTableRuleTablefor theestimate_imagealgorithm.Methods
append_rule,apply,apply_children,breakpoint_for_name,breakpoint_for_obj,get_children,insert_rule,replace_childrenAttributes
action_as_range_array,action_ConcatenationOperator,action_recurse,action_VectorArray,rules
-
pymor.algorithms.image.estimate_image(operators=(), vectors=(), domain=None, extends=False, orthonormalize=True, product=None, riesz_representatives=False)[source]¶ Estimate the image of given
Operatorsfor all mu.Let
operatorsbe a list ofOperatorswith common source and range, and letvectorsbe a list ofVectorArraysor vector-likeOperatorsin the range of these operators. Given aVectorArraydomainof vectors in the source of the operators, this algorithms determines aVectorArrayimageof range vectors such that the linear span ofimagecontains:op.apply(U, mu=mu)for all operatorsopinoperators, for all possibleParametersmuand for allVectorArraysUcontained in the linear span ofdomain,Ufor allVectorArraysinvectors,v.as_range_array(mu)for allOperatorsinvectorsand all possibleParametersmu.
The algorithm will try to choose
imageas small as possible. However, no optimality is guaranteed. The image estimation algorithm is specified byCollectOperatorRangeRulesandCollectVectorRangeRules.Parameters
- operators
See above.
- vectors
See above.
- domain
See above. If
None, an emptydomainVectorArrayis assumed.- extends
For some operators, e.g.
EmpiricalInterpolatedOperator, as well as for all elements ofvectors,imageis estimated independently from the choice ofdomain. IfextendsisTrue, such operators are ignored. (This is useful in case these vectors have already been obtained by earlier calls to this function.)- orthonormalize
Compute an orthonormal basis for the linear span of
imageusing thegram_schmidtalgorithm.- product
Inner product
Operatorw.r.t. which to orthonormalize.- riesz_representatives
If
True, compute Riesz representatives of the vectors inimagebefore orthonormalizing (useful for dual norm computation when the range of theoperatorsis a dual space).
Returns
The
VectorArrayimage.Raises
- ImageCollectionError
Is raised when for a given
Operatorno image estimate is possible.
-
pymor.algorithms.image.estimate_image_hierarchical(operators=(), vectors=(), domain=None, extends=None, orthonormalize=True, product=None, riesz_representatives=False)[source]¶ Estimate the image of given
Operatorsfor all mu.This is an extended version of
estimate_image, which callsestimate_imageindividually for each vector ofdomain.As a result, the vectors in the returned
imageVectorArraywill be ordered by thedomainvector they correspond to (starting with vectors which correspond to the elements ofvectorsand toOperatorsfor which the image is estimated independently fromdomain).This function also returns an
image_dimslist, such that the firstimage_dims[i+1]vectors ofimagecorrespond to the firstivectors ofdomain(the firstimage_dims[0]vectors correspond tovectorsand toOperatorswith fixed image estimate).Parameters
- operators
See
estimate_image.- vectors
See
estimate_image.- domain
See
estimate_image.- extends
When additional vectors have been appended to the
domainVectorArrayafterestimate_image_hierarchicalhas been called, andestimate_image_hierarchicalshall be called again for the extendeddomainarray,extendscan be set to(image, image_dims), whereimage,image_dimsare the return values of the lastestimate_image_hierarchicalcall. The olddomainvectors will then be skipped during computation andimage,image_dimswill be modified in-place.- orthonormalize
See
estimate_image.- product
See
estimate_image.- riesz_representatives
See
estimate_image.
Returns
- image
See above.
- image_dims
See above.
Raises
- ImageCollectionError
Is raised when for a given
Operatorno image estimate is possible.
krylov module¶
Module for computing (rational) Krylov subspaces’ bases.
-
pymor.algorithms.krylov.rational_arnoldi(A, E, b, sigma, trans=False)[source]¶ Rational Arnoldi algorithm.
If
trans == False, using Arnoldi process, computes a real orthonormal basis for the rational Krylov subspace\[\mathrm{span}\{ (\sigma_1 E - A)^{-1} b, (\sigma_2 E - A)^{-1} b, \ldots, (\sigma_r E - A)^{-1} b \},\]otherwise, computes the same for
\[\mathrm{span}\{ (\sigma_1 E - A)^{-T} b^T, (\sigma_2 E - A)^{-T} b^T, \ldots, (\sigma_r E - A)^{-T} b^T \}.\]Interpolation points in
sigmaare allowed to repeat (in any order). Then, in the above expression,\[\underbrace{ (\sigma_i E - A)^{-1} b, \ldots, (\sigma_i E - A)^{-1} b }_{m \text{ times}}\]is replaced by
\[(\sigma_i E - A)^{-1} b, (\sigma_i E - A)^{-1} E (\sigma_i E - A)^{-1} b, \ldots, \left((\sigma_i E - A)^{-1} E\right)^{m - 1} (\sigma_i E - A)^{-1} b.\]Analogously for the
trans == Truecase.Parameters
Returns
- V
Orthonormal basis for the Krylov subspace
VectorArray.
-
pymor.algorithms.krylov.tangential_rational_krylov(A, E, B, b, sigma, trans=False, orth=True)[source]¶ Tangential Rational Krylov subspace.
If
trans == False, computes a real basis for the rational Krylov subspace\[\mathrm{span}\{ (\sigma_1 E - A)^{-1} B b_1, (\sigma_2 E - A)^{-1} B b_2, \ldots, (\sigma_r E - A)^{-1} B b_r \},\]otherwise, computes the same for
\[\mathrm{span}\{ (\sigma_1 E - A)^{-T} B^T b_1, (\sigma_2 E - A)^{-T} B^T b_2, \ldots, (\sigma_r E - A)^{-T} B^T b_r \}.\]Interpolation points in
sigmaare assumed to be pairwise distinct.Parameters
- A
Real
OperatorA.- E
Real
OperatorE.- B
Real
OperatorB.- b
VectorArrayfromB.source, iftrans == False, orB.range, iftrans == True.
- sigma
Sequence of interpolation points (closed under conjugation), of the same length as
b.- trans
Boolean, see above.
- orth
If
True, orthonormalizes the basis usingpymor.algorithms.gram_schmidt.gram_schmidt.
Returns
- V
Optionally orthonormal basis for the Krylov subspace
VectorArray.
lincomb module¶
-
class
pymor.algorithms.lincomb.AssembleLincombRules(coefficients, solver_options, name)[source]¶ Bases:
pymor.algorithms.rules.RuleTableMethods
append_rule,apply,apply_children,breakpoint_for_name,breakpoint_for_obj,get_children,insert_rule,replace_childrenAttributes
action_BlockDiagonalOperator,action_BlockOperatorBase,action_BlockSpaceIdentityOperator,action_call_assemble_lincomb_method,action_failed,action_IdentityAndSecondOrderModelOperator,action_IdentityOperator,action_merge_into_low_rank_updated_operator,action_merge_low_rank_operators,action_only_one_operator,action_VectorArrayOperator,action_zero_coeff,action_ZeroOperator,rules
-
pymor.algorithms.lincomb.assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
Returns a new
Operatorwhich represents the sumc_1*O_1 + ... + c_N*O_N
where
O_iareOperatorsandc_iscalar coefficients.This function is called in the
assemblemethod ofLincombOperatorand is not intended to be used directly. The assembledOperatoris expected to no longer be aLincombOperatornor should it contain anyLincombOperators. If an assembly of the given linear combination is not possible,Noneis returned. The special case of aLincombOperatorwith a single operator (i.e. a scaledOperator) is allowed as assemble_lincomb implementsapply_inversefor this special case.To form the linear combination of backend
Operators(containing actual matrix data),_assemble_lincombwill be called on the firstOperatorin the linear combination.Parameters
- operators
List of
OperatorsO_iwhose linear combination is formed.- coefficients
List of the corresponding linear coefficients
c_i.- solver_options
solver_optionsfor the assembled operator.- name
Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
line_search module¶
-
pymor.algorithms.line_search.armijo(f, starting_point, direction, grad=None, initial_value=None, alpha_init=1.0, tau=0.5, beta=0.0001, maxiter=10)[source]¶ Armijo line search algorithm.
This method computes a step size such that the Armijo condition (see [NW06], p. 33) is fulfilled.
Parameters
- f
Real-valued function that can be evaluated for its value.
- starting_point
A
VectorArrayof length 1 containing the starting point of the line search.- direction
Descent direction along which the line search is performed.
- grad
Gradient of
fin the pointstarting_point.- initial_value
Value of
fin the pointstarting_point.- alpha_init
Initial step size that is gradually reduced.
- tau
The fraction by which the step size is reduced in each iteration.
- beta
Control parameter to adjust the required decrease of the function value of
f.- maxiter
Use
alpha_initas default if the iteration count reaches this value without finding a point fulfilling the Armijo condition.
Returns
- alpha
Step size computed according to the Armijo condition.
Defaults
alpha_init, tau, beta, maxiter (see
pymor.core.defaults)
lradi module¶
-
pymor.algorithms.lradi.lyap_lrcf_solver_options(lradi_tol=1e-10, lradi_maxiter=500, lradi_shifts='projection_shifts', projection_shifts_init_maxiter=20, projection_shifts_init_seed=None)[source]¶ Return available Lyapunov solvers with default options.
Parameters
- lradi_tol
See
solve_lyap_lrcf.- lradi_maxiter
See
solve_lyap_lrcf.- lradi_shifts
See
solve_lyap_lrcf.- projection_shifts_init_maxiter
- projection_shifts_init_seed
Returns
A dict of available solvers with default solver options.
Defaults
lradi_tol, lradi_maxiter, lradi_shifts, projection_shifts_init_maxiter, projection_shifts_init_seed (see
pymor.core.defaults)
-
pymor.algorithms.lradi.projection_shifts(A, E, V, prev_shifts)[source]¶ Find further shift parameters for low-rank ADI iteration using Galerkin projection on spaces spanned by LR-ADI iterates.
See [PK16], pp. 92-95.
Parameters
- A
The
OperatorA from the corresponding Lyapunov equation.- E
The
OperatorE from the corresponding Lyapunov equation.- V
A
VectorArrayrepresenting the currently computed iterate.- prev_shifts
A
NumPy arraycontaining the set of all previously used shift parameters.
Returns
- shifts
A
NumPy arraycontaining a set of stable shift parameters.
-
pymor.algorithms.lradi.projection_shifts_init(A, E, B, shift_options)[source]¶ Find starting shift parameters for low-rank ADI iteration using Galerkin projection on spaces spanned by LR-ADI iterates.
See [PK16], pp. 92-95.
Parameters
- A
The
OperatorA from the corresponding Lyapunov equation.- E
The
OperatorE from the corresponding Lyapunov equation.- B
The
VectorArrayB from the corresponding Lyapunov equation.- shift_options
The shift options to use (see
lyap_lrcf_solver_options).
Returns
- shifts
A
NumPy arraycontaining a set of stable shift parameters.
-
pymor.algorithms.lradi.solve_lyap_lrcf(A, E, B, trans=False, options=None)[source]¶ Compute an approximate low-rank solution of a Lyapunov equation.
See
pymor.algorithms.lyapunov.solve_lyap_lrcffor a general description.This function uses the low-rank ADI iteration as described in Algorithm 4.3 in [PK16].
Parameters
- A
The non-parametric
OperatorA.- E
The non-parametric
OperatorE orNone.- B
The operator B as a
VectorArrayfromA.source.- trans
Whether the first
Operatorin the Lyapunov equation is transposed.- options
The solver options to use (see
lyap_lrcf_solver_options).
Returns
- Z
Low-rank Cholesky factor of the Lyapunov equation solution,
VectorArrayfromA.source.
lrradi module¶
-
pymor.algorithms.lrradi.hamiltonian_shifts(A, E, B, R, K, Z, shift_options)[source]¶ Compute further shift parameters for low-rank RADI iteration.
Compute Galerkin projection of Hamiltonian matrix on space spanned by last few columns of \(Z\) and return the eigenvalue of the projected Hamiltonian with the most impact on convergence as the next shift parameter.
See [BBKS18], pp. 318-321.
Parameters
- A
The
OperatorA from the corresponding Riccati equation.- E
The
OperatorE from the corresponding Riccati equation.- B
The
VectorArrayB from the corresponding Riccati equation.- R
A
VectorArrayrepresenting the currently computed residual factor.- K
A
VectorArrayrepresenting the currently computed iterate.- Z
A
VectorArrayrepresenting the currently computed solution factor.- shift_options
The shift options to use (see
ricc_lrcf_solver_options).
Returns
- shifts
A
NumPy arraycontaining a set of stable shift parameters.
-
pymor.algorithms.lrradi.hamiltonian_shifts_init(A, E, B, C, shift_options)[source]¶ Compute initial shift parameters for low-rank RADI iteration.
Compute Galerkin projection of Hamiltonian matrix on space spanned by \(C\) and return the eigenvalue of the projected Hamiltonian with the most impact on convergence as the next shift parameter.
See [BBKS18], pp. 318-321.
Parameters
- A
The
OperatorA from the corresponding Riccati equation.- E
The
OperatorE from the corresponding Riccati equation.- B
The
VectorArrayB from the corresponding Riccati equation.- C
The
VectorArrayC from the corresponding Riccati equation.- shift_options
The shift options to use (see
ricc_lrcf_solver_options).
Returns
- shifts
A
NumPy arraycontaining a set of stable shift parameters.
-
pymor.algorithms.lrradi.ricc_lrcf_solver_options(lrradi_tol=1e-10, lrradi_maxiter=500, lrradi_shifts='hamiltonian_shifts', hamiltonian_shifts_init_maxiter=20, hamiltonian_shifts_init_seed=None, hamiltonian_shifts_subspace_columns=6)[source]¶ Returns available Riccati equation solvers with default solver options.
Parameters
- lrradi_tol
See
solve_ricc_lrcf.- lrradi_maxiter
See
solve_ricc_lrcf.- lrradi_shifts
See
solve_ricc_lrcf.- hamiltonian_shifts_init_maxiter
- hamiltonian_shifts_init_seed
- hamiltonian_shifts_subspace_columns
See
hamiltonian_shifts.
Returns
A dict of available solvers with default solver options.
Defaults
lrradi_tol, lrradi_maxiter, lrradi_shifts, hamiltonian_shifts_init_maxiter, hamiltonian_shifts_init_seed, hamiltonian_shifts_subspace_columns (see
pymor.core.defaults)
-
pymor.algorithms.lrradi.solve_ricc_lrcf(A, E, B, C, R=None, trans=False, options=None)[source]¶ Compute an approximate low-rank solution of a Riccati equation.
See
pymor.algorithms.riccati.solve_ricc_lrcffor a general description.This function is an implementation of Algorithm 2 in [BBKS18].
Parameters
- A
The
OperatorA.- E
The
OperatorE orNone.- B
The operator B as a
VectorArrayfromA.source.- C
The operator C as a
VectorArrayfromA.source.- R
The operator R as a 2D
NumPy arrayorNone.- trans
Whether the first
Operatorin the Riccati equation is transposed.- options
The solver options to use. (see
ricc_lrcf_solver_options)
Returns
- Z
Low-rank Cholesky factor of the Riccati equation solution,
VectorArrayfromA.source.
lyapunov module¶
-
pymor.algorithms.lyapunov._chol(A)[source]¶ Cholesky decomposition.
This implementation uses SVD to compute the Cholesky factor (can be used for singular matrices).
Parameters
- A
Symmetric positive semidefinite matrix as a
NumPy array.
Returns
- L
Cholesky factor of A (in the sense that L * L^T approximates A).
-
pymor.algorithms.lyapunov.mat_eqn_sparse_min_size(value=1000)[source]¶ Returns minimal size for which a sparse solver will be used by default.
Defaults
value (see
pymor.core.defaults)
-
pymor.algorithms.lyapunov.solve_lyap_dense(A, E, B, trans=False, options=None, default_solver_backend='pymess')[source]¶ Compute the solution of a Lyapunov equation.
Returns the solution \(X\) of a (generalized) continuous-time algebraic Lyapunov equation:
if trans is
Falseand E isNone:\[A X + X A^T + B B^T = 0,\]if trans is
Falseand E is anOperator:\[A X E^T + E X A^T + B B^T = 0,\]if trans is
Trueand E isNone:\[A^T X + X A + B^T B = 0,\]if trans is
Trueand E is anOperator:\[A^T X E + E^T X A + B^T B = 0.\]
We assume A and E are real
NumPy arrays, E is invertible, and that no two eigenvalues of (A, E) sum to zero (i.e., there exists a unique solution X).If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:
pymess(seepymor.bindings.pymess.solve_lyap_dense)slycot(seepymor.bindings.slycot.solve_lyap_dense)scipy(seepymor.bindings.scipy.solve_lyap_dense)
Parameters
- A
The operator A as a 2D
NumPy array.- E
The operator E as a 2D
NumPy arrayorNone.- B
The operator B as a 2D
NumPy array.- trans
Whether the first operator in the Lyapunov equation is transposed.
- options
The solver options to use. See:
- default_solver_backend
Default solver backend to use (pymess, slycot, scipy).
Returns
- X
Lyapunov equation solution as a
NumPy array.
Defaults
default_solver_backend (see
pymor.core.defaults)
-
pymor.algorithms.lyapunov.solve_lyap_lrcf(A, E, B, trans=False, options=None, default_sparse_solver_backend='pymess', default_dense_solver_backend='pymess')[source]¶ Compute an approximate low-rank solution of a Lyapunov equation.
Returns a low-rank Cholesky factor \(Z\) such that \(Z Z^T\) approximates the solution \(X\) of a (generalized) continuous-time algebraic Lyapunov equation:
if trans is
Falseand E isNone:\[A X + X A^T + B B^T = 0,\]if trans is
Falseand E is anOperator:\[A X E^T + E X A^T + B B^T = 0,\]if trans is
Trueand E isNone:\[A^T X + X A + B^T B = 0,\]if trans is
Trueand E is anOperator:\[A^T X E + E^T X A + B^T B = 0.\]
We assume A and E are real
Operators, E is invertible, and all the eigenvalues of (A, E) all lie in the open left half-plane. Operator B needs to be given as aVectorArrayfromA.source, and for large-scale problems, we assumelen(B)is small.If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:
for sparse problems (minimum size specified by
mat_eqn_sparse_min_size)pymess(seepymor.bindings.pymess.solve_lyap_lrcf),lradi(seepymor.algorithms.lradi.solve_lyap_lrcf),
for dense problems (smaller than
mat_eqn_sparse_min_size)pymess(seepymor.bindings.pymess.solve_lyap_lrcf),slycot(seepymor.bindings.slycot.solve_lyap_lrcf),scipy(seepymor.bindings.scipy.solve_lyap_lrcf).
Parameters
- A
The non-parametric
OperatorA.- E
The non-parametric
OperatorE orNone.- B
The operator B as a
VectorArrayfromA.source.- trans
Whether the first
Operatorin the Lyapunov equation is transposed.- options
The solver options to use. See:
- default_sparse_solver_backend
Default sparse solver backend to use (pymess, lradi).
- default_dense_solver_backend
Default dense solver backend to use (pymess, slycot, scipy).
Returns
- Z
Low-rank Cholesky factor of the Lyapunov equation solution,
VectorArrayfromA.source.
Defaults
default_sparse_solver_backend, default_dense_solver_backend (see
pymor.core.defaults)
newton module¶
-
pymor.algorithms.newton.newton(operator, rhs, initial_guess=None, mu=None, range_product=None, source_product=None, least_squares=False, miniter=0, maxiter=100, atol=0.0, rtol=1e-07, relax='armijo', line_search_params=None, stagnation_window=3, stagnation_threshold=inf, error_measure='update', return_stages=False, return_residuals=False)[source]¶ Newton algorithm.
This method solves the nonlinear equation
A(U, mu) = V
for
Uusing the Newton method.Parameters
- operator
The
OperatorA.Amust implement thejacobianinterface method.- rhs
VectorArrayof length 1 containing the vectorV.- initial_guess
If not
None, aVectorArrayof length 1 containing an initial guess for the solutionU.- mu
The
parameter valuesfor which to solve the equation.- range_product
The inner product
Operatoronoperator.rangewith which the norm of the resiudal is computed. IfNone, the Euclidean inner product is used.- source_product
The inner product
Operatoronoperator.sourcewith which the norm of the solution and update vectors is computed. IfNone, the Euclidean inner product is used.- least_squares
If
True, use a least squares linear solver (e.g. for residual minimization).- miniter
Minimum amount of iterations to perform.
- maxiter
Fail if the iteration count reaches this value without converging.
- atol
Finish when the error measure is below this threshold.
- rtol
Finish when the error measure has been reduced by this factor relative to the norm of the initial residual resp. the norm of the current solution.
- relax
If real valued, relaxation factor for Newton updates; otherwise
'armijo'to indicate that thearmijoline search algorithm shall be used.- line_search_params
Dictionary of additional parameters passed to the line search method.
- stagnation_window
Finish when the error measure has not been reduced by a factor of
stagnation_thresholdduring the laststagnation_windowiterations.- stagnation_threshold
See
stagnation_window.- error_measure
If
'residual', convergence depends on the norm of the residual. If'update', convergence depends on the norm of the update vector.- return_stages
If
True, return aVectorArrayof the intermediate approximations ofUafter each iteration.- return_residuals
If
True, return aVectorArrayof all residual vectors which have been computed during the Newton iterations.
Returns
- U
VectorArrayof length 1 containing the computed solution- data
Dict containing the following fields:
- solution_norms
NumPy arrayof the solution norms after each iteration.- update_norms
NumPy arrayof the norms of the update vectors for each iteration.- residual_norms
NumPy arrayof the residual norms after each iteration.- stages
See
return_stages.- residuals
See
return_residuals.
Raises
- NewtonError
Raised if the Newton algorithm failed to converge.
Defaults
miniter, maxiter, rtol, atol, relax, stagnation_window, stagnation_threshold (see
pymor.core.defaults)
pod module¶
-
pymor.algorithms.pod.pod(A, product=None, modes=None, rtol=1e-07, atol=0.0, l2_err=0.0, method='method_of_snapshots', orth_tol=1e-10)[source]¶ Proper orthogonal decomposition of
A.Viewing the
VectorArrayAas aA.dimxlen(A)matrix, the return values of this method are theVectorArrayof left singular vectors and aNumPy arrayof singular values of the singular value decomposition ofA, where the inner product on R^(dim(A)) is given byproductand the inner product on R^(len(A)) is the Euclidean inner product.Parameters
- A
The
VectorArrayfor which the POD is to be computed.- product
Inner product
Operatorw.r.t. which the POD is computed.- modes
If not
None, at most the firstmodesPOD modes (singular vectors) are returned.- rtol
Singular values smaller than this value multiplied by the largest singular value are ignored.
- atol
Singular values smaller than this value are ignored.
- l2_err
Do not return more modes than needed to bound the l2-approximation error by this value. I.e. the number of returned modes is at most
argmin_N { sum_{n=N+1}^{infty} s_n^2 <= l2_err^2 }
where
s_ndenotes the n-th singular value.- method
Which SVD method from
svd_vato use ('method_of_snapshots'or'qr_svd').- orth_tol
POD modes are reorthogonalized if the orthogonality error is above this value.
Returns
- POD
VectorArrayof POD modes.- SVALS
One-dimensional
NumPy arrayof singular values.
Defaults
rtol, atol, l2_err, method, orth_tol (see
pymor.core.defaults)
preassemble module¶
-
class
pymor.algorithms.preassemble.PreAssembleRules[source]¶ Bases:
pymor.algorithms.rules.RuleTableMethods
append_rule,apply,apply_children,breakpoint_for_name,breakpoint_for_obj,get_children,insert_rule,replace_childrenAttributes
action_AdjointOperator,action_assemble,action_identity,action_recurse,action_recurse_and_assemble,rules
-
pymor.algorithms.preassemble.preassemble(obj)[source]¶ Preassemble non-parametric operators.
If
objis a non-parametricOperator, returnobj.assemble()otherwise returnobj. Recursively replaces children ofobj.
projection module¶
-
class
pymor.algorithms.projection.ProjectRules(range_basis, source_basis)[source]¶ Bases:
pymor.algorithms.rules.RuleTableRuleTablefor theprojectalgorithm.Methods
append_rule,apply,apply_children,breakpoint_for_name,breakpoint_for_obj,get_children,insert_rule,replace_childrenAttributes
action_AdjointOperator,action_AffineOperator,action_apply_basis,action_BlockOperatorBase,action_ConcatenationOperator,action_ConstantOperator,action_EmpiricalInterpolatedOperator,action_LincombOperator,action_no_bases,action_SelectionOperator,action_ZeroOperator,rules
-
class
pymor.algorithms.projection.ProjectToSubbasisRules(dim_range, dim_source)[source]¶ Bases:
pymor.algorithms.rules.RuleTableRuleTablefor theproject_to_subbasisalgorithm.Methods
append_rule,apply,apply_children,breakpoint_for_name,breakpoint_for_obj,get_children,insert_rule,replace_childrenAttributes
action_BlockColumnOperator,action_BlockRowOperator,action_ConstantOperator,action_IdentityOperator,action_NumpyMatrixOperator,action_ProjectedEmpiciralInterpolatedOperator,action_ProjectedOperator,action_recurse,action_VectorArrayOperator,action_ZeroOperator,rules
-
pymor.algorithms.projection.project(op, range_basis, source_basis, product=None)[source]¶ Petrov-Galerkin projection of a given
Operator.Given an inner product
( ⋅, ⋅), source vectorsb_1, ..., b_Nand range vectorsc_1, ..., c_M, the projectionop_projofopis defined by[ op_proj(e_j) ]_i = ( c_i, op(b_j) )
for all i,j, where
e_jdenotes the j-th canonical basis vector of R^N.In particular, if the
c_iare orthonormal w.r.t. the given product, thenop_projis the coordinate representation w.r.t. theb_i/c_ibases of the restriction ofoptospan(b_i)concatenated with the orthogonal projection ontospan(c_i).From another point of view, if
opis viewed as a bilinear form (seeapply2) and( ⋅, ⋅ )is the Euclidean inner product, thenop_projrepresents the matrix of the bilinear form restricted tospan(b_i) / span(c_i)(w.r.t. theb_i/c_ibases).How the projection is realized will depend on the given
Operator. While a projectedNumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general. The exact algorithm is specified inProjectRules.Parameters
- range_basis
The vectors
c_1, ..., c_Mas aVectorArray. IfNone, no projection in the range space is performed.- source_basis
The vectors
b_1, ..., b_Nas aVectorArrayorNone. IfNone, no restriction of the source space is performed.- product
An
Operatorrepresenting the inner product. IfNone, the Euclidean inner product is chosen.
Returns
The projected
Operatorop_proj.
-
pymor.algorithms.projection.project_to_subbasis(op, dim_range=None, dim_source=None)[source]¶ Project already projected
Operatorto a subbasis.The purpose of this method is to further project an operator that has been obtained through
projectto subbases of the original projection bases, i.e.project_to_subbasis(project(op, r_basis, s_basis, prod), dim_range, dim_source)
should be the same as
project(op, r_basis[:dim_range], s_basis[:dim_source], prod)
For a
NumpyMatrixOperatorthis amounts to extracting the upper-left (dim_range, dim_source) corner of its matrix.The subbasis projection algorithm is specified in
ProjectToSubbasisRules.Parameters
- dim_range
Dimension of the range subbasis.
- dim_source
Dimension of the source subbasis.
Returns
The projected
Operator.
randrangefinder module¶
-
pymor.algorithms.randrangefinder.adaptive_rrf(A, source_product=None, range_product=None, tol=0.0001, failure_tolerance=1e-15, num_testvecs=20, lambda_min=None, iscomplex=False)[source]¶ Adaptive randomized range approximation of
A.This is an implementation of Algorithm 1 in [BS18].
Given the
OperatorA, the return value of this method is theVectorArrayBwith the property\[\Vert A - P_{span(B)} A \Vert \leq tol\]with a failure probability smaller than
failure_tolerance, where the norm denotes the operator norm. The inner product of the range ofAis given byrange_productand the inner product of the source ofAis given bysource_product.Parameters
- A
The
OperatorA.- source_product
Inner product
Operatorof the source of A.- range_product
Inner product
Operatorof the range of A.- tol
Error tolerance for the algorithm.
- failure_tolerance
Maximum failure probability.
- num_testvecs
Number of test vectors.
- lambda_min
The smallest eigenvalue of source_product. If
None, the smallest eigenvalue is computed using scipy.- iscomplex
If
True, the random vectors are chosen complex.
Returns
- B
VectorArraywhich contains the basis, whose span approximates the range of A.
Defaults
tol, failure_tolerance, num_testvecs (see
pymor.core.defaults)
-
pymor.algorithms.randrangefinder.rrf(A, source_product=None, range_product=None, q=2, l=8, iscomplex=False)[source]¶ Randomized range approximation of
A.This is an implementation of Algorithm 4.4 in [HMT11].
Given the
OperatorA, the return value of this method is theVectorArrayQwhose vectors form an approximate orthonomal basis for the range ofA.Parameters
Returns
- Q
VectorArraywhich contains the basis, whose span approximates the range of A.
Defaults
q, l (see
pymor.core.defaults)
riccati module¶
-
pymor.algorithms.riccati.solve_pos_ricc_lrcf(A, E, B, C, R=None, trans=False, options=None, default_dense_solver_backend='pymess')[source]¶ Compute an approximate low-rank solution of a positive Riccati equation.
Returns a low-rank Cholesky factor \(Z\) such that \(Z Z^T\) approximates the solution \(X\) of a (generalized) positive continuous-time algebraic Riccati equation:
if trans is
False\[A X E^T + E X A^T + E X C^T R^{-1} C X E^T + B B^T = 0.\]if trans is
True\[A^T X E + E^T X A + E^T X B R^{-1} B^T X E + C^T C = 0.\]
If E is None, it is taken to be identity, and similarly for R.
If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:
pymess(seepymor.bindings.pymess.solve_pos_ricc_lrcf),slycot(seepymor.bindings.slycot.solve_pos_ricc_lrcf),scipy(seepymor.bindings.scipy.solve_pos_ricc_lrcf).
Parameters
- A
The non-parametric
OperatorA.- E
The non-parametric
OperatorE orNone.- B
The operator B as a
VectorArrayfromA.source.- C
The operator C as a
VectorArrayfromA.source.- R
The operator R as a 2D
NumPy arrayorNone.- trans
Whether the first
Operatorin the positive Riccati equation is transposed.- options
The solver options to use. See:
- default_dense_solver_backend
Default dense solver backend to use (pymess, slycot, scipy).
Returns
- Z
Low-rank Cholesky factor of the positive Riccati equation solution,
VectorArrayfromA.source.
Defaults
default_dense_solver_backend (see
pymor.core.defaults)
-
pymor.algorithms.riccati.solve_ricc_lrcf(A, E, B, C, R=None, trans=False, options=None, default_sparse_solver_backend='pymess', default_dense_solver_backend='pymess')[source]¶ Compute an approximate low-rank solution of a Riccati equation.
Returns a low-rank Cholesky factor \(Z\) such that \(Z Z^T\) approximates the solution \(X\) of a (generalized) continuous-time algebraic Riccati equation:
if trans is
False\[A X E^T + E X A^T - E X C^T R^{-1} C X E^T + B B^T = 0.\]if trans is
True\[A^T X E + E^T X A - E^T X B R^{-1} B^T X E + C^T C = 0.\]
If E is None, it is taken to be identity, and similarly for R.
We assume:
A and E are real
Operators,B and C are real
VectorArraysfromA.source,R is a real
NumPy array,(E, A, B, C) is stabilizable and detectable, and
R is symmetric positive definite.
For large-scale problems, we additionally assume that
len(B)andlen(C)are small.If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:
for sparse problems (minimum size specified by
mat_eqn_sparse_min_size)pymess(seepymor.bindings.pymess.solve_ricc_lrcf),lrradi(seepymor.algorithms.lrradi.solve_ricc_lrcf),
for dense problems (smaller than
mat_eqn_sparse_min_size)pymess(seepymor.bindings.pymess.solve_ricc_lrcf),slycot(seepymor.bindings.slycot.solve_ricc_lrcf),scipy(seepymor.bindings.scipy.solve_ricc_lrcf).
Parameters
- A
The non-parametric
OperatorA.- E
The non-parametric
OperatorE orNone.- B
The operator B as a
VectorArrayfromA.source.- C
The operator C as a
VectorArrayfromA.source.- R
The operator R as a 2D
NumPy arrayorNone.- trans
Whether the first
Operatorin the Riccati equation is transposed.- options
The solver options to use. See:
- default_sparse_solver_backend
Default sparse solver backend to use (pymess, lrradi).
- default_dense_solver_backend
Default dense solver backend to use (pymess, slycot, scipy).
Returns
- Z
Low-rank Cholesky factor of the Riccati equation solution,
VectorArrayfromA.source.
Defaults
default_sparse_solver_backend, default_dense_solver_backend (see
pymor.core.defaults)
rules module¶
-
class
pymor.algorithms.rules.RuleTable(use_caching=False)[source]¶ Bases:
pymor.core.base.BasicObjectDefine algorithm by a table of match conditions and corresponding actions.
RuleTablemanages a table ofrules, stored in therulesattributes, which can beappliedto given objects.A new table is created by subclassing
RuleTableand defining new methods which are decorated withmatch_class,match_genericor anotherrulesubclass. The order of the method definitions determines the order in which the definedrulesare applied.Parameters
- use_caching
If
True, cache results ofapply.
Methods
append_rule,apply,apply_children,breakpoint_for_name,breakpoint_for_obj,get_children,insert_rule,replace_childrenAttributes
-
apply(obj)[source]¶ Sequentially apply rules to given object.
This method iterates over all rules of the given
RuleTable. For eachrule, it is checked if itmatchesthe given object. IfFalse, the nextrulein the table is considered. IfTruethe correspondingactionis executed withobjas parameter. If execution ofactionraisesRuleNotMatchingError, the rule is considered as not matching, and execution continues with evaluation of the next rule. Otherwise, execution is stopped and the return value ofrule.actionis returned to the caller.If no
rulematches, aNoMatchingRuleErroris raised.Parameters
- obj
The object to apply the
RuleTableto.
Returns
Return value of the action of the first matching
rulein the table.Raises
- NoMatchingRuleError
No
rulecould be applied to the given object.
-
apply_children(obj, children=None)[source]¶ Apply rules to all children of the given object.
This method calls
applyto each child of the given object. The children of the object are either provided by thechildrenparameter or automatically inferred by theget_childrenmethod.Parameters
- obj
The object to apply the
RuleTableto.- children
Noneor a list of attribute names defining the children to consider.
Returns
Result of : meth:
applyfor all given children.
-
classmethod
breakpoint_for_name(name)[source]¶ Add a conditional breakpoint for objects of given name.
Break execution in
apply, when being applied to an object with a certain name.Parameters
- name
nameof the object for which to add the conditional breakpoint.
-
classmethod
breakpoint_for_obj(obj)[source]¶ Add a conditional breakpoint for given object.
Break execution in
apply, when being applied to a certain object.Parameters
- obj
Object for which to add the conditional breakpoint.
-
classmethod
get_children(obj)[source]¶ Determine children of given object.
This method returns a list of the names of all attributes
a, for which one of the folling is true:
-
replace_children(obj, children=None)[source]¶ Replace children of object according to rule table.
Same as
apply_children, but additionally callsobj.with_to replace the children ofobjwith the result of the correspondingapplycall.
-
class
pymor.algorithms.rules.RuleTableMeta(name, parents, dct)[source]¶ Bases:
pymor.core.base.UberMetaMeta class for
RuleTable.Methods
register,__instancecheck__,__subclasscheck__typemro,__dir__,__prepare__,__sizeof__,__subclasses__-
static
__new__(cls, name, parents, dct)[source]¶ I copy docstrings from base class methods to deriving classes.
Copying of docstrings is disabled when the
PYMOR_WITH_SPHINXenvironment variable is set to1.
-
__str__()¶ Return repr(self).
-
static
-
class
pymor.algorithms.rules.match_always(action)[source]¶ Bases:
pymor.algorithms.rules.rulerulethat always matches.Attributes
condition_typeaction,action_description,condition_description,source
-
class
pymor.algorithms.rules.match_class(*classes)[source]¶ Bases:
pymor.algorithms.rules.match_class_baserulethat matches when obj is instance of one of the given classes.Attributes
condition_typeaction,action_description,condition_description,source
-
class
pymor.algorithms.rules.match_class_all(*classes)[source]¶ Bases:
pymor.algorithms.rules.match_class_baserulethat matches when each item of obj is instance of one of the given classes.Attributes
condition_typeaction,action_description,condition_description,source
-
class
pymor.algorithms.rules.match_class_any(*classes)[source]¶ Bases:
pymor.algorithms.rules.match_class_baserulethat matches when any item of obj is instance of one of the given classes.Attributes
condition_typeaction,action_description,condition_description,source
-
class
pymor.algorithms.rules.match_class_base(*classes)[source]¶ Bases:
pymor.algorithms.rules.rule
-
class
pymor.algorithms.rules.match_generic(condition, condition_description=None)[source]¶ Bases:
pymor.algorithms.rules.rulerulewith matching condition given by an arbitrary function.Parameters
- condition
Function of one argument which checks if given object matches condition.
- condition_description
Optional string describing the condition implemented by
condition.
Attributes
condition_typeaction,action_description,condition_description,source
-
class
pymor.algorithms.rules.rule[source]¶ Bases:
objectDecorator to make a method a rule in a given
RuleTable.The decorated function will become the
actionto perform in case the rulematches. Matching conditions are specified by subclassing and overriding thematchesmethod.If an action is decorated by multiple rules, all these rules must match for the action to apply.
-
action¶ Method to call in case the rule matches.
-
samdp module¶
-
pymor.algorithms.samdp._select_max_eig(H, G, X, V, B, C, which)[source]¶ Compute poles sorted from largest to smallest residual.
Parameters
- H
The
NumPy arrayH from the SAMDP algorithm.- G
The
NumPy arrayG from the SAMDP algorithm.- X
A
VectorArraydescribing the orthogonal search space used in the SAMDP algorithm.- V
A
VectorArraydescribing the orthogonal search space used in the SAMDP algorithm.- B
The
VectorArrayB from the corresponding LTI system modified by deflation.- C
The
VectorArrayC from the corresponding LTI system modified by deflation.- which
A string that indicates which poles to select. See
samdp.
Returns
- poles
A
NumPy arraycontaining poles sorted according to the chosen strategy.- rightevs
A
NumPy arraycontaining the right eigenvectors of the computed poles.- leftevs
A
NumPy arraycontaining the left eigenvectors of the computed poles.- residue
A 1D
NumPy arraycontaining the norms of the residues.
-
pymor.algorithms.samdp._twosided_rqi(A, E, x, y, theta, init_res, imagtol, rqitol, maxiter)[source]¶ Refine an initial guess for an eigentriplet of the matrix pair (A, E).
Parameters
- A
The
OperatorA from the LTI system.- E
The
OperatorE from the LTI system.- x
Initial guess for right eigenvector of matrix pair (A, E).
- y
Initial guess for left eigenvector of matrix pair (A, E).
- theta
Initial guess for eigenvalue of matrix pair (A, E).
- init_res
Residual of initial guess.
- imagtol
Relative tolerance for imaginary parts of pairs of complex conjugate eigenvalues.
- rqitol
Convergence tolerance for the relative change of the pole.
- maxiter
Maximum number of iteration.
Returns
- x
Refined right eigenvector of matrix pair (A, E).
- y
Refined left eigenvector of matrix pair (A, E).
- theta
Refined eigenvalue of matrix pair (A, E).
- residual
Residual of the computed triplet.
-
pymor.algorithms.samdp.samdp(A, E, B, C, nwanted, init_shifts=None, which='LR', tol=1e-10, imagtol=1e-06, conjtol=1e-08, dorqitol=0.0001, rqitol=1e-10, maxrestart=100, krestart=20, rqi_maxiter=10, seed=0)[source]¶ Compute the dominant pole triplets and residues of the transfer function of an LTI system.
This function uses the subspace accelerated dominant pole (SAMDP) algorithm as described in [RM06] in Algorithm 2 in order to compute dominant pole triplets and residues of the transfer function
\[H(s) = C (s E - A)^{-1} B\]of an LTI system. It is possible to take advantage of prior knowledge about the poles by specifying shift parameters, which are injected after a new pole has been found.
Parameters
- A
The
OperatorA.- E
The
OperatorE orNone.- B
The operator B as a
VectorArrayfromA.source.- C
The operator C as a
VectorArrayfromA.source.- nwanted
The number of dominant poles that should be computed.
- init_shifts
A
NumPy arraycontaining shifts which are injected after a new pole has been found.- which
A string specifying the strategy by which the dominant poles and residues are selected. Possible values are:
'LR': select poles with largest norm(residual) / abs(Re(pole))'LS': select poles with largest norm(residual) / abs(pole)'LM': select poles with largest norm(residual)
- tol
Tolerance for the residual of the poles.
- imagtol
Relative tolerance for imaginary parts of pairs of complex conjugate eigenvalues.
- conjtol
Tolerance for the residual of the complex conjugate of a pole.
- dorqitol
If the residual is smaller than dorqitol the two-sided Rayleigh quotient iteration is executed.
- rqitol
Tolerance for the relative change of a pole in the two-sided Rayleigh quotient iteration.
- maxrestart
The maximum number of restarts.
- krestart
Maximum dimension of search space before performing a restart.
- rqi_maxiter
Maximum number of iterations for the two-sided Rayleigh quotient iteration.
- seed
Random seed which is used for computing the initial shift and random restarts.
Returns
- poles
A 1D
NumPy arraycontaining the computed dominant poles.- residues
A 3D
NumPy arrayof shape(len(poles), len(C), len(B))containing the computed residues.- rightev
A
VectorArraycontaining the right eigenvectors of the computed poles.- leftev
A
VectorArraycontaining the left eigenvectors of the computed poles.
Defaults
which, tol, imagtol, conjtol, dorqitol, rqitol, maxrestart, krestart, init_shifts, rqi_maxiter, seed (see
pymor.core.defaults)
simplify module¶
-
class
pymor.algorithms.simplify.ExpandRules[source]¶ Bases:
pymor.algorithms.rules.RuleTableMethods
append_rule,apply,apply_children,breakpoint_for_name,breakpoint_for_obj,get_children,insert_rule,replace_childrenAttributes
action_ConcatenationOperator,action_LincombOperator,action_recurse,rules
-
pymor.algorithms.simplify.expand(obj)[source]¶ Expand concatenations of LincombOperators.
To any given
OperatororModel, the following transformations are applied recursively:ConcatenationsofLincombOperatorsare expanded. E.g.(O1 + O2) @ (O3 + O4)
becomes:
O1 @ O3 + O1 @ O4 + O2 @ O3 + O2 @ O4
LincombOperatorsinsideLincombOperatorsare merged into a singleLincombOperatorConcatenationOperatorsinsideConcatenationOperatorsare merged into a singleConcatenationOperator.
Parameters
Returns
The transformed object.
svd_va module¶
Module for SVD method of operators represented by VectorArrays.
-
pymor.algorithms.svd_va.method_of_snapshots(A, product=None, modes=None, rtol=1e-07, atol=0.0, l2_err=0.0)[source]¶ SVD of a
VectorArrayusing the method of snapshots.Viewing the
VectorArrayAas aA.dimxlen(A)matrix, the return value of this method is the singular value decomposition ofA, where the inner product on R^(dim(A)) is given byproductand the inner product on R^(len(A)) is the Euclidean inner product.Warning
The left singular vectors may not be numerically orthonormal for ill-conditioned
A.Parameters
- A
The
VectorArrayfor which the SVD is to be computed.- product
Inner product
Operatorw.r.t. which the SVD is computed.- modes
If not
None, at most the firstmodessingular values and vectors are returned.- rtol
Singular values smaller than this value multiplied by the largest singular value are ignored.
- atol
Singular values smaller than this value are ignored.
- l2_err
Do not return more modes than needed to bound the l2-approximation error by this value. I.e. the number of returned modes is at most
argmin_N { sum_{n=N+1}^{infty} s_n^2 <= l2_err^2 }
where
s_ndenotes the n-th singular value.
Returns
- U
VectorArrayof left singular vectors.- s
One-dimensional
NumPy arrayof singular values.- Vh
NumPy arrayof right singular vectors.
Defaults
rtol, atol, l2_err (see
pymor.core.defaults)
-
pymor.algorithms.svd_va.qr_svd(A, product=None, modes=None, rtol=4e-08, atol=0.0, l2_err=0.0)[source]¶ SVD of a
VectorArrayusing Gram-Schmidt orthogonalization.Viewing the
VectorArrayAas aA.dimxlen(A)matrix, the return value of this method is the singular value decomposition ofA, where the inner product on R^(dim(A)) is given byproductand the inner product on R^(len(A)) is the Euclidean inner product.Parameters
- A
The
VectorArrayfor which the SVD is to be computed.- product
Inner product
Operatorw.r.t. which the left singular vectors are computed.- modes
If not
None, at most the firstmodessingular values and vectors are returned.- rtol
Singular values smaller than this value multiplied by the largest singular value are ignored.
- atol
Singular values smaller than this value are ignored.
- l2_err
Do not return more modes than needed to bound the l2-approximation error by this value. I.e. the number of returned modes is at most
argmin_N { sum_{n=N+1}^{infty} s_n^2 <= l2_err^2 }
where
s_ndenotes the n-th singular value.
Returns
- U
VectorArrayof left singular vectors.- s
One-dimensional
NumPy arrayof singular values.- Vh
NumPy arrayof right singular vectors.
Defaults
rtol, atol, l2_err (see
pymor.core.defaults)
sylvester module¶
-
pymor.algorithms.sylvester.solve_sylv_schur(A, Ar, E=None, Er=None, B=None, Br=None, C=None, Cr=None)[source]¶ Solve Sylvester equation by Schur decomposition.
Solves Sylvester equation
\[A V E_r^T + E V A_r^T + B B_r^T = 0\]or
\[A^T W E_r + E^T W A_r + C^T C_r = 0\]or both using (generalized) Schur decomposition (Algorithms 3 and 4 in [BKS11]), if the necessary parameters are given.
Parameters
- A
Real
Operator.- Ar
Real
Operator. It is converted into aNumPy arrayusingto_matrix.- E
Real
OperatororNone(then assumed to be the identity).- Er
Real
OperatororNone(then assumed to be the identity). It is converted into aNumPy arrayusingto_matrix.- B
Real
OperatororNone.- Br
Real
OperatororNone. It is assumed thatBr.range.from_numpyis implemented.- C
Real
OperatororNone.- Cr
Real
OperatororNone. It is assumed thatCr.source.from_numpyis implemented.
Returns
- V
Returned if
BandBrare given,VectorArrayfromA.source.- W
Returned if
CandCrare given,VectorArrayfromA.source.
Raises
- ValueError
If
VandWcannot be returned.
timestepping module¶
This module provides generic time-stepping algorithms for the solution of instationary problems.
The algorithms are generic in the sense that each algorithms operates exclusively
on Operators and VectorArrays. In particular, the algorithms
can also be used to turn an arbitrary stationary Model provided
by an external library into an instationary Model.
Currently, implementations of explicit_euler and implicit_euler
time-stepping are provided. The TimeStepper defines a
common interface that has to be fulfilled by the time-steppers used
by InstationaryModel. The classes ExplicitEulerTimeStepper
and ImplicitEulerTimeStepper encapsulate explicit_euler and
implicit_euler to provide this interface.
-
class
pymor.algorithms.timestepping.ExplicitEulerTimeStepper(*args, **kwargs)[source]¶ Bases:
pymor.algorithms.timestepping.TimeStepperExplicit Euler time-stepper.
Solves equations of the form
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- nt
The number of time-steps the time-stepper will perform.
Methods
Attributes
-
solve(initial_time, end_time, initial_data, operator, rhs=None, mass=None, mu=None, num_values=None)[source]¶ Apply time-stepper to the equation
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- initial_time
The time at which to begin time-stepping.
- end_time
The time until which to perform time-stepping.
- initial_data
The solution vector at
initial_time.- operator
The
OperatorA.- rhs
The right-hand side F (either
VectorArrayof length 1 orOperatorwithsource.dim == 1). IfNone, zero right-hand side is assumed.- mass
The
OperatorM. IfNone, the identity operator is assumed.- mu
Parameter valuesfor whichoperatorandrhsare evaluated. The current time is added tomuwith keyt.- num_values
The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned.
Returns
VectorArraycontaining the solution trajectory.
-
class
pymor.algorithms.timestepping.ImplicitEulerTimeStepper(*args, **kwargs)[source]¶ Bases:
pymor.algorithms.timestepping.TimeStepperImplict Euler time-stepper.
Solves equations of the form
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- nt
The number of time-steps the time-stepper will perform.
- solver_options
The
solver_optionsused to invertM + dt*A. The special values'mass'and'operator'are recognized, in which case the solver_options of M (resp. A) are used.
Methods
Attributes
-
solve(initial_time, end_time, initial_data, operator, rhs=None, mass=None, mu=None, num_values=None)[source]¶ Apply time-stepper to the equation
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- initial_time
The time at which to begin time-stepping.
- end_time
The time until which to perform time-stepping.
- initial_data
The solution vector at
initial_time.- operator
The
OperatorA.- rhs
The right-hand side F (either
VectorArrayof length 1 orOperatorwithsource.dim == 1). IfNone, zero right-hand side is assumed.- mass
The
OperatorM. IfNone, the identity operator is assumed.- mu
Parameter valuesfor whichoperatorandrhsare evaluated. The current time is added tomuwith keyt.- num_values
The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned.
Returns
VectorArraycontaining the solution trajectory.
-
class
pymor.algorithms.timestepping.TimeStepper(*args, **kwargs)[source]¶ Bases:
pymor.core.base.ImmutableObjectInterface for time-stepping algorithms.
Algorithms implementing this interface solve time-dependent problems of the form
M * d_t u + A(u, mu, t) = F(mu, t).
Time-steppers used by
InstationaryModelhave to fulfill this interface.Methods
Attributes
-
abstract
solve(initial_time, end_time, initial_data, operator, rhs=None, mass=None, mu=None, num_values=None)[source]¶ Apply time-stepper to the equation
M * d_t u + A(u, mu, t) = F(mu, t).
Parameters
- initial_time
The time at which to begin time-stepping.
- end_time
The time until which to perform time-stepping.
- initial_data
The solution vector at
initial_time.- operator
The
OperatorA.- rhs
The right-hand side F (either
VectorArrayof length 1 orOperatorwithsource.dim == 1). IfNone, zero right-hand side is assumed.- mass
The
OperatorM. IfNone, the identity operator is assumed.- mu
Parameter valuesfor whichoperatorandrhsare evaluated. The current time is added tomuwith keyt.- num_values
The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned.
Returns
VectorArraycontaining the solution trajectory.
-
abstract
-
pymor.algorithms.timestepping.explicit_euler(A, F, U0, t0, t1, nt, mu=None, num_values=None)[source]¶
-
pymor.algorithms.timestepping.implicit_euler(A, F, M, U0, t0, t1, nt, mu=None, num_values=None, solver_options='operator')[source]¶
to_matrix module¶
-
class
pymor.algorithms.to_matrix.ToMatrixRules(format, mu)[source]¶ Bases:
pymor.algorithms.rules.RuleTableMethods
append_rule,apply,apply_children,breakpoint_for_name,breakpoint_for_obj,get_children,insert_rule,replace_childrenAttributes
action_AdjointOperator,action_BlockOperator,action_ComponentProjectionOperator,action_ConcatenationOperator,action_IdentityOperator,action_LincombOperator,action_LowRankOperator,action_LowRankUpdatedOperator,action_NumpyMatrixOperator,action_VectorArrayOperator,action_ZeroOperator,rules
-
pymor.algorithms.to_matrix.to_matrix(op, format=None, mu=None)[source]¶ Convert a linear
Operatorto a matrix.Parameters
- op
The
Operatorto convert.- format
Format of the resulting matrix:
NumPy arrayif ‘dense’, otherwise the appropriateSciPy spmatrix. IfNone, a choice between dense and sparse format is automatically made.- mu
The
parameter valuesfor which to convertop.
Returns
- res
The matrix equivalent to
op.