pyMOR - Model Order Reduction with python¶
pyMOR is a software library for building model order reduction applications with the Python programming language. Its main focus lies on the application of reduced basis methods to parameterized partial differential equations. All algorithms in pyMOR are formulated in terms of abstract interfaces for seamless integration with external high-dimensional PDE solvers. Moreover, pure Python implementations of finite element and finite volume discretizations using the NumPy/SciPy scientific computing stack are provided for getting started quickly.
Getting started¶
Installation¶
Before trying out pyMOR, you need to install it. We provide packages for Ubuntu via our PPA:
sudo apt-add-repository ppa:pymor/stable
sudo apt-get update
sudo apt-get install python-pymor python-pymor-demos python-pymor-doc
Daily snapshots can be installed by using the pymor/daily PPA instead of
pymor/stable. The current release can also be installed via
pip. Please take a look at our
README file for
further details. The
README
also contains instructions for setting up a development environment for working
on pyMOR itself.
Trying it out¶
While we consider pyMOR mainly as a library for building MOR applications, we
ship a few example scripts. These can be found in the src/pymordemos
directory of the source repository. Try launching one of
them using the pymor-demo script contained in the python-pymor-demos
package:
pymor-demo thermalblock --plot-err --plot-solutions 3 2 3 32
The demo scripts can also be launched directly from the source tree:
./thermalblock.py --plot-err --plot-solutions 3 2 3 32
This will solve and reduce the so called thermal block problem using the reduced basis method with a greedy basis generation algorithm. The thermal block problem consists in solving the stationary diffusion problem
- ∇ ⋅ [ d(x, μ) ∇ u(x, μ) ] = 1 for x in Ω
u(x, μ) = 0 for x in ∂Ω
on the domain Ω = [0,1]^2 for the unknown u. The domain is partitioned into
XBLOCKS x YBLOCKS blocks (XBLOCKS and YBLOCKS are the first
two arguments to thermalblock.py). The thermal conductivity d(x, μ)
is constant on each block (i,j) with value μ_ij:
(0,1)------------------(1,1)
| | | |
| μ_11 | μ_12 | μ_13 |
| | | |
|---------------------------
| | | |
| μ_21 | μ_22 | μ_23 |
| | | |
(0,0)------------------(1,0)
The real numbers μ_ij form the XBLOCKS x YBLOCKS - dimensional parameter
on which the solution depends.
Running thermalblock.py will first produce plots of two detailed
solutions of the problem for different randomly chosen parameters
using linear finite elements. (The size of the grid can be controlled
via the --grid parameter. The randomly chosen parameters will
actually be the same for each run, since a the random generator
is initialized with a fixed default seed in
new_random_state.)
After closing the window, the reduced basis for model order reduction
is generated using a greedy search algorithm with error estimator.
The third parameter SNAPSHOTS of thermalblock.py determines how many
different values per parameter component μ_ij should be considered.
I.e. the parameter training set for basis generation will have the
size SNAPSHOTS^(XBLOCKS x YBLOCKS). After the basis of size 32 (the
last parameter) has been computed, the quality of the obtained reduced model
(on the 32-dimensional reduced basis space) is evaluated by comparing the
solutions of the reduced and detailed models for new, randomly chosen
parameters. Finally, plots of the detailed and reduced solutions, as well
as the difference between the two, are displayed for the random parameter
which maximises reduction error.
The thermalblock demo explained¶
In the following we will walk through the thermal block demo step by
step in an interactive Python shell. We assume that you are familiar
with the reduced basis method and that you know the basics of
Python programming as well as working
with NumPy. (Note that our code will differ a bit from
thermalblock.py as we will hardcode the various options the script
offers and leave out some features.)
First, start a Python shell. We recommend using IPython
ipython
You can paste the following input lines starting with >>> by copying
them to the system clipboard and then executing
%paste
inside the IPython shell.
First, we will import the most commonly used methods and classes of pyMOR by executing:
>>> from pymor.basic import *
Loading pymor version 0.3.0
Next we will instantiate a class describing the analytical problem
we want so solve. In this case, a
ThermalBlockProblem:
>>> p = ThermalBlockProblem(num_blocks=(3, 2))
We want to discretize this problem using the finite element method.
We could do this by hand, creating a Grid, instatiating
DiffusionOperatorP1 finite element diffusion
operators for each subblock of the domain, forming a LincombOperator
to represent the affine decomposition, instantiating a
L2ProductFunctionalP1 as right hand side, and
putting it all together into a StationaryDiscretization. However, since
ThermalBlockProblem derives
form EllipticProblem, we can use
a predifined discretizer to do the work for us. In this case, we use
discretize_elliptic_cg:
>>> d, d_data = discretize_elliptic_cg(p, diameter=1. / 100.)
d is the StationaryDiscretization which has been created for us,
whereas d_data contains some additional data, in this case the Grid
and the BoundaryInfo which have been created during discretization. We
can have a look at the grid,
>>> print(d_data['grid'])
Tria-Grid on domain [0,1] x [0,1]
x0-intervals: 100, x1-intervals: 100
faces: 40000, edges: 60200, vertices: 20201
and, as always, we can display its class documentation using
help(d_data['grid']), or in the case of IPython
d_data['grid']?.
Let’s solve the thermal block problem and visualize the solution:
>>> U = d.solve([1.0, 0.1, 0.3, 0.1, 0.2, 1.0])
>>> d.visualize(U, title='Solution')
00:45|discretizations.basic.StationaryDiscretization: Solving ThermalBlock_CG for {diffusion: [1.0, 0.1, 0.3, 0.1, 0.2, 1.0]} ...
...
...
Each class in pyMOR that describes a Parameter dependent mathematical
object, like the StationaryDiscretization in our case, derives from
Parametric and determines the Parameters it expects during __init__
by calling build_parameter_type.
The resulting ParameterType is stored in the object’s
parameter_type attribute. Let us
have a look:
>>> print(d.parameter_type)
{diffusion: (2, 3)}
This tells us, that the Parameter which
~pymor.discretizations.interfaces.DiscretizationInterface.solve expects
should be a dictionary with one key 'diffusion' whose value is a
NumPy array of shape (2, 3), corresponding to the block structure of
the problem. However, by using the
parse_parameter method, pyMOR is
smart enough to correctly parse the input [1.0, 0.1, 0.3, 0.1, 0.2, 1.0].
Next we want to use the greedy algorithm
to reduce the problem. For this we need to choose a basis extension algorithm
as well as a reductor which will perform the actual RB-projection. We will
use gram_schmidt_basis_extension and
reduce_coercive. The latter
will also assemble an error estimator to estimate the reduction error. This
will significantly speed up the basis generation, as we will only need to
solve the high-dimensional problem for those parameters in the training set
which are actually selected for basis extension. To control the condition of
the reduced system matrix, we must ensure that the generated basis is
orthonormal w.r.t. the H1-product on the solution space. For this we pass
the h1_product attribute of the discretization to the basis extension algorithm.
We pass the same product to the reductor which uses it for computing the
Riesz representatives required for error estimation. Moreover, we have to provide
a ParameterFunctional which computes a lower bound for the coercivity of
the problem for a given parameter.
>>> from functools import partial
>>> extension_algorithm = partial(gram_schmidt_basis_extension, product=d.h1_product)
>>> reductor = partial(
... reduce_coercive,
... error_product=d.h1_product,
... coercivity_estimator=ExpressionParameterFunctional('min(diffusion)', d.parameter_type)
... )
Moreover, we need to select a Parameter training set. The discretization
d already comes with a ParameterSpace which it has inherited from the
analytical problem. We can sample our parameters from this space, which is a
CubicParameterSpace. E.g.:
>>> samples = d.parameter_space.sample_uniformly(4)
>>> print(samples[0])
{diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]}
Now we start the basis generation:
>>> greedy_data = greedy(d, reductor, samples,
... extension_algorithm=extension_algorithm,
... use_estimator=True,
... max_extensions=32)
01:44 greedy: Started greedy search on 4096 samples
01:44 greedy: Reducing ...
01:44 | reduce_coercive: RB projection ...
...
01:45 | reduce_coercive: Assembling error estimator ...
01:45 | | reduce_residual: Estimating residual range ...
01:45 | | | estimate_image_hierarchical: Estimating image for basis vector -1 ...
01:45 | | | estimate_image_hierarchical: Orthonormalizing ...
01:45 | | reduce_residual: Projecting residual operator ...
01:45 greedy: Estimating errors ...
01:47 greedy: Maximum error after 0 extensions: 9.86736953629 (mu = {diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]})
01:47 greedy: Computing solution snapshot for mu = {diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]} ...
01:47 | StationaryDiscretization: Solving ThermalBlock_CG for {diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]} ...
01:47 greedy: Extending basis with solution snapshot ...
01:47 greedy: Reducing ...
...
01:47 greedy: Estimating errors ...
01:50 greedy: Maximum error after 1 extensions: 3.30998133771 (mu = {diffusion: [0.1, 0.1, 1.0, 0.1, 0.1, 0.1]})
01:50 greedy: Computing solution snapshot for mu = {diffusion: [0.1, 0.1, 1.0, 0.1, 0.1, 0.1]} ...
01:50 | StationaryDiscretization: Solving ThermalBlock_CG for {diffusion: [0.1, 0.1, 1.0, 0.1, 0.1, 0.1]} ...
01:50 greedy: Extending basis with solution snapshot ...
...
...
03:52 greedy: Maximum number of 32 extensions reached.
03:52 greedy: Reducing once more ...
...
03:55 greedy: Greedy search took 130.547789097 seconds
The max_extensions parameter defines how many basis vectors we want to
obtain. greedy_data is a dictionary containing various data that has
been generated during the run of the algorithm:
>>> print(greedy_data.keys())
['reduction_data', 'reconstructor', 'time', 'basis', 'extensions', 'reduced_discretization', 'max_errs', 'max_err_mus']
The most important items are 'reduced_discretization' and
'reconstructor' which hold the reduced Discretization obtained
from applying our reductor with the final reduced basis, as well as a
reconstructor to reconstruct detailed solutions from the reduced solution
vectors. The reduced basis is stored as 'basis' item.
>>> rd = greedy_data['reduced_discretization']
>>> rc = greedy_data['reconstructor']
>>> rb = greedy_data['basis']
All vectors in pyMOR are stored in so called VectorArrays. For example
the solution U computed above is given as a VectorArray of length 1.
For the reduced basis we have:
>>> print(type(rb))
<class 'pymor.vectorarrays.numpy.NumpyVectorArray'>
>>> print(len(rb))
32
>>> print(rb.dim)
20201
Let us check if the reduced basis really is orthonormal with respect to
the H1-product. For this we use the apply2
method:
>>> import numpy as np
>>> gram_matrix = d.h1_product.apply2(rb, rb)
>>> print(np.max(np.abs(gram_matrix - np.eye(32))))
1.16563426164e-13
Looks good! We can now solve the reduced model for the same parameter as above.
The result is a vector of coefficients w.r.t. the reduced basis, which is
currently stored in rb. To form the linear combination, we can use the
reconstructor:
>>> u = rd.solve([1.0, 0.1, 0.3, 0.1, 0.2, 1.0])
>>> print(u)
[[ 5.79477471e-01 5.91289054e-02 1.89924036e-01 1.89149529e-02
1.81103127e-01 2.69920752e-02 -1.79611519e-01 7.99676272e-03
1.54092560e-01 5.76326362e-02 1.97982347e-01 -2.13775254e-02
3.12892660e-02 -1.27037440e-01 -1.51352508e-02 3.36101087e-02
2.05779889e-02 -4.96445984e-03 3.21176662e-02 -2.52674851e-02
2.92150040e-02 3.23570362e-03 -4.14288199e-03 5.48325425e-03
4.10728945e-03 1.59251955e-03 -9.23470903e-03 -2.57483574e-03
-2.52451212e-03 -5.08125873e-04 2.71427033e-03 5.83210112e-05]]
>>> U_red = rc.reconstruct(u)
>>> print(U_red.dim)
20201
Finally we compute the reduction error and display the reduced solution along with the detailed solution and the error:
>>> ERR = U - U_red
>>> print(d.h1_norm(ERR))
[ 0.00944595]
>>> d.visualize((U, U_red, ERR),
... legend=('Detailed', 'Reduced', 'Error'),
... separate_colorbars=True)
We can nicely observe that, as expected, the error is maximized along the jumps of the diffusion coeffient.
Learning more¶
As a next step, you should read our Technical Overview which discusses the most important concepts and design decisions behind pyMOR. After that you should be fit to delve into the reference documentation.
Should you have any problems regarding pyMOR, questions or feature requests, do not hestitate to contact us at our mailing list!
Technical Overview¶
Three Central Classes¶
From a bird’s eye perspective, pyMOR is a collection of generic algorithms operating on objects of the following types:
VectorArraysVector arrays are ordered collections of vectors. Each vector of the array must be of the same
dimension. Subsets of vectors can becopiedto a new array,appendedto an existing array,deletedfrom the array orreplacedby vectors of a different array. Basic linear algebra operations can be performed on the vectors of the array: vectors can bescaledin-place, the BLASaxpyoperation is supported andscalar productsbetween vectors can be formed. Linear combinations of vectors can be formed using thelincombmethod. Moreover, various norms can be computed and selectedcomponentsof the vectors can be extracted forempirical interpolation.Each of these methods takes optional
indparameters to specify the subset of vectors on which to operate. If the parameter is not specified, the whole array is selected for the operation.New vector arrays can be created using the
emptyandzerosmethod. As a convenience, many of Python’s math special methods are implemented in terms of the interface methods.Note that there is not the notion of a single vector in pyMOR. The main reason for this design choice is to take advantage of vectorized implementations like
NumpyVectorArraywhich internally store the vectors as two-dimensionalNumPyarrays. As an example, the application of a linear matrix based operator to an array via theapplymethod boils down to a call toNumPy‘s optimizeddotmethod. If there were only lists of vectors in pyMOR, the above matrix-matrix multiplication would have to be expressed by a loop of matrix-vector multiplications. However, when working with external solvers, vector arrays will often be just lists of vectors. For this use-case we provideListVectorArray, a vector array based on a Python list of vectors.Associated to each vector array is a
VectorSpace. A Vector space in pyMOR is simply the combination of aVectorArraysubclass and an appropriatesubtype. ForNumpyVectorArrays, the subtype is a single integer denoting the dimension of the array. Subtypes for other array classes could, e.g., include a socket for communication with a specific PDE solver instance.Two arrays in pyMOR are compatible (e.g. can be added) if they are from the same
VectorSpace, i.e. they are instances of the same class and share the same subtype. TheVectorSpaceis also precisely the information needed to create new arrays of null vectors using themake_arrayclass method. In factemptyandzerosare implemented by callingmake_arraywith thesubtypeof theVectorArrayinstance for which they have been called.OperatorsThe main property of operators in pyMOR is that they can be
appliedtoVectorArraysresulting in a newVectorArray. For this operation to be allowed, the operator’ssourceVectorSpacemust be identical with theVectorSpaceof the given array. The result will be a vector array from therangespace. An operator can belinearor not. Theapply_inversemethod provides an interface for (linear) solvers.Operators in pyMOR are also used to represent bilinear forms via the
apply2method. A functional in pyMOR is simply an operator withVectorSpace(NumpyVectorArray, 1)asrange. Dually, a vector-like operator is an operator with aVectorSpace(NumpyVectorArray, 1)assource. Such vector-like operators are used in pyMOR to representParameterdependent vectors such as the initial data of anInstationaryDiscretization. For linear functionals and vector-like operators, theas_vectormethod can be called to obtain a vector representation of the operator as aVectorArrayof length 1.Linear combinations of operators can be formed using a
LincombOperator. When such a linear combination isassembled,assemble_lincombis called to ensure that, for instance, linear combinations of operators represented by a matrix lead to a new operator holding the linear combination of the matrices. Theprojectedmethod is used to perform the reduced basis projection of a given operator. While each operator in pyMOR can beprojected, specializations of this method ensure that, if possible, the projected operator will no longer depend on high-dimensional data.Default implementations for many methods of the operator interface can be found in
OperatorBase. Base classes forNumPy-based operators can be found inpymor.operators.numpy. Several methods for constructing new operators from existing ones are contained inpymor.operators.constructions.DiscretizationsDiscretizations in pyMOR encode the mathematical structure of a given discrete problem by acting as container classes for operators. Each discretization object has
operators,functionals,vector_operatorsandproductsdictionaries holding theOperatorswhich appear in the formulation of the discrete problem. The keys in these dictionaries describe the role of the respective operator in the discrete problem.Apart from describing the discrete problem, discretizations also implement algorithms for
solvingthe given problem, returningVectorArrayswith spacesolution_space. The solution can becached, s.t. subsequent solving of the problem for the same parameters reduces to looking up the solution in pyMOR’s cache.While special discretization classes may be implemented which make use of the specific types of operators they contain (e.g. using some external high-dimensional solver for the problem), it is generally favourable to implement the solution algorithms only through the interfaces provided by the operators contained in the discretization, as this allows to use the same discretization class to solve high-dimensional and reduced problems. This has been done for the simple stationary and instationary discretizations found in
pymor.discretizations.basic.Discretizations can also implement
estimateandvisualizemethods to estimate the discretization error of a computed solution and create graphic representations ofVectorArraysfrom thesolution_space.
Base Classes¶
While VectorArrays are mutable objects, both Operators and Discretizations
are immutable in pyMOR: the application of an Operator to the same
VectorArray will always lead to the same result, solving a Discretization
for the same parameter will always produce the same solution array. This has two
main benefits:
- If multiple objects/algorithms hold references to the same
OperatororDiscretization, none of the objects has to worry that the referenced object changes without their knowledge. - It becomes affordable to generate persistent keys for
cachingof computation results by generating state ids which uniquely identify the object’s state. Since the state cannot change, these ids have to be computed only once for the lifetime of the object.
A class can be made immutable in pyMOR by deriving from ImmutableInterface,
which ensures that write access to the object’s attributes is prohibited after
__init__ has been executed. However, note that changes to private attributes
(attributes whose name starts with _) are still allowed. It lies in the
implementors responsibility to ensure that changes to these attributes do not
affect the outcome of calls to relevant interface methods. As an example, a call
to enable_caching will set the
objects private __cache_region attribute, which might affect the speed of a
subsequent solve call, but not its result.
Of course, in many situations one may wish to change properties of an immutable
object, e.g. the number of timesteps for a given discretization. This can be
easily achieved using the
with_ method every immutable
object has: a call of the form o.with_(a=x, b=y) will return a copy of o
in which the attribute a now has the value x and the attribute b the
value y. It can be generally assumed that calls to
with_ are inexpensive. The
set of allowed arguments can be found in the
with_arguments attribute.
All immutable classes in pyMOR and most other classes derive from
BasicInterface which, through its meta class, provides several convenience
features for pyMOR. Most notably, every subclass of BasicInterface obtains its
own logger instance with a class
specific prefix.
Creating Discretizations¶
pyMOR ships a small (and still quite incomplete) framework for creating finite
element or finite volume discretizations based on the NumPy/Scipy software stack. To end up with an appropriate
Discretization, one starts by instantiating an analytical problem which
describes the problem we want to discretize. analytical problems contain
Functions which define the analytical data functions associated with the
problem and a DomainDescription that provides a geometrical definition of the
domain the problem is posed on and associates a BoundaryType to each part of
its boundary.
To obtain a Discretization from an analytical problem we use a
discretizer. A discretizer will first mesh the
computational domain by feeding the DomainDescription into a
domaindiscretizer which will return the Grid
along with a BoundaryInfo associating boundary entities with BoundaryTypes.
Next, the Grid, BoundaryInfo and the various data functions of the
analytical problem are used to instatiate finite element or finite volume operators.
Finally these operators are used to instatiate one of the provided
Discretization classes.
In pyMOR, analytical problems, Functions, DomainDescriptions,
BoundaryInfos and Grids are all immutable, enabling efficient
disk caching for the resulting Discretizations, persistent over various
runs of the applications written with pyMOR.
While pyMOR’s internal discretizations are useful for getting started quickly
with model reduction experiments, pyMOR’s main goal is to allow the reduction of
discretizations provided by external solvers. In order to do so, all that needs
to be done is to provide VectorArrays, Operators and Discretizations which
interact appropriately with the solver. pyMOR makes no assumption on how the
communication with the solver is managed. For instance, communication could take
place via a network protocol or job files. In particular it should be stressed
that in general no communication of high-dimensional data between the solver
and pyMOR is necessary: VectorArrays can merely hold handles to data in the
solver’s memory or some on-disk database. Where possible, we favour, however, a
deep integration of the solver with pyMOR by linking the solver code as a Python
extension module. This allows Python to directly access the solver’s data
structures which can be used to quickly add features to the high-dimensional
code without any recompilation. A minimal example for such an integration using
pybindgen can be found in the
src/pymordemos/minimal_cpp_demo directory of the pyMOR repository.
The dune-pymor repository contains
experimental bindings for the DUNE software
framework.
Parameters¶
pyMOR classes implement dependence on a parameter by deriving from the
Parametric mix-in class. This class gives each instance a
parameter_type attribute describing the
form of Parameters the relevant methods of the object (apply, solve,
evaluate, etc.) expect. A Parameter in pyMOR is basically a Python
dict with strings as keys and NumPy arrays as values. Each such value
is called a Parameter component. The ParameterType of a Parameter is
simply obtained by replacing the arrays in the Parameter with their shape.
I.e. a ParameterType specifies the names of the parameter components and their
expected shapes.
The ParameterType of a Parametric object is determined by the class
implementor during __init__ via a call to
build_parameter_type, which can be
used, to infer the ParameterType from the ParameterTypes of objects the
given object depends upon. I.e. an Operator implementing the L2-product with
some Function will inherit the ParameterType of the Function.
Reading the reference documentation on pyMOR’s
parameter handling facilities is strongly advised for implementors of
Parametric classes.
Defaults¶
pyMOR offers a convenient mechanism for handling default values such as solver
tolerances, cache sizes, log levels, etc. Each default in pyMOR is the default
value of an optional argument of some function. Such an argument is made a
default by decorating the function with the defaults
decorator:
@defaults('tolerance')
def some_algorithm(x, y, tolerance=1e-5)
...
Default values can be changed by calling set_defaults.
A configuration file with all defaults defined in pyMOR can be obtained with
write_defaults_to_file. This file can then be loaded,
either programmatically or automatically by setting the PYMOR_DEFAULTS environment
variable.
As an additional feature, if None is passed as value for a function argument
which is a default, its default value is used instead of None. This allows
writing code of the following form:
def method_called_by_user(U, V, tolerance_for_algorithm=None):
...
algorithm(U, V, tolerance=tolerance_for_algorithm)
...
See the defaults module for more information.
The Reduction Process¶
The reduction process in pyMOR is handled by so called reductors
which take arbitrary Discretizations and additional data (e.g. the reduced
basis) to create reduced Discretizations along with reconstructor classes
which allow to transform solution vectors of the reduced Discretization back
to vectors of the solution space of the high-dimensional Discretization (e.g.
by linear combination with the reduced basis). If proper offline/online
decomposition is achieved by the reductor, the reduced Discretization will
not store any high-dimensional data. Note that there is no inherent distinction
between low- and high-dimensional Discretizations in pyMOR. The only
difference lies in the different types of operators, the Discretization
contains.
This observation is particularly apparent in the case of the classical
reduced basis method: the operators and functionals of a given discrete problem
are projected onto the reduced basis space whereas the structure of the problem
(i.e. the type of Discretization containing the operators) stays the same.
pyMOR reflects this fact by offering with
reduce_generic_rb a generic algorithm which can
be used to RB-project any discretization available to pyMOR. It should be noted
however that this reductor is only able to efficiently
offline/online-decompose affinely Parameter-dependent linear problems.
Non-linear problems or such with no affine Parameter dependence require
additional techniques such as empirical interpolation.
If you want to further dive into the inner workings of pyMOR, we highly
recommend to study the source code of
reduce_generic_rb and to step through calls of
this method with a Python debugger, such as ipdb.
Environment Variables¶
pyMOR respects the following environment variables:
- PYMOR_CACHE_DISABLE
- If
1, disable caching globally, overriding calls toenable_caching. This is mainly useful for debugging. Seepymor.core.cachefor more details. - PYMOR_COLORS_DISABLE
- If
1, disable coloring of logging output. - PYMOR_COPY_DOCSTRINGS_DISABLE
- By default, docstrings of methods in base classes are copied
to overriding methods, if these do not define their own
docstring. Setting this variable to
1disables this feature. (We use this for when auto-generating API-documentation with sphinx.) - PYMOR_DEFAULTS
- If empty or
NONE, do not load anydefaultsfrom file. Otherwise, a:-separated list of the paths to a Python scripts containing defaults.
Release Notes¶
pyMOR 0.4 (September 28, 2016)¶
With the pyMOR 0.4 release we have changed the copyright of pyMOR to
Copyright 2013-2016 pyMOR developers and contributors. All rights reserved.
Moreover, we have added a Contribution guideline to help new users with starting to contribute to pyMOR. Over 800 single commits have entered this release. For a full list of changes see here. pyMOR 0.4 contains contributions by Andreas Buhr, Michael Laier, Falk Meyer, Petar Mlinarić and Michael Schaefer. See here for more details.
Release highlights¶
FEniCS and deal.II support¶
pyMOR now includes wrapper classes for integrating PDE solvers
written with the dolfin library of the FEniCS
project. For a usage example, see pymordemos.thermalblock_simple.discretize_fenics.
Experimental support for deal.II can be
found in the pymor-deal.II
repository of the pyMOR GitHub organization.
Parallelization of pyMOR’s reduction algorithms¶
We have added a parallelization framework to pyMOR which allows
parallel execution of reduction algorithms based on a simple
WorkerPool interface [#14].
The greedy [#155]
and ei_greedy algorithms [#162]
have been refactored to utilize this interface.
Two WorkerPool implementations are shipped with pyMOR:
IPythonPool utilizes the parallel
computing features of IPython, allowing
parallel algorithm execution in large heterogeneous clusters of
computing nodes. MPIPool can be used
to benefit from existing MPI-based parallel HPC computing architectures
[#161].
Support classes for MPI distributed external PDE solvers¶
While pyMOR’s VectorArray, Operator and Discretization
interfaces are agnostic to the concrete (parallel) implementation
of the corresponding objects in the PDE solver, external solvers
are often integrated by creating wrapper classes directly corresponding
to the solvers data structures. However, when the solver is executed
in an MPI distributed context, these wrapper classes will then only
correspond to the rank-local data of a distributed VectorArray or
Operator.
To facilitate the integration of MPI parallel solvers, we have added
MPI helper classes [#163]
in pymor.vectorarrays.mpi, pymor.operators.mpi
and pymor.discretizations.mpi that allow an automatic
wrapping of existing sequential bindings for MPI distributed use.
These wrapper classes are based on a simple event loop provided
by pymor.tools.mpi, which is used in the interface methods of
the wrapper classes to dispatch into MPI distributed execution
of the corresponding methods on the underlying MPI distributed
objects.
The resulting objects can be used on MPI rank 0 (including interactive
Python sessions) without any further changes to pyMOR or the user code.
For an example, see pymordemos.thermalblock_simple.discretize_fenics.
New reduction algorithms¶
adaptive_greedyuses adaptive parameter training set refinement according to [HDO11] to prevent overfitting of the reduced model to the training set [#213].reduce_parabolicreduces linear parabolic problems usingreduce_generic_rband assembles an error estimator similar to [GP05], [HO08]. Theparabolic_mordemo contains a simple sample application using this reductor [#190].- The
estimate_imageandestimate_image_hierarchicalalgorithms can be used to find an as small as possible space in which the images of a given list of operators for a given source space are contained for all possible parametersmu. For possible applications, seereduce_residualwhich now usesestimate_image_hierarchicalfor Petrov-Galerkin projection of the residual operator [#223].
Copy-on-write semantics for VectorArrays¶
The copy method
of the VectorArray interface is now assumed to have copy-on-write
semantics. I.e., the returned VectorArray will contain a reference to the same
data as the original array, and the actual data will only be copied when one of
the arrays is changed. Both NumpyVectorArray and ListVectorArray have been
updated accordingly [#55].
As a main benefit of this approach, immutable objects having a VectorArray as
an attribute now can safely create copies of the passed VectorArrays (to ensure
the immutability of their state) without having to worry about unnecessarily
increased memory consumption.
Improvements to pyMOR’s discretizaion tookit¶
- An unstructured triangular
Gridis now provided byUnstructuredTriangleGrid. Such aGridcan be obtained using thediscretize_gmshmethod, which can parse Gmsh output files. Moreover, this method can generateGmshinput files to create unstructured meshes for an arbitraryPolygonalDomain[#9]. - Basic support for parabolic problems has been added.
The
discretize_parabolic_cganddiscretize_parabolic_fvmethods can be used to build continuous finite element or finite volumeDiscretizationsfrom a givenpymor.analyticalproblems.parabolic.ParabolicProblem. Theparabolicdemo demonstrates the use of these methods [#189]. - The
pymor.discretizers.diskmodule contains methods to create stationary and instationary affinely decomposedDiscretizationsfrom matrix data files and an.inifile defining the given problem. EllipticProblemscan now also contain advection and reaction terms in addition to the diffusion part.discretize_elliptic_cghas been extended accordingly [#211].- The
continuous Galerkinmodule has been extended to support Robin boundary conditions [#110]. BitmapFunctionallows to use grayscale image data as dataFunctions[#194].- For the visualization of time-dependent data, the colorbars can now be rescaled with each new frame [#91].
Caching improvements¶
- state id generation is now based on deterministic pickling.
In previous version of pyMOR, the state id of
immutableobjects was computed from the state ids of the parameters passed to the object’s__init__method. This approach was complicated and error-prone. Instead, we now compute the state id as a hash of a deterministic serialization of the object’s state. While this approach is more robust, it is also slightly more expensive. However, due to the object’s immutability, the state id only has to be computed once, and state ids are now only required for storing results in persistent cache regions (see below). Computing such results will usually be much more expensive than the state id calculation [#106]. CacheRegionsnow have apersistentattribute indicating whether the cache data will be kept between program runs. For persistent cache regions the state id of the object for which the cached method is called has to be computed to obtain a unique persistent id for the given object. For non-persistent regions the object’suidcan be used instead.pymor.core.cache_regionsnow by default contains'memory','disk'and'persistent'cache regions [#182], [#121] .defaultscan now be marked to not affect state id computation. In previous version of pyMOR, changing anydefaultvalue caused a change of the state id pyMOR’s defaults dictionary, leading to cache misses. While this in general is desirable, as, for instance, changed linear solver default error tolerances might lead to different solutions for the sameDiscretizationobject, it is clear for many I/O related defaults, that these will not affect the outcome of any computation. For these defaults, thedefaultsdecorator now accepts asid_ignoreparameter, to exclude these defaults from state id computation, preventing changes of these defaults causing cache misses [#81].- As an alternative to using the
@cacheddecorator,cached_method_callcan be used to cache the results of a function call. This is now used insolveto enable parsing of the input parameter before it enters the cache key calculation [#231].
Additional new features¶
apply_inverse_adjointhas been added to theOperatorinterface [#133].Support for complex values in
NumpyVectorArrayandNumpyMatrixOperator[#131].- New
ProductParameterFunctional. This
ParameterFunctionalrepresents the product of a given list ofParameterFunctionals.
- New
- New
SelectionOperator[#105]. This
Operatorrepresents oneOperatorof a given list ofOperators, depending on the evaluation of a providedParameterFunctional,
- New
- New block matrix operators [#215].
BlockOperatorandBlockDiagonalOperatorrepresent block matrices ofOperatorswhich can be applied to appropriately shapedBlockVectorArrays.
from_filefactory method forNumpyVectorArrayandNumpyMatrixOperator[#118].NumpyVectorArray.from_fileandNumpyMatrixOperator.from_filecan be used to construct such objects from data files of various formats (MATLAB, matrix market, NumPy data files, text).
ListVectorArray-basedNumpyMatrixOperator[#164].The
playgroundnow containsNumpyListVectorArrayMatrixOperatorwhich can applyNumPy/SciPymatrices to aListVectorArray. ThisOperatoris mainly intended for performance testing purposes. Thethermalblockdemo now has an option--list-vector-arrayfor using this operator instead ofNumpyMatrixOperator.
- Log indentation support [#230].
pyMOR’s log output can now be indented via the
logger.block(msg)context manger to reflect the hierarchy of subalgorithms.
- Default implementation of
as_vectorfor functionals [#107]. OperatorBase.as_vectornow contains a default implementation for functionals by callingapply_adjoint.
- Default implementation of
pycontractshas been removed as a dependency of pyMOR [#127].Test coverage has been raised to 80 percent.
Backward incompatible changes¶
VectorArrayimplementations have been moved to thepymor.vectorarrayssub-package [#89].- The
dotmethod of theVectorArrayinterface has been split intodotandpairwise_dot[#76]. The
pairwiseparameter ofdothas been removed, always assumingpairwise == False. The methodpairwise_dotcorresponds to thepairwise == Truecase. Similarly thepariwiseparameter of theapply2method of theOperatorinterface has been removed and apairwise_apply2method has been added.
- The
almost_equalhas been removed from theVectorArrayinterface [#143].As a replacement, the new method
pymor.algorithms.basic.almost_equalcan be used to compareVectorArraysfor almost equality by the norm of their difference.
lincombhas been removed from theOperatorinterface [#83].Instead, a
LincombOperatorshould be directly instantiated.
- Removal of the
optionsparameter ofapply_inversein favor ofsolver_optionsattribute [#122]. The
optionsparameter ofOperatorInterface.apply_inversehas been replaced by thesolver_optionsattribute. This attribute controls which fixed (linear) solver options are used whenapply_inverseis called. Seehere <https://github.com/pymor/pymor/pull/184>for more details.
- Removal of the
- Renaming of reductors for coercive problems [#224].
pymor.reductors.linear.reduce_stationary_affine_linearandpymor.reductors.stationary.reduce_stationary_coercivehave been renamed topymor.reductors.coercive.reduce_coerciveandpymor.reductors.coercive.reduce_coercive_simple. The old names are deprecated and will be removed in pyMOR 0.5.
Non-parametric objects have now
parameter_type{}instead ofNone[#84].Sampling methods of
ParameterSpacesnow return iterables instead of iterators [#108].- Caching of
solveis now disabled by default [#178]. Caching of
solvemust now be explicitly enabled by usingpymor.core.cache.CacheableInterface.enable_caching.
- Caching of
The default value for
extension_algorithmparameter ofgreedyhas been removed [#82].- Changes to
ei_greedy[#159], [#160]. The default for the
projectionparameter has been changed from'orthogonal'to'ei'to let the default algorithm agree with literature. In addition acopyparameter with defaultTruehas been added. WhencopyisTrue, the input data is copied before executing the algorithm, ensuring, that the originalVectorArrayis left unchanged. When possible,copyshould be set toFalsein order to reduce memory consumption.
- Changes to
The
copyparameter ofpymor.algorithms.gram_schmidt.gram_schmidtnow defaults toTrue[#123].with_has been moved fromBasicInterfacetoImmutableInterface[#154].BasicInterface.add_attributeshas been removed [#158].- Python fallbacks to Cython functions have been removed [#145].
In order to use pyMOR’s discretization toolkit, building of the
_unstructured,inplace,relationsCython extension modules is now required.
Further improvements¶
- [#78] update apply_inverse signature
- [#115] [algorithms.gram_schmidt] silence numpy warning
- [#144] L2ProductP1 uses wrong quadrature rule in 1D case
- [#147] Debian doc packages have weird title
- [#151] add tests for ‘almost_equal’ using different norms
- [#156] Let thermal block demo use error estimator by default
- [#195] Add more tests / fixtures for operators in pymor.operators.constructions
- [#197] possible problem in caching
- [#207] No useful error message in case PySide.QtOpenGL cannot be imported
- [#209] Allow ‘pip install pymor’ to work even when numpy/scipy are not installed yet
- [#219] add minimum versions for dependencies
- [#228] merge fixes in python3 branch back to master
- [#269] Provide a helpful error message when cython modules are missing
- [#276] Infinite recursion in apply for IdentityOperator * scalar
pyMOR 0.3 (March 2, 2015)¶
- Introduction of the vector space concept for even simpler integration with external solvers.
- Addition of a generic Newton algorithm.
- Support for Jacobian evaluation of empirically interpolated operators.
- Greatly improved performance of the EI-Greedy algorithm. Addition of the DEIM algorithm.
- A new algorithm for residual operator projection and a new, numerically stable a posteriori error estimator for stationary coercive problems based on this algorithm. (cf. A. Buhr, C. Engwer, M. Ohlberger, S. Rave, ‘A numerically stable a posteriori error estimator for reduced basis approximations of elliptic equations’, proceedings of WCCM 2014, Barcelona, 2014.)
- A new, easy to use mechanism for setting and accessing default values.
- Serialization via the pickle module is now possible for each class in pyMOR. (See the new ‘analyze_pickle’ demo.)
- Addition of generic iterative linear solvers which can be used in conjunction with any operator satisfying pyMOR’s operator interface. Support for least squares solvers and PyAMG (http://www.pyamg.org/).
- An improved SQLite-based cache backend.
- Improvements to the built-in discretizations: support for bilinear finite elements and addition of a finite volume diffusion operator.
- Test coverage has been raised from 46% to 75%.
Over 500 single commits have entered this release. A full list of all changes can be obtained under the following address: https://github.com/pymor/pymor/compare/0.2.2...0.3.0
API Documentation¶
pymor package¶
Subpackages¶
pymor.algorithms package¶
Submodules¶
-
class
pymor.algorithms.adaptivegreedy.AdaptiveSampleSet(parameter_space)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceAn adaptive parameter sample set.
Used by
adaptive_greedy.Methods
AdaptiveSampleSetmap_vertex_to_mu,refine,visualizeBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
AdaptiveSampleSetElementBasicInterfacelocked,logger,logging_disabled,name,uid
-
pymor.algorithms.adaptivegreedy._estimate(mu, rd=None, d=None, rc=None, error_norm=None)[source]¶ Called by
adaptive_greedy.
-
pymor.algorithms.adaptivegreedy.adaptive_greedy(discretization, reductor, parameter_space=None, initial_basis=None, use_estimator=True, error_norm=None, extension_algorithm=<function gram_schmidt_basis_extension>, 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=<pymor.parallel.dummy.DummyPool object>)[source]¶ Greedy basis generation algorithm with adaptively refined training set.
This method extends pyMOR’s default
greedygreedy basis generation algorithm by adaptive refinement of the parameter training set according to [HDO11] to prevent overfitting of the reduced basis to the training set. This is achieved by estimating the reduction 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.[HDO11] Haasdonk, B.; Dihlmann, M. & Ohlberger, M., A training set and multiple bases generation approach for parameterized model reduction based on adaptive grids in parameter space, Math. Comput. Model. Dyn. Syst., 2011, 17, 423-442 Parameters
- discretization
- See
greedy. - reductor
- See
greedy. - parameter_space
- The
ParameterSpacefor which to compute the reduced model. IfNone, the parameter space of thediscretizationis used. - initial_basis
- See
greedy. - use_estimator
- See
greedy. - error_norm
- See
greedy. - extension_algorithm
- See
greedy. - target_error
- See
greedy. - max_extensions
- See
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.
- a list of
- 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
greedy.
Returns
Dict with the following fields
basis: The reduced basis. reduced_discretization: The reduced Discretizationobtained for the computed basis.reconstructor: Reconstructor for reduced_discretization.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. reduction_data: Reduction data returned by the last reductor call.
Module containing some basic but generic linear algebra algorithms.
-
pymor.algorithms.basic.almost_equal(U, V, U_ind=None, V_ind=None, product=None, norm=None, 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
normorproductparameter.If the length of
U(U_ind) resp.V(V_ind) is 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.- U_ind, V_ind
- Indices of the vectors that are to be compared (see
VectorArray). - product
- If specified, use this inner product
Operatorto compute the norm.productandnormare mutually exclusive. - norm
- If specified, must be a callable, which is used to compute the norm
or, alternatively, one of the string ‘l1’, ‘l2’, ‘sup’, in which case the
respective
VectorArraynorm methods are used.productandnormare mutually exclusive. If neither is specified,norm='l2'is assumed. - rtol
- The relative tolerance.
- atol
- The absolute tolerance.
Defaults
rtol, atol (see
pymor.core.defaults)
This module contains algorithms for extending a given reduced basis by a new vector.
The methods are mainly designed to be used in conjunction with
the greedy algorithm. Each method is of the form
extension_algorithm(basis, U, ...)
where basis and U are VectorArrays containing the old basis and new vectors
to be added. The methods return a tuple new_basis, data where new_basis holds the
extended basis and data is a dict containing additional information about the extension
process. The data dict at least has the key hierarchic whose value signifies
if the new basis contains the old basis as its first vectors.
If the basis extension fails, e.g. because the new vector is not linearly
independent from the basis, an ExtensionError
exception is raised.
-
pymor.algorithms.basisextension.gram_schmidt_basis_extension(basis, U, product=None, copy_basis=True, copy_U=True)[source]¶ Extend basis using Gram-Schmidt orthonormalization.
Parameters
- basis
VectorArraycontaining the basis to extend.- U
VectorArraycontaining the new basis vectors.- product
- The inner product w.r.t. which to orthonormalize; if
None, the Euclidean product is used. - copy_basis
- If
copy_basisisFalse, the old basis is extended in-place. - copy_U
- If
copy_UisFalse, the new basis vectors are removed fromU.
Returns
- new_basis
- The extended basis.
- extension_data
Dict containing the following fields:
hierarchic: Trueifnew_basiscontainsbasisas its first vectors.
Raises
- ExtensionError
- Gram-Schmidt orthonormalization has failed. This is the case when no
vector in
Uis linearly independent of the basis.
-
pymor.algorithms.basisextension.pod_basis_extension(basis, U, count=1, copy_basis=True, product=None, orthonormalize=True)[source]¶ Extend basis with the first
countPOD modes of the defect of the projection ofUonto the current basis.Warning
The provided basis is assumed to be orthonormal w.r.t. the given inner product!
Parameters
- basis
VectorArraycontaining the basis to extend. The basis is expected to be orthonormal w.r.t.product.- U
VectorArraycontaining the vectors to which the POD is applied.- count
- Number of POD modes that shall be appended to the basis.
- product
- The inner product w.r.t. which to orthonormalize; if
None, the Euclidean product is used. - copy_basis
- If
copy_basisisFalse, the old basis is extended in-place. - orthonormalize
- If
True, re-orthonormalize the new basis vectors obtained by the POD in order to improve numerical accuracy.
Returns
- new_basis
- The extended basis.
- extension_data
Dict containing the following fields:
hierarchic: Trueifnew_basiscontainsbasisas its first vectors.
Raises
- ExtensionError
- POD has produced no new vectors. This is the case when no vector in
Uis linearly independent of the basis.
-
pymor.algorithms.basisextension.trivial_basis_extension(basis, U, copy_basis=True, copy_U=True)[source]¶ Extend basis by simply appending the new vectors.
We check if the new vectors are already contained in the basis, but we do not check for linear independence.
Parameters
- basis
VectorArraycontaining the basis to extend.- U
VectorArraycontaining the new basis vectors.- copy_basis
- If
copy_basisisFalse, the old basis is extended in-place. - copy_U
- If
copy_UisFalse, the new basis vectors are removed fromU.
Returns
- new_basis
- The extended basis.
- extension_data
Dict containing the following fields:
hierarchic: Trueifnew_basiscontainsbasisas its first vectors.
Raises
- ExtensionError
- Raised when all vectors in
Uare already contained in the basis.
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 discretization with
a single function call.
-
pymor.algorithms.ei.deim(U, modes=None, error_norm=None, product=None)[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. - error_norm
- Norm w.r.t. which to calculate the interpolation error. If
None, the Euclidean norm is used. - product
- Inner product
Operatorused for the POD.
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:
errors: Sequence of maximum approximation errors during greedy search.
-
pymor.algorithms.ei.ei_greedy(U, error_norm=None, atol=None, rtol=None, max_interpolation_dofs=None, projection='ei', product=None, copy=True, pool=<pymor.parallel.dummy.DummyPool object>)[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.
- projection
- If
'ei', compute the approximation error by comparing the given vectors by their interpolants. If'orthogonal', compute the error by comparing with the orthogonal projection onto the span of the collateral basis. - product
- If
projection == 'orthogonal', the inner product which is used to perform the projection. IfNone, the Euclidean product is used. - 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(discretization, operator_names, parameter_sample, error_norm=None, atol=None, rtol=None, max_interpolation_dofs=None, projection='ei', product=None, pool=<pymor.parallel.dummy.DummyPool object>)[source]¶ Empirical operator interpolation using the EI-Greedy algorithm.
This is a convenience method to facilitate the use of
ei_greedy. Given aDiscretization, names ofOperators, and a sample ofParameters, first the operators are evaluated on the solution snapshots of the discretization for the provided parameters. These evaluations are then used as input forei_greedy. Finally the resulting interpolation data is used to createEmpiricalInterpolatedOperatorsand a new discretization 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
- discretization
- The
DiscretizationwhoseOperatorswill be interpolated. - operator_names
- List of keys in the
operatorsdict of the discretization. The correspondingOperatorswill be interpolated. - parameter_sample
- A list of
Parametersfor which solution snapshots are calculated. - error_norm
- See
ei_greedy. - atol
- See
ei_greedy. - rtol
- See
ei_greedy. - max_interpolation_dofs
- See
ei_greedy. - projection
- See
ei_greedy. - product
- See
ei_greedy. - pool
- If not
None, theWorkerPoolto use for parallelization.
Returns
- ei_discretization
DiscretizationwithOperatorsgiven 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.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.error.reduction_error_analysis(reduced_discretization, discretization=None, reconstructor=None, test_mus=10, basis_sizes=0, random_seed=None, estimator=True, condition=False, error_norms=(), error_norm_names=None, estimator_norm_index=0, custom=(), plot=False, plot_custom_logarithmic=True, pool=<pymor.parallel.dummy.DummyPool object>)[source]¶ Analyze the model reduction error.
The maximum model reduction error is estimated by solving the reduced
Discretizationfor given randomParameters.Parameters
- reduced_discretization
- The reduced
Discretization. - discretization
- The high-dimensional
Discretization. Must be specified iferror_normsare given. - reconstructor
- The reconstructor for
reduced_discretization. Must be specified iferror_normsare given. - test_mus
- Either a list of
Parametersto compute the errors for, or the number of parameters which are sampled randomly fromparameter_space(if given) orreduced_discretization.parameter_space. - 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
~pymor.reductors.basic.reduce_to_subbasisto quickly obtain smaller reducedDiscretizationsfromrb_discretization. - random_seed
- If
test_musis a number, use this value as random seed for drawing theParameters. - estimator
- If
Trueevaluate the error estimator ofreduced_discretizationon the testParameters. - condition
- If
True, compute the condition of the reduced system matrix for the given testParameters(can only be specified ifrb_discretizationis an instance ofStationaryDiscretizationandrb_discretization.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. - estimator_norm_index
- When
estimatorisTrueanderror_normsare specified, this is the index of the norm inerror_normsw.r.t. which to compute the effectivity of the estimator. - custom
List of custom functions which are evaluated for each test
Parameterand basis size. The functions must have the signaturedef custom_value(reduced_discretization, discretization=d, reconstructor, 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.)estimates: NumPy arrayof the model reduction error estimates w.r.t. all given testParametersand reduced basis dimensions. (Only present whenestimatorisTrue.)max_estimate: Maxima of estimatesover the given testParameters.max_estimate_mus: Parameterscorresponding tomax_estimates.effectivities: errorsdivided byestimates. (Only present whenestimatorisTrueanderror_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.)
This module contains some iterative linear solvers which only use the Operator interface
-
pymor.algorithms.genericsolvers.apply_inverse(op, rhs, options=None)[source]¶ Solve linear equation system.
Applies the inverse of
opto the vectors inrhs.Parameters
- op
- The linear, non-parametric
Operatorto invert. - rhs
VectorArrayof right-hand sides for the equation system.- options
- The solver options to use. (See
options.)
Returns
VectorArrayof the solution vectors.
-
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.options(default_solver='generic_lgmres', default_least_squares_solver='least_squares_generic_lsmr', generic_lgmres_tol=1e-05, generic_lgmres_maxiter=1000, generic_lgmres_inner_m=39, generic_lgmres_outer_k=3, least_squares_generic_lsmr_damp=0.0, least_squares_generic_lsmr_atol=1e-06, least_squares_generic_lsmr_btol=1e-06, least_squares_generic_lsmr_conlim=100000000.0, least_squares_generic_lsmr_maxiter=None, least_squares_generic_lsmr_show=False, least_squares_generic_lsqr_damp=0.0, least_squares_generic_lsqr_atol=1e-06, least_squares_generic_lsqr_btol=1e-06, least_squares_generic_lsqr_conlim=100000000.0, least_squares_generic_lsqr_iter_lim=None, least_squares_generic_lsqr_show=False)[source]¶ Returns
solver_options(with default values) for arbitrary linearOperators.Parameters
- default_solver
- Default solver to use (generic_lgmres, least_squares_generic_lsmr, least_squares_generic_lsqr).
- default_least_squares_solver
- Default solver to use for least squares problems (least_squares_generic_lsmr, least_squares_generic_lsqr).
- generic_lgmres_tol
- See
scipy.sparse.linalg.lgmres. - generic_lgmres_maxiter
- See
scipy.sparse.linalg.lgmres. - generic_lgmres_inner_m
- See
scipy.sparse.linalg.lgmres. - generic_lgmres_outer_k
- See
scipy.sparse.linalg.lgmres. - least_squares_generic_lsmr_damp
- See
scipy.sparse.linalg.lsmr. - least_squares_generic_lsmr_atol
- See
scipy.sparse.linalg.lsmr. - least_squares_generic_lsmr_btol
- See
scipy.sparse.linalg.lsmr. - least_squares_generic_lsmr_conlim
- See
scipy.sparse.linalg.lsmr. - least_squares_generic_lsmr_maxiter
- See
scipy.sparse.linalg.lsmr. - least_squares_generic_lsmr_show
- See
scipy.sparse.linalg.lsmr. - least_squares_generic_lsqr_damp
- See
scipy.sparse.linalg.lsqr. - least_squares_generic_lsqr_atol
- See
scipy.sparse.linalg.lsqr. - least_squares_generic_lsqr_btol
- See
scipy.sparse.linalg.lsqr. - least_squares_generic_lsqr_conlim
- See
scipy.sparse.linalg.lsqr. - least_squares_generic_lsqr_iter_lim
- See
scipy.sparse.linalg.lsqr. - least_squares_generic_lsqr_show
- See
scipy.sparse.linalg.lsqr.
Returns
A tuple of possible values for
solver_options.Defaults
default_solver, default_least_squares_solver, generic_lgmres_tol, generic_lgmres_maxiter, generic_lgmres_inner_m, generic_lgmres_outer_k, least_squares_generic_lsmr_damp, least_squares_generic_lsmr_atol, least_squares_generic_lsmr_btol, least_squares_generic_lsmr_conlim, least_squares_generic_lsmr_maxiter, least_squares_generic_lsmr_show, least_squares_generic_lsqr_atol, least_squares_generic_lsqr_btol, least_squares_generic_lsqr_conlim, least_squares_generic_lsqr_iter_lim, least_squares_generic_lsqr_show (see
pymor.core.defaults)
-
pymor.algorithms.gram_schmidt.gram_schmidt(A, product=None, atol=1e-13, rtol=1e-13, offset=0, find_duplicates=True, reiterate=True, reiteration_threshold=0.1, check=True, check_tol=0.001, copy=True)[source]¶ Orthonormalize a
VectorArrayusing the stabilized 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. - 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
The orthonormalized
VectorArray.Defaults
atol, rtol, reiterate, reiteration_threshold, check, check_tol (see
pymor.core.defaults)
-
pymor.algorithms.greedy.greedy(discretization, reductor, samples, initial_basis=None, use_estimator=True, error_norm=None, extension_algorithm=<function gram_schmidt_basis_extension>, atol=None, rtol=None, max_extensions=None, pool=None)[source]¶ Greedy basis generation algorithm.
This algorithm generates a reduced basis by iteratively adding the worst approximated solution snapshot for a given training set to the reduced basis. The approximation error is computed either by directly comparing the reduced solution to the detailed solution or by using an error estimator (
use_estimator == True). The reduction and basis extension steps are performed by calling the methods provided by thereductorandextension_algorithmarguments.Parameters
- discretization
- The
Discretizationto reduce. - reductor
- Reductor for reducing the given
Discretization. This has to be a function of the formreductor(discretization, basis, extends=None). The method has to return a tuple(reduced_discretization, reconstructor, reduction_data). In case the last basis extension washierarchic(seeextension_algorithm), the extends argument is set to(last_reduced_discretization, last_reconstructor, last_reduction_data)which can be used by the reductor to speed up the reduction process. For an example seereduce_coercive. - samples
- The set of
Parametersamples on which to perform the greedy search. - initial_basis
- The initial reduced basis at the start of the algorithm. If
None, an empty basis is used as initial basis. - use_estimator
- If
True, usereduced_discretization.estimate()to estimate the errors on the sample set. Otherwisediscretization.solve()is called to compute the exact model reduction error. - error_norm
- If
use_estimator == False, use this function to calculate the norm of the error. IfNone, the Euclidean norm is used. - extension_algorithm
- The extension algorithm to be used to extend the current reduced
basis with the maximum error snapshot. This has to be a function
of the form
extension_algorithm(old_basis, new_vector), which returns a tuple(new_basis, extension_data), whereextension_datais a dict at least containing the keyhierarchic.hierarchicshould be set toTrueifnew_basiscontainsold_basisas its first vectors. - atol
- If not
None, stop the algorithm if the maximum (estimated) error on the sample set drops below this value. - rtol
- If not
None, stop the algorithm if the maximum (estimated) relative error on the sample set drops below this value. - max_extensions
- If not
None, stop the algorithm aftermax_extensionsextension steps. - pool
- If not
None, theWorkerPoolto use for parallelization.
Returns
Dict with the following fields
basis: The reduced basis. reduced_discretization: The reduced Discretizationobtained for the computed basis.reconstructor: Reconstructor for reduced_discretization.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. reduction_data: The reduction_datareturned by the lastreductorcall.
-
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_vector(mu)for allOperatorsinvectorsand all possibleParametersmu.
The algorithm will try to choose
imageas small as possible. However, no optimality is guaranteed.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 thefunctionalsand 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.
-
pymor.algorithms.newton.newton(operator, rhs, initial_guess=None, mu=None, error_norm=None, least_squares=False, miniter=0, maxiter=100, rtol=-1.0, atol=-1.0, stagnation_window=3, stagnation_threshold=0.9, return_stages=False, return_residuals=False)[source]¶ Basic 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
None, aVectorArrayof length 1 containing an initial guess for the solutionU. - mu
- The
Parameterfor which to solve the equation. - error_norm
- The norm with which the norm of the residual is computed. If
None, the Euclidean norm 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.
- rtol
- Finish when the residual norm has been reduced by this factor relative to the norm of the initial residual.
- atol
- Finish when the residual norm is below this threshold.
- stagnation_window
- Finish when the residual norm has not been reduced by a factor of
stagnation_thresholdduring the laststagnation_windowiterations. - stagnation_threshold
- See
stagnation_window. - 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:
error_sequence: NumPy arraycontaining the residual norms after each iteration.stages: See return_stages.residuals: See return_residuals.
Raises
- NewtonError
- Raised if the Netwon algorithm failed to converge.
Defaults
miniter, maxiter, rtol, atol, stagnation_window, stagnation_threshold (see
pymor.core.defaults)
-
pymor.algorithms.pod.pod(A, modes=None, product=None, rtol=4e-08, atol=0.0, l2_mean_err=0.0, symmetrize=False, orthonormalize=True, check=True, check_tol=1e-10)[source]¶ Proper orthogonal decomposition of
A.Viewing the
VectorArrayAas aA.dimxlen(A)matrix, the return value of this method is theVectorArrayof left-singular vectors 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. - modes
- If not
None, only the firstmodesPOD modes (singular vectors) are returned. - product
- Inner product
Operatorw.r.t. which the POD is computed. - 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_mean_err
Do not return more modes than needed to bound the mean l2-approximation error by this value. I.e. the number of returned modes is at most
argmin_N { 1 / len(A) * sum_{n=N+1}^{infty} s_n^2 <= l2_mean_err^2 }
where
s_ndenotes the n-th singular value.- symmetrize
- If
True, symmetrize the Gramian again before proceeding. - orthonormalize
- If
True, orthonormalize the computed POD modes again using thegram_schmidtalgorithm. - check
- If
True, check the computed POD modes for orthonormality. - check_tol
- Tolerance for the orthonormality check.
Returns
- POD
VectorArrayof POD modes.- SVALS
- Sequence of singular values.
Defaults
rtol, atol, l2_mean_err, symmetrize, orthonormalize, check, check_tol (see
pymor.core.defaults)
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 Discretization provided
by an external library into an instationary Discretization.
Currently, implementations of explicit_euler and implicit_euler
time-stepping are provided. The TimeStepperInterface defines a
common interface that has to be fulfilled by the time-steppers used
by InstationaryDiscretization. The classes ExplicitEulerTimeStepper
and ImplicitEulerTimeStepper encapsulate explicit_euler and
implicit_euler to provide this interface.
-
class
pymor.algorithms.timestepping.ExplicitEulerTimeStepper(nt)[source]¶ Bases:
pymor.algorithms.timestepping.TimeStepperInterfaceExplicit 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
ExplicitEulerTimeSteppersolveImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
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 orOperatorwithrange.dim == 1). IfNone, zero right-hand side is assumed. - mass
- The
OperatorM. IfNone, the identity operator is assumed. - mu
Parameterfor whichoperatorandrhsare evaluated. The current time is added tomuwith key_t.- 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(nt, solver_options='operator')[source]¶ Bases:
pymor.algorithms.timestepping.TimeStepperInterfaceImplict 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
ImplicitEulerTimeSteppersolveImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
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 orOperatorwithrange.dim == 1). IfNone, zero right-hand side is assumed. - mass
- The
OperatorM. IfNone, the identity operator is assumed. - mu
Parameterfor whichoperatorandrhsare evaluated. The current time is added tomuwith key_t.- 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.TimeStepperInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInterface 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
InstationaryDiscretizationhave to fulfill this interface.Methods
TimeStepperInterfacesolveImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
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 orOperatorwithrange.dim == 1). IfNone, zero right-hand side is assumed. - mass
- The
OperatorM. IfNone, the identity operator is assumed. - mu
Parameterfor whichoperatorandrhsare evaluated. The current time is added tomuwith key_t.- 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.
-
-
pymor.algorithms.timestepping.explicit_euler(A, F, U0, t0, t1, nt, mu=None, num_values=None)[source]¶
pymor.analyticalproblems package¶
Submodules¶
-
class
pymor.analyticalproblems.advection.InstationaryAdvectionProblem(domain=RectDomain([[0 0], [1 1]]), rhs=ConstantFunction(array(1.0), 2), flux_function=ConstantFunction(array([0, 0]), 1), flux_function_derivative=ConstantFunction(array([0, 0]), 1), dirichlet_data=ConstantFunction(array(0), 2), initial_data=ConstantFunction(array(1), 2), T=1, name=None)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInstationary advection problem.
The problem is to solve the scalar conservation law:
∂_t u(x, t, μ) + ∇ ⋅ f(u(x, t, μ), t, μ) = s(x, t, μ) u(x, 0, μ) = u_0(x, μ)for u with t in [0, T], x in Ω.
Parameters
- domain
- A
DomainDescriptionof the domain Ω the problem is posed on. - rhs
- The
Functions. Note that the current time is handled as an additional'_t'component of theParametermupassed torhs. - flux_function
- The
Functionf. Note that the current time is handled as an additional'_t'component of theParametermuwhich is passed toflux_function.flux_function.dim_domainhas to be 1, whereasflux_function.shape_rangehas to be(dim Ω,). - flux_function_derivative
- The derivative of f with respect to u.
- dirichlet_data
Functionproviding the Dirichlet boundary values.- initial_data
Functionproviding the initial values u_0.- T
- The final time T.
- name
- Name of the problem.
Methods
ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
-
domain¶
-
rhs¶
-
flux_function¶
-
flux_function_derivative¶
-
dirichlet_data¶
-
initial_data¶
-
T¶
-
class
pymor.analyticalproblems.burgers.Burgers2DBumpInitialData[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceMethods
-
class
pymor.analyticalproblems.burgers.Burgers2DFlux(vx, vy)[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceMethods
-
class
pymor.analyticalproblems.burgers.Burgers2DFluxDerivative(vx, vy)[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceMethods
-
class
pymor.analyticalproblems.burgers.Burgers2DProblem(vx=1.0, vy=1.0, torus=True, initial_data_type='sin', parameter_range=(1.0, 2.0))[source]¶ Bases:
pymor.analyticalproblems.advection.InstationaryAdvectionProblemTwo-dimensional Burgers-type problem.
The problem is to solve
∂_t u(x, t, μ) + ∇ ⋅ (v * u(x, t, μ)^μ) = 0 u(x, 0, μ) = u_0(x)for u with t in [0, 0.3], x in [0, 2] x [0, 1].
Parameters
- vx
- The x component of the velocity vector v.
- vy
- The y component of the velocity vector v.
- torus
- If
True, impose periodic boundary conditions. Otherwise, Dirichlet left and bottom, outflow top and right. - initial_data_type
- Type of initial data (
'sin'or'bump'). - parameter_range
- The interval in which μ is allowed to vary.
-
class
pymor.analyticalproblems.burgers.Burgers2DSinInitialData[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceMethods
-
class
pymor.analyticalproblems.burgers.BurgersBumpInitialData[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceMethods
-
class
pymor.analyticalproblems.burgers.BurgersFlux(v)[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceMethods
-
class
pymor.analyticalproblems.burgers.BurgersFluxDerivative(v)[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceMethods
-
class
pymor.analyticalproblems.burgers.BurgersProblem(v=1.0, circle=True, initial_data_type='sin', parameter_range=(1.0, 2.0))[source]¶ Bases:
pymor.analyticalproblems.advection.InstationaryAdvectionProblemOne-dimensional Burgers-type problem.
The problem is to solve
∂_t u(x, t, μ) + ∂_x (v * u(x, t, μ)^μ) = 0 u(x, 0, μ) = u_0(x)for u with t in [0, 0.3] and x in [0, 2].
Parameters
- v
- The velocity v.
- circle
- If
True, impose periodic boundary conditions. Otherwise Dirichlet left, outflow right. - initial_data_type
- Type of initial data (
'sin'or'bump'). - parameter_range
- The interval in which μ is allowed to vary.
-
class
pymor.analyticalproblems.burgers.BurgersSinInitialData[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceMethods
-
class
pymor.analyticalproblems.elliptic.EllipticProblem(domain=RectDomain([[0 0], [1 1]]), rhs=ConstantFunction(array(1.0), 2), diffusion_functions=None, diffusion_functionals=None, advection_functions=None, advection_functionals=None, reaction_functions=None, reaction_functionals=None, dirichlet_data=None, neumann_data=None, robin_data=None, parameter_space=None, name=None)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceAffinely decomposed linear elliptic problem.
The problem consists in solving
| Kd Kv Kr | - ∇ ⋅ ∑ θ_{d,k}(μ) ⋅ d_k(x) ∇ u(x, μ) + ∇ ⋅ ∑ θ_{v,k}(μ) v_k(x) u(x, μ) + ∑ θ_{r,k}(μ) r_k(x) u(x, μ) = f(x, μ) | k=0 k=0 k=0for u.
Parameters
- domain
- A
DomainDescriptionof the domain the problem is posed on. - rhs
- The
Functionf(x, μ).rhs.dim_domainhas to agree with the dimension ofdomain, whereasrhs.shape_rangehas to be(). - diffusion_functions
- List containing the
Functionsd_k(x), each havingshape_rangeof either()or(dim domain, dim domain). - diffusion_functionals
- List containing the
ParameterFunctionalsθ_{d,k}(μ). Iflen(diffusion_functions) == 1,diffusion_functionalsis allowed to beNone, in which case no parameter dependence is assumed. - advection_functions
- List containing the
Functionsv_k(x), each havingshape_rangeof(dim domain,). - advection_functionals
- List containing the
ParameterFunctionalsθ_{v,k}(μ). Iflen(advection_functions) == 1,advection_functionalsis allowed to beNone, in which case no parameter dependence is assumed. - reaction_functions
- List containing the
Functionsr_k(x), each havingshape_rangeof(). - reaction_functionals
- List containing the
ParameterFunctionalsθ_{r,k}(μ). Iflen(reaction_functions) == 1,reaction_functionalsis allowed to beNone, in which case no parameter dependence is assumed. - dirichlet_data
Functionproviding the Dirichlet boundary values.- neumann_data
Functionproviding the Neumann boundary values.- robin_data
- Tuple of two
Functionsproviding the Robin parameter and boundary values. - parameter_space
ParameterSpacefor the problem.- name
- Name of the problem.
Methods
ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
-
domain¶
-
rhs¶
-
diffusion_functions¶
-
diffusion_functionals¶
-
advection_functions¶
-
advection_functionals¶
-
reaction_functions¶
-
reaction_functionals¶
-
dirichlet_data¶
-
neumann_data¶
-
robin_data¶
-
class
pymor.analyticalproblems.helmholtz.HelmholtzProblem(domain=RectDomain([[0 0], [1 1]]), rhs=None, parameter_range=(0.0, 100.0), dirichlet_data=None, neumann_data=None)[source]¶ Bases:
pymor.analyticalproblems.elliptic.EllipticProblemHelmholtz equation problem.
This problem is to solve the Helmholtz equation
- ∆ u(x, k) - k^2 u(x, k) = f(x, k)
on a given domain.
Parameters
- domain
- A
DomainDescriptionof the domain the problem is posed on. - rhs
- The
Functionf(x, μ). - parameter_range
- A tuple
(k_min, k_max)describing the interval in which k is allowd to vary. - dirichlet_data
Functionproviding the Dirichlet boundary values.- neumann_data
Functionproviding the Neumann boundary values.- name
- Name of the problem.
Methods
ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
-
class
pymor.analyticalproblems.parabolic.ParabolicProblem(domain=RectDomain([[0 0], [1 1]]), rhs=ConstantFunction(array(1.0), 2), diffusion_functions=(ConstantFunction(array(1.0), 2),), diffusion_functionals=None, dirichlet_data=None, neumann_data=None, initial_data=ConstantFunction(array(1.0), 2), T=1, parameter_space=None, name=None)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceAffinely decomposed linear parabolic problem.
The problem consists in solving
| K | ∂_t u(x, t, μ) - ∇ ⋅ ∑ θ_k(μ) ⋅ d_k(x) ∇ u(x, t, μ) = f(x, t, μ) | k=0 | u(x, 0, μ) = u_0(x, μ)
for u with t in [0, T], x in Ω.
Parameters
- domain
- A
DomainDescriptionof the domain the problem is posed on. - rhs
- The
Functionf(x, μ).rhs.dim_domainhas to agree with the dimension ofdomain, whereasrhs.shape_rangehas to be(). - diffusion_functions
- List containing the
Functionsd_k(x), each havingshape_rangeof either()or(dim domain, dim domain). - diffusion_functionals
- List containing the
ParameterFunctionalsθ_k(μ). Iflen(diffusion_functions) == 1,diffusion_functionalsis allowed to beNone, in which case no parameter dependence is assumed. - dirichlet_data
Functionproviding the Dirichlet boundary values.- neumann_data
Functionproviding the Neumann boundary values.- initial_data
Functionproviding the initial values.- T
- The final time T.
- parameter_space
ParameterSpacefor the problem.- name
- Name of the problem.
Methods
ParabolicProblemelliptic_part,from_ellipticImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
-
domain¶
-
rhs¶
-
diffusion_functions¶
-
diffusion_functionals¶
-
dirichlet_data¶
-
neumann_data¶
-
initial_data¶
-
T¶
-
class
pymor.analyticalproblems.thermalblock.ThermalBlockDiffusionFunction(x, y, nx, ny)[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceMethods
-
class
pymor.analyticalproblems.thermalblock.ThermalBlockProblem(num_blocks=(3, 3), parameter_range=(0.1, 1), rhs=ConstantFunction(array(1.0), 2))[source]¶ Bases:
pymor.analyticalproblems.elliptic.EllipticProblemAnalytical description of a 2D ‘thermal block’ diffusion problem.
This problem is to solve the elliptic equation
- ∇ ⋅ [ d(x, μ) ∇ u(x, μ) ] = f(x, μ)
on the domain [0,1]^2 with Dirichlet zero boundary values. The domain is partitioned into nx x ny blocks and the diffusion function d(x, μ) is constant on each such block (i,j) with value μ_ij.
---------------------------- | | | | | μ_11 | μ_12 | μ_13 | | | | | |--------------------------- | | | | | μ_21 | μ_22 | μ_23 | | | | | ----------------------------
The Problem is implemented as an
EllipticProblemwith the characteristic functions of the blocks asdiffusion_functions.Parameters
Methods
ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
pymor.core package¶
Submodules¶
This module contains pure python backports of library features from python >= 3 to 2.7
-
class
pymor.core.backports.abstractclassmethod(callable_method)[source]¶ Bases:
classmethodA decorator indicating abstract classmethods.
Similar to abstractmethod.
Usage:
class C(metaclass=ABCMeta): @abstractclassmethod def my_abstract_classmethod(cls, ...): ...
‘abstractclassmethod’ is deprecated. Use ‘classmethod’ with ‘abstractmethod’ instead.
Methods
classmethod__new__
-
class
pymor.core.backports.abstractstaticmethod(callable_method)[source]¶ Bases:
staticmethodA decorator indicating abstract staticmethods.
Similar to abstractmethod.
Usage:
class C(metaclass=ABCMeta): @abstractstaticmethod def my_abstract_staticmethod(...): ...
‘abstractstaticmethod’ is deprecated. Use ‘staticmethod’ with ‘abstractmethod’ instead.
Methods
staticmethod__new__
This module provides the caching facilities of pyMOR.
Any class that wishes to provide cached method calls should derive from
CacheableInterface. Methods which are to be cached can then
be marked using the cached decorator.
To ensure consistency, CacheableInterface derives from
ImmutableInterface: The return value of a cached method call should
only depend on its arguments as well as the immutable state of the class
instance.
Making this assumption, the keys for cache lookup are created from the following data:
- the instance’s state id in case of a
persistentCacheRegion, else the instance’suid,- the method’s
__name__,- the state id of the arguments,
- the state id of pyMOR’s global
defaults.
Note that instances of ImmutableInterface are allowed to have mutable
private attributes. It is the implementors responsibility not to break things.
(See this warning.)
Backends for storage of cached return values derive from CacheRegion.
Currently two backends are provided for memory-based and disk-based caching
(MemoryRegion and SQLiteRegion). The available regions
are stored in the module level cache_regions dict. The user can add
additional regions (e.g. multiple disk cache regions) as required.
CacheableInterface.cache_region specifies a key of the cache_regions dict
to select a cache region which should be used by the instance.
(Setting cache_region to None or 'none' disables caching.)
By default, a ‘memory’, a ‘disk’ and a ‘persistent’ cache region are configured. The
paths and maximum sizes of the disk regions, as well as the maximum number of keys of
the memory cache region can be configured via the
pymor.core.cache.default_regions.disk_path,
pymor.core.cache.default_regions.disk_max_size,
pymor.core.cache.default_regions.persistent_path,
pymor.core.cache.default_regions.persistent_max_size and
pymor.core.cache.default_regions.memory_max_keys defaults.
There two ways to disable and enable caching in pyMOR:
- Calling
disable_caching(enable_caching), to disable (enable) caching globally.- Calling
CacheableInterface.disable_caching(CacheableInterface.enable_caching) to disable (enable) caching for a given instance.
Caching of a method is only active if caching has been enabled both globally
(enabled by default) and on instance level. For debugging purposes, it is moreover
possible to set the environment variable PYMOR_CACHE_DISABLE=1 which overrides
any call to enable_caching.
A cache region can be emptied using CacheRegion.clear. The function
clear_caches clears each cache region registered in cache_regions.
-
class
pymor.core.cache.CacheRegion[source]¶ Bases:
objectBase class for all pyMOR cache regions.
Methods
CacheRegionclear,get,setAttributes
CacheRegionpersistent-
persistent¶ If
True, cache entries are kept between multiple program runs.
-
-
class
pymor.core.cache.CacheableInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceBase class for anything that wants to use our built-in caching.
Methods
Attributes
CacheableInterfacecache_region,sid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
cache_region¶ Name of the
CacheRegionto use. Must correspond to a key in thecache_regionsdict. IfNoneor'none', caching is disabled.
-
cached_method_call(method, *args, **kwargs)[source]¶ Call a given
methodand cache the return value.This method can be used as an alternative to the
cacheddecorator.Parameters
- method
- The method that is to be called. This has to be a method
of
self. - args
- Positional arguments for
method. - kwargs
- Keyword arguments for
method
Returns
The (possibly cached) return value of
method(*args, **kwargs).
-
enable_caching(region)[source]¶ Enable caching for this instance.
When setting the object’s cache region to a
persistentCacheRegion, the object’s state id will be computed.Parameters
- region
- Name of the
CacheRegionto use. Must correspond to a key in thecache_regionsdict. IfNoneor'none', caching is disabled.
-
-
class
pymor.core.cache.MemoryRegion(max_keys)[source]¶ Bases:
pymor.core.cache.CacheRegionMethods
MemoryRegionclear,get,setAttributes
MemoryRegionNO_VALUECacheRegionpersistent
-
class
pymor.core.cache.SQLiteRegion(path, max_size, persistent)[source]¶ Bases:
pymor.core.cache.CacheRegionMethods
SQLiteRegionclear,get,housekeeping,setAttributes
CacheRegionpersistent
-
class
pymor.core.cache.cached(function)[source]¶ Bases:
objectDecorator to make a method of
CacheableInterfaceactually cached.
-
pymor.core.cache.default_regions(disk_path='/tmp/pymor.cache.docs', disk_max_size=1073741824, persistent_path='/tmp/pymor.persistent.cache.docs', persistent_max_size=1073741824, memory_max_keys=1000)[source]¶
Created on Fri Nov 2 10:12:55 2012 Collection of function/class based decorators.
-
class
pymor.core.decorators.DecoratorBase(func)[source]¶ Bases:
objectA base for all decorators that does the common automagic
Methods
DecoratorBase__get__
-
class
pymor.core.decorators.DecoratorWithArgsBase[source]¶ Bases:
objectA base for all decorators with args that sadly can do little common automagic
Methods
DecoratorWithArgsBasemark
-
class
pymor.core.decorators.Deprecated(alt='no alternative given')[source]¶ Bases:
pymor.core.decorators.DecoratorBaseThis is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
Methods
DecoratorBase__get__
This module contains pyMOR’s facilities for handling default values.
A default value in pyMOR is always the default value of some
function argument. To mark the value of an optional function argument
as a user-modifiable default value use the defaults decorator.
As an additional feature, if None is passed for such an argument,
its default value is used instead of None. This is useful
for writing code of the following form:
@default('option')
def algorithm(U, option=42):
...
def method_called_by_user(V, option_for_algorithm=None):
...
algorithm(U, option=option_for_algorithm)
...
If the user does not provide option_for_algorithm to
method_called_by_user, the default 42 is automatically chosen
without the implementor of method_called_by_user having to care
about this.
The user interface for handling default values in pyMOR is provided
by set_defaults, load_defaults_from_file,
write_defaults_to_file and print_defaults.
If pyMOR is imported, it will automatically search for a configuration
file named pymor_defaults.py in the current working directory.
If found, the file is loaded via load_defaults_from_file.
However, as a security precaution, the file will only be loaded if it is
owned by the user running the Python interpreter
(load_defaults_from_file uses exec to load the configuration).
As an alternative, the environment variable PYMOR_DEFAULTS can be
used to specify the path of a configuration file. If empty or set to
NONE, no configuration file will be loaded whatsoever.
Warning
The state of pyMOR’s global defaults enters the calculation of each
state id. Thus, if you first instantiate an immutable object and
then change the defaults, the resulting object will have a different
state id than if you first change the defaults. (This is necessary
as the object can save internal state upon initialization, which
depends on the state of the global defaults.) As a consequence, the
key generated for caching will depend on the
time the defaults have been changed. While no wrong results will be
produced, changing defaults at different times will cause unnecessary
cache misses and will pollute the cache with duplicate entries.
An exemption from this rule are defaults which are listed in the
sid_ignore argument of the defaults decorator. Such
defaults will not enter the state id calculation. This allows the
user to change defaults related to input/output, e.g.
logging, without breaking caching.
Before marking defaults as ignored in your own code, however, make
sure to double check that these defaults will not affect the result
of any mathematical algorithm.
-
class
pymor.core.defaults.DefaultContainer[source]¶ Bases:
objectInternal singleton class holding all default values defined in pyMOR.
Not to be used directly.
Methods
DefaultContainerget,import_all,keys,updateAttributes
DefaultContainersid
-
pymor.core.defaults.defaults(*args, **kwargs)[source]¶ Function decorator for marking function arguments as user-configurable defaults.
If a function decorated with
defaultsis called, the values of the marked default parameters are set to the values defined viaload_defaults_from_fileorset_defaultsin case no value has been provided by the caller of the function. Moreover, ifNoneis passed as a value for a default argument, the argument is set to its default value, as well. If no value has been specified usingset_defaultsorload_defaults_from_file, the default value provided in the function signature is used.If the argument
argof functionfin sub-modulemof packagepis marked as a default value, its value will be changeable by the aforementioned methods under the pathp.m.f.arg.Note that the
defaultsdecorator can also be used in user code.Parameters
- args
- List of strings containing the names of the arguments of the decorated function to mark as pyMOR defaults. Each of these arguments has to be a keyword argument (with a default value).
- sid_ignore
- List of strings naming the defaults in
argswhich should not enter state id calculation (because they do not affect the outcome of any computation). Such defaults will typically be IO related. Use with extreme caution! - qualname
- If a method of a class is decorated, the fully qualified name of the method has to be provided, as this name cannot be derived at decoration time in Python 2.
-
pymor.core.defaults.defaults_sid()[source]¶ Return a state id for pyMOR’s global
defaults.This method is used for the calculation of state ids of
immutableobjects and forcachekey generation.
-
pymor.core.defaults.load_defaults_from_file(filename='./pymor_defaults.py')[source]¶ Loads
defaultvalues defined in configuration file.Suitable configuration files can be created via
write_defaults_to_file. The file is loaded via Python’sexecfunction, so be very careful with configuration files you have not created your own. You have been warned!Note that defaults should generally only be changed/loaded before state ids have been calculated. See this warning for details.
Parameters
- filename
- Path of the configuration file.
-
pymor.core.defaults.print_defaults(import_all=True, shorten_paths=2)[source]¶ Print all
defaultvalues set in pyMOR.Parameters
- import_all
- While
print_defaultswill always print all defaults defined in loaded configuration files or set viaset_defaults, default values set in the function signature can only be printed after the modules containing these functions have been imported. Ifimport_allis set toTrue,print_defaultswill therefore first import all of pyMOR’s modules, to provide a complete lists of defaults. - shorten_paths
- Shorten the paths of all default values by
shorten_pathscomponents. The last two path components will always be printed.
-
pymor.core.defaults.set_defaults(defaults)[source]¶ Set
defaultvalues.This method sets the default value of function arguments marked via the
defaultsdecorator, overriding default values specified in the function signature or set earlier viaload_defaults_from_fileor previousset_defaultscalls.Note that defaults should generally only be changed/loaded before state ids have been calculated. See this warning for details.
Parameters
- defaults
- Dictionary of default values. Keys are the full paths of the default
values (see
defaults).
-
pymor.core.defaults.write_defaults_to_file(filename='./pymor_defaults.py', packages=('pymor', ))[source]¶ Write the currently set
defaultvalues to a configuration file.The resulting file is an ordinary Python script and can be modified by the user at will. It can be loaded in a later session using
load_defaults_from_file.Parameters
- filename
- Name of the file to write to.
- packages
- List of package names.
To discover all default values that have been defined using the
defaultsdecorator,write_defaults_to_filewill recursively import all sub-modules of the named packages before creating the configuration file.
This is an empty module usable as a placeholder(-dict) for dynamically created types and such
-
class
pymor.core.exceptions.AccuracyError[source]¶ Bases:
exceptions.ExceptionIs raised if the result of a computation is inaccurate
Methods
Exception__new__Attributes
BaseExceptionargs,message
-
class
pymor.core.exceptions.ConstError[source]¶ Bases:
exceptions.ExceptionI get thrown when you try to add a new member to a locked class instance
Methods
Exception__new__Attributes
BaseExceptionargs,message
-
class
pymor.core.exceptions.ExtensionError[source]¶ Bases:
exceptions.ExceptionIs raised if a (basis) extension algorithm fails.
This will mostly happen during a basis extension when the new snapshot is already in the span of the basis.
Methods
Exception__new__Attributes
BaseExceptionargs,message
-
class
pymor.core.exceptions.GmshError[source]¶ Bases:
exceptions.ExceptionIs raised when a Gmsh related error occurs.
Methods
Exception__new__Attributes
BaseExceptionargs,message
-
class
pymor.core.exceptions.ImageCollectionError(op)[source]¶ Bases:
exceptions.ExceptionIs raised when a pymor.algorithms.image.estimate_image fails for given operator.
Methods
Exception__new__Attributes
BaseExceptionargs,message
-
class
pymor.core.exceptions.InversionError[source]¶ Bases:
exceptions.ExceptionIs raised if an operator inversion algorithm fails.
Methods
Exception__new__Attributes
BaseExceptionargs,message
-
class
pymor.core.exceptions.NewtonError[source]¶ Bases:
exceptions.ExceptionIs raised if the Newton algorithm fails to converge.
Methods
Exception__new__Attributes
BaseExceptionargs,message
-
class
pymor.core.exceptions.SIDGenerationError[source]¶ Bases:
exceptions.ExceptionIs raised when generate_sid fails.
Methods
Exception__new__Attributes
BaseExceptionargs,message
This module provides base classes from which most classes in pyMOR inherit.
The purpose of these classes is to provide some common functionality for
all objects in pyMOR. The most notable features provided by BasicInterface
are the following:
BasicInterfacesets classUberMetaas metaclass which itself inherits fromabc.ABCMeta. Thus it is possible to define interface classes with abstract methods using theabstractmethoddecorator. There are also decorators for abstract class methods, static methods, and properties.- Using metaclass magic, each class deriving from
BasicInterfacecomes with its ownloggerinstance accessible through itsloggerattribute. The logger prefix is automatically set to the class name.- Logging can be disabled and re-enabled for each instance using the
BasicInterface.disable_loggingandBasicInterface.enable_loggingmethods.- An instance can be made immutable using
BasicInterface.lock. If an instance is locked, each attempt to change one of its attributes raises an exception. Private attributes (of the form_name) are exempted from this rule. Locked instances can be unlocked again usingBasicInterface.unlock.BasicInterface.uidprovides a unique id for each instance. Whileid(obj)is only guaranteed to be unique among all living Python objects,BasicInterface.uidwill be (almost) unique among all pyMOR objects that have ever existed, including previous runs of the application. This is achieved by building the id from a uuid4 which is newly created for each pyMOR run and a counter which is increased for any object that requests an uid.- If not set by the user to another value,
BasicInterface.nameis set to the name of the object’s class.
ImmutableInterface derives from BasicInterface and adds the following
functionality:
Using more metaclass magic, each instance which derives from
ImmutableInterfaceis locked after its__init__method has returned.A unique state id for the instance can be calculated by calling
generate_sidand is then stored as the object’ssidattribute. The state id is obtained by deterministically serializing the object’s state and then computing a checksum of the resulting byte stream.
ImmutableInterface.sid_ignorecan be set to a set of attribute names which should be excluded from state id calculation.
ImmutableInterface.with_can be used to create a copy of an instance with some changed attributes. E.g.obj.with_(a=x, b=y)creates a copy with the
aandbattributes ofobjset toxandy. (Note that in generalaandbdo not necessarily have to correspond to class attributes ofobj; it is up to the implementor to interpret the provided arguments.)ImmutableInterface.with_argumentsholds the set of allowed arguments.
ImmutableInterfaceprovides a default implementation ofwith_which works by creating a new instance, passing the arguments ofwith_to__init__. The missing__init__arguments are taken from instance attributes of the same name.
-
class
pymor.core.interfaces.BasicInterface[source]¶ Bases:
objectBase class for most classes in pyMOR.
Methods
BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid-
logger¶ A per-class instance of
logging.Loggerwith the class name as prefix.
-
logging_disabled¶ Trueif logging has been disabled.
-
name¶ The name of the instance. If not set by the user, the name is set to the class name.
-
uid¶ A unique id for each instance. The uid is obtained by using
UIDand is unique for all pyMOR objects ever created.
-
__setattr__(key, value)[source]¶ depending on _locked state I delegate the setattr call to object or raise an Exception
-
classmethod
has_interface_name()[source]¶ Trueif the class name ends withInterface. Used for introspection.
-
classmethod
implementor_names(descend=False)[source]¶ For convenience I return a list of my implementor names instead of class objects
-
classmethod
implementors(descend=False)[source]¶ I return a, potentially empty, list of my subclass-objects. If
descendisTrue, I traverse my entire subclass hierarchy and return a flattened list.
-
-
class
pymor.core.interfaces.ImmutableInterface[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceBase class for immutable objects in pyMOR.
Instances of
ImmutableInterfaceare immutable in the sense that they arelockedafter__init__returns.Warning
For instances of
ImmutableInterface, the result of member function calls should be completely determined by the function’s arguments together with the object’s state id and the current state of pyMOR’s globaldefaults.While, in principle, you are allowed to modify private members after instance initialization, this should never affect the outcome of future method calls. In particular, if you update any internal state after initialization, you have to ensure that this state is not affected by possible changes of the global
defaults.Also note that mutable private attributes will cause false cache misses when these attributes enter state id calculation. If your implementation uses such attributes, you should therefore add their names to the
sid_ignoreset.Methods
ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
add_with_arguments¶ Set of additional arguments for
with_. (Seewith_arguments.)
-
sid¶ The objects state id. Only available after
generate_sidhas been called.
-
with_arguments¶ Set of allowed keyword arguments for
with_. This is the union of the argument names of__init__and the names specified viaadd_with_arguments.
-
__metaclass__¶ alias of
ImmutableMeta
-
generate_sid(debug=False)[source]¶ Generate a unique state id for the given object.
The generated state id is stored in the object’s
sidattribute.Parameters
- debug
- If
True, produce some debugging output.
Returns
The generated state id.
-
unlock()[source]¶ Make the instance mutable.
Warning
Unlocking an instance of
ImmutableInterfacewill result in the deletion of its state id. However, this will not delete the state ids of objects referencing it. You really should not unlock an object unless you really know what you are doing.
-
with_(**kwargs)[source]¶ Returns a copy with changed attributes.
The default implementation is to create a new class instance with the given keyword arguments as arguments for
__init__. Missing arguments are obtained form instance attributes with the same name.Parameters
**kwargs- Names of attributes to change with their new values. Each attribute name
has to be contained in
with_arguments.
Returns
Copy of
selfwith changed attributes.
-
-
class
pymor.core.interfaces.ImmutableMeta(name, bases, namespace)[source]¶ Bases:
pymor.core.interfaces.UberMetaMetaclass for
ImmutableInterface.
-
class
pymor.core.interfaces.UID[source]¶ Bases:
objectProvides unique, quickly computed ids by combinding a session UUID4 with a counter.
Attributes
UIDcounter,prefix,uid
-
class
pymor.core.interfaces.UberMeta(name, bases, namespace)[source]¶ Bases:
abc.ABCMetaMethods
UberMeta__new__ABCMetaregister,__instancecheck__,__subclasscheck__typemro,__subclasses__-
static
__new__(classname, bases, classdict)[source]¶ I copy docstrings from base class methods to deriving classes. I also forward “abstract{class|static}method” decorations in the base class to “{class|static}method” decorations in the new subclass.
Copying of docstrings can be prevented by setting the
PYMOR_COPY_DOCSTRINGS_DISABLEenvironment variable to1.
-
static
-
class
pymor.core.interfaces.abstractclassmethod(callable_method)[source]¶ Bases:
pymor.core.backports.abstractclassmethodI mark my wrapped function with an additional __isabstractclassmethod__ member, where my abstractclassmethod_base sets __isabstractmethod__ = True.
Methods
classmethod__new__
-
class
pymor.core.interfaces.abstractstaticmethod(callable_method)[source]¶ Bases:
pymor.core.backports.abstractstaticmethodI mark my wrapped function with an additional __isabstractstaticmethod__ member, where my abstractclassmethod_base sets __isabstractmethod__ = True.
Methods
staticmethod__new__
This module contains pyMOR’s logging facilities.
pyMOR’s logging facilities are based on the logging module of the
Python standard library. To obtain a new logger object use getLogger.
Logging can be configured via the set_log_format and
set_log_levels methods.
-
class
pymor.core.logger.ColoredFormatter[source]¶ Bases:
logging.FormatterA logging.Formatter that inserts tty control characters to color loglevel keyword output. Coloring can be disabled by setting the
PYMOR_COLORS_DISABLEenvironment variable to1.Methods
ColoredFormatterformatFormatterconverter,formatException,formatTime,usesTime
-
class
pymor.core.logger.DummyLogger[source]¶ Bases:
objectMethods
DummyLoggerblock,critical,debug,error,exception,getChild,getEffectiveLevel,info,info2,info3,isEnabledFor,log,nop,warn,warningAttributes
DummyLoggerpropagate
-
pymor.core.logger.getLogger(module, level=None, filename='')[source]¶ Get the logger of the respective module for pyMOR’s logging facility.
Parameters
- module
- Name of the module.
- level
- If set,
logger.setLevel(level)is called (seesetLevel). - filename
- If not empty, path of an existing file where everything logged will be written to.
Defaults
filename (see
pymor.core.defaults)
-
pymor.core.logger.set_log_format(max_hierarchy_level=1, indent_blocks=True, block_timings=False)[source]¶ Set log levels for pyMOR’s logging facility.
Parameters
- max_hierarchy_level
- The number of components of the loggers name which are printed. (The first component is always stripped, the last component always preserved.)
- indent_blocks
- If
True, indent log messages inside a code block started withwith logger.block(...). - block_timings
- If
True, measure the duration of a code block started withwith logger.block(...).
Defaults
max_hierarchy_level, indent_blocks, block_timings (see
pymor.core.defaults)
-
pymor.core.logger.set_log_levels(levels={'pymor': 'INFO'})[source]¶ Set log levels for pyMOR’s logging facility.
Parameters
- levels
- Dict of log levels. Keys are names of loggers (see
logging.getLogger), values are the log levels to set for the loggers of the given names (seesetLevel).
Defaults
levels (see
pymor.core.defaults)
This module contains methods for object serialization.
Instead of importing serialization functions from Python’s
pickle module directly, you should use the dump, dumps,
load, loads functions defined here. In particular, these
methods will use dumps_function to serialize
function objects which cannot be pickled by Python’s standard
methods. Note, however, pickling such methods should be avoided
since the implementation of dumps_function uses non-portable
implementation details of CPython to achieve its goals.
-
pymor.core.pickle._global_names(code_object)[source]¶ Return all names in code_object.co_names which are used in a LOAD_GLOBAL statement.
-
pymor.core.pickle.dumps_function(function)[source]¶ Tries hard to pickle a function object:
- The function’s code object is serialized using the
marshalmodule. - For all global names used in the function’s code object the corresponding object in the function’s global namespace is pickled. In case this object is a module, the modules __package__ name is pickled.
- All default arguments are pickled.
- All objects in the function’s closure are pickled.
Note that also this is heavily implementation specific and will probably only work with CPython. If possible, avoid using this method.
- The function’s code object is serialized using the
-
pymor.core.pickle.loads_function(s)[source]¶ Restores a function serialized with
dumps_function.
pymor.discretizations package¶
Submodules¶
-
class
pymor.discretizations.basic.DiscretizationBase(operators, functionals, vector_operators, products=None, estimator=None, visualizer=None, cache_region=None, name=None)[source]¶ Bases:
pymor.discretizations.interfaces.DiscretizationInterfaceBase class for
Discretizationsproviding some common functionality.Methods
Attributes
-
estimate(U, mu=None)[source]¶ Estimate the discretization error for a given solution.
The discretization error could be the error w.r.t. the analytical solution of the given problem or the model reduction error w.r.t. a corresponding high-dimensional
Discretization.Parameters
- U
- The solution obtained by
solve. - mu
Parameterfor whichUhas been obtained.
Returns
The estimated error.
-
visualize(U, **kwargs)[source]¶ Visualize a solution
VectorArrayU.Parameters
- U
- The
VectorArrayfromsolution_spacethat shall be visualized. - kwargs
- See docstring of
self.visualizer.visualize.
-
-
class
pymor.discretizations.basic.InstationaryDiscretization(T, initial_data=None, operator=None, rhs=None, mass=None, time_stepper=None, num_values=None, products=None, operators=None, functionals=None, vector_operators=None, parameter_space=None, estimator=None, visualizer=None, cache_region=None, name=None)[source]¶ Bases:
pymor.discretizations.basic.DiscretizationBaseGeneric class for discretizations of instationary problems.
This class describes instationary problems given by the equations:
M * ∂_t u(t, μ) + L(u(μ), t, μ) = F(t, μ) u(0, μ) = u_0(μ)for t in [0,T], where L is a (possibly non-linear) time-dependent
Operator, F is a time-dependent linearFunctional, and u_0 the initial data. The massOperatorM is assumed to be linear, time-independent andParameter-independent.Parameters
- T
- The final time T.
- initial_data
- The initial data
u_0. Either aVectorArrayof length 1 or (for theParameter-dependent case) a vector-likeOperator(i.e. a linearOperatorwithsource.dim == 1) which applied toNumpyVectorArray(np.array([1]))will yield the initial data for a givenParameter. - operator
- The
OperatorL. - rhs
- The
FunctionalF. - mass
- The mass
OperatorM. IfNone, the identity is assumed. - time_stepper
- The
time-stepperto be used bysolve. - num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned. - products
- A dict of product
Operatorsdefined on the discrete space the problem is posed on. For each product a corresponding norm is added as a method of the discretization. - operators
- A dict of
Operatorsassociated with the discretization. - functionals
- A dict of (output)
Functionalsassociated with the discretization. - vector_operators
- A dict of vector-like
Operatorsassociated with the discretization. - parameter_space
- The
ParameterSpacefor which the discrete problem is posed. - estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, discretization)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, discretization, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of theCacheRegionto use.- name
- Name of the discretization.
Methods
Attributes
-
T¶ The final time T.
-
initial_data¶ The intial data u_0 given by a vector-like
Operator. The same asvector_operators['initial_data'].
-
rhs¶ The
FunctionalF. The same asfunctionals['rhs'].
-
mass¶ The mass operator M. The same as
operators['mass'].
-
time_stepper¶ The provided
time-stepper.
-
with_(**kwargs)[source]¶ Returns a copy with changed attributes.
The default implementation is to create a new class instance with the given keyword arguments as arguments for
__init__. Missing arguments are obtained form instance attributes with the same name.Parameters
**kwargs- Names of attributes to change with their new values. Each attribute name
has to be contained in
with_arguments.
Returns
Copy of
selfwith changed attributes.
-
class
pymor.discretizations.basic.StationaryDiscretization(operator=None, rhs=None, products=None, operators=None, functionals=None, vector_operators=None, parameter_space=None, estimator=None, visualizer=None, cache_region=None, name=None)[source]¶ Bases:
pymor.discretizations.basic.DiscretizationBaseGeneric class for discretizations of stationary problems.
This class describes discrete problems given by the equation:
L(u(μ), μ) = F(μ)
with a linear functional F and a (possibly non-linear) operator L.
Parameters
- operator
- The
OperatorL. - rhs
- The
FunctionalF. - products
- A dict of inner product
Operatorsdefined on the discrete space the problem is posed on. For each product a corresponding norm is added as a method of the discretization. - operators
- A dict of
Operatorsassociated with the discretization. - functionals
- A dict of (output)
Functionalsassociated with the discretization. - vector_operators
- A dict of vector-like
Operatorsassociated with the discretization. - parameter_space
- The
ParameterSpacefor which the discrete problem is posed. - estimator
- An error estimator for the problem. This can be any object with
an
estimate(U, mu, discretization)method. Ifestimatoris notNone, anestimate(U, mu)method is added to the discretization which will callestimator.estimate(U, mu, self). - visualizer
- A visualizer for the problem. This can be any object with
a
visualize(U, discretization, ...)method. Ifvisualizeris notNone, avisualize(U, *args, **kwargs)method is added to the discretization which forwards its arguments to the visualizer’svisualizemethod. - cache_region
Noneor name of theCacheRegionto use.- name
- Name of the discretization.
Methods
Attributes
-
rhs¶ The
FunctionalF. The same asfunctionals['rhs'].
-
with_(**kwargs)[source]¶ Returns a copy with changed attributes.
The default implementation is to create a new class instance with the given keyword arguments as arguments for
__init__. Missing arguments are obtained form instance attributes with the same name.Parameters
**kwargs- Names of attributes to change with their new values. Each attribute name
has to be contained in
with_arguments.
Returns
Copy of
selfwith changed attributes.
-
class
pymor.discretizations.interfaces.DiscretizationInterface[source]¶ Bases:
pymor.core.cache.CacheableInterface,pymor.parameters.base.ParametricInterface for discretization objects.
A discretization object defines a discrete problem via its
classand theOperatorsit contains. Furthermore, discretizatoins can besolvedfor a givenParameterresulting in a solutionVectorArray.Methods
Attributes
-
solution_space¶ VectorSpaceof theVectorArraysreturned bysolve.
-
linear¶ Trueif the discretization describes a linear problem.
-
operators¶ Dictionary of all
Operatorscontained in the discretization (seepymor.reductors.basic.reduce_generic_rbfor a usage example).
-
functionals¶ Same as
operatorsbut forFunctionals.
-
vector_operators¶ Same as operators but for
Operatorsrepresenting vectors, i.e. linearOperatorswithsource.dim == 1.
-
estimate(U, mu=None)[source]¶ Estimate the discretization error for a given solution.
The discretization error could be the error w.r.t. the analytical solution of the given problem or the model reduction error w.r.t. a corresponding high-dimensional
Discretization.Returns
The estimated error.
-
solve(mu=None, **kwargs)[source]¶ Solve the discrete problem for the
Parametermu.The result will be
cachedin case caching has been activated for the given discretization.Parameters
- mu
Parameterfor which to solve.
Returns
The solution given as a
VectorArray.
-
visualize(U, **kwargs)[source]¶ Visualize a solution
VectorArrayU.Parameters
- U
- The
VectorArrayfromsolution_spacethat shall be visualized.
-
-
class
pymor.discretizations.mpi.MPIDiscretization(obj_id, operators, functionals, vector_operators, products=None, pickle_subtypes=True, array_type=<class 'pymor.vectorarrays.mpi.MPIVectorArray'>)[source]¶ Bases:
pymor.discretizations.basic.DiscretizationBaseWrapper class for MPI distributed
Discretizations.Given a single-rank implementation of a
Discretization, this wrapper class uses the event loop frompymor.tools.mpito allow an MPI distributed usage of theDiscretization. The underlying implementation needs to be MPI aware. In particular, the discretization’ssolvemethod has to perform an MPI parallel solve of the discretization.Note that this class is not intended to be instantiated directly. Instead, you should use
mpi_wrap_discretization.Parameters
- obj_id
ObjectIdof the localDiscretizationon each rank.- operators
- Dictionary of all
Operatorscontained in the discretization, wrapped for use on rank 0. Usempi_wrap_discretizationto automatically wrap all operators of a given MPI-awareDiscretization. - functionals
- See
operators. - vector_operators
- See
operators. - products
- See
operators. - pickle_subtypes
- If
pickle_subtypesisFalse, a unique identifier is computed for each localsolution_spacesubtype, which is then transferred to rank 0 instead of the true subtype. This allows to useMPIVectorArray,MPIOperator,MPIDiscretizationeven when the local subtypes are not picklable. - array_type
- This class will be used to wrap the local
VectorArraysreturned bysolveon each rank into an MPI distributedVectorArraymanaged from rank 0. By default,MPIVectorArraywill be used, other options areMPIVectorArrayAutoCommandMPIVectorArrayNoComm.
Methods
Attributes
-
class
pymor.discretizations.mpi.MPIVisualizer(d_obj_id)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceMethods
MPIVisualizervisualizeImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid
-
pymor.discretizations.mpi.mpi_wrap_discretization(local_discretizations, use_with=False, with_apply2=False, pickle_subtypes=True, array_type=<class 'pymor.vectorarrays.mpi.MPIVectorArray'>)[source]¶ Wrap MPI distributed local
Discretizationsto a globalDiscretizationon rank 0.Given MPI distributed local
Discretizationsreferred to by theObjectIdlocal_discretizations, return a newDiscretizationwhich manages these distributed discretizations from rank 0. This is done by first wrapping allOperatorsof theDiscretizationusingmpi_wrap_operator.Alternatively,
local_discretizationscan be a callable (with no arguments) which is then called on each rank to instantiate the localDiscretizations.When
use_withisFalse, anMPIDiscretizationis instantiated with the wrapped operators. A call tosolvewill then use an MPI parallel call to thesolvemethods of the wrapped localDiscretizationsto obtain the solution. This is usually what you want when the actual solve is performed by an implementation in the external solver.When
use_withisTrue,with_is called on the localDiscretizationon rank 0, to obtain a newDiscretizationwith the wrapped MPIOperators. This is mainly useful when the local discretizations are genericDiscretizationsas inpymor.discretizations.basicandsolveis implemented directly in pyMOR via operations on the containedOperators.Parameters
- local_discretizations
ObjectIdof the localDiscretizationson each rank or a callable generating theDiscretizations.- use_with
- See above.
- with_apply2
- See
MPIOperator. - pickle_subtypes
- See
MPIOperator. - array_type
- See
MPIOperator.
pymor.discretizers package¶
Submodules¶
-
pymor.discretizers.advection.discretize_nonlinear_instationary_advection_fv(analytical_problem, diameter=None, nt=100, num_flux='lax_friedrichs', lxf_lambda=1.0, eo_gausspoints=5, eo_intervals=1, num_values=None, domain_discretizer=None, grid=None, boundary_info=None)[source]¶ Discretizes an
InstationaryAdvectionProblemusing the finite volume method.Explicit Euler time-stepping is used for time discretization.
Parameters
- analytical_problem
- The
InstationaryAdvectionProblemto discretize. - diameter
- If not
None,diameteris passed as an argument to thedomain_discretizer. - nt
- The number of time steps.
- num_flux
- The numerical flux to use in the finite volume formulation. Allowed
values are
'lax_friedrichs','engquist_osher','simplified_engquist_osher'(seepymor.operators.fv). - lxf_lambda
- The stabilization parameter for the Lax-Friedrichs numerical flux (ignored, if different flux is chosen).
- eo_gausspoints
- Number of Gauss points for the Engquist-Osher numerical flux (ignored, if different flux is chosen).
- eo_intervals
- Number of sub-intervals to use for integration when using Engquist-Osher numerical flux (ignored, if different flux is chosen).
- num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned. - domain_discretizer
- Discretizer to be used for discretizing the analytical domain. This has
to be a function
domain_discretizer(domain_description, diameter). IfNone,discretize_domain_defaultis used. - grid
- Instead of using a domain discretizer, the
Gridcan also be passed directly using this parameter. - boundary_info
- A
BoundaryInfospecifying the boundary types of the grid boundary entities. Must be provided ifgridis specified.
Returns
- discretization
- The
Discretizationthat has been generated. - data
Dictionary with the following entries:
grid: The generated Grid.boundary_info: The generated BoundaryInfo.
-
pymor.discretizers.disk.discretize_instationary_from_disk(parameter_file, T=None, steps=None, u0=None, time_stepper=None)[source]¶ Load a linear affinely decomposed
InstationaryDiscretizationfrom file.Similarly to
discretize_stationary_from_disk, the discretization is specified via anini.-file of the following form[system-matrices] L_1.mat: l_1(μ_1,...,μ_n) L_2.mat: l_2(μ_1,...,μ_n) ... [rhs-vectors] F_1.mat: f_1(μ_1,...,μ_n) F_2.mat: f_2(μ_1,...,μ_n) ... [mass-matrix] D.mat [initial-solution] u0: u0.mat [parameter] μ_1: a_1,b_1 ... μ_n: a_n,b_n [products] Prod1: P_1.mat Prod2: P_2.mat ... [time] T: final time steps: number of time steps
Parameters
- parameter_file
- Path to the ‘.ini’ parameter file.
- T
- End-time of desired solution. If
None, the value specified in the parameter file is used. - steps
- Number of time steps to. If
None, the value specified in the parameter file is used. - u0
- Initial solution. If
Nonethe initial solution is obtained from parameter file. - time_stepper
- The desired
time stepperto use. IfNone, implicit Euler time stepping is used.
Returns
- discretization
- The
InstationaryDiscretizationthat has been generated.
-
pymor.discretizers.disk.discretize_stationary_from_disk(parameter_file)[source]¶ Load a linear affinely decomposed
StationaryDiscretizationfrom file.The discretization is defined via an
.ini-style file as follows[system-matrices] L_1.mat: l_1(μ_1,...,μ_n) L_2.mat: l_2(μ_1,...,μ_n) ... [rhs-vectors] F_1.mat: f_1(μ_1,...,μ_n) F_2.mat: f_2(μ_1,...,μ_n) ... [parameter] μ_1: a_1,b_1 ... μ_n: a_n,b_n [products] Prod1: P_1.mat Prod2: P_2.mat ...
Here,
L_1.mat,L_2.mat, ...,F_1.mat,F_2.mat, ... are files containing matricesL_1,L_2, ... and vectorsF_1.mat,F_2.mat, ... which correspond to the affine components of the operator and right-hand side functional. The respective coefficient functionals, are given via the string expressionsl_1(...),l_2(...), ...,f_1(...)in the (scalar-valued)Parametercomponentsw_1, ...,w_n. The allowed lower and upper boundsa_i, b_ifor the componentμ_iare specified in the[parameters]section. The resulting operator and right-hand side are then of the formL(μ) = l_1(μ)*L_1 + l_2(μ)*L_2+ ... F(μ) = f_1(μ)*F_1 + f_2(μ)*L_2+ ...
In the
[products]section, an optional list of inner productsProd1,Prod2, .. with corresponding matricesP_1.mat,P_2.matcan be specified.Example:
[system-matrices] matrix1.mat: 1. matrix2.mat: 1. - theta**2 [rhs-vectors] rhs.mat: 1. [parameter] theta: 0, 0.5 [products] h1: h1.mat l2: mass.mat
Parameters
- parameter_file
- Path to the parameter file.
Returns
- discretization
- The
StationaryDiscretizationthat has been generated.
-
pymor.discretizers.elliptic.discretize_elliptic_cg(analytical_problem, diameter=None, domain_discretizer=None, grid=None, boundary_info=None)[source]¶ Discretizes an
EllipticProblemusing finite elements.Parameters
- analytical_problem
- The
EllipticProblemto discretize. - diameter
- If not
None,diameteris passed as an argument to thedomain_discretizer. - domain_discretizer
- Discretizer to be used for discretizing the analytical domain. This has
to be a function
domain_discretizer(domain_description, diameter, ...). IfNone,discretize_domain_defaultis used. - grid
- Instead of using a domain discretizer, the
Gridcan also be passed directly using this parameter. - boundary_info
- A
BoundaryInfospecifying the boundary types of the grid boundary entities. Must be provided ifgridis specified.
Returns
- discretization
- The
Discretizationthat has been generated. - data
Dictionary with the following entries:
grid: The generated Grid.boundary_info: The generated BoundaryInfo.
-
pymor.discretizers.elliptic.discretize_elliptic_fv(analytical_problem, diameter=None, domain_discretizer=None, grid=None, boundary_info=None)[source]¶ Discretizes an
EllipticProblemusing the finite volume method.Parameters
- analytical_problem
- The
EllipticProblemto discretize. - diameter
- If not
None,diameteris passed as an argument to thedomain_discretizer. - domain_discretizer
- Discretizer to be used for discretizing the analytical domain. This has
to be a function
domain_discretizer(domain_description, diameter, ...). IfNone,discretize_domain_defaultis used. - grid
- Instead of using a domain discretizer, the
Gridcan also be passed directly using this parameter. - boundary_info
- A
BoundaryInfospecifying the boundary types of the grid boundary entities. Must be provided ifgridis specified.
Returns
- discretization
- The
Discretizationthat has been generated. - data
Dictionary with the following entries:
grid: The generated Grid.boundary_info: The generated BoundaryInfo.
-
pymor.discretizers.parabolic.discretize_parabolic_cg(analytical_problem, diameter=None, domain_discretizer=None, grid=None, boundary_info=None, num_values=None, time_stepper=None, nt=None)[source]¶ Discretizes an
ParabolicProblemusing finite elements.Parameters
- analytical_problem
- The
ParabolicProblemto discretize. - diameter
- If not
None,diameteris passed as an argument to thedomain_discretizer. - domain_discretizer
- Discretizer to be used for discretizing the analytical domain. This has
to be a function
domain_discretizer(domain_description, diameter, ...). IfNone,discretize_domain_defaultis used. - grid
- Instead of using a domain discretizer, the
Gridcan also be passed directly using this parameter. - boundary_info
- A
BoundaryInfospecifying the boundary types of the grid boundary entities. Must be provided ifgridis specified. - num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned. - time_stepper
- The
time-stepperto be used bysolve. - nt
- If
time_stepperis not specified, the number of time steps for implicit Euler time stepping.
Returns
- discretization
- The
Discretizationthat has been generated. - data
Dictionary with the following entries:
grid: The generated Grid.boundary_info: The generated BoundaryInfo.
-
pymor.discretizers.parabolic.discretize_parabolic_fv(analytical_problem, diameter=None, domain_discretizer=None, grid=None, boundary_info=None, num_values=None, time_stepper=None, nt=None)[source]¶ Discretizes an
ParabolicProblemusing the finite volume method.Parameters
- analytical_problem
- The
ParabolicProblemto discretize. - diameter
- If not
None,diameteris passed to thedomain_discretizer. - domain_discretizer
- Discretizer to be used for discretizing the analytical domain. This has
to be a function
domain_discretizer(domain_description, diameter, ...). If further arguments should be passed to the discretizer, usefunctools.partial. IfNone,discretize_domain_defaultis used. - grid
- Instead of using a domain discretizer, the
Gridcan also be passed directly using this parameter. - boundary_info
- A
BoundaryInfospecifying the boundary types of the grid boundary entities. Must be provided ifgridis specified. - num_values
- The number of returned vectors of the solution trajectory. If
None, each intermediate vector that is calculated is returned. - time_stepper
- The
time-stepperto be used bysolve. - nt
- If
time_stepperis not specified, the number of time steps for implicit Euler time stepping.
Returns
- discretization
- The
Discretizationthat has been generated. - data
Dictionary with the following entries:
grid: The generated Grid.boundary_info: The generated BoundaryInfo.
pymor.domaindescriptions package¶
Submodules¶
-
class
pymor.domaindescriptions.basic.CircleDomain(domain=(0, 1))[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a domain with the topology of a circle, i.e. a line with identified end points.
Parameters
- domain
- List [x_l, x_r] providing the left and right endpoint.
Methods
CircleDomain__repr__ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
CircleDomaindim,domain,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
domain¶
-
class
pymor.domaindescriptions.basic.CylindricalDomain(domain=([0, 0], [1, 1]), top=BoundaryType('dirichlet'), bottom=BoundaryType('dirichlet'))[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a cylindrical domain.
BoundaryTypescan be associated edgewise.Parameters
- domain
- List of two points defining the lower-left and upper-right corner of the domain. The left and right edge are identified.
- top
- The
BoundaryTypeof the top edge. - bottom
- The
BoundaryTypeof the bottom edge.
Methods
CylindricalDomain__repr__ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
CylindricalDomainbottom,diameter,dim,domain,height,lower_left,top,upper_right,volume,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
domain¶
-
top¶
-
bottom¶
-
class
pymor.domaindescriptions.basic.LineDomain(domain=(0, 1), left=BoundaryType('dirichlet'), right=BoundaryType('dirichlet'))[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes an interval domain.
BoundaryTypescan be associated edgewise.Parameters
- domain
- List [x_l, x_r] providing the left and right endpoint.
- left
- The
BoundaryTypeof the left endpoint. - right
- The
BoundaryTypeof the right endpoint.
Methods
LineDomain__repr__ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
LineDomaindim,domain,left,right,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
domain¶
-
left¶
-
right¶
-
class
pymor.domaindescriptions.basic.RectDomain(domain=([0, 0], [1, 1]), left=BoundaryType('dirichlet'), right=BoundaryType('dirichlet'), top=BoundaryType('dirichlet'), bottom=BoundaryType('dirichlet'))[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a rectangular domain.
BoundaryTypescan be associated edgewise.Parameters
- domain
- List of two points defining the lower-left and upper-right corner of the domain.
- left
- The
BoundaryTypeof the left edge. - right
- The
BoundaryTypeof the right edge. - top
- The
BoundaryTypeof the top edge. - bottom
- The
BoundaryTypeof the bottom edge.
Methods
RectDomain__repr__ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
RectDomainbottom,diameter,dim,domain,height,left,lower_left,right,top,upper_right,volume,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
domain¶
-
left¶
-
right¶
-
top¶
-
bottom¶
-
class
pymor.domaindescriptions.basic.TorusDomain(domain=([0, 0], [1, 1]))[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a domain with the topology of a torus.
Parameters
- domain
- List of two points defining the lower-left and upper-right corner of the domain. The left and right edge are identified, as well as the bottom and top edge
Methods
TorusDomain__repr__ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
TorusDomaindiameter,dim,domain,height,lower_left,upper_right,volume,widthDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
domain¶
-
class
pymor.domaindescriptions.boundarytypes.BoundaryType(type_)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceRepresents a boundary type, i.e. Dirichlet, Neumann, etc.
By defining a global registry of possible boundary types, we prevent hard to track down errors due to typos. Only boundary types that have been registered before using
register_typecan be instantiated.The boundary types which are registered by default are ‘dirichlet’, ‘neumann’ and ‘robin’.
Parameters
type_- Name of the boundary type as a string.
Methods
Attributes
BoundaryTypetypesImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
types¶ Set of the names of registered boundary types.
-
classmethod
register_type(name)[source]¶ Register a new
BoundaryTypewith namename.
-
class
pymor.domaindescriptions.interfaces.DomainDescriptionInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceDescribes a geometric domain along with its boundary.
Methods
ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
DomainDescriptionInterfaceboundary_types,dim,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
dim¶ The dimension of the domain
-
boundary_types¶ Set of
BoundaryTypesthe domain has.
-
-
class
pymor.domaindescriptions.polygonal.CircularSectorDomain(angle, radius, arc=BoundaryType('dirichlet'), radii=BoundaryType('dirichlet'), num_points=100)[source]¶ Bases:
pymor.domaindescriptions.polygonal.PolygonalDomainDescribes a circular sector domain of variable radius.
Parameters
- angle
- The angle between 0 and 2*pi of the circular sector.
- radius
- The radius of the circular sector.
- arc
- The
BoundaryTypeof the arc. - radii
- The
BoundaryTypeof the two radii. - num_points
- The number of points of the polygonal chain approximating the circular boundary.
Methods
CircularSectorDomain__repr__ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
CircularSectorDomainangle,arc,num_points,radii,radiusPolygonalDomaindim,holes,pointsDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
angle¶
-
radius¶
-
arc¶
-
radii¶
-
num_points¶
-
class
pymor.domaindescriptions.polygonal.DiscDomain(radius, boundary=BoundaryType('dirichlet'), num_points=100)[source]¶ Bases:
pymor.domaindescriptions.polygonal.PolygonalDomainDescribes a disc domain of variable radius.
Parameters
- radius
- The radius of the disc.
- boundary
- The
BoundaryTypeof the boundary. - num_points
- The number of points of the polygonal chain approximating the boundary.
Methods
DiscDomain__repr__ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
DiscDomainboundary,num_points,radiusPolygonalDomaindim,holes,pointsDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
radius¶
-
boundary¶
-
num_points¶
-
class
pymor.domaindescriptions.polygonal.PolygonalDomain(points, boundary_types, holes=[])[source]¶ Bases:
pymor.domaindescriptions.interfaces.DomainDescriptionInterfaceDescribes a domain with a polygonal boundary and polygonal holes inside the domain.
Parameters
- points
- List of points [x_0, x_1] that describe the polygonal chain that bounds the domain.
- boundary_types
- Either a dictionary
{boundary_type: [i_0, ...], boundary_type: [j_0, ...], ...}withi_0, ...being the ids of boundary segments for a givenBoundaryType(0is the line connecting point0to1,1is the line connecting point1to2etc.), or a function that returns theBoundaryTypefor a given coordinate. - holes
- List of lists of points that describe the polygonal chains that bound the holes inside the domain.
Methods
PolygonalDomain__repr__ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
PolygonalDomaindim,holes,pointsDomainDescriptionInterfaceboundary_types,has_dirichlet,has_neumann,has_robinImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
points¶
-
boundary_types¶
-
holes¶
pymor.domaindiscretizers package¶
Submodules¶
-
pymor.domaindiscretizers.default.discretize_domain_default(domain_description, diameter=0.01, grid_type=None)[source]¶ Mesh a
DomainDescriptionusing an appropriate default implementation.This method can discretize the following
DomainDescriptions:DomainDescription grid_type default RectDomainTriaGridX RectGridCylindricalDomainTriaGridX RectGridTorusDomainTriaGridX RectGridLineDomainOnedGridX CircleDomainOnedGridX PolygonalDomainGmshGridX Parameters
- domain_description
- A
DomainDescriptionof the domain to mesh. - diameter
- Maximal diameter of the codim-0 entities of the generated
Grid. - grid_type
- The class of the
Gridwhich is to be constructed. IfNone, a default choice is made according to the table above.
Returns
- grid
- The generated
Grid. - boundary_info
- The generated
BoundaryInfo.
-
pymor.domaindiscretizers.gmsh.discretize_gmsh(domain_description=None, geo_file=None, geo_file_path=None, msh_file_path=None, mesh_algorithm='del2d', clscale=1.0, options='', refinement_steps=0)[source]¶ Mesh a
DomainDescriptionor an already existing Gmsh GEO-file using the Gmsh mesher.Parameters
- domain_description
- A
DomainDescriptionof thePolygonalDomainorRectDomainto discretize. Has to beNonewhengeo_fileis given. - geo_file
- File handle of the Gmsh Geo-file to discretize. Has to be
Nonewhendomain_descriptionis given. - geo_file_path
- Path of the created Gmsh GEO-file. When meshing a
PolygonalDomainorRectDomainandgeo_file_pathisNone, a temporary file will be created. Ifgeo_fileis specified, this is ignored and the path togeo_filewill be used. - msh_file_path
- Path of the created Gmsh MSH-file. If
None, a temporary file will be created. - mesh_algorithm
- The mesh generation algorithm to use (meshadapt, del2d, front2d).
- clscale
- Mesh element size scaling factor.
- options
- Other options to control the meshing procedure of Gmsh. See http://geuz.org/gmsh/doc/texinfo/gmsh.html#Command_002dline-options for all available options.
- refinement_steps
- Number of refinement steps to do after the initial meshing.
Returns
- grid
- The generated
GmshGrid. - boundary_info
- The generated
GmshBoundaryInfo.
pymor.functions package¶
Submodules¶
-
class
pymor.functions.basic.ConstantFunction(value=array(1.0), dim_domain=1, name=None)[source]¶ Bases:
pymor.functions.basic.FunctionBaseA constant
Functionf: R^d -> R^shape(c), f(x) = c
Parameters
- value
- The constant c.
- dim_domain
- The dimension d.
- name
- The name of the function.
Methods
-
class
pymor.functions.basic.ExpressionFunction(expression, dim_domain=1, shape_range=(), parameter_type=None, name=None)[source]¶ Bases:
pymor.functions.basic.GenericFunctionTurns a Python expression given as a string into a
Function.Some
NumPyarithmetic functions like ‘sin’, ‘log’, ‘min’ are supported. For a full list see thefunctionsclass attribute.Warning
evalis used to evaluate the given expression. Using this class with expression strings from untrusted sources will cause mayhem and destruction!Parameters
- expression
- A Python expression of one variable
xand a parametermugiven as a string. - dim_domain
- The dimension of the domain.
- shape_range
- The shape of the values returned by the expression.
- parameter_type
- The
ParameterTypethe expression accepts. - name
- The name of the function.
Methods
-
class
pymor.functions.basic.FunctionBase[source]¶ Bases:
pymor.functions.interfaces.FunctionInterfaceBase class for
Functionsproviding some common functionality.Methods
Attributes
-
__add__(other)[source]¶ Returns a new
LincombFunctionrepresenting the sum of two functions, or of one function and a constant.
-
__mul__(other)[source]¶ Returns a new
LincombFunctionrepresenting the product of a function by a scalar.
-
__neg__()[source]¶ Returns a new
LincombFunctionrepresenting the function scaled by -1.
-
__radd__(other)¶ Returns a new
LincombFunctionrepresenting the sum of two functions, or of one function and a constant.
-
__rmul__(other)¶ Returns a new
LincombFunctionrepresenting the product of a function by a scalar.
-
__sub__(other)[source]¶ Returns a new
LincombFunctionrepresenting the difference of two functions, or of one function and a constant.
-
-
class
pymor.functions.basic.GenericFunction(mapping, dim_domain=1, shape_range=(), parameter_type=None, name=None)[source]¶ Bases:
pymor.functions.basic.FunctionBaseWrapper making an arbitrary Python function between
NumPy arraysa properFunction.Note that a
GenericFunctioncan only bepickledif the function it is wrapping can be pickled (cf.dumps_function). For this reason, it is usually preferable to useExpressionFunctioninstead ofGenericFunction.Parameters
- mapping
The function to wrap. If
parameter_typeisNone, the function is of the formmapping(x). Ifparameter_typeis notNone, the function has to have the signaturemapping(x, mu). Moreover, the function is expected to be vectorized, i.e.:mapping(x).shape == x.shape[:-1] + shape_range.
- dim_domain
- The dimension of the domain.
- shape_range
- The shape of the values returned by the mapping.
- parameter_type
- The
ParameterTypethe mapping accepts. - name
- The name of the function.
Methods
-
class
pymor.functions.basic.LincombFunction(functions, coefficients, name=None)[source]¶ Bases:
pymor.functions.basic.FunctionBaseA
Functionrepresenting a linear combination ofFunctions.The linear coefficients can be provided either as scalars or as
ParameterFunctionals.Parameters
- functions
- List of
Functionswhose linear combination is formed. - coefficients
- A list of linear coefficients. A linear coefficient can
either be a fixed number or a
ParameterFunctional. - name
- Name of the function.
Methods
Attributes
-
functions¶
-
coefficients¶
-
class
pymor.functions.bitmap.BitmapFunction(filename, bounding_box=[[0.0, 0.0], [1.0, 1.0]], range=[0.0, 1.0])[source]¶ Bases:
pymor.functions.basic.FunctionBaseDefine a 2D
Functionvia a grayscale image.Parameters
- filename
- Path of the image representing the function.
- bounding_box
- Lower left and upper right coordinates of the domain of the function.
- range
- A pixel of value p is mapped to
(p / 255.) * range[1] + range[0].
Methods
-
class
pymor.functions.interfaces.FunctionInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInterface for
Parameterdependent analytical functions.Every
Functionis a map of the formf(μ): Ω ⊆ R^d -> R^(shape_range)
The returned values are
NumPy arraysof arbitrary (but fixed) shape. Note that NumPy distinguishes between one-dimensional arrays of length 1 (with shape(1,)) and zero-dimensional scalar arrays (with shape()). In pyMOR, we usually expect scalar-valued functions to haveshape_range == ().While the function might raise an error if it is evaluated for an argument not in the domain Ω, the exact behavior is left undefined.
Functions are vectorized in the sense, that if
x.ndim == k, thenf(x, μ)[i0, i1, ..., i(k-2)] == f(x[i0, i1, ..., i(k-2)], μ).
In particular,
f(x, μ).shape == x.shape[:-1] + shape_range.Methods
Attributes
-
dim_domain¶ The dimension d > 0.
-
shape_range¶ The shape of the function values.
-
pymor.grids package¶
Submodules¶
-
class
pymor.grids.boundaryinfos.AllDirichletBoundaryInfo(grid)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceBoundaryInfowhereBoundaryType('dirichlet')is attached to each boundary entity.Methods
AllDirichletBoundaryInfomaskBoundaryInfoInterfacecheck_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
mask(boundary_type, codim)[source]¶ retval[i] is
Trueif the codim-codimentity of global indexiis associated to theBoundaryTypeboundary_type.
-
-
class
pymor.grids.boundaryinfos.BoundaryInfoFromIndicators(grid, indicators, assert_unique_type=None, assert_some_type=None)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceBoundaryInfowhere theBoundaryTypesare determined by indicator functions.Parameters
- grid
- The
Gridto which theBoundaryInfois associated. - indicators
- Dict where each key is a
BoundaryTypeand the corresponding value is a boolean valued function defined on the analytical domain which indicates if a point belongs to a boundary of the givenBoundaryType(the indicator functions must be vectorized).
Methods
BoundaryInfoFromIndicatorsmaskBoundaryInfoInterfacecheck_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
mask(boundary_type, codim)[source]¶ retval[i] is
Trueif the codim-codimentity of global indexiis associated to theBoundaryTypeboundary_type.
-
class
pymor.grids.boundaryinfos.EmptyBoundaryInfo(grid)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceBoundaryInfowith noBoundaryTypesattached to any boundary.Methods
EmptyBoundaryInfomaskBoundaryInfoInterfacecheck_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
mask(boundary_type, codim)[source]¶ retval[i] is
Trueif the codim-codimentity of global indexiis associated to theBoundaryTypeboundary_type.
-
-
class
pymor.grids.boundaryinfos.SubGridBoundaryInfo(subgrid, grid, grid_boundary_info, new_boundary_type=None)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceDerives a
BoundaryInfofor aSubGrid.Parameters
- subrid
- The
SubGridfor which aBoundaryInfois created. - grid
- The parent
Grid. - grid_boundary_info
- The
BoundaryInfoof the parentGridfrom which to derive theBoundaryInfo - new_boundary_type
- The
BoundaryTypewhich is assigned to the new boundaries ofsubgrid. IfNone, noBoundaryTypeis assigned.
Methods
SubGridBoundaryInfomaskBoundaryInfoInterfacecheck_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
mask(boundary_type, codim)[source]¶ retval[i] is
Trueif the codim-codimentity of global indexiis associated to theBoundaryTypeboundary_type.
-
pymor.grids.constructions.flatten_grid(grid)[source]¶ This method is used by our visualizers to render n-dimensional grids which cannot be embedded into R^n by duplicating vertices which would have to be mapped to multiple points at once (think of grids on rectangular domains with identified edges).
Parameters
- grid
- The
Gridto flatten.
Returns
- subentities
- The
subentities(0, grid.dim)relation for the flattened grid. - coordinates
- The coordinates of the codim-
grid.dimentities. - entity_map
- Maps the indices of the codim-
grid.dimentities of the flattened grid to the indices of the corresponding entities in the original grid.
-
class
pymor.grids.defaultimpl.AffineGridDefaultImplementations[source]¶ Bases:
objectProvides default implementations for
AffineGrids.
-
class
pymor.grids.defaultimpl.ConformalTopologicalGridDefaultImplementations[source]¶ Bases:
objectProvides default informations for
ConformalTopologicalGrids.
-
class
pymor.grids.defaultimpl.ReferenceElementDefaultImplementations[source]¶ Bases:
objectProvides default implementations for
ReferenceElements.
-
class
pymor.grids.gmsh.GmshBoundaryInfo(grid, sections)[source]¶ Bases:
pymor.grids.interfaces.BoundaryInfoInterfaceBoundaryInfofor aGmshGrid.Parameters
Methods
GmshBoundaryInfomaskBoundaryInfoInterfacecheck_boundary_types,dirichlet_boundaries,dirichlet_mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
mask(boundary_type, codim)[source]¶ retval[i] is
Trueif the codim-codimentity of global indexiis associated to theBoundaryTypeboundary_type.
-
-
class
pymor.grids.gmsh.GmshGrid(sections)[source]¶ Bases:
pymor.grids.unstructured.UnstructuredTriangleGridAn
UnstructuredTriangleGridbuilt from an existing Gmsh MSH-file.Parameters
- sections
- Parsed sections of the MSH-file as returned by
load_gmsh.
Methods
Attributes
-
pymor.grids.gmsh.load_gmsh(gmsh_file)[source]¶ Parse a Gmsh file and create a corresponding
GmshGridandGmshBoundaryInfo.Parameters
- gmsh_file
- File handle of the Gmsh MSH-file.
Returns
- grid
- The generated
GmshGrid. - boundary_info
- The generated
GmshBoundaryInfo.
-
class
pymor.grids.interfaces.AffineGridInterface[source]¶ Bases:
pymor.grids.defaultimpl.AffineGridDefaultImplementations,pymor.grids.interfaces.ConformalTopologicalGridInterfaceTopological grid with geometry where each codim-0 entity is affinely mapped to the same
ReferenceElement.The grid is completely determined via the subentity relation given by
subentitiesand the embeddings given byembeddings. In addition, onlysizeandreference_elementhave to be implemented. Cached default implementations for all other methods are provided byAffineGridDefaultImplementations.Methods
Attributes
-
dim_outer¶ The dimension of the space into which the grid is embedded.
-
bounding_box()[source]¶ returns a
(2, dim_outer)-shaped array containing lower/upper bounding box coordinates.
-
embeddings(codim)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
integration_elements(codim)[source]¶ retval[e]is given assqrt(det(A^T*A)), whereA = embeddings(codim)[0][e].
-
jacobian_inverse_transposed(codim)[source]¶ retval[e]is the transposed (pseudo-)inverse of the Jacobian ofembeddings(codim)[e].
-
quadrature_points(codim, order=None, npoints=None, quadrature_type='default')[source]¶ retval[e]is an array of quadrature points in global coordinates for the codim-codimentity with global indexe.The quadrature is of order
orderor hasnpointsintegration points. To integrate a functionfovereone has to formnp.dot(f(quadrature_points(codim, order)[e]), reference_element(codim).quadrature(order)[1]) * integration_elements(codim)[e]. # NOQA
-
reference_element(codim)[source]¶ The
ReferenceElementof the codim-codimentities.
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
unit_outer_normals()[source]¶ retval[e,i]is the unit outer normal to the i-th codim-1 subentity of the codim-0 entitiy with global indexe.
-
-
class
pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterface[source]¶ Bases:
pymor.grids.interfaces.AffineGridInterfaceAffineGridwith an additionalorthogonal_centersmethod.Methods
Attributes
-
orthogonal_centers()[source]¶ retval[e]is a point inside the codim-0 entity with global indexesuch that the line segment fromretval[e]toretval[e2]is always orthogonal to the codim-1 entity shared by the codim-0 entities with global indexeande2.(This is mainly useful for gradient approximation in finite volume schemes.)
-
-
class
pymor.grids.interfaces.BoundaryInfoInterface[source]¶ Bases:
pymor.core.cache.CacheableInterfaceProvides
BoundaryTypesfor the boundaries of a givenConformalTopologicalGrid.For every
BoundaryTypeand codimension a mask is provided, marking grid entities of the respective type and codimension by their global index.Methods
BoundaryInfoInterfacecheck_boundary_types,dirichlet_boundaries,dirichlet_mask,mask,neumann_boundaries,neumann_mask,no_boundary_type_mask,robin_boundaries,robin_mask,unique_boundary_type_maskCacheableInterfacecached_method_call,disable_caching,enable_cachingImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
BoundaryInfoInterfaceboundary_types,cache_region,has_dirichlet,has_neumann,has_robinCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
boundary_types¶ set of all
BoundaryTypesthe grid has.
-
mask(boundary_type, codim)[source]¶ retval[i] is
Trueif the codim-codimentity of global indexiis associated to theBoundaryTypeboundary_type.
-
no_boundary_type_mask(codim)[source]¶ retval[i] is
Trueif the codim-codimentity of global indexiis associated to noBoundaryType.
-
unique_boundary_type_mask(codim)[source]¶ retval[i] is
Trueif the codim-codimentity of global indexiis associated to one and only oneBoundaryType.
-
-
class
pymor.grids.interfaces.ConformalTopologicalGridInterface[source]¶ Bases:
pymor.grids.defaultimpl.ConformalTopologicalGridDefaultImplementations,pymor.core.cache.CacheableInterfaceA topological grid without hanging nodes.
The grid is completely determined via the subentity relation given by
subentities. In addition, onlysizehas to be implemented, cached default implementations for all other methods are provided byConformalTopologicalGridDefaultImplementations.Methods
Attributes
ConformalTopologicalGridInterfacecache_region,dimCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
dim¶ The dimension of the grid.
-
boundaries(codim)[source]¶ Returns the global indices of all codim-
codimboundary entities.By definition, a codim-1 entity is a boundary entity if it has only one codim-0 superentity. For
codim != 1, a codim-codimentity is a boundary entity if it has a codim-1 sub/super-entity.
-
boundary_mask(codim)[source]¶ retval[e]is true iff the codim-codimentity with global indexeis a boundary entity.By definition, a codim-1 entity is a boundary entity if it has only one codim-0 superentity. For
codim != 1, a codim-codimentity is a boundary entity if it has a codim-1 sub/super-entity.
-
neighbours(codim, neighbour_codim, intersection_codim=None)[source]¶ retval[e,n]is the global index of then-th codim-neighbour_codimentitiy of the codim-codimentityethat shares withea subentity of codimensionintersection_codim.If
intersection_codim == None, it is set tocodim + 1ifcodim == neighbour_codimand tomin(codim, neighbour_codim)otherwise.The default implementation is to compute the result from
subentities(codim, intersection_codim)andsuperentities(intersection_codim, neihbour_codim).
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.Only
subentities(codim, codim+1)has to be implemented; a default implementation is provided which evaluatessubentities(codim, subentity_codim)by computing the transitive closure ofsubentities(codim, codim+1).
-
superentities(codim, superentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-superentity_codimsuperentity of the codim-codimentity with global indexe.retval[e]is sorted by global index.The default implementation is to compute the result from
subentities(superentity_codim, codim).
-
-
class
pymor.grids.interfaces.ReferenceElementInterface[source]¶ Bases:
pymor.grids.defaultimpl.ReferenceElementDefaultImplementations,pymor.core.cache.CacheableInterfaceDefines a reference element.
All reference elements have the property that all subentities of a given codimension are of the same type. I.e. a three-dimensional reference element cannot have triangles and rectangles as faces at the same time.
Methods
Attributes
ReferenceElementInterfacecache_region,dim,volumeCacheableInterfacesid_ignoreImmutableInterfaceadd_with_arguments,sid,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
dim¶ The dimension of the reference element
-
volume¶ The volume of the reference element
-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.oned.OnedGrid(domain=(0, 1), num_intervals=4, identify_left_right=False)[source]¶ Bases:
pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterfaceOne-dimensional
Gridon an interval.Parameters
- domain
- Tuple
(left, right)containing the left and right boundary of the domain. - num_intervals
- The number of codim-0 entities.
Methods
Attributes
-
bounding_box()[source]¶ returns a
(2, dim_outer)-shaped array containing lower/upper bounding box coordinates.
-
embeddings(codim)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
orthogonal_centers()[source]¶ retval[e]is a point inside the codim-0 entity with global indexesuch that the line segment fromretval[e]toretval[e2]is always orthogonal to the codim-1 entity shared by the codim-0 entities with global indexeande2.(This is mainly useful for gradient approximation in finite volume schemes.)
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
visualize(U, codim=2, **kwargs)[source]¶ Visualize scalar data associated to the grid as a patch plot.
Parameters
- U
NumPy arrayof the data to visualize. IfU.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofNumPy arrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - kwargs
- See
visualize_patch
-
class
pymor.grids.rect.RectGrid(num_intervals=(2, 2), domain=([0, 0], [1, 1]), identify_left_right=False, identify_bottom_top=False)[source]¶ Bases:
pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterfaceBasic implementation of a rectangular
Gridon a rectangular domain.The global face, edge and vertex indices are given as follows
x1 ^ | 6--10---7--11---8 | | | 3 2 4 3 5 | | | 3---8---4---9---5 | | | 0 0 1 1 2 | | | 0---6---1---7---2 --> x0
Parameters
- num_intervals
- Tuple
(n0, n1)determining a grid withn0xn1codim-0 entities. - domain
- Tuple
(ll, ur)wherelldefines the lower left andurthe upper right corner of the domain.
Methods
Attributes
-
bounding_box()[source]¶ returns a
(2, dim_outer)-shaped array containing lower/upper bounding box coordinates.
-
embeddings(codim=0)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
global_to_structured(codim)[source]¶ Returns an array which maps global codim-
codimindices to structured indices.I.e. if
GTS = global_to_structured(codim)andSTG = structured_to_global(codim), thenSTG[GTS[:, 0], GTS[:, 1]] == numpy.arange(size(codim)).
-
orthogonal_centers()[source]¶ retval[e]is a point inside the codim-0 entity with global indexesuch that the line segment fromretval[e]toretval[e2]is always orthogonal to the codim-1 entity shared by the codim-0 entities with global indexeande2.(This is mainly useful for gradient approximation in finite volume schemes.)
-
structured_to_global(codim)[source]¶ Returns an
NumPy arraywhich maps structured indices to global codim-codimindices.In other words
structured_to_global(codim)[i, j]is the global index of the i-th in x0-direction and j-th in x1-direction codim-codimentity of the grid.
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
vertex_coordinates(dim)[source]¶ Returns an array of the x_dim coordinates of the grid vertices.
I.e.
centers(2)[structured_to_global(2)[i, j]] == np.array([vertex_coordinates(0)[i], vertex_coordinates(1)[j]])
-
visualize(U, codim=2, **kwargs)[source]¶ Visualize scalar data associated to the grid as a patch plot.
Parameters
- U
NumPy arrayof the data to visualize. IfU.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofNumPy arrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - kwargs
- See
visualize_patch
-
class
pymor.grids.referenceelements.Line[source]¶ Bases:
pymor.grids.interfaces.ReferenceElementInterfaceMethods
Attributes
-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.referenceelements.Point[source]¶ Bases:
pymor.grids.interfaces.ReferenceElementInterfaceMethods
Attributes
-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.referenceelements.Square[source]¶ Bases:
pymor.grids.interfaces.ReferenceElementInterfaceMethods
Attributes
-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.referenceelements.Triangle[source]¶ Bases:
pymor.grids.interfaces.ReferenceElementInterfaceMethods
Attributes
-
mapped_diameter(A)[source]¶ The diameter of the reference element after transforming it with the matrix
A(vectorized).
-
quadrature(order=None, npoints=None, quadrature_type='default')[source]¶ Returns tuple
(P, W)wherePis an array of quadrature points with corresponding weightsW.The quadrature is of order
orderor hasnpointsintegration points.
-
quadrature_info()[source]¶ Returns a tuple of dicts
(O, N)whereO[quadrature_type]is a list of orders which are implemented forquadrature_typeandN[quadrature_type]is a list of the corresponding numbers of integration points.
-
subentities(codim, subentity_codim)[source]¶ subentities(c,sc)[i,j]is, with respect to the indexing inside the reference element, the index of thej-th codim-subentity_codimsubentity of thei-th codim-codimsubentity of the reference element.
-
subentity_embedding(subentity_codim)[source]¶ Returns a tuple
(A, B)which defines the embedding of the codim-subentity_codimsubentities into the reference element.For
subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1)andsub_reference_element(subentity_codim - 1).subentity_embedding(1)choosing always the superentity with smallest index.
-
-
class
pymor.grids.subgrid.SubGrid(grid, entities)[source]¶ Bases:
pymor.grids.interfaces.AffineGridInterfaceA subgrid of a
Grid.Given a
Gridand a list of codim-0 entities we construct the minimal subgrid of the grid, containing all the given entities.Parameters
- grid
Gridof which a subgrid is to be created.- entities
NumPy arrayof global indices of the codim-0 entities which are to be contained in the subgrid.
Methods
Attributes
-
parent_grid¶ The
Gridfrom which the subgrid was constructed.Subgridonly stores aweakrefto the grid, so accessing this property might returnNoneif the original grid has been destroyed.
-
embeddings(codim)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
indices_from_parent_indices(ind, codim)[source]¶ Maps a
NumPy arrayof indicies of codim-codimentites of the parent grid to indicies of the subgrid.Raises
- ValueError
- Not all provided indices correspond to entities contained in the subgrid.
-
parent_indices(codim)[source]¶ retval[e]is the index of thee-th codim-codimentity in the parent grid.
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
class
pymor.grids.tria.TriaGrid(num_intervals=(2, 2), domain=([0, 0], [1, 1]), identify_left_right=False, identify_bottom_top=False)[source]¶ Bases:
pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterfaceBasic implementation of a triangular grid on a rectangular domain.
The global face, edge and vertex indices are given as follows
6---------10----------7---------11----------8 | \ / | \ / | | 22 10 18 | 23 11 19 | | \ / | \ / | 3 14 11 6 4 15 12 7 5 | / \ | / \ | | 14 2 26 | 15 3 27 | | / \ | / \ | 3----------8----------4----------9----------5 | \ / | \ / | | 20 8 16 | 21 9 17 | | \ / | \ / | 0 12 9 4 1 13 10 5 2 | / \ | / \ | | 12 0 24 | 13 1 25 | | / \ | / \ | 0----------6----------1----------7----------2
Parameters
- num_intervals
- Tuple
(n0, n1)determining a grid withn0xn1codim-0 entities. - domain
- Tuple
(ll, ur)wherelldefines the lower left andurthe upper right corner of the domain.
Methods
Attributes
-
bounding_box()[source]¶ returns a
(2, dim_outer)-shaped array containing lower/upper bounding box coordinates.
-
embeddings(codim=0)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
subentities(codim, subentity_codim)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
visualize(U, codim=2, **kwargs)[source]¶ Visualize scalar data associated to the grid as a patch plot.
Parameters
- U
NumPy arrayof the data to visualize. IfU.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofNumPy arrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - kwargs
- See
visualize_patch
-
class
pymor.grids.unstructured.UnstructuredTriangleGrid(vertices, faces)[source]¶ Bases:
pymor.grids.interfaces.AffineGridInterfaceA generic unstructured, triangular grid.
Parameters
- vertices
- A (num_vertices, 2)-shaped
NumPy arraycontaining the coordinates of all vertices in the grid. The row numbers in the array will be the global indices of the given vertices (codim 2 entities). - faces
- A (num_faces, 3)-shaped
NumPy arraycontaining the global indices of the vertices which define a given triangle in the grid. The row numbers in the array will be the global indices of the given triangles (codim 0 entities).
Methods
Attributes
-
embeddings(codim=0)[source]¶ Returns tuple
(A, B)whereA[e]andB[e]are the linear part and the translation part of the map from the reference element ofetoe.For
codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entitye_0ofewith lowest global index and composing it with the subentity_embedding ofeintoe_0determined by the reference element.
-
subentities(codim=0, subentity_codim=None)[source]¶ retval[e,s]is the global index of thes-th codim-subentity_codimsubentity of the codim-codimentity with global indexe.The ordering of
subentities(0, subentity_codim)[e]has to correspond, w.r.t. the embedding ofe, to the local ordering inside the reference element.For
codim > 0, we provide a default implementation by calculating the subentities ofeas follows:- Find the
codim-1parent entitye_0ofewith minimal global index - Lookup the local indices of the subentities of
einsidee_0using the reference element. - Map these local indices to global indices using
subentities(codim - 1, subentity_codim).
This procedures assures that
subentities(codim, subentity_codim)[e]has the right ordering w.r.t. the embedding determined bye_0, which agrees with what is returned byembeddings(codim)- Find the
-
visualize(U, codim=2, **kwargs)[source]¶ Visualize scalar data associated to the grid as a patch plot.
Parameters
- U
NumPy arrayof the data to visualize. IfU.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofNumPy arrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - kwargs
- See
visualize_patch
pymor.gui package¶
Submodules¶
This module provides a widget for displaying patch plots of
scalar data assigned to 2D-grids using OpenGL. This widget is not
intended to be used directly. Instead, use
visualize_patch or
PatchVisualizer.
-
class
pymor.gui.gl.ColorBarWidget(parent, U=None, vmin=None, vmax=None)[source]¶ Bases:
QGLWidgetMethods
ColorBarWidgetinitializeGL,paintEvent,resizeGL,set
-
class
pymor.gui.gl.GLPatchWidget(parent, grid, vmin=None, vmax=None, bounding_box=([0, 0], [1, 1]), codim=2)[source]¶ Bases:
QGLWidgetMethods
GLPatchWidgetinitializeGL,paintGL,resizeGL,set,set_coordinates
This module provides a widgets for displaying plots of
scalar data assigned to one- and two-dimensional grids using
matplotlib. This widget is not intended to be used directly.
Instead, use visualize_matplotlib_1d or
Matplotlib1DVisualizer.
-
class
pymor.gui.matplotlib.Matplotlib1DWidget(parent, grid, count, vmin=None, vmax=None, legend=None, codim=1, separate_plots=False, dpi=100)[source]¶ Bases:
FigureCanvasQTAggMethods
Matplotlib1DWidgetset
-
class
pymor.gui.matplotlib.MatplotlibPatchWidget(parent, grid, bounding_box=None, vmin=None, vmax=None, codim=2, dpi=100)[source]¶ Bases:
FigureCanvasQTAggMethods
MatplotlibPatchWidgetset
This module provides a few methods and classes for visualizing data associated to grids. We use the PySide bindings for the Qt widget toolkit for the GUI.
-
class
pymor.gui.qt.Matplotlib1DVisualizer(grid, codim=1, block=False)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceVisualize scalar data associated to a one-dimensional
Gridas a plot.The grid’s
ReferenceElementmust be the line. The data can either be attached to the subintervals or vertices of the grid.Parameters
- grid
- The underlying
Grid. - codim
- The codimension of the entities the data in
Uis attached to (either 0 or 1). - block
- If
True, block execution until the plot window is closed.
Methods
Matplotlib1DVisualizervisualizeBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid-
visualize(U, discretization, title=None, legend=None, block=None)[source]¶ Visualize the provided data.
Parameters
- U
VectorArrayof the data to visualize. Iflen(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofVectorArrayscan be provided, in which case several plots are made into the same axes. The lengths of all arrays have to agree.- discretization
- Filled in by
pymor.discretizations.DiscretizationBase.visualize(ignored). - title
- Title of the plot.
- legend
- Description of the data that is plotted. Most useful if
Uis a tuple in which caselegendhas to be a tuple of strings of the same length. - block
- If
True, block execution until the plot window is closed. IfNone, use the default provided during instantiation.
-
class
pymor.gui.qt.PatchVisualizer(grid, bounding_box=([0, 0], [1, 1]), codim=2, backend=None, block=False)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceVisualize scalar data associated to a two-dimensional
Gridas a patch plot.The grid’s
ReferenceElementmust be the triangle or square. The data can either be attached to the faces or vertices of the grid.Parameters
- grid
- The underlying
Grid. - bounding_box
- A bounding box in which the grid is contained.
- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - backend
- Plot backend to use (‘gl’ or ‘matplotlib’).
- block
- If
True, block execution until the plot window is closed.
Methods
PatchVisualizervisualizeBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid-
visualize(U, discretization, title=None, legend=None, separate_colorbars=False, rescale_colorbars=False, block=None, filename=None, columns=2)[source]¶ Visualize the provided data.
Parameters
- U
VectorArrayof the data to visualize. Iflen(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofVectorArrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- discretization
- Filled in
pymor.discretizations.DiscretizationBase.visualize(ignored). - title
- Title of the plot.
- legend
- Description of the data that is plotted. Most useful if
Uis a tuple in which caselegendhas to be a tuple of strings of the same length. - separate_colorbars
- If
True, use separate colorbars for each subplot. - rescale_colorbars
- If
True, rescale colorbars to data in each frame. - block
- If
True, block execution until the plot window is closed. IfNone, use the default provided during instantiation. - filename
- If specified, write the data to a VTK-file using
pymor.tools.vtkio.write_vtkinstead of displaying it. - columns
- The number of columns in the visualizer GUI in case multiple plots are displayed at the same time.
-
class
pymor.gui.qt.PlotMainWindow(U, plot, length=1, title=None)[source]¶ Bases:
objectBase class for plot main windows.
Methods
PlotMainWindowrewind,slider_changed,speed_changed,step_backward,step_forward,to_end,toggle_play,update_solution
-
pymor.gui.qt._launch_qt_app(main_window_factory, block)[source]¶ Wrapper to display plot in a separate process.
-
pymor.gui.qt.visualize_matplotlib_1d(grid, U, codim=1, title=None, legend=None, separate_plots=False, block=False)[source]¶ Visualize scalar data associated to a one-dimensional
Gridas a plot.The grid’s
ReferenceElementmust be the line. The data can either be attached to the subintervals or vertices of the grid.Parameters
- grid
- The underlying
Grid. - U
VectorArrayof the data to visualize. Iflen(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofVectorArrayscan be provided, in which case several plots are made into the same axes. The lengths of all arrays have to agree.- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 1). - title
- Title of the plot.
- legend
- Description of the data that is plotted. Most useful if
Uis a tuple in which caselegendhas to be a tuple of strings of the same length. - separate_plots
- If
True, use subplots to visualize multipleVectorArrays. - block
- If
True, block execution until the plot window is closed.
-
pymor.gui.qt.visualize_patch(grid, U, bounding_box=([0, 0], [1, 1]), codim=2, title=None, legend=None, separate_colorbars=False, rescale_colorbars=False, backend='gl', block=False, columns=2)[source]¶ Visualize scalar data associated to a two-dimensional
Gridas a patch plot.The grid’s
ReferenceElementmust be the triangle or square. The data can either be attached to the faces or vertices of the grid.Parameters
- grid
- The underlying
Grid. - U
VectorArrayof the data to visualize. Iflen(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple ofVectorArrayscan be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.- bounding_box
- A bounding box in which the grid is contained.
- codim
- The codimension of the entities the data in
Uis attached to (either 0 or 2). - title
- Title of the plot.
- legend
- Description of the data that is plotted. Most useful if
Uis a tuple in which caselegendhas to be a tuple of strings of the same length. - separate_colorbars
- If
True, use separate colorbars for each subplot. - rescale_colorbars
- If
True, rescale colorbars to data in each frame. - backend
- Plot backend to use (‘gl’ or ‘matplotlib’).
- block
- If
True, block execution until the plot window is closed. - columns
- The number of columns in the visualizer GUI in case multiple plots are displayed at the same time.
Defaults
backend (see
pymor.core.defaults)
pymor.operators package¶
Submodules¶
-
class
pymor.operators.basic.OperatorBase[source]¶ Bases:
pymor.operators.interfaces.OperatorInterfaceBase class for
Operatorsproviding some default implementations.When implementing a new operator, it is usually advisable to derive from this class.
Methods
Attributes
-
__radd__(other)¶ Sum of two operators.
-
apply2(V, U, U_ind=None, V_ind=None, mu=None, product=None)[source]¶ Treat the operator as a 2-form by calculating (V, op(U)).
In general
op.apply2(V, U)is equivalent to:product.apply2(V, op.apply(U)).
In case no
producthas been specified,op.apply2(V, U)is equivialent to:V.dot(op.apply(U)).
In the latter case, assuming that
opis a linear operator given by multiplication with a matrix M, then:op.apply2(V, U) = V^T*M*U.
Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- V_ind
- The indices of the vectors in
Vto which the operator shall be applied (seeVectorArraydocumentation for further details). - U_ind
- The indices of the vectors in
Uto which the operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator. - product
- The inner product used in the expression
(V, op(U))given as anOperator. IfNone, the euclidean product is chosen.
Returns
A
NumPy arraywith shape(len(V_ind), len(U_ind))containing the 2-form evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, ind=None, mu=None, source_product=None, range_product=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the inverse adjoint operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - source_product
- See
apply_adjoint. - range_product
- See
apply_adjoint. - least_squares
If
True, solve the least squares problem:v = argmin ||op*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_vector(mu=None)[source]¶ Return a vector representation of a linear functional or vector operator.
This method may only be called on linear functionals, i.e. linear
OperatorswithNumpyVectorSpace(1)asrange, or on operators describing vectors, i.e. linearOperatorswithNumpyVectorSpace(1)assource.In the case of a functional, the identity
self.as_vector(mu).dot(U) == self.apply(U, mu)
holds, whereas in the case of a vector-like operator we have
self.as_vector(mu) == self.apply(NumpyVectorArray(1), mu).
Parameters
- mu
- The
Parameterfor which to return the vector representation.
Returns
- V
VectorArrayof length 1 containing the vector representation.Vbelongs toself.sourcefor functionals and toself.rangefor vector-like operators.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
pairwise_apply2(V, U, U_ind=None, V_ind=None, mu=None, product=None)[source]¶ Treat the operator as a 2-form by calculating (V, op(U)).
Same as
OperatorInterface.apply2, except that vectors fromVandUare applied in pairs.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- V_ind
- The indices of the vectors in
Vto which the operator shall be applied (seeVectorArraydocumentation for further details). - U_ind
- The indices of the vectors in
Uto which the operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator. - product
- The inner product used in the expression
(V, op(U))given as anOperator. IfNone, the euclidean product is chosen.
Returns
A
NumPy arraywith shape(len(V_ind),) == (len(U_ind),)containing the 2-form evaluations.
-
projected(range_basis, source_basis, product=None, name=None)[source]¶ Project the operator to subspaces of the source and range space.
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 restrictedspan(b_i) / spanc(c_i)(w.r.t. theb_i/c_ibases).How the projected operator is realized will depend on the implementation of the operator to project. While a projected
NumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general.A default implementation is provided in
OperatorBase.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. - name
- Name of the projected operator.
Returns
The projected
Operatorop_proj.
-
-
class
pymor.operators.basic.ProjectedOperator(operator, range_basis, source_basis, product=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseGeneric
Operatorrepresenting the projection of anOperatorto a subspace.This operator is implemented as the concatenation of the linear combination with
source_basis, application of the originaloperatorand projection ontorange_basis. As such, this operator can be used to obtain a reduced basis projection of any givenOperator. However, no offline/online decomposition is performed, so this operator is mainly useful for testing before implementing offline/online decomposition for a specific application.This operator is instantiated in the default implementation of
projectedinOperatorBasefor parametric or nonlinear operators.Parameters
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
-
class
pymor.operators.block.BlockDiagonalOperator(blocks)[source]¶ Bases:
pymor.operators.block.BlockOperatorBlock diagonal
Operatorof arbitraryOperators.This is a specialization of
BlockOperatorfor the block diagonal case.Methods
Attributes
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, ind=None, mu=None, source_product=None, range_product=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the inverse adjoint operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - source_product
- See
apply_adjoint. - range_product
- See
apply_adjoint. - least_squares
If
True, solve the least squares problem:v = argmin ||op*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
-
class
pymor.operators.block.BlockOperator(blocks)[source]¶ Bases:
pymor.operators.basic.OperatorBaseA sparse matrix of arbitrary
Operators.This operator can be
appliedtoBlockVectorArraysof an appropriatesubtype.Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
This module provides some operators for continuous finite element discretizations.
-
class
pymor.operators.cg.AdvectionOperatorP1(grid, boundary_info, advection_function=None, advection_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear advection
Operatorfor linear finite elements.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ v(x) u(x) ]
The function
vis vector-valued. The current implementation works in one and two dimensions, but can be trivially extended to arbitrary dimensions.Parameters
- grid
- The
Gridfor which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- advection_function
- The
Functionv(x)withshape_range = (grid.dim_outer, ). IfNone, constant one is assumed. - advection_constant
- The constant
c. IfNone,cis set to one. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one. - name
- Name of the operator.
Methods
Attributes
-
class
pymor.operators.cg.AdvectionOperatorQ1(grid, boundary_info, advection_function=None, advection_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear advection
Operatorfor bilinear finite elements.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ v(x) u(x) ]
The function
vhas to be vector-valued. The current implementation works in two dimensions, but can be trivially extended to arbitrary dimensions.Parameters
- grid
- The
Gridfor which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- advection_function
- The
Functionv(x)withshape_range = (grid.dim_outer, ). IfNone, constant one is assumed. - advection_constant
- The constant
c. IfNone,cis set to one. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one. - name
- Name of the operator.
Methods
Attributes
-
class
pymor.operators.cg.DiffusionOperatorP1(grid, boundary_info, diffusion_function=None, diffusion_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorDiffusion
Operatorfor linear finite elements.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ d(x) ∇ u(x) ]
The function
dcan be scalar- or matrix-valued. The current implementation works in one and two dimensions, but can be trivially extended to arbitrary dimensions.Parameters
- grid
- The
Gridfor which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- diffusion_function
- The
Functiond(x)withshape_range == ()orshape_range = (grid.dim_outer, grid.dim_outer). IfNone, constant one is assumed. - diffusion_constant
- The constant
c. IfNone,cis set to one. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one. - name
- Name of the operator.
Methods
Attributes
-
class
pymor.operators.cg.DiffusionOperatorQ1(grid, boundary_info, diffusion_function=None, diffusion_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorDiffusion
Operatorfor bilinear finite elements.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ d(x) ∇ u(x) ]
The function
dcan be scalar- or matrix-valued. The current implementation works in two dimensions, but can be trivially extended to arbitrary dimensions.Parameters
- grid
- The
Gridfor which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- diffusion_function
- The
Functiond(x)withshape_range == ()orshape_range = (grid.dim_outer, grid.dim_outer). IfNone, constant one is assumed. - diffusion_constant
- The constant
c. IfNone,cis set to one. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one. - name
- Name of the operator.
Methods
Attributes
-
class
pymor.operators.cg.InterpolationOperator(grid, function)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorVector-like Lagrange interpolation
Operatorfor continuous finite element spaces.Methods
Attributes
-
class
pymor.operators.cg.L2ProductFunctionalP1(grid, function, boundary_info=None, dirichlet_data=None, neumann_data=None, robin_data=None, order=2, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear finite element
Functionalrepresenting the inner product with an L2-Function.Boundary treatment can be performed by providing
boundary_infoanddirichlet_data, in which case the DOFs corresponding to Dirichlet boundaries are set to the values provided bydirichlet_data. Neumann boundaries are handled by providing aneumann_datafunction, Robin boundaries by providing arobin_datatuple.The current implementation works in one and two dimensions, but can be trivially extended to arbitrary dimensions.
Parameters
- grid
Gridfor which to assemble the functional.- function
- The
Functionwith which to take the inner product. - boundary_info
BoundaryInfodetermining the Dirichlet and Neumann boundaries orNone. IfNone, no boundary treatment is performed.- dirichlet_data
Functionproviding the Dirichlet boundary values. IfNone, constant-zero boundary is assumed.- neumann_data
Functionproviding the Neumann boundary values. IfNone, constant-zero is assumed.- robin_data
- Tuple of two
Functionsproviding the Robin parameter and boundary values, seeRobinBoundaryOperator. IfNone, constant-zero for both functions is assumed. - order
- Order of the Gauss quadrature to use for numerical integration.
- name
- The name of the functional.
Methods
Attributes
-
class
pymor.operators.cg.L2ProductFunctionalQ1(grid, function, boundary_info=None, dirichlet_data=None, neumann_data=None, robin_data=None, order=2, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorBilinear finite element
Functionalrepresenting the inner product with an L2-Function.Boundary treatment can be performed by providing
boundary_infoanddirichlet_data, in which case the DOFs corresponding to Dirichlet boundaries are set to the values provided bydirichlet_data. Neumann boundaries are handled by providing aneumann_datafunction, Robin boundaries by providing arobin_datatuple.The current implementation works in two dimensions, but can be trivially extended to arbitrary dimensions.
Parameters
- grid
Gridfor which to assemble the functional.- function
- The
Functionwith which to take the inner product. - boundary_info
BoundaryInfodetermining the Dirichlet boundaries orNone. IfNone, no boundary treatment is performed.- dirichlet_data
Functionproviding the Dirichlet boundary values. IfNone, constant-zero boundary is assumed.- neumann_data
Functionproviding the Neumann boundary values. IfNone, constant-zero is assumed.- robin_data
- Tuple of two
Functionsproviding the Robin parameter and boundary values, seeRobinBoundaryOperator. IfNone, constant-zero for both functions is assumed. - order
- Order of the Gauss quadrature to use for numerical integration.
- name
- The name of the functional.
Methods
Attributes
-
class
pymor.operators.cg.L2ProductP1(grid, boundary_info, dirichlet_clear_rows=True, dirichlet_clear_columns=False, dirichlet_clear_diag=False, coefficient_function=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorOperatorrepresenting the L2-product between linear finite element functions.The current implementation works in one and two dimensions, but can be trivially extended to arbitrary dimensions.
Parameters
- grid
- The
Gridfor which to assemble the product. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- dirichlet_clear_rows
- If
True, set the rows of the system matrix corresponding to Dirichlet boundary DOFs to zero. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise, if eitherdirichlet_clear_rowsordirichlet_clear_columnsisTrue, the diagonal entries are set to one. - coefficient_function
- Coefficient
Functionfor product withshape_range == (). IfNone, constant one is assumed. - name
- The name of the product.
Methods
Attributes
-
class
pymor.operators.cg.L2ProductQ1(grid, boundary_info, dirichlet_clear_rows=True, dirichlet_clear_columns=False, dirichlet_clear_diag=False, coefficient_function=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorOperatorrepresenting the L2-product between bilinear finite element functions.The current implementation works in two dimensions, but can be trivially extended to arbitrary dimensions.
Parameters
- grid
- The
Gridfor which to assemble the product. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- dirichlet_clear_rows
- If
True, set the rows of the system matrix corresponding to Dirichlet boundary DOFs to zero. - dirichlet_clear_columns
- If
True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero. - dirichlet_clear_diag
- If
True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise, if eitherdirichlet_clear_rowsordirichlet_clear_columnsisTrue, the diagonal entries are set to one. - coefficient_function
- Coefficient
Functionfor product withshape_range == (). IfNone, constant one is assumed. - name
- The name of the product.
Methods
Attributes
-
class
pymor.operators.cg.RobinBoundaryOperator(grid, boundary_info, robin_data=None, order=2, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorRobin boundary
Operatorfor linear finite elements.The operator represents the contribution of Robin boundary conditions to the stiffness matrix, where the boundary condition is supposed to be given in the form
-[ d(x) ∇u(x) ] ⋅ n(x) = c(x) (u(x) - g(x))
dandnare the diffusion function (seeDiffusionOperatorP1) and the unit outer normal inx, whilecis the (scalar) Robin parameter function andgis the (also scalar) Robin boundary value function.Parameters
- grid
- The
Gridover which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- robin_data
- Tuple providing two
Functionsthat represent the Robin parameter and boundary value function. IfNone, the resulting operator is zero. - name
- Name of the operator.
Methods
Attributes
Module containing some constructions to obtain new operators from old ones.
-
class
pymor.operators.constructions.AdjointOperator(operator, source_product=None, range_product=None, name=None, with_apply_inverse=True, solver_options=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseRepresents the adjoint of a given linear
Operator.See
apply_adjoint.Parameters
- operator
- The
Operatorof which the adjoint is formed. - source_product
- If not
None, inner productOperatorfor the sourceVectorSpacew.r.t. which to take the adjoint. - range_product
- If not
None, inner productOperatorfor the rangeVectorSpacew.r.t. which to take the adjoint. - name
- If not
None, name of the operator. - with_apply_inverse
- If
True, provide ownapply_inverseandapply_inverse_adjointimplementations by calling these methods on the givenoperator. (Is set toFalsein the default implementation of andapply_inverse_adjoint.) - solver_options
- When
with_apply_inverseisFalse, thesolver_optionsto use for theapply_inversedefault implementation.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, ind=None, mu=None, source_product=None, range_product=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the inverse adjoint operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - source_product
- See
apply_adjoint. - range_product
- See
apply_adjoint. - least_squares
If
True, solve the least squares problem:v = argmin ||op*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
projected(range_basis, source_basis, product=None, name=None)[source]¶ Project the operator to subspaces of the source and range space.
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 restrictedspan(b_i) / spanc(c_i)(w.r.t. theb_i/c_ibases).How the projected operator is realized will depend on the implementation of the operator to project. While a projected
NumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general.A default implementation is provided in
OperatorBase.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. - name
- Name of the projected operator.
Returns
The projected
Operatorop_proj.
-
class
pymor.operators.constructions.ComponentProjection(components, source, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseOperatorrepresenting the projection of aVectorArrayon some of its components.Parameters
- components
- List or 1D
NumPy arrayof the indices of the vectorcomponentsthat ar to be extracted by the operator. - source
- Source
VectorSpaceof the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.Concatenation(second, first, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseOperatorrepresenting the concatenation of twoOperators.Parameters
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
projected(range_basis, source_basis, product=None, name=None)[source]¶ Project the operator to subspaces of the source and range space.
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 restrictedspan(b_i) / spanc(c_i)(w.r.t. theb_i/c_ibases).How the projected operator is realized will depend on the implementation of the operator to project. While a projected
NumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general.A default implementation is provided in
OperatorBase.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. - name
- Name of the projected operator.
Returns
The projected
Operatorop_proj.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
-
class
pymor.operators.constructions.ConstantOperator(value, source, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseA constant
Operatoralways returning the same vector.Parameters
- value
- A
VectorArrayof length 1 containing the vector which is returned by the operator. - source
- Source
VectorSpaceof the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
projected(range_basis, source_basis, product=None, name=None)[source]¶ Project the operator to subspaces of the source and range space.
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 restrictedspan(b_i) / spanc(c_i)(w.r.t. theb_i/c_ibases).How the projected operator is realized will depend on the implementation of the operator to project. While a projected
NumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general.A default implementation is provided in
OperatorBase.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. - name
- Name of the projected operator.
Returns
The projected
Operatorop_proj.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.FixedParameterOperator(operator, mu=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseMakes an
OperatorParameter-independent by setting a fixedParameter.Parameters
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, ind=None, mu=None, source_product=None, range_product=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the inverse adjoint operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - source_product
- See
apply_adjoint. - range_product
- See
apply_adjoint. - least_squares
If
True, solve the least squares problem:v = argmin ||op*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
-
class
pymor.operators.constructions.IdentityOperator(space, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseThe identity
Operator.In other words:
op.apply(U) == U
Parameters
- space
- The
VectorSpacethe operator acts on. - name
- Name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, ind=None, mu=None, source_product=None, range_product=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the inverse adjoint operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - source_product
- See
apply_adjoint. - range_product
- See
apply_adjoint. - least_squares
If
True, solve the least squares problem:v = argmin ||op*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operator. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.InducedNorm(product, raise_negative, tol, name)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInstantiated by
induced_norm. Do not use directly.Methods
-
class
pymor.operators.constructions.LincombOperator(operators, coefficients, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseLinear combination of arbitrary
Operators.This
Operatorrepresents a (possiblyParameterdependent) linear combination of a given list ofOperators.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- A list of linear coefficients. A linear coefficient can
either be a fixed number or a
ParameterFunctional. - name
- Name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply2(V, U, U_ind=None, V_ind=None, mu=None, product=None)[source]¶ Treat the operator as a 2-form by calculating (V, op(U)).
In general
op.apply2(V, U)is equivalent to:product.apply2(V, op.apply(U)).
In case no
producthas been specified,op.apply2(V, U)is equivialent to:V.dot(op.apply(U)).
In the latter case, assuming that
opis a linear operator given by multiplication with a matrix M, then:op.apply2(V, U) = V^T*M*U.
Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- V_ind
- The indices of the vectors in
Vto which the operator shall be applied (seeVectorArraydocumentation for further details). - U_ind
- The indices of the vectors in
Uto which the operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator. - product
- The inner product used in the expression
(V, op(U))given as anOperator. IfNone, the euclidean product is chosen.
Returns
A
NumPy arraywith shape(len(V_ind), len(U_ind))containing the 2-form evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
as_vector(mu=None)[source]¶ Return a vector representation of a linear functional or vector operator.
This method may only be called on linear functionals, i.e. linear
OperatorswithNumpyVectorSpace(1)asrange, or on operators describing vectors, i.e. linearOperatorswithNumpyVectorSpace(1)assource.In the case of a functional, the identity
self.as_vector(mu).dot(U) == self.apply(U, mu)
holds, whereas in the case of a vector-like operator we have
self.as_vector(mu) == self.apply(NumpyVectorArray(1), mu).
Parameters
- mu
- The
Parameterfor which to return the vector representation.
Returns
- V
VectorArrayof length 1 containing the vector representation.Vbelongs toself.sourcefor functionals and toself.rangefor vector-like operators.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
evaluate_coefficients(mu)[source]¶ Compute the linear coefficients for a given
Parameter.Parameters
- mu
Parameterfor which to compute the linear coefficients.
Returns
List of linear coefficients.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
pairwise_apply2(V, U, U_ind=None, V_ind=None, mu=None, product=None)[source]¶ Treat the operator as a 2-form by calculating (V, op(U)).
Same as
OperatorInterface.apply2, except that vectors fromVandUare applied in pairs.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- V_ind
- The indices of the vectors in
Vto which the operator shall be applied (seeVectorArraydocumentation for further details). - U_ind
- The indices of the vectors in
Uto which the operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator. - product
- The inner product used in the expression
(V, op(U))given as anOperator. IfNone, the euclidean product is chosen.
Returns
A
NumPy arraywith shape(len(V_ind),) == (len(U_ind),)containing the 2-form evaluations.
-
projected(range_basis, source_basis, product=None, name=None)[source]¶ Project the operator to subspaces of the source and range space.
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 restrictedspan(b_i) / spanc(c_i)(w.r.t. theb_i/c_ibases).How the projected operator is realized will depend on the implementation of the operator to project. While a projected
NumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general.A default implementation is provided in
OperatorBase.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. - name
- Name of the projected operator.
Returns
The projected
Operatorop_proj.
-
projected_to_subbasis(dim_range=None, dim_source=None, name=None)[source]¶ See
pymor.operators.numpy.NumpyMatrixOperator.projected_to_subbasis.
-
class
pymor.operators.constructions.SelectionOperator(operators, parameter_functional, boundaries, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseAn
Operatorselected from a list ofOperators.operators[i]is used ifparameter_functional(mu)is less or equal thanboundaries[i]and greater thanboundaries[i-1]:-infty ------- boundaries[i] ---------- boundaries[i+1] ------- infty | | --- operators[i] ---|---- operators[i+1] ----|---- operators[i+2] | |
Parameters
- operators
- List of
Operatorsfrom which oneOperatoris selected based on the givenParameter. - parameter_functional
- The
ParameterFunctionalused for the selection of oneOperator. - boundaries
- The interval boundaries as defined above.
- name
- Name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
as_vector(mu=None)[source]¶ Return a vector representation of a linear functional or vector operator.
This method may only be called on linear functionals, i.e. linear
OperatorswithNumpyVectorSpace(1)asrange, or on operators describing vectors, i.e. linearOperatorswithNumpyVectorSpace(1)assource.In the case of a functional, the identity
self.as_vector(mu).dot(U) == self.apply(U, mu)
holds, whereas in the case of a vector-like operator we have
self.as_vector(mu) == self.apply(NumpyVectorArray(1), mu).
Parameters
- mu
- The
Parameterfor which to return the vector representation.
Returns
- V
VectorArrayof length 1 containing the vector representation.Vbelongs toself.sourcefor functionals and toself.rangefor vector-like operators.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
projected(range_basis, source_basis, product=None, name=None)[source]¶ Project the operator to subspaces of the source and range space.
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 restrictedspan(b_i) / spanc(c_i)(w.r.t. theb_i/c_ibases).How the projected operator is realized will depend on the implementation of the operator to project. While a projected
NumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general.A default implementation is provided in
OperatorBase.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. - name
- Name of the projected operator.
Returns
The projected
Operatorop_proj.
-
class
pymor.operators.constructions.VectorArrayOperator(array, transposed=False, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseWraps a
VectorArrayas anOperator.If
transposedisFalse, the operator maps fromNumpyVectorSpace(len(array))toarray.spaceby forming linear combinations of the vectors in the array with given coefficient arrays.If
transposed == True, the operator maps fromarray.spacetoNumpyVectorSpace(len(array))by forming the inner products of the argument with the vectors in the given array.Parameters
- array
- The
VectorArraywhich is to be treated as an operator. - transposed
- See description above.
- name
- The name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse_adjoint(U, ind=None, mu=None, source_product=None, range_product=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the inverse adjoint operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - source_product
- See
apply_adjoint. - range_product
- See
apply_adjoint. - least_squares
If
True, solve the least squares problem:v = argmin ||op*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_vector(mu=None)[source]¶ Return a vector representation of a linear functional or vector operator.
This method may only be called on linear functionals, i.e. linear
OperatorswithNumpyVectorSpace(1)asrange, or on operators describing vectors, i.e. linearOperatorswithNumpyVectorSpace(1)assource.In the case of a functional, the identity
self.as_vector(mu).dot(U) == self.apply(U, mu)
holds, whereas in the case of a vector-like operator we have
self.as_vector(mu) == self.apply(NumpyVectorArray(1), mu).
Parameters
- mu
- The
Parameterfor which to return the vector representation.
Returns
- V
VectorArrayof length 1 containing the vector representation.Vbelongs toself.sourcefor functionals and toself.rangefor vector-like operators.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operator. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
class
pymor.operators.constructions.VectorFunctional(vector, product=None, name=None)[source]¶ Bases:
pymor.operators.constructions.VectorArrayOperatorWrap a vector as a linear
Functional.Given a vector
vof dimensiond, this class represents the functionalf: R^d ----> R^1 u |---> (u, v)
where
( , )denotes the inner product given byproduct.In particular, if
productisNoneVectorFunctional(vector).as_vector() == vector.
If
productis not none, we obtainVectorFunctional(vector).as_vector() == product.apply(vector).
Parameters
- vector
VectorArrayof length 1 containing the vectorv.- product
Operatorrepresenting the scalar product to use.- name
- Name of the operator.
Methods
-
class
pymor.operators.constructions.VectorOperator(vector, name=None)[source]¶ Bases:
pymor.operators.constructions.VectorArrayOperatorWrap a vector as a vector-like
Operator.Given a vector
vof dimensiond, this class represents the operatorop: R^1 ----> R^d x |---> x⋅vIn particular:
VectorOperator(vector).as_vector() == vector
Parameters
- vector
VectorArrayof length 1 containing the vectorv.- name
- Name of the operator.
Methods
-
class
pymor.operators.constructions.ZeroOperator(source, range, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseThe
Operatorwhich maps every vector to zero.Parameters
- source
- Source
VectorSpaceof the operator. - range
- Range
VectorSpaceof the operator. - name
- Name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, ind=None, mu=None, source_product=None, range_product=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the inverse adjoint operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - source_product
- See
apply_adjoint. - range_product
- See
apply_adjoint. - least_squares
If
True, solve the least squares problem:v = argmin ||op*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operator. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
projected(range_basis, source_basis, product=None, name=None)[source]¶ Project the operator to subspaces of the source and range space.
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 restrictedspan(b_i) / spanc(c_i)(w.r.t. theb_i/c_ibases).How the projected operator is realized will depend on the implementation of the operator to project. While a projected
NumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general.A default implementation is provided in
OperatorBase.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. - name
- Name of the projected operator.
Returns
The projected
Operatorop_proj.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
pymor.operators.constructions.induced_norm(product, raise_negative=True, tol=1e-10, name=None)[source]¶ Obtain induced norm of an inner product.
The norm of the vectors in a
VectorArrayU is calculated by callingproduct.pairwise_apply2(U, U, mu=mu).
In addition, negative norm squares of absolute value smaller than
tolare clipped to0. Ifraise_negativeisTrue, aValueErrorexception is raised if there are negative norm squares of absolute value larger thantol.Parameters
- product
- The inner product
Operatorfor which the norm is to be calculated. - raise_negative
- If
True, raise an exception if calculated norm is negative. - tol
- See above.
Returns
- norm
- A function
norm(U, mu=None)taking aVectorArrayUas input together with theParametermuwhich is passed to the product.
Defaults
raise_negative, tol (see
pymor.core.defaults)
-
class
pymor.operators.ei.EmpiricalInterpolatedOperator(operator, interpolation_dofs, collateral_basis, triangular, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseInterpolate an
Operatorusing Empirical Operator Interpolation.Let
Lbe anOperator,0 <= c_1, ..., c_M < L.range.dimindices of interpolation DOFs and letb_1, ..., b_M in R^(L.range.dim)be collateral basis vectors. If moreoverψ_j(U)denotes the j-th component ofU, the empirical interpolationL_EIofLw.r.t. the given data is given by| M | L_EI(U, μ) = ∑ b_i⋅λ_i such that | i=1 | | ψ_(c_i)(L_EI(U, μ)) = ψ_(c_i)(L(U, μ)) for i=0,...,M
Since the original operator only has to be evaluated at the given interpolation DOFs,
EmpiricalInterpolatedOperatorcallsrestrictedto obtain a restricted version of the operator which is used to quickly obtain the required evaluations. If therestrictedmethod, is not implemented, the full operator will be evaluated (which will lead to the same result, but without any speedup).The interpolation DOFs and the collateral basis can be generated using the algorithms provided in the
pymor.algorithms.eimodule.Parameters
- operator
- The
Operatorto interpolate. - interpolation_dofs
- List or 1D
NumPy arrayof the interpolation DOFsc_1, ..., c_M. - collateral_basis
VectorArraycontaining the collateral basisb_1, ..., b_M.- triangular
- If
True, assume that ψ_(c_i)(b_j) = 0 for i < j, which means that the interpolation matrix is triangular. - name
- Name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
projected(range_basis, source_basis, product=None, name=None)[source]¶ Project the operator to subspaces of the source and range space.
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 restrictedspan(b_i) / spanc(c_i)(w.r.t. theb_i/c_ibases).How the projected operator is realized will depend on the implementation of the operator to project. While a projected
NumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general.A default implementation is provided in
OperatorBase.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. - name
- Name of the projected operator.
Returns
The projected
Operatorop_proj.
-
class
pymor.operators.ei.ProjectedEmpiciralInterpolatedOperator(restricted_operator, interpolation_matrix, source_basis_dofs, projected_collateral_basis, triangular, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseA projected
EmpiricalInterpolatedOperator.Not intended to be used directly. Instead use
projected.Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
This module provides some operators for finite volume discretizations.
-
class
pymor.operators.fv.DiffusionOperator(grid, boundary_info, diffusion_function=None, diffusion_constant=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorFinite Volume Diffusion
Operator.The operator is of the form
(Lu)(x) = c ∇ ⋅ [ d(x) ∇ u(x) ]
Parameters
- grid
- The
Gridover which to assemble the operator. - boundary_info
BoundaryInfofor the treatment of Dirichlet boundary conditions.- diffusion_function
- The scalar-valued
Functiond(x). IfNone, constant one is assumed. - diffusion_constant
- The constant
c. IfNone,cis set to one. - name
- Name of the operator.
Methods
Attributes
-
class
pymor.operators.fv.EngquistOsherFlux(flux, flux_derivative, gausspoints=5, intervals=1)[source]¶ Bases:
pymor.operators.fv.NumericalConvectiveFluxInterfaceEngquist-Osher numerical flux.
If
fis the analytical flux, andf'its derivative, the Engquist-Osher flux is given by:F(U_in, U_out, normal, vol) = vol * [c^+(U_in, normal) + c^-(U_out, normal)] U_in c^+(U_in, normal) = f(0)⋅normal + ∫ max(f'(s)⋅normal, 0) ds s=0 U_out c^-(U_out, normal) = ∫ min(f'(s)⋅normal, 0) ds s=0Parameters
Methods
EngquistOsherFluxevaluate_stage1,evaluate_stage2ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Parametricbuild_parameter_type,local_parameter,parse_parameter,strip_parameter
-
class
pymor.operators.fv.L2Product(grid, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorOperatorrepresenting the L2-product between finite volume functions.Parameters
- grid
- The
Gridfor which to assemble the product. - name
- The name of the product.
Methods
Attributes
-
class
pymor.operators.fv.L2ProductFunctional(grid, function=None, boundary_info=None, dirichlet_data=None, diffusion_function=None, diffusion_constant=None, neumann_data=None, order=1, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorFinite volume
Functionalrepresenting the inner product with an L2-Function.Additionally, boundary conditions can be enforced by providing
dirichlet_dataandneumann_datafunctions.Parameters
- grid
Gridfor which to assemble the functional.- function
- The
Functionwith which to take the inner product orNone. - boundary_info
BoundaryInfodetermining the Dirichlet and Neumann boundaries orNone. IfNone, no boundary treatment is performed.- dirichlet_data
Functionproviding the Dirichlet boundary values. IfNone, constant-zero boundary is assumed.- diffusion_function
- See
DiffusionOperator. Has to be specified in casedirichlet_datais given. - diffusion_constant
- See
DiffusionOperator. Has to be specified in casedirichlet_datais given. - neumann_data
Functionproviding the Neumann boundary values. IfNone, constant-zero is assumed.- order
- Order of the Gauss quadrature to use for numerical integration.
- name
- The name of the functional.
Methods
Attributes
-
class
pymor.operators.fv.LaxFriedrichsFlux(flux, lxf_lambda=1.0)[source]¶ Bases:
pymor.operators.fv.NumericalConvectiveFluxInterfaceLax-Friedrichs numerical flux.
If
fis the analytical flux, the Lax-Friedrichs fluxFis given by:F(U_in, U_out, normal, vol) = vol * [normal⋅(f(U_in) + f(U_out))/2 + (U_in - U_out)/(2*λ)]
Parameters
- flux
Functiondefining the analytical fluxf.- lxf_lambda
- The stabilization parameter
λ.
Methods
LaxFriedrichsFluxevaluate_stage1,evaluate_stage2ImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Parametricbuild_parameter_type,local_parameter,parse_parameter,strip_parameter
-
class
pymor.operators.fv.LinearAdvectionLaxFriedrichs(grid, boundary_info, velocity_field, lxf_lambda=1.0, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorLinear advection finite Volume
Operatorusing Lax-Friedrichs flux.The operator is of the form
L(u, mu)(x) = ∇ ⋅ (v(x, mu)⋅u(x))
See
LaxFriedrichsFluxfor the definition of the Lax-Friedrichs flux.Parameters
- grid
Gridover which to assemble the operator.- boundary_info
BoundaryInfodetermining the Dirichlet and Neumann boundaries.- velocity_field
Functiondefining the velocity fieldv.- lxf_lambda
- The stabilization parameter
λ. - name
- The name of the operator.
Methods
Attributes
-
class
pymor.operators.fv.NonlinearAdvectionOperator(grid, boundary_info, numerical_flux, dirichlet_data=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseNonlinear finite volume advection
Operator.The operator is of the form
L(u, mu)(x) = ∇ ⋅ f(u(x), mu)
Parameters
- grid
Gridfor which to evaluate the operator.- boundary_info
BoundaryInfodetermining the Dirichlet and Neumann boundaries.- numerical_flux
- The
NumericalConvectiveFluxto use. - dirichlet_data
Functionproviding the Dirichlet boundary values. IfNone, constant-zero boundary is assumed.- name
- The name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
with_(**kwargs)[source]¶ Returns a copy with changed attributes.
The default implementation is to create a new class instance with the given keyword arguments as arguments for
__init__. Missing arguments are obtained form instance attributes with the same name.Parameters
**kwargs- Names of attributes to change with their new values. Each attribute name
has to be contained in
with_arguments.
Returns
Copy of
selfwith changed attributes.
-
class
pymor.operators.fv.NumericalConvectiveFluxInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInterface for numerical convective fluxes for finite volume schemes.
Numerical fluxes defined by this interfaces are functions of the form
F(U_inner, U_outer, unit_outer_normal, edge_volume, mu).- The flux evaluation is vectorized and happens in two stages:
evaluate_stage1receives aNumPy arrayUof all values which appear asU_innerorU_outerfor all edges the flux shall be evaluated at and returns atupleofNumPy arrayseach of the same length asU.evaluate_stage2receives the reorderedstage1_datafor each edge as well as the unit outer normal and the volume of the edges.stage1_datais given as follows: IfR_lisl-th entry of thetuplereturned byevaluate_stage1, thel-th entryD_lof of thestage1_datatuple has the shape(num_edges, 2) + R_l.shape[1:]. If for edgekthe valuesU_innerandU_outerare thei-th andj-th value in theUarray provided toevaluate_stage1, we haveD_l[k, 0] == R_l[i], D_l[k, 1] == R_l[j].
evaluate_stage2returns aNumPy arrayof the flux evaluations for each edge.
Methods
-
class
pymor.operators.fv.SimplifiedEngquistOsherFlux(flux, flux_derivative)[source]¶ Bases:
pymor.operators.fv.NumericalConvectiveFluxInterfaceEngquist-Osher numerical flux. Simplified Implementation for special case.
For the definition of the Engquist-Osher flux see
EngquistOsherFlux. This class provides a faster and more accurate implementation for the special case thatf(0) == 0and the derivative offonly changes sign at0.Parameters
Methods
-
pymor.operators.fv.nonlinear_advection_engquist_osher_operator(grid, boundary_info, flux, flux_derivative, gausspoints=5, intervals=1, dirichlet_data=None, solver_options=None, name=None)[source]¶ Instantiate a
NonlinearAdvectionOperatorusingEngquistOsherFlux.
-
pymor.operators.fv.nonlinear_advection_lax_friedrichs_operator(grid, boundary_info, flux, lxf_lambda=1.0, dirichlet_data=None, solver_options=None, name=None)[source]¶ Instantiate a
NonlinearAdvectionOperatorusingLaxFriedrichsFlux.
-
pymor.operators.fv.nonlinear_advection_simplified_engquist_osher_operator(grid, boundary_info, flux, flux_derivative, dirichlet_data=None, solver_options=None, name=None)[source]¶ Instantiate a
NonlinearAdvectionOperatorusingSimplifiedEngquistOsherFlux.
-
class
pymor.operators.interfaces.OperatorInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInterface for
Parameterdependent discrete operators.An operator in pyMOR is simply a mapping which for any given
Parametermaps vectors from its sourceVectorSpaceto vectors in its rangeVectorSpace.Note that there is no special distinction between functionals and operators in pyMOR. A functional is simply an operator with
NumpyVectorSpace(1)as its rangeVectorSpace.Methods
Attributes
-
solver_options¶ If not
None, a dict which can contain the following keys:‘inverse’: solver options used for apply_inverse‘inverse_adjoint’: solver options used for apply_inverse_adjoint‘jacobian’: solver options for the operators returned by jacobian(has no effect for linear operators)If
solver_optionsisNoneor a dict entry is missing orNone, default options are used. The interpretation of the given solver options is up to the operator at hand. In general, values insolver_optionsshould either be strings (indicating a solver type) or dicts of options, usually with an entry'type'which specifies the solver type to use and further items which configure this solver.
-
linear¶ Trueif the operator is linear.
-
source¶ The source
VectorSpace.
-
range¶ The range
VectorSpace.
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply2(V, U, U_ind=None, V_ind=None, mu=None, product=None)[source]¶ Treat the operator as a 2-form by calculating (V, op(U)).
In general
op.apply2(V, U)is equivalent to:product.apply2(V, op.apply(U)).
In case no
producthas been specified,op.apply2(V, U)is equivialent to:V.dot(op.apply(U)).
In the latter case, assuming that
opis a linear operator given by multiplication with a matrix M, then:op.apply2(V, U) = V^T*M*U.
Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- V_ind
- The indices of the vectors in
Vto which the operator shall be applied (seeVectorArraydocumentation for further details). - U_ind
- The indices of the vectors in
Uto which the operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator. - product
- The inner product used in the expression
(V, op(U))given as anOperator. IfNone, the euclidean product is chosen.
Returns
A
NumPy arraywith shape(len(V_ind), len(U_ind))containing the 2-form evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, ind=None, mu=None, source_product=None, range_product=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the inverse adjoint operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - source_product
- See
apply_adjoint. - range_product
- See
apply_adjoint. - least_squares
If
True, solve the least squares problem:v = argmin ||op*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_vector(mu=None)[source]¶ Return a vector representation of a linear functional or vector operator.
This method may only be called on linear functionals, i.e. linear
OperatorswithNumpyVectorSpace(1)asrange, or on operators describing vectors, i.e. linearOperatorswithNumpyVectorSpace(1)assource.In the case of a functional, the identity
self.as_vector(mu).dot(U) == self.apply(U, mu)
holds, whereas in the case of a vector-like operator we have
self.as_vector(mu) == self.apply(NumpyVectorArray(1), mu).
Parameters
- mu
- The
Parameterfor which to return the vector representation.
Returns
- V
VectorArrayof length 1 containing the vector representation.Vbelongs toself.sourcefor functionals and toself.rangefor vector-like operators.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operator. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
pairwise_apply2(V, U, U_ind=None, V_ind=None, mu=None, product=None)[source]¶ Treat the operator as a 2-form by calculating (V, op(U)).
Same as
OperatorInterface.apply2, except that vectors fromVandUare applied in pairs.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- V_ind
- The indices of the vectors in
Vto which the operator shall be applied (seeVectorArraydocumentation for further details). - U_ind
- The indices of the vectors in
Uto which the operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator. - product
- The inner product used in the expression
(V, op(U))given as anOperator. IfNone, the euclidean product is chosen.
Returns
A
NumPy arraywith shape(len(V_ind),) == (len(U_ind),)containing the 2-form evaluations.
-
projected(range_basis, source_basis, product=None, name=None)[source]¶ Project the operator to subspaces of the source and range space.
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 restrictedspan(b_i) / spanc(c_i)(w.r.t. theb_i/c_ibases).How the projected operator is realized will depend on the implementation of the operator to project. While a projected
NumpyMatrixOperatorwill again be aNumpyMatrixOperator, only a genericProjectedOperatorcan be returned in general.A default implementation is provided in
OperatorBase.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. - name
- Name of the projected operator.
Returns
The projected
Operatorop_proj.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
-
class
pymor.operators.mpi.MPIOperator(obj_id, functional=False, vector=False, with_apply2=False, pickle_subtypes=True, array_type=<class 'pymor.vectorarrays.mpi.MPIVectorArray'>)[source]¶ Bases:
pymor.operators.basic.OperatorBaseMPI distributed
Operator.Given a single-rank implementation of an
Operator, this wrapper class uses the event loop frompymor.tools.mpito allow an MPI distributed usage of theOperator.Instances of
MPIOperatorcan be used on rank 0 like any other (non-distributed)Operator.Note, however, that the underlying
Operatorimplementation needs to be MPI aware. For instance, the operator’sapplymethod has to perform the necessary MPI communication to obtain all DOFs hosted on other MPI ranks which are required for the local operator evaluation.Instead of instantiating
MPIOperatordirectly, it is usually preferable to usempi_wrap_operatorinstead.Parameters
- obj_id
ObjectIdof the localOperatorson each rank.- functional
- Set to
Trueif the operator represents aFunctional. As required for functionals in pyMOR, this will set the range of the operator toNumpyVectorSpace(1)instead ofMPIVectorArray-based space. - vector
- Set to
Trueif the operator represents a (parametric) vector. As required for vector-likeOperatorsin pyMOR, this will set the source of the operator toNumpyVectorSpace(1)instead of anMPIVectorArray-based space. - with_apply2
- Set to
Trueif the operator implementation has its own MPI aware implementation ofapply2andpairwise_apply2. Otherwise, the default implementations usingapplyanddotwill be used. - pickle_subtypes
- If
pickle_subtypesisFalse, a unique identifier is computed for each local source/range subtype, which is then transferred to rank 0 instead of the true subtype. This allows the useage ofMPIVectorArrayeven when the local subtypes are not picklable. - array_type
- This class will be used to wrap the local
VectorArraysreturned by the local operators into an MPI distributedVectorArraymanaged from rank 0. By default,MPIVectorArraywill be used, other options areMPIVectorArrayAutoCommandMPIVectorArrayNoComm.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply2(V, U, U_ind=None, V_ind=None, mu=None, product=None)[source]¶ Treat the operator as a 2-form by calculating (V, op(U)).
In general
op.apply2(V, U)is equivalent to:product.apply2(V, op.apply(U)).
In case no
producthas been specified,op.apply2(V, U)is equivialent to:V.dot(op.apply(U)).
In the latter case, assuming that
opis a linear operator given by multiplication with a matrix M, then:op.apply2(V, U) = V^T*M*U.
Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- V_ind
- The indices of the vectors in
Vto which the operator shall be applied (seeVectorArraydocumentation for further details). - U_ind
- The indices of the vectors in
Uto which the operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator. - product
- The inner product used in the expression
(V, op(U))given as anOperator. IfNone, the euclidean product is chosen.
Returns
A
NumPy arraywith shape(len(V_ind), len(U_ind))containing the 2-form evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_vector(mu=None)[source]¶ Return a vector representation of a linear functional or vector operator.
This method may only be called on linear functionals, i.e. linear
OperatorswithNumpyVectorSpace(1)asrange, or on operators describing vectors, i.e. linearOperatorswithNumpyVectorSpace(1)assource.In the case of a functional, the identity
self.as_vector(mu).dot(U) == self.apply(U, mu)
holds, whereas in the case of a vector-like operator we have
self.as_vector(mu) == self.apply(NumpyVectorArray(1), mu).
Parameters
- mu
- The
Parameterfor which to return the vector representation.
Returns
- V
VectorArrayof length 1 containing the vector representation.Vbelongs toself.sourcefor functionals and toself.rangefor vector-like operators.
-
assemble(mu=None)[source]¶ Assemble the operator for a given parameter.
The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a
LincombOperatorwill try to form the linear combination of its operators, whereas an arbitrary operator might simply return aFixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on aParameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
Parameter-independent, assembled
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operator. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
jacobian(U, mu=None)[source]¶ Return the operator’s Jacobian as a new
Operator.Parameters
- U
- Length 1
VectorArraycontaining the vector for which to compute the Jacobian. - mu
- The
Parameterfor which to compute the Jacobian.
Returns
Linear
Operatorrepresenting the Jacobian.
-
pairwise_apply2(V, U, U_ind=None, V_ind=None, mu=None, product=None)[source]¶ Treat the operator as a 2-form by calculating (V, op(U)).
Same as
OperatorInterface.apply2, except that vectors fromVandUare applied in pairs.Parameters
- V
VectorArrayof the left arguments V.- U
VectorArrayof the right right arguments U.- V_ind
- The indices of the vectors in
Vto which the operator shall be applied (seeVectorArraydocumentation for further details). - U_ind
- The indices of the vectors in
Uto which the operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator. - product
- The inner product used in the expression
(V, op(U))given as anOperator. IfNone, the euclidean product is chosen.
Returns
A
NumPy arraywith shape(len(V_ind),) == (len(U_ind),)containing the 2-form evaluations.
-
restricted(dofs)[source]¶ Restrict the operator range to a given set of degrees of freedom.
This method returns a restricted version
restricted_opof the operator along with an arraysource_dofssuch that for anyVectorArrayUinself.sourcethe following is true:self.apply(U, mu).components(dofs) == restricted_op.apply(NumpyVectorArray(U.components(source_dofs)), mu))
Such an operator is mainly useful for
empirical interpolationwhere the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only fewsource_dofswill be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.Parameters
- dofs
- One-dimensional
NumPy arrayof degrees of freedom in the operatorrangeto which to restrict.
Returns
- restricted_op
- The restricted operator as defined above. The operator will have
NumpyVectorSpace(len(source_dofs))assourceandNumpyVectorSpace(len(dofs))asrange. - source_dofs
- One-dimensional
NumPy arrayof source degrees of freedom as defined above.
-
pymor.operators.mpi.mpi_wrap_operator(obj_id, functional=False, vector=False, with_apply2=False, pickle_subtypes=True, array_type=<class 'pymor.vectorarrays.mpi.MPIVectorArray'>)[source]¶ Wrap MPI distributed local
Operatorsto a globalOperatoron rank 0.Given MPI distributed local
Operatorsreferred to by theObjectIdobj_id, return a newOperatorwhich manages these distributed operators from rank 0. This is done by instantiatingMPIOperator. Additionally, the structure of the wrapped operators is preserved. E.g.LincombOperatorswill be wrapped as aLincombOperatorofMPIOperators.Parameters
See : class:
MPIOperator.Returns
The wrapped
Operator.
This module provides the following NumPy based Operators:
NumpyMatrixOperatorwraps a 2DNumPy arrayas anOperator.NumpyMatrixBasedOperatorshould be used as base class for allOperatorswhich assemble into aNumpyMatrixOperator.NumpyGenericOperatorwraps an arbitrary Python function betweenNumPy arraysas anOperator.
-
class
pymor.operators.numpy.NumpyGenericOperator(mapping, dim_source=1, dim_range=1, linear=False, parameter_type=None, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseWraps an arbitrary Python function between
NumPy arraysas a anOperator.Parameters
- mapping
The function to wrap. If
parameter_typeisNone, the function is of the formmapping(U)and is expected to be vectorized. In particular:mapping(U).shape == U.shape[:-1] + (dim_range,).
If
parameter_typeis notNone, the function has to have the signaturemapping(U, mu).- dim_source
- Dimension of the operator’s source.
- dim_range
- Dimension of the operator’s range.
- linear
- Set to
Trueif the providedmappingis linear. - parameter_type
- The
ParameterTypeof theParametersthe mapping accepts. - name
- Name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
class
pymor.operators.numpy.NumpyMatrixBasedOperator[source]¶ Bases:
pymor.operators.basic.OperatorBaseBase class for operators which assemble into a
NumpyMatrixOperator.Methods
Attributes
-
sparse¶ Trueif the operator assembles into a sparse matrix,Falseif the operator assembles into a dense matrix,Noneif unknown.
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_vector(mu=None)[source]¶ Return a vector representation of a linear functional or vector operator.
This method may only be called on linear functionals, i.e. linear
OperatorswithNumpyVectorSpace(1)asrange, or on operators describing vectors, i.e. linearOperatorswithNumpyVectorSpace(1)assource.In the case of a functional, the identity
self.as_vector(mu).dot(U) == self.apply(U, mu)
holds, whereas in the case of a vector-like operator we have
self.as_vector(mu) == self.apply(NumpyVectorArray(1), mu).
Parameters
- mu
- The
Parameterfor which to return the vector representation.
Returns
- V
VectorArrayof length 1 containing the vector representation.Vbelongs toself.sourcefor functionals and toself.rangefor vector-like operators.
-
assemble(mu=None)[source]¶ Assembles the operator for a given
Parameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
The assembled parameter independent
Operator.
-
export_matrix(filename, matrix_name=None, output_format='matlab', mu=None)[source]¶ Save the matrix of the operator to a file.
Parameters
- filename
- Name of output file.
- matrix_name
- The name, the output matrix is given. (Comment field is used in
case of Matrix Market output_format.) If
None, theOperator‘snameis used. - output_format
- Output file format. Either
matlabormatrixmarket.
-
-
class
pymor.operators.numpy.NumpyMatrixOperator(matrix, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixBasedOperatorWraps a 2D
NumPy arrayas anOperator.Parameters
- matrix
- The
NumPy arraywhich is to be wrapped. - name
- Name of the operator.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
apply_inverse_adjoint(U, ind=None, mu=None, source_product=None, range_product=None, least_squares=False)[source]¶ Apply the inverse adjoint operator.
Parameters
- U
VectorArrayof vectors to which the inverse adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the inverse adjoint operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse adjoint operator. - source_product
- See
apply_adjoint. - range_product
- See
apply_adjoint. - least_squares
If
True, solve the least squares problem:v = argmin ||op*(v) - u||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse adjoint operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_vector(mu=None)[source]¶ Return a vector representation of a linear functional or vector operator.
This method may only be called on linear functionals, i.e. linear
OperatorswithNumpyVectorSpace(1)asrange, or on operators describing vectors, i.e. linearOperatorswithNumpyVectorSpace(1)assource.In the case of a functional, the identity
self.as_vector(mu).dot(U) == self.apply(U, mu)
holds, whereas in the case of a vector-like operator we have
self.as_vector(mu) == self.apply(NumpyVectorArray(1), mu).
Parameters
- mu
- The
Parameterfor which to return the vector representation.
Returns
- V
VectorArrayof length 1 containing the vector representation.Vbelongs toself.sourcefor functionals and toself.rangefor vector-like operators.
-
assemble(mu=None)[source]¶ Assembles the operator for a given
Parameter.Parameters
- mu
- The
Parameterfor which to assemble the operator.
Returns
The assembled parameter independent
Operator.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operator. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
projected_to_subbasis(dim_range=None, dim_source=None, name=None)[source]¶ Project the operator to a subbasis.
The purpose of this method is to further project an operator that has been obtained through
projectedto subbases of the original projection bases, i.e.op.projected(r_basis, s_basis, prod).projected_to_subbasis(dim_range, dim_source)
should be the same as
op.projected(r_basis.copy(range(dim_range)), s_basis.copy(range(dim_source)), prod)
For a
NumpyMatrixOperatorthis amounts to extracting the upper-left (dim_range, dim_source) corner of the matrix it wraps.Parameters
- dim_range
- Dimension of the range subbasis.
- dim_source
- Dimension of the source subbasis.
Returns
The projected
Operator.
-
pymor.operators.numpy._apply_inverse(matrix, V, options=None)[source]¶ Solve linear equation system.
Applies the inverse of
matrixto the row vectors inV.See
dense_optionsfor documentation of all possible options for sparse matrices.See
sparse_optionsfor documentation of all possible options for sparse matrices.This method is called by
NumpyMatrixOperator.apply_inverseand usually should not be used directly.Parameters
- matrix
- The left-hand side of the linear equation systems to
solve as a
NumPymatrix. - V
- 2-dimensional
NumPy arraycontaining as row vectors the right-hand sides of the linear equation systems to solve. - options
- The solver options to use. (See
_options.)
Returns
NumPy arrayof the solution vectors.
-
pymor.operators.numpy._options(matrix=None, sparse=None)[source]¶ Returns possible
solver_options(with default values) for a givenNumPymatrix.See
dense_optionsfor documentation of all possible options for dense matrices.See
sparse_optionsfor documentation of all possible options for sparse matrices.Parameters
- matrix
- The matrix for which to return the options.
- sparse
- Instead of providing a matrix via the
matrixargument,sparsecan be set toTrueorFalseto request the invert options for sparse or dense matrices.
Returns
A tuple of all possible
solver_options.
-
pymor.operators.numpy.dense_options(default_solver='solve', default_least_squares_solver='least_squares_lstsq', least_squares_lstsq_rcond=-1.0)[source]¶ Returns possible
solver_options(with default values) for denseNumPymatricies.Parameters
- default_solver
- Default dense solver to use (solve, least_squares_lstsq, generic_lgmres, least_squares_generic_lsmr, least_squares_generic_lsqr).
- default_least_squares_solver
- Default solver to use for least squares problems (least_squares_lstsq, least_squares_generic_lsmr, least_squares_generic_lsqr).
- least_squares_lstsq_rcond
- See
numpy.linalg.lstsq.
Returns
A tuple of possible values for
solver_options.Defaults
default_solver, default_least_squares_solver, least_squares_lstsq_rcond (see
pymor.core.defaults)
-
pymor.operators.numpy.sparse_options(default_solver='spsolve', default_least_squares_solver='least_squares_lsmr', bicgstab_tol=1e-15, bicgstab_maxiter=None, spilu_drop_tol=0.0001, spilu_fill_factor=10, spilu_drop_rule='basic,area', spilu_permc_spec='COLAMD', spsolve_permc_spec='COLAMD', spsolve_keep_factorization=True, 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, pyamg_tol=1e-05, pyamg_maxiter=400, pyamg_verb=False, pyamg_rs_strength=('classical', {'theta': 0.25}), pyamg_rs_CF='RS', pyamg_rs_presmoother=('gauss_seidel', {'sweep': 'symmetric'}), pyamg_rs_postsmoother=('gauss_seidel', {'sweep': 'symmetric'}), pyamg_rs_max_levels=10, pyamg_rs_max_coarse=500, pyamg_rs_coarse_solver='pinv2', pyamg_rs_cycle='V', pyamg_rs_accel=None, pyamg_rs_tol=1e-05, pyamg_rs_maxiter=100, pyamg_sa_symmetry='hermitian', pyamg_sa_strength='symmetric', pyamg_sa_aggregate='standard', pyamg_sa_smooth=('jacobi', {'omega': 1.3333333333333333}), pyamg_sa_presmoother=('block_gauss_seidel', {'sweep': 'symmetric'}), pyamg_sa_postsmoother=('block_gauss_seidel', {'sweep': 'symmetric'}), pyamg_sa_improve_candidates=[('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4}), None], pyamg_sa_max_levels=10, pyamg_sa_max_coarse=500, pyamg_sa_diagonal_dominance=False, pyamg_sa_coarse_solver='pinv2', pyamg_sa_cycle='V', pyamg_sa_accel=None, pyamg_sa_tol=1e-05, pyamg_sa_maxiter=100)[source]¶ Returns possible
solver_options(with default values) for sparseNumPymatricies.Parameters
- default_solver
- Default sparse solver to use (spsolve, bicgstab, bicgstab_spilu, pyamg, pyamg_rs, pyamg_sa, generic_lgmres, least_squares_lsmr, least_squares_lsqr).
- default_least_squares_solver
- Default solver to use for least squares problems (least_squares_lsmr, least_squares_lsqr).
- bicgstab_tol
- See
scipy.sparse.linalg.bicgstab. - bicgstab_maxiter
- See
scipy.sparse.linalg.bicgstab. - spilu_drop_tol
- See
scipy.sparse.linalg.spilu. - spilu_fill_factor
- See
scipy.sparse.linalg.spilu. - spilu_drop_rule
- See
scipy.sparse.linalg.spilu. - spilu_permc_spec
- See
scipy.sparse.linalg.spilu. - spsolve_permc_spec
- See
scipy.sparse.linalg.spsolve. - lgmres_tol
- See
scipy.sparse.linalg.lgmres. - lgmres_maxiter
- See
scipy.sparse.linalg.lgmres. - lgmres_inner_m
- See
scipy.sparse.linalg.lgmres. - lgmres_outer_k
- See
scipy.sparse.linalg.lgmres. - least_squares_lsmr_damp
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_atol
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_btol
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_conlim
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_maxiter
- See
scipy.sparse.linalg.lsmr. - least_squares_lsmr_show
- See
scipy.sparse.linalg.lsmr. - least_squares_lsqr_damp
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_atol
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_btol
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_conlim
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_iter_lim
- See
scipy.sparse.linalg.lsqr. - least_squares_lsqr_show
- See
scipy.sparse.linalg.lsqr. - pyamg_tol
- Tolerance for PyAMG blackbox solver.
- pyamg_maxiter
- Maximum iterations for PyAMG blackbox solver.
- pyamg_verb
- Verbosity flag for PyAMG blackbox solver.
- pyamg_rs_strength
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_CF
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_presmoother
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_postsmoother
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_max_levels
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_max_coarse
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_coarse_solver
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_cycle
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_accel
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_tol
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_rs_maxiter
- Parameter for PyAMG Ruge-Stuben solver.
- pyamg_sa_symmetry
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_strength
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_aggregate
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_smooth
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_presmoother
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_postsmoother
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_improve_candidates
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_max_levels
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_max_coarse
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_diagonal_dominance
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_coarse_solver
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_cycle
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_accel
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_tol
- Parameter for PyAMG Smoothed-Aggregation solver.
- pyamg_sa_maxiter
- Parameter for PyAMG Smoothed-Aggregation solver.
Returns
A tuple of all possible
solver_options.Defaults
default_solver, default_least_squares_solver, bicgstab_tol, bicgstab_maxiter, spilu_drop_tol, spilu_fill_factor, spilu_drop_rule, spilu_permc_spec, spsolve_permc_spec, spsolve_keep_factorization, 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, pyamg_tol, pyamg_maxiter, pyamg_verb, pyamg_rs_strength, pyamg_rs_CF, pyamg_rs_postsmoother, pyamg_rs_max_levels, pyamg_rs_max_coarse, pyamg_rs_coarse_solver, pyamg_rs_cycle, pyamg_rs_accel, pyamg_rs_tol, pyamg_rs_maxiter, pyamg_sa_symmetry, pyamg_sa_strength, pyamg_sa_aggregate, pyamg_sa_smooth, pyamg_sa_presmoother, pyamg_sa_postsmoother, pyamg_sa_improve_candidates, pyamg_sa_max_levels, pyamg_sa_max_coarse, pyamg_sa_diagonal_dominance, pyamg_sa_coarse_solver, pyamg_sa_cycle, pyamg_sa_accel, pyamg_sa_tol, pyamg_sa_maxiter (see
pymor.core.defaults)
pymor.parallel package¶
Submodules¶
This module contains a base class for implementing WorkerPoolInterface.
-
class
pymor.parallel.basic.RemoteObject(pool, remote_id, uid=None)[source]¶ Bases:
pymor.parallel.interfaces.RemoteObjectInterfaceMethods
RemoteObjectInterfaceremoveAttributes
RemoteObjectInterfaceremoved
-
class
pymor.parallel.basic.WorkerPoolBase[source]¶ Bases:
pymor.parallel.basic.WorkerPoolDefaultImplementations,pymor.parallel.interfaces.WorkerPoolInterfaceMethods
Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid-
apply(function, *args, **kwargs)[source]¶ Apply function in parallel on each worker.
This calls
functionon each worker in parallel, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by worker number (from
0tolen(pool) - 1).
-
apply_only(function, worker, *args, **kwargs)[source]¶ Apply function on a single worker.
This calls
functionon on the worker with numberworker, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute.
- worker
- The worker on which to execute the function. (Number between
0andlen(pool) - 1.) - args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
Return value of the function execution.
-
map(function, *args, **kwargs)[source]¶ Parallel version of the builtin
mapfunction.Each positional argument (after
function) must be a sequence of same length n.mapcallsfunctionin parallel on each of these n positional argument combinations, always passingkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The sequences of positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by the sequence of positional arguments.
-
push(obj)[source]¶ Push a copy of
objto all workers of the pool.A
RemoteObjectis returned as a handle to the pushed object. This object can be used as a keyword argument toapply,apply_only,mapand will then be transparently mapped to the respective copy of the pushed object on the worker.Immutableobjects will be pushed only once. If the sameimmutableobject is pushed a second time, the returnedRemoteObjectwill refer to the already transferred copy. It is therefore safe to usepushto ensure that a givenimmutableobject is available on the worker. No unnecessary copies will be created.Parameters
- obj
- The object to push to all workers.
Returns
A
RemoteObjectreferring to the pushed data.
-
-
class
pymor.parallel.basic.WorkerPoolDefaultImplementations[source]¶ Bases:
objectMethods
WorkerPoolDefaultImplementationsscatter_array,scatter_list
-
pymor.parallel.default.new_parallel_pool(ipython_num_engines=None, ipython_profile=None, allow_mpi=True)[source]¶ Creates a new default
WorkerPool.If
ipython_num_enginesoripython_profileis provided as an argument or set as adefault, anIPythonPoolWorkerPoolwill be created using the given parameters via theipclusterscript.Otherwise, when
allow_mpiisTrueand an MPI parallel run is detected, anMPIPoolWorkerPoolwill be created.Otherwise, a sequential run is assumed and
pymor.parallel.dummy.dummy_poolis returned.Defaults
ipython_num_engines, ipython_profile, allow_mpi (see
pymor.core.defaults)
-
class
pymor.parallel.dummy.DummyPool[source]¶ Bases:
pymor.parallel.interfaces.WorkerPoolInterfaceMethods
Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid-
apply(function, *args, **kwargs)[source]¶ Apply function in parallel on each worker.
This calls
functionon each worker in parallel, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by worker number (from
0tolen(pool) - 1).
-
apply_only(function, worker, *args, **kwargs)[source]¶ Apply function on a single worker.
This calls
functionon on the worker with numberworker, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute.
- worker
- The worker on which to execute the function. (Number between
0andlen(pool) - 1.) - args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
Return value of the function execution.
-
map(function, *args, **kwargs)[source]¶ Parallel version of the builtin
mapfunction.Each positional argument (after
function) must be a sequence of same length n.mapcallsfunctionin parallel on each of these n positional argument combinations, always passingkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The sequences of positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by the sequence of positional arguments.
-
push(obj)[source]¶ Push a copy of
objto all workers of the pool.A
RemoteObjectis returned as a handle to the pushed object. This object can be used as a keyword argument toapply,apply_only,mapand will then be transparently mapped to the respective copy of the pushed object on the worker.Immutableobjects will be pushed only once. If the sameimmutableobject is pushed a second time, the returnedRemoteObjectwill refer to the already transferred copy. It is therefore safe to usepushto ensure that a givenimmutableobject is available on the worker. No unnecessary copies will be created.Parameters
- obj
- The object to push to all workers.
Returns
A
RemoteObjectreferring to the pushed data.
-
scatter_array(U, copy=True)[source]¶ Distribute
VectorArrayevenly among the workers.On each worker a
VectorArrayis created holding an (up to rounding) equal amount of vectors ofU. The returnedRemoteObjecttherefore refers to different data on each of the workers.Parameters
- U
- The
VectorArrayto distribute. - copy
- If
False,Uwill be emptied during distribution of the vectors.
Returns
A
RemoteObjectreferring to the scattered data.
-
scatter_list(l)[source]¶ Distribute list of objects evenly among the workers.
On each worker a
listis created holding an (up to rounding) equal amount of objects ofl. The returnedRemoteObjecttherefore refers to different data on each of the workers.Parameters
- l
- The list (sequence) of objects to distribute.
Returns
A
RemoteObjectreferring to the scattered data.
-
-
class
pymor.parallel.dummy.DummyRemoteObject(obj)[source]¶ Bases:
pymor.parallel.interfaces.RemoteObjectInterfaceMethods
RemoteObjectInterfaceremoveAttributes
RemoteObjectInterfaceremoved
-
class
pymor.parallel.interfaces.RemoteObjectInterface[source]¶ Bases:
objectHandle to remote data on the workers of a
WorkerPool.See documentation of
WorkerPoolInterfacefor usage of these handles in conjunction withapply,scatter_array,scatter_list.Remote objects can be used as a context manager: when leaving the context, the remote object’s
removemethod is called to ensure proper cleanup of remote resources.Methods
RemoteObjectInterfaceremoveAttributes
RemoteObjectInterfaceremoved-
remove()[source]¶ Remove the remote object from the workers.
Remove the object this handle refers to from all workers. Note that the object will only be destroyed if no other object on the worker holds a reference to that object. Moreover,
immutableobjects will only be destroyed ifremovehas been called on allRemoteObjectswhich refer to the object (seepush).
-
-
class
pymor.parallel.interfaces.WorkerPoolInterface[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceInterface for parallel worker pools.
WorkerPoolsallow to easily parallelize algorithms which involve no or little communication between the workers at runtime. The interface methods give the user simple means to distribute data to workers (push,scatter_array,scatter_list) and execute functions on the distributed data in parallel (apply), collecting the return values from each function call. A single worker can be instructed to execute a function using theWorkerPoolInterface.apply_onlymethod. Finally, a parallelizedmapfunction is available, which automatically scatters the data among the workers.All operations are performed synchronously.
Methods
Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid-
apply(function, *args, **kwargs)[source]¶ Apply function in parallel on each worker.
This calls
functionon each worker in parallel, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by worker number (from
0tolen(pool) - 1).
-
apply_only(function, worker, *args, **kwargs)[source]¶ Apply function on a single worker.
This calls
functionon on the worker with numberworker, passingargsas positional andkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute.
- worker
- The worker on which to execute the function. (Number between
0andlen(pool) - 1.) - args
- The positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
Return value of the function execution.
-
map(function, *args, **kwargs)[source]¶ Parallel version of the builtin
mapfunction.Each positional argument (after
function) must be a sequence of same length n.mapcallsfunctionin parallel on each of these n positional argument combinations, always passingkwargsas keyword arguments. Keyword arguments which areRemoteObjectsare automatically mapped to the respective object on the worker. Moreover, keyword arguments which areimmutableobjects that have already been pushed to the workers will not be transmitted again. (Immutableobjects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)Parameters
- function
- The function to execute on each worker.
- args
- The sequences of positional arguments for
function. - kwargs
- The keyword arguments for
function.
Returns
List of return values of the function executions, ordered by the sequence of positional arguments.
-
push(obj)[source]¶ Push a copy of
objto all workers of the pool.A
RemoteObjectis returned as a handle to the pushed object. This object can be used as a keyword argument toapply,apply_only,mapand will then be transparently mapped to the respective copy of the pushed object on the worker.Immutableobjects will be pushed only once. If the sameimmutableobject is pushed a second time, the returnedRemoteObjectwill refer to the already transferred copy. It is therefore safe to usepushto ensure that a givenimmutableobject is available on the worker. No unnecessary copies will be created.Parameters
- obj
- The object to push to all workers.
Returns
A
RemoteObjectreferring to the pushed data.
-
scatter_array(U, copy=True)[source]¶ Distribute
VectorArrayevenly among the workers.On each worker a
VectorArrayis created holding an (up to rounding) equal amount of vectors ofU. The returnedRemoteObjecttherefore refers to different data on each of the workers.Parameters
- U
- The
VectorArrayto distribute. - copy
- If
False,Uwill be emptied during distribution of the vectors.
Returns
A
RemoteObjectreferring to the scattered data.
-
scatter_list(l)[source]¶ Distribute list of objects evenly among the workers.
On each worker a
listis created holding an (up to rounding) equal amount of objects ofl. The returnedRemoteObjecttherefore refers to different data on each of the workers.Parameters
- l
- The list (sequence) of objects to distribute.
Returns
A
RemoteObjectreferring to the scattered data.
-
-
class
pymor.parallel.ipython.IPythonPool(num_engines=None, **kwargs)[source]¶ Bases:
pymor.parallel.basic.WorkerPoolBaseWorkerPoolbased on the IPython parallel computing features.Parameters
- num_engines
- Number of IPython engines to use. If
None, all available engines are used. - kwargs
- Keyword arguments used to instantiate the IPython cluster client.
Methods
Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.parallel.ipython.RemoteId[source]¶ Bases:
intMethods
intbit_length,conjugate,__new__,__trunc__Attributes
intdenominator,imag,numerator,real
-
class
pymor.parallel.ipython.new_ipcluster_pool(profile=None, cluster_id=None, num_engines=None, ipython_dir=None, min_wait=1, timeout=60)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceCreate a new IPython parallel cluster and connect to it.
This context manager can be used to create an
IPythonPoolWorkerPool. When entering the context a new IPython cluster is created using theipclusterscript and anIPythonPoolis instantiated for the newly created cluster. When leaving the context the cluster is shut down.Parameters
- profile
- Passed as
--profileparameter to theipclusterscript. - cluster_id
- Passed as
--cluster-idparameter to theipclusterscript. - nun_engines
- Passed as
--nparameter to theipclusterscript. - ipython_dir
- Passed as
--ipython-dirparameter to theipclusterscript. - min_wait
- Wait at least this many seconds before trying to connect to the new cluster.
- timeout
- Wait at most this many seconds for all Ipython cluster engines to become available.
Methods
BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.parallel.manager.RemoteObjectManager[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceA simple context manager to keep track of
RemoteObjects.When leaving this context, all
RemoteObjectsthat have beenmanagedby this object will beremoved.Methods
RemoteObjectManagermanage,remove_objectsBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid-
manage(remote_object)[source]¶ Add a
RemoteObjectto the list of managed objects.Parameters
- remote_object
- The object to add to the list.
Returns
remote_object
-
-
class
pymor.parallel.mpi.MPIPool[source]¶ Bases:
pymor.parallel.basic.WorkerPoolBaseWorkerPoolbased pyMOR’s MPIevent loop.Methods
Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid
pymor.parameters package¶
Submodules¶
This module contains the implementation of pyMOR’s parameter handling facilities.
A Parameter in pyMOR is basically a dict of NumPy arrays. Each item of the
dict is called a parameter component. The ParameterType of a Parameter is the dict
of the shapes of the parameter components, i.e.
mu.parameter_type['component'] == mu['component'].shape
Classes which represent mathematical objects depending on parameters, e.g. Functions,
Operators, Discretizations derive from the Parametric mixin. Each Parametric
object has a parameter_type attribute holding the ParameterType
of the Parameters the object’s evaluate, apply, solve, etc. methods expect.
Note that the ParameterType of the given Parameter is allowed to be a
superset of the object’s ParameterType.
The ParameterType of a Parametric object is determined in its __init__
method by calling build_parameter_type which computes the
ParameterType as the union of the ParameterTypes of the objects given to the
method. This way, e.g., an Operator can inherit the ParameterTypes of the
data functions it depends upon.
A Parametric object can have a ParameterSpace assigned to it by setting the
parameter_space attribute (the ParameterType of the space
has to agree with the ParameterType of the object). The
parse_parameter method parses a user input according to
the object’s ParameterType to make it a Parameter (e.g. if the ParameterType
consists of a single one-dimensional component, the user can simply supply a list
of numbers of the right length). Moreover, when given a Parameter,
parse_parameter ensures the Parameter has an appropriate
ParameterType. The local_parameter method is used to extract
the local parameter components of the given Parameter and performs some name
mapping (see the documentation of build_parameter_type for
details).
-
class
pymor.parameters.base.Parameter(v)[source]¶ Bases:
dictClass representing a parameter.
A
Parameteris simply adictwhere each key is a string and each value is aNumPy array. We call an item of the dictionary a parameter component.A
Parameterdiffers from an ordinarydictin the following ways:- It is ensured that each value is a
NumPy array. - We overwrite
copyto ensure that not only thedictbut also theNumPy arraysare copied. - The
allclosemethod allows to compareParametersfor equality in a mathematically meaningful way. - Each
Parameterhas asidproperty providing a unique state id. - We override
__str__to ensure alphanumerical ordering of the keys and pretty printing of the values. - The
parameter_typeproperty can be used to obtain theParameterTypeof the parameter. - Use
from_parameter_typeto construct aParameterfrom aParameterTypeand user supplied input.
Parameters
- v
- Anything that
dictaccepts for the construction of a dictionary.
Methods
Parameterallclose,clear,copy,from_parameter_type,fromkeys,pop,popitem,updatedictget,has_key,items,iteritems,iterkeys,itervalues,keys,setdefault,values,viewitems,viewkeys,viewvalues,__contains__,__getitem__,__new__,__sizeof__Attributes
Parameterparameter_type,sid-
parameter_type¶ The
ParameterTypeof theParameter.
-
allclose(mu)[source]¶ Compare two
Parametersusingfloat_cmp_all.Parameters
- mu
- The
Parameterwith which to compare.
Returns
Trueif bothParametershave the sameParameterTypeand all parameter components are almost equal, elseFalse.
-
classmethod
from_parameter_type(mu, parameter_type=None)[source]¶ Takes a user input
muand interprets it as aParameteraccording to the givenParameterType.Depending on the
ParameterType,mucan be given as aParameter, dict, tuple, list, array or scalar.Parameters
- mu
- The user input which shall be interpreted as a
Parameter. - parameter_type
- The
ParameterTypew.r.t. whichmuis to be interpreted.
Returns
The resulting
Parameter.Raises
- ValueError
- Is raised if
mucannot be interpreted as aParameterofParameterTypeparameter_type.
- It is ensured that each value is a
-
class
pymor.parameters.base.ParameterType(t)[source]¶ Bases:
dictClass representing a parameter type.
A parameter type is simply a dictionary with strings as keys and tuples of natural numbers as values. The keys are the names of the parameter components and the tuples their expected shape (compare
Parameter).Apart from checking the correct format of its values, the only difference between a
ParameterTypeand an ordinarydictis, thatParameterTypeorders its keys alphabetically.Parameters
- t
- If
tis an object with aparameter_typeattribute, a copy of thisParameterTypeis created. Otherwise,tcan be anything from which adictcan be constructed.
Methods
ParameterTypeclear,copy,fromkeys,items,iteritems,iterkeys,itervalues,keys,pop,popitem,update,valuesdictget,has_key,setdefault,viewitems,viewkeys,viewvalues,__contains__,__getitem__,__new__,__sizeof__Attributes
ParameterTypesid
-
class
pymor.parameters.base.Parametric[source]¶ Bases:
objectMixin class for objects representing mathematical entities depending on a
Parameter.Each such object has a
ParameterTypestored in theparameter_typeattribute, which should be set by the implementor during__init__using thebuild_parameter_typemethod. Methods expecting theParameter(typicallyevaluate,apply,solve, etc. ..) should accept an optional argumentmudefaulting toNone. This argumentmushould then be fed intoparse_parameterto obtain aParameterof correctParameterTypefrom the (user supplied) inputmu. The local parameter components (seebuild_parameter_type) can be extracted usinglocal_type.Attributes
Parametricparameter_local_type,parameter_space,parameter_type,parametric-
parameter_type¶ The
ParameterTypeof theParametersthe object expects.
-
parameter_local_type¶ The
ParameterTypeof the parameter components which are introduced by the object itself and are not inherited by other objects it depends on. (Seebuild_parameter_type.)
-
parameter_space¶ ParameterSpacethe parameters are expected to lie in orNone.
-
parametric¶ Trueif the object really depends on a parameter, i.e.parameter_typeis not empty.
-
build_parameter_type(local_type=None, global_names=None, local_global=False, inherits=None, provides=None)[source]¶ Builds the
ParameterTypeof the object. Should be called by__init__.The
ParameterTypeof aParametricobject is determined by the parameter components the object itself requires for evaluation, and by the parameter components required by the objects the object depends upon for evaluation. We speak of local and inherited parameter components. TheParameterTypeof the local parameter components are provided via thelocal_typeparameter, whereas theParametricobjects from which parameter components are inherited are provided as theinheritsparameter.Since the implementor does not necessarily know the future use of the object, a mapping between the names of the local parameter components and their intended global names (from the user perspective) can be provided via the
global_namesparameter. This mapping of names will be usually provided by the user when instantiating the class. (E.g. aFunctionevaluating x->x^a could depend on a local parameter component named ‘base’, whereas the user wishes to name the component ‘decay_rate’.) If such a mapping is not desired, thelocal_globalparameter must be set toTrue. (To later extract the local parameter components with their local names from a givenParameteruse thelocal_parametermethod.)After the name mapping, all parameter components (local or inherited by one of the objects provided via
inherits) with the same name are treated as identical and are thus required to have the same shapes. The object’sParameterTypeis then made up by the shapes of all parameter components appearing.Additionally components of the resulting
ParameterTypecan be removed by specifying them via theprovidesdict. The idea is that the object itself may provide parameter components to the inherited objects which thus should not become part of the object’s own parameter type. (A typical application would beInstationaryDiscretization, which provides a time parameter component to its (time-dependent) operators during time-stepping.)Note
As parameter components of the
ParameterTypesof different objects are treated as equal if they have the same name, renaming a local parameter component is not merely a convenience feature but can also have a semantic meaning by identifying local parameter components with inherited ones.Parameters
- local_type
ParameterTypeof the local parameter components.- global_names
- A
dictof the form{'localname': 'globalname', ...}defining a name mapping specifying global parameter component names for each key oflocal_type. IfNoneandlocal_typeis notNone,local_globalmust be set toTrue. - local_global
- If
True,treat the names of the local parameter components as global names of these components. In this case,global_namesmust beNone. - inherits
- Iterable where each entry is a
Parametricobject whoseParameterTypeshall become part of the builtParameterType. - provides
Dictof parameter component names and their shapes which are provided by the object itself to the objects in theinheritedlist. The parameter components listed here will not become part of the object’sParameterType.
-
local_parameter(mu)[source]¶ Extract the local parameter components with their local names from a given
Parameter.See
build_parameter_typefor details.
-
parse_parameter(mu)[source]¶ Interpret a user supplied parameter
muas aParameter.If
muis not already aParameter,Parameter.from_parameter_typeis used, to makemua parameter of the correctParameterType. Ifmuis already aParameter, it is checked if itsParameterTypematches our own. (It is actually allowed that theParameterTypeofmuis a superset of our ownParameterTypein the obvious sense.)Parameters
- mu
- The input to parse as a
Parameter.
-
strip_parameter(mu)[source]¶ Remove all components of the
Parametermuwhich are not part of the object’sParameterType.Otherwise
strip_parameterbehaves likeparse_parameter.This method is mainly useful for caching where the key should only contain the relevant parameter components.
-
-
class
pymor.parameters.functionals.ExpressionParameterFunctional(expression, parameter_type, name=None)[source]¶ Bases:
pymor.parameters.functionals.GenericParameterFunctionalTurns a Python expression given as a string into a
ParameterFunctional.Some
NumPyarithmetic functions likesin,log,minare supported. For a full list see thefunctionsclass attribute.Warning
evalis used to evaluate the given expression. Using this class with expression strings from untrusted sources will cause mayhem and destruction!Parameters
- expression
- A Python expression in the parameter components of the given
parameter_type. - parameter_type
- The
ParameterTypeof theParametersthe functional expects.
Methods
-
class
pymor.parameters.functionals.GenericParameterFunctional(mapping, parameter_type, name=None)[source]¶ Bases:
pymor.parameters.interfaces.ParameterFunctionalInterfaceA wrapper making an arbitrary Python function a
ParameterFunctionalNote that a GenericParameterFunctional can only be
pickledif the function it is wrapping can be pickled. For this reason, it is usually preferable to useExpressionParameterFunctionalinstead ofGenericParameterFunctional.Parameters
- parameter_type
- The
ParameterTypeof theParametersthe functional expects. - mapping
- The function to wrap. The function has signature
mapping(mu). - name
- The name of the functional.
Methods
-
class
pymor.parameters.functionals.ProductParameterFunctional(factors, name=None)[source]¶ Bases:
pymor.parameters.interfaces.ParameterFunctionalInterfaceForms the product of a list of
ParameterFunctionalsor numbers.Parameters
- factors
- A list of
ParameterFunctionalsor numbers. - name
- Name of the functional.
Methods
-
class
pymor.parameters.functionals.ProjectionParameterFunctional(component_name, component_shape, coordinates=(), name=None)[source]¶ Bases:
pymor.parameters.interfaces.ParameterFunctionalInterfaceParameterFunctionalreturning a component of the given parameter.For given parameter
mu, this functional evaluates tomu[component_name][coordinates]
Parameters
- component_name
- The name of the parameter component to return.
- component_shape
- The shape of the parameter component.
- coordinates
- See above.
- name
- Name of the functional.
Methods
-
class
pymor.parameters.interfaces.ParameterFunctionalInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterface,pymor.parameters.base.ParametricInterface for
Parameterfunctionals.A parameter functional is simply a function mapping a
Parameterto a number.Methods
-
class
pymor.parameters.interfaces.ParameterSpaceInterface[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInterface for
Parameterspaces.Methods
ParameterSpaceInterfacecontainsImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
ParameterSpaceInterfaceparameter_typeImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
parameter_type¶ ParameterTypeof the space.
-
-
class
pymor.parameters.spaces.CubicParameterSpace(parameter_type, minimum=None, maximum=None, ranges=None)[source]¶ Bases:
pymor.parameters.interfaces.ParameterSpaceInterfaceSimple
ParameterSpacewhere each summand is an n-cube.Parameters
- parameter_type
- The
ParameterTypeof the space. - minimum
- The minimum for each matrix entry of each
Parametercomponent. Must beNoneifrangesis specified. - maximum
- The maximum for each matrix entry of each
Parametercomponent. Must beNoneifrangesis specified. - ranges
- dict whose keys agree with
parameter_typeand whose values are tuples (min, max) specifying the minimum and maximum of each matrix entry of correspondingParametercomponent. Must beNoneifminimumandmaximumare specified.
Methods
Attributes
ParameterSpaceInterfaceparameter_typeImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid-
sample_randomly(count=None, random_state=None, seed=None)[source]¶ Randomly sample
Parametersfrom the space.Warning
When neither
random_statenorseedare specified, repeated calls to this method will return the same sequence of parameters!Parameters
- count
Noneor number of random parameters (see below).- random_state
RandomStateto use for sampling. IfNone, a new random state is generated usingseedas random seed.- seed
- Random seed to use. If
None, thedefaultrandom seed is used.
Returns
If
countisNone, an inexhaustible iterator returning randomParameters. Otherwise a list ofcountrandomParameters.
-
sample_uniformly(counts)[source]¶ Uniformly sample
Parametersfrom the space.
pymor.playground package¶
Subpackages¶
-
class
pymor.playground.core.network_cache.NetworkFilesystemRegion(server_path, secret='')[source]¶ Bases:
pymor.core.cache.CacheRegionMethods
NetworkFilesystemRegionclear,get,setAttributes
NetworkFilesystemRegionpersistent
-
class
pymor.playground.core.network_cache.NetworkFilesystemRegionServer(addr, path, secret=None)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceMethods
NetworkFilesystemRegionServerserve_foreverBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid
-
pymor.playground.discretizers.numpylistvectorarray.convert_to_numpy_list_vector_array(d)[source]¶ Use NumpyListVectorArrayMatrixOperator instead of NumpyMatrixOperator.
This simple function converts linear, affinely decomposed discretizations to use
NumpyListVectorArrayMatrixOperatorinstead ofNumpyMatrixOperator.
-
class
pymor.playground.functions.expression_function.ExpressionFunction(expressions, variables='x y z')[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceMethods
ExpressionFunction__call__BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.playground.operators.numpy.NumpyListVectorArrayMatrixOperator(matrix, functional=False, vector=False, solver_options=None, name=None)[source]¶ Bases:
pymor.operators.numpy.NumpyMatrixOperatorVariant of
NumpyMatrixOperatorusingListVectorArrayinstead ofNumpyVectorArray.Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
apply_adjoint(U, ind=None, mu=None, source_product=None, range_product=None)[source]¶ Apply the adjoint operator.
For a linear operator
opthe adjointop^*ofopis given by:(op^*(v), u)_s = (v, op(u))_r,
where
( , )_sand( , )_rdenote the inner products on the source and range space ofop. Ifopand the two products are given by the matricesM,P_sandP_r, then:op^*(v) = P_s^(-1) * M^T * P_r * v,
with
M^Tdenoting the transposed ofM. Thus, if( , )_sand( , )_rare the Euclidean inner products,op^*vis simply given by multiplication of the matrix ofopwithvfrom the left.Parameters
- U
VectorArrayof vectors to which the adjoint operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to apply the adjoint operator. - source_product
- The inner product
Operatoron the source space. IfNone, the Euclidean product is chosen. - range_product
- The inner product
Operatoron the range space. IfNone, the Euclidean product is chosen.
Returns
VectorArrayof the adjoint operator evaluations.
-
apply_inverse(V, ind=None, mu=None, least_squares=False)[source]¶ Apply the inverse operator.
Parameters
- V
VectorArrayof vectors to which the inverse operator is applied.- ind
- The indices of the vectors in
Vto which the inverse operator shall be applied (seeVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the inverse operator. - least_squares
If
True, solve the least squares problem:u = argmin ||op(u) - v||_2.
Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate
solver_optionsare set for the operator, most implementations will choose a least squares solver by default which may be undesirable.
Returns
VectorArrayof the inverse operator evaluations.Raises
- InversionError
- The operator could not be inverted.
-
as_vector(mu=None)[source]¶ Return a vector representation of a linear functional or vector operator.
This method may only be called on linear functionals, i.e. linear
OperatorswithNumpyVectorSpace(1)asrange, or on operators describing vectors, i.e. linearOperatorswithNumpyVectorSpace(1)assource.In the case of a functional, the identity
self.as_vector(mu).dot(U) == self.apply(U, mu)
holds, whereas in the case of a vector-like operator we have
self.as_vector(mu) == self.apply(NumpyVectorArray(1), mu).
Parameters
- mu
- The
Parameterfor which to return the vector representation.
Returns
- V
VectorArrayof length 1 containing the vector representation.Vbelongs toself.sourcefor functionals and toself.rangefor vector-like operators.
-
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]¶ Try to assemble a linear combination of the given operators.
This method is called in the
assemblemethod ofLincombOperatoron the first of its operator. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returnsNoneto indicate that assembly is not possible.Parameters
- operators
- List of
Operatorswhose linear combination is formed. - coefficients
- List of the corresponding linear coefficients.
- solver_options
solver_optionsfor the assembled operator.- name
- Name of the assembled operator.
Returns
The assembled
Operatorif assembly is possible, otherwiseNone.
-
-
class
pymor.playground.vectorarrays.disk.DiskVectorArray(vectors, subtype=())[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorArrayInterfaceVectorArrayimplementation via a list of vectors stored in temporary files.Methods
Attributes
DiskVectorArraydata,dim,subtypeVectorArrayInterfacespaceBasicInterfacelocked,logger,logging_disabled,name,uid-
amax(ind=None)[source]¶ The maximum absolute value of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose maximum absolute value is to be calculated (see class documentation).
Returns
- max_ind
NumPy arraycontaining for each vector an index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its components.
-
append(other, o_ind=None, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - o_ind
- Indices of the vectors that are to be appended (see class documentation).
- remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x, ind=None, x_ind=None)[source]¶ BLAS AXPY operation.
This method forms the sum
self[ind] = alpha*x[x_ind] + self[ind]
If the length of
x(x_ind) is 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofself(ind) andx(x_ind) have to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands. - ind
- Indices of the vectors of
selfthat are to be added (see class documentation). Repeated indices are forbidden. - x_ind
- Indices of the vectors in
xthat are to be added (see class documentation). Repeated indices are allowed.
-
components(component_indices, ind=None)[source]¶ Extract components of the vectors contained in the array.
Parameters
- component_indices
- List or 1D
NumPy arrayof indices of the vector components that are to be returned. - ind
- Indices of the vectors whose components are to be retrieved (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thecomponent_indices[j]-th component of theind[i]-th vector of the array.
-
copy(ind=None)[source]¶ Returns a copy of a subarray.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in array are copied (i.e.indis specified).Parameters
- ind
- Indices of the vectors that are to be copied (see class documentation).
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dot(other, ind=None, o_ind=None)[source]¶ Returns the inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
l1_norm(ind=None)[source]¶ The l1-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
l2_norm(ind=None)[source]¶ The l2-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
lincomb(coefficients, ind=None)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self). - ind
- Indices of the vectors which are linear combined (see class documentation).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other, ind=None, o_ind=None)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
remove(ind=None)[source]¶ Remove vectors from the array.
Parameters
- ind
- Indices of the vectors that are to be removed (see class documentation).
-
replace(other, ind=None, o_ind=None, remove_from_other=False)[source]¶ Replace vectors of the array.
Parameters
- other
- A
VectorArraycontaining the replacement vectors. - ind
- Indices of the vectors that are to be replaced (see class documentation). Repeated indices are forbidden.
- o_ind
- Indices of the replacement vectors (see class documentation).
len(ind)has to agree withlen(o_ind). Repeated indices are allowed. - remove_from_other
- If
True, the new vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
scal(alpha, ind=None)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self[ind] = alpha*self[ind]
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied. - ind
- Indices of the vectors of
selfthat are to be scaled (see class documentation). Repeated indices are forbidden.
-
pymor.reductors package¶
Submodules¶
-
class
pymor.reductors.basic.GenericRBReconstructor(RB)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceSimple reconstructor forming linear combinations with a reduced basis.
Methods
GenericRBReconstructorreconstruct,restricted_to_subbasisBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.reductors.basic.SubbasisReconstructor(dim, dim_subbasis, old_recontructor=None)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceReturned by
reduce_to_subbasis.Methods
SubbasisReconstructorreconstructBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
BasicInterfacelocked,logger,logging_disabled,name,uid
-
pymor.reductors.basic.reduce_generic_rb(discretization, RB, vector_product=None, disable_caching=True, extends=None)[source]¶ Generic reduced basis reductor.
Replaces each
Operatorof the givenDiscretizationwith the Galerkin projection onto the span of the given reduced basis.Parameters
- discretization
- The
Discretizationwhich is to be reduced. - RB
VectorArraycontaining the reduced basis on which to project.- vector_product
- Inner product for the projection of vector-like
Operators. (A typical vector-like operator would be theinitial_dataOperatorof anInstationaryDiscretizationholding the initial data of a Cauchy problem.) - disable_caching
- If
True, caching of solutions is disabled for the reducedDiscretization. - extends
- Set by
greedyto the result of the last reduction in case the basis extension washierarchic(ignored).
Returns
- rd
- The reduced
Discretization. - rc
- The
reconstructorproviding areconstruct(U)method which reconstructs high-dimensional solutions from solutionsUof the reducedDiscretization. - reduction_data
- Additional data produced by the reduction process (empty).
-
pymor.reductors.basic.reduce_to_subbasis(discretization, dim, reconstructor=None)[source]¶ Further reduce a
Discretizationto the subbasis formed by the firstdimbasis vectors.This is achieved by calling
projected_to_subbasisfor each operator of the givenDiscretization. Additionally, if a reconstructor for theDiscretizationis provided, itsrestricted_to_subbasismethod is also called to obtain a reconstructor for the further reducedDiscretization. OtherwiseSubbasisReconstructoris used (which will be less efficient).Parameters
- discretization
- The
Discretizationto further reduce. - dim
- The dimension of the subbasis.
- reconstructor
- Reconstructor for
discretizationorNone.
Returns
- rd
- The further reduced
Discretization. - rc
- Reconstructor for
rd.
-
class
pymor.reductors.coercive.ReduceCoerciveEstimator(residual, residual_range_dims, coercivity_estimator)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInstantiated by
reduce_coercive.Not to be used directly.
Methods
ReduceCoerciveEstimatorestimate,restricted_to_subbasisImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.reductors.coercive.ReduceCoerciveSimpleEstimator(estimator_matrix, coercivity_estimator)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInstantiated by
reduce_coercive_simple.Not to be used directly.
Methods
ReduceCoerciveSimpleEstimatorestimate,restricted_to_subbasisImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid
-
pymor.reductors.coercive.reduce_coercive(discretization, RB, error_product=None, coercivity_estimator=None, disable_caching=True, extends=None)[source]¶ Reductor for
StationaryDiscretizationswith coercive linear operator.This reductor uses
reduce_generic_rbfor the actual reduce basis projection. The only addition is an error estimator which evaluates the dual norm of the residual with respect to a given inner product. For the reduction of the residual we usereduce_residualfor improved numerical stability [BEOR14].[BEOR14] (1, 2) A. Buhr, C. Engwer, M. Ohlberger, S. Rave, A Numerically Stable A Posteriori Error Estimator for Reduced Basis Approximations of Elliptic Equations, Proceedings of the 11th World Congress on Computational Mechanics, 2014. Parameters
- discretization
- The
Discretizationwhich is to be reduced. - RB
VectorArraycontaining the reduced basis on which to project.- error_product
- Inner product
Operatorused to calculate Riesz representative of the residual. IfNone, the Euclidean product is used. - coercivity_estimator
Noneor aParameterFunctionalreturning a lower bound for the coercivity constant of the given problem. Note that the computed error estimate is only guaranteed to be an upper bound for the error when an appropriate coercivity estimate is specified.- disable_caching
- If
True, caching of solutions is disabled for the reducedDiscretization. - extends
- Set by
greedyto the result of the last reduction in case the basis extension washierarchic(used to prevent re-computation of residual range basis vectors already obtained from previous reductions).
Returns
- rd
- The reduced
Discretization. - rc
- The
reconstructorproviding areconstruct(U)method which reconstructs high-dimensional solutions from solutionsUof the reducedDiscretization. - reduction_data
- Additional data produced by the reduction process (compare the
extendsparameter).
-
pymor.reductors.coercive.reduce_coercive_simple(discretization, RB, error_product=None, coercivity_estimator=None, disable_caching=True, extends=None)[source]¶ Reductor for linear
StationaryDiscretizationswith affinely decomposed operator and rhs.Note
The reductor
reduce_coercivecan be used for arbitrary coerciveStationaryDiscretizationsand offers an improved error estimator with better numerical stability.This reductor uses
reduce_generic_rbfor the actual reduced basis projection. The only addition is an error estimator. The estimator evaluates the norm of the residual with respect to a given inner product.Parameters
- discretization
- The
Discretizationwhich is to be reduced. - RB
VectorArraycontaining the reduced basis on which to project.- error_product
- Inner product
Operatorused to calculate the Riesz representative of the residual. IfNone, the Euclidean product is used. - coercivity_estimator
Noneor aParameterFunctionalreturning a lower bound for the coercivity constant of the given problem. Note that the computed error estimate is only guaranteed to be an upper bound for the error when an appropriate coercivity estimate is specified.- disable_caching
- If
True, caching of solutions is disabled for the reducedDiscretization. - extends
- Set by
greedyto the result of the last reduction in case the basis extension washierarchic(used to prevent re-computation of residual range basis vectors already obtained from previous reductions).
Returns
- rd
- The reduced
Discretization. - rc
- The
reconstructorproviding areconstruct(U)method which reconstructs high-dimensional solutions from solutionsUof the reducedDiscretization. - reduction_data
- Additional data produced by the reduction process (compare the
extendsparameter).
-
class
pymor.reductors.parabolic.ReduceParabolicEstimator(residual, residual_range_dims, initial_residual, initial_residual_range_dims, coercivity_estimator)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceInstantiated by
reduce_parabolic.Not to be used directly.
Methods
ReduceParabolicEstimatorestimate,restricted_to_subbasisImmutableInterfacegenerate_sid,unlock,with_BasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,__setattr__Attributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid
-
pymor.reductors.parabolic.reduce_parabolic(discretization, RB, product=None, coercivity_estimator=None, disable_caching=True, extends=None)[source]¶ Reductor for parabolic equations.
This reductor uses
reduce_generic_rbfor the actual RB-projection. The only addition is the assembly of an error estimator which bounds the discrete l2-in time / energy-in space error similar to [GP05], [HO08] as follows:![\left[ C_a^{-1}(\mu)\|e_N(\mu)\|^2 + \sum_{n=1}^{N} \Delta t\|e_n(\mu)\|^2_e \right]^{1/2}
\leq \left[ C_a^{-1}(\mu)\Delta t \sum_{n=1}^{N}\|\mathcal{R}^n(u_n(\mu), \mu)\|^2_{e,-1}
+ C_a^{-1}(\mu)\|e_0\|^2 \right]^{1/2}](_images/math/f85904507cddb59d98fd4c592d4602b1207b449f.png)
Here,
denotes the norm induced by the problem’s mass matrix
(e.g. the L^2-norm) and
is an arbitrary energy norm w.r.t.
which the space operator
is coercive, and
is a
lower bound for its coercivity constant. Finally,
denotes
the implicit Euler timestepping residual for the (fixed) time step size
,
where
denotes the mass operator and
the source term.
The dual norm of the residual is computed using the numerically stable projection
from [BEOR14].Warning
The reduced basis
RBis required to be orthonormal w.r.t. the given energy product. If not, the projection of the initial values will be computed incorrectly.[GP05] M. A. Grepl, A. T. Patera, A Posteriori Error Bounds For Reduced-Basis Approximations Of Parametrized Parabolic Partial Differential Equations, M2AN 39(1), 157-181, 2005. [HO08] B. Haasdonk, M. Ohlberger, Reduced basis method for finite volume approximations of parametrized evolution equations, M2AN 42(2), 277-302, 2008. Parameters
- discretization
- The
InstationaryDiscretizationwhich is to be reduced. - RB
VectorArraycontaining the reduced basis on which to project.- product
- The energy inner product
Operatorw.r.t. the reduction error is estimated. RB must be to be orthonomrmal w.r.t. this product! - coercivity_estimator
Noneor aParameterFunctionalreturning a lower bound
for the coercivity constant of discretization.operatorw.r.t.product.- disable_caching
- If
True, caching of solutions is disabled for the reducedDiscretization. - extends
- Set by
greedyto the result of the last reduction in case the basis extension washierarchic(used to prevent re-computation of residual range basis vectors already obtained from previous reductions).
Returns
- rd
- The reduced
Discretization. - rc
- The reconstructor providing a
reconstruct(U)method which reconstructs high-dimensional solutions from solutionsUof the reducedDiscretization. - reduction_data
- Additional data produced by the reduction process (compare the
extendsparameter).
-
class
pymor.reductors.residual.ImplicitEulerResidualOperator(operator, mass, functional, dt, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseReturned by
reduce_implicit_euler_residual.Methods
Attributes
-
apply(U, U_old, ind, ind_old=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
-
class
pymor.reductors.residual.NonProjectedImplicitEulerResidualOperator(operator, mass, functional, dt, product)[source]¶ Bases:
pymor.reductors.residual.ImplicitEulerResidualOperatorReturned by
reduce_implicit_euler_residual.Not to be used directly.
Methods
Attributes
-
apply(U, U_old, ind=None, ind_old=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
-
class
pymor.reductors.residual.NonProjectedReconstructor(product)[source]¶ Bases:
pymor.core.interfaces.ImmutableInterfaceReturned by
reduce_residual.Not to be used directly.
Methods
Attributes
ImmutableInterfaceadd_with_arguments,sid,sid_ignore,with_argumentsBasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.reductors.residual.NonProjectedResidualOperator(operator, rhs, rhs_is_functional, product)[source]¶ Bases:
pymor.reductors.residual.ResidualOperatorReturned by
reduce_residual.Not to be used directly.
Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
-
class
pymor.reductors.residual.ResidualOperator(operator, rhs, rhs_is_functional=True, name=None)[source]¶ Bases:
pymor.operators.basic.OperatorBaseReturned by
reduce_residual.Methods
Attributes
-
apply(U, ind=None, mu=None)[source]¶ Apply the operator to a
VectorArray.Parameters
- U
VectorArrayof vectors to which the operator is applied.- ind
- The indices of the vectors in
Uto which the operator shall be applied (see theVectorArraydocumentation for further details). - mu
- The
Parameterfor which to evaluate the operator.
Returns
VectorArrayof the operator evaluations.
-
-
pymor.reductors.residual.reduce_implicit_euler_residual(operator, mass, dt, functional=None, RB=None, product=None, extends=None)[source]¶ Reduced basis residual reductor with mass operator for implicit Euler timestepping.
Given an operator, mass and a functional, the concatenation of residual operator with the Riesz isomorphism is given by:
riesz_residual.apply(U, U_old, mu) == product.apply_inverse(operator.apply(U, mu) + 1/dt*mass.apply(U, mu) - 1/dt*mass.apply(U_old, mu) - functional.as_vector(mu))
This reductor determines a low-dimensional subspace of the image of a reduced basis space under
riesz_residualusingestimate_image_hierarchical, computes an orthonormal basisresidual_rangeof this range space and then returns the Petrov-Galerkin projectionprojected_riesz_residual === riesz_residual.projected(range_basis=residual_range, source_basis=RB)
of the
riesz_residualoperator. Given reduced basis coefficient vectorsuandu_old, the dual norm of the residual can then be computed asprojected_riesz_residual.apply(u, u_old, mu).l2_norm()
Moreover, a
reconstructoris provided such thatreconstructor.reconstruct(projected_riesz_residual.apply(u, u_old, mu)) == riesz_residual.apply(RB.lincomb(u), RB.lincomb(u_old), mu)
Parameters
- operator
- See definition of
riesz_residual. - mass
- The mass operator. See definition of
riesz_residual. - dt
- The time step size. See definition of
riesz_residual. - functional
- See definition of
riesz_residual. IfNone, zero right-hand side is assumed. - RB
VectorArraycontaining a basis of the reduced space onto which to project.- product
- Inner product
Operatorw.r.t. which to compute the Riesz representatives. - extends
- Set by
greedyto the result of the last reduction in case the basis extension washierarchic(used to prevent re-computation ofresidual_rangebasis vectors already obtained from previous reductions).
Returns
- projected_riesz_residual
- See above.
- reconstructor
- See above.
- reduction_data
- Additional data produced by the reduction process (compare the
extendsparameter).
-
pymor.reductors.residual.reduce_residual(operator, rhs=None, RB=None, rhs_is_functional=True, product=None, extends=None)[source]¶ Generic reduced basis residual reductor.
Given an operator and a right-hand side, the residual is given by:
residual.apply(U, mu) == operator.apply(U, mu) - rhs.as_vector(mu)
When the rhs is a functional we are usually interested in the Riesz representative of the residual:
residual.apply(U, mu) == product.apply_inverse(operator.apply(U, mu) - rhs.as_vector(mu))
Given a basis
RBof a subspace of the source space ofoperator, this method usesestimate_image_hierarchicalto determine a low-dimensional subspace containing the image of the subspace underresidual(resp.riesz_residual), computes an orthonormal basisresidual_rangefor this range space and then returns the Petrov-Galerkin projectionprojected_residual === residual.projected(range_basis=residual_range, source_basis=RB)
of the residual operator. Given an reduced basis coefficient vector
u, w.r.t.RB, the (dual) norm of the residual can then be computed asprojected_residual.apply(u, mu).l2_norm()
Moreover, a
reconstructoris provided such thatreconstructor.reconstruct(projected_residual.apply(u, mu)) == residual.apply(RB.lincomb(u), mu)
Parameters
- operator
- See definition of
residual. - rhs
- See definition of
residual. IfNone, zero right-hand side is assumed. - rhs_is_functional
- Set this to
Truewhenrhsis aFunctional. - RB
VectorArraycontaining a basis of the reduced space onto which to project.- product
- Inner product
Operatorw.r.t. which to compute the Riesz representatives in caserhs_is_functionalisTrue. WhenproductisNone, no Riesz representatives are computed - extends
- Set by
greedyto the result of the last reduction in case the basis extension washierarchic(used to prevent re-computation ofresidual_rangebasis vectors already obtained from previous reductions).
Returns
- projected_residual
- See above.
- reconstructor
- See above.
- reduction_data
- Additional data produced by the reduction process (compare the
extendsparameter).
pymor.tools package¶
Submodules¶
-
pymor.tools.floatcmp.float_cmp(x, y, rtol=1e-14, atol=1e-14)[source]¶ Compare x and y component-wise for almost equality.
For scalars we define almost equality as
float_cmp(x,y) <=> |x - y| <= atol + |y|*rtol
Note
Numpy’s
allclosemethod uses the same definition but treats arrays containing infinities as close if the infinities are at the same places and all other entries are close. In our definition, arrays containing infinities can never be close which seems more appropriate in most cases.Parameters
- x, y
NumPy arraysto be compared. Have to be broadcastable to the same shape.- rtol
- The relative tolerance.
- atol
- The absolute tolerance.
Defaults
rtol, atol (see
pymor.core.defaults)
-
class
pymor.tools.frozendict.FrozenDict(*args, **kwargs)[source]¶ Bases:
dictAn immutable dictionary.
Methods
dictcopy,fromkeys,get,has_key,items,iteritems,iterkeys,itervalues,keys,values,viewitems,viewkeys,viewvalues,__contains__,__getitem__,__sizeof__Attributes
FrozenDictclear,pop,popitem,setdefault,update
-
pymor.tools.inverse.inv_transposed_two_by_two(A)[source]¶ Efficiently compute the tranposed inverses of a
NumPy arrayof 2x2-matrices| retval[i1,...,ik,m,n] = numpy.linalg.inv(A[i1,...,ik,:,:]).
-
pymor.tools.inverse.inv_two_by_two(A)[source]¶ Efficiently compute the inverses of a
NumPy arrayof 2x2-matrices| retval[i1,...,ik,m,n] = numpy.linalg.inv(A[i1,...,ik,:,:]).
This module provides helper methods to use pyMOR in parallel with MPI.
Executing this module will run event_loop on all MPI ranks
except for rank 0 where either a given script is executed:
mpirun -n 16 python -m pymor.tools.mpi /path/to/script
or an interactive session is started:
mpirun -n 16 python -m pymor.tools.mpi
When IPython is available, an IPython kernel is started which the user can connect to by calling:
ipython console --existing file_name_printed_by_ipython.json
(Starting the IPython console directly will not work properly with most MPI implementations.) When IPython is not available, the builtin Python REPL is started.
When event_loop is running on the MPI ranks, call
can be used on rank 0 to execute the same Python function (given
as first argument) simultaneously on all MPI ranks (including
rank 0). Calling quit will exit event_loop on
all MPI ranks.
Additionally, this module provides several helper methods which are
intended to be used in conjunction with call: mpi_info
will print a summary of all active MPI ranks, run_code
will execute the given code string on all MPI ranks,
import_module imports the module with the given path.
A simple object management is implemented with the
manage_object, get_object and remove_object
methods. It is the user’s responsibility to ensure that calls to
manage_object are executed in the same order on all MPI ranks
to ensure that the returned ObjectId refers to the same
distributed object on all ranks. The functions function_call,
function_call_manage, method_call,
method_call_manage map instances ObjectId
transparently to distributed objects. function_call_manage and
method_call_manage will call manage_object on the
return value and return the corresponding ObjectId. The functions
method_call and method_call_manage are given an
ObjectId and a string as first and second argument and execute
the method named by the second argument on the object referred to by the
first argument.
-
class
pymor.tools.mpi.ObjectId[source]¶ Bases:
intA handle to an MPI distributed object.
Methods
intbit_length,conjugate,__new__,__trunc__Attributes
intdenominator,imag,numerator,real
-
pymor.tools.mpi.call(method, *args, **kwargs)[source]¶ Execute method on all MPI ranks.
Assuming
event_loopis running on all MPI ranks (except rank 0), this will executemethodon all ranks (including rank 0) with positional argumentsargsand keyword argumentskwargs.Parameters
- method
- The function to execute on all ranks (must be picklable).
- args
- The positional arguments for
method. - kwargs
- The keyword arguments for
method.
Returns
The return value of
methodon rank 0.
-
pymor.tools.mpi.event_loop()[source]¶ Launches an MPI-based event loop.
Events can be sent by either calling
callon rank 0 to execute an arbitrary method on all ranks or by callingquitto exit the loop.
-
pymor.tools.mpi.event_loop_settings(auto_launch=True)[source]¶ Settings for pyMOR’s MPI event loop.
Parameters
- auto_launch
- If
True, automatically executeevent_loopon all MPI ranks (except 0) when pyMOR is imported.
Defaults
auto_launch (see
pymor.core.defaults)
-
pymor.tools.mpi.function_call(f, *args, **kwargs)[source]¶ Execute the function
fwith given arguments.Intended to be used in conjunction with
call. Arguments of typeObjectIdare transparently mapped to the object they refer to.
-
pymor.tools.mpi.function_call_manage(f, *args, **kwargs)[source]¶ Execute the function
fand manage the return value.Intended to be used in conjunction with
call. The return value offis managed by callingmanage_objectand the correspondingObjectIdis returned. Arguments of typeObjectIdare transparently mapped to the object they refer to.
-
pymor.tools.mpi.import_module(path)[source]¶ Import the module named by
path.Intended to be used in conjunction with
call.
-
pymor.tools.mpi.method_call(obj_id, name_, *args, **kwargs)[source]¶ Execute a method with given arguments.
Intended to be used in conjunction with
call. Arguments of typeObjectIdare transparently mapped to the object they refer to.Parameters
- obj_id
- The
ObjectIdof the object on which to call the method. name_- Name of the method to call.
- args
- Positional arguments for the method.
- kwargs
- Keyword arguments for the method.
-
pymor.tools.mpi.method_call_manage(obj_id, name_, *args, **kwargs)[source]¶ Execute a method with given arguments and manage the return value.
Intended to be used in conjunction with
call. The return value of the called method is managed by callingmanage_objectand the correspondingObjectIdis returned. Arguments of typeObjectIdare transparently mapped to the object they refer to.Parameters
- obj_id
- The
ObjectIdof the object on which to call the method. name_- Name of the method to call.
- args
- Positional arguments for the method.
- kwargs
- Keyword arguments for the method.
-
pymor.tools.mpi.mpi_info()[source]¶ Print some information on the MPI setup.
Intended to be used in conjunction with
call.
-
pymor.tools.mpi.quit()[source]¶ Exit the event loop on all MPI ranks.
This will cause
event_loopto terminate on all MPI ranks.
-
pymor.tools.mpi.remove_object(obj_id)[source]¶ Remove the object referred to by
obj_idfrom the registry.
-
pymor.tools.pprint.format_array(array, compact_print=False)[source]¶ Creates a formatted string representation of a
NumPy array.Parameters
- compact_print
- If
True, return a shorter version of string representation.
Returns
The string representation.
Defaults
compact_print (see
pymor.core.defaults)
-
class
pymor.tools.quadratures.GaussQuadratures[source]¶ Bases:
objectGauss quadrature on the interval [0, 1]
Methods
GaussQuadraturesiter_quadrature,maxpoints,quadratureAttributes
GaussQuadraturesa,order_map,orders,points,weights
-
pymor.tools.random.new_random_state(seed=42)[source]¶ Returns a new
NumPyRandomState.Parameters
- seed
- Seed to use for initializing the random state.
Returns
New
RandomStateobject.Defaults
seed (see
pymor.core.defaults)
-
class
pymor.tools.timing.Timer(section, log=<logging.Logger object>)[source]¶ Bases:
objectYou can use me as a context manager, plain instance or decorator to time execution of a code scope:
with Timer() as timer: do_some_stuff() do more stuff() #outputs time in (s) ### OR ### @timing.Timer('name', logging.debug) def function(*args): do_stuff function(1) #outputs time in (s) to logging.debug ### OR ### timer = timing.Timer() timer.start() do_stuff() timer.stop() print(timer.dt)
Methods
Timerstart,stop
-
pymor.tools.vtkio._write_meta_file(filename_base, steps, fn_tpl)[source]¶ Outputs a collection file for a series of vtu files
This DOES NOT WORK for the currently used legacy vtk format below
-
pymor.tools.vtkio.write_vtk(grid, data, filename_base, codim=2, binary_vtk=True, last_step=None)[source]¶ Output grid-associated data in (legacy) vtk format
Parameters
- grid
- a
Gridwith triangular or rectilinear reference element - data
- VectorArrayInterface instance with either cell (ie one datapoint per codim 0 entity) or vertex (ie one datapoint per codim 2 entity) data in each array element
- filename_base
- common component for output files in timeseries
- last_step
- if set must be <= len(data) to restrict output of timeseries
pymor.vectorarrays package¶
Submodules¶
-
class
pymor.vectorarrays.block.BlockVectorArray(blocks, copy=False)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorArrayInterfaceVectorArraywhere each vector is a direct sum of sub-vectors.Given a list of equal length
VectorArraysblocks, thisVectorArrayrepresents the direct sums of the vectors contained in the arrays.The
subtypeof the array will be the tuple(blocks[0].space, blocks[1].space, ..., blocks[-1].space).
BlockVectorArraycan be used in conjunction withBlockOperator.Parameters
- blocks
- The list of sub-arrays.
- copy
- If
True, copy all arrays contained inblocks.
Methods
Attributes
BlockVectorArraydata,dim,num_blocks,subtypeVectorArrayInterfacespaceBasicInterfacelocked,logger,logging_disabled,name,uid-
amax(ind=None)[source]¶ The maximum absolute value of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose maximum absolute value is to be calculated (see class documentation).
Returns
- max_ind
NumPy arraycontaining for each vector an index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its components.
-
append(other, o_ind=None, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - o_ind
- Indices of the vectors that are to be appended (see class documentation).
- remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x, ind=None, x_ind=None)[source]¶ BLAS AXPY operation.
This method forms the sum
self[ind] = alpha*x[x_ind] + self[ind]
If the length of
x(x_ind) is 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofself(ind) andx(x_ind) have to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands. - ind
- Indices of the vectors of
selfthat are to be added (see class documentation). Repeated indices are forbidden. - x_ind
- Indices of the vectors in
xthat are to be added (see class documentation). Repeated indices are allowed.
-
components(component_indices, ind=None)[source]¶ Extract components of the vectors contained in the array.
Parameters
- component_indices
- List or 1D
NumPy arrayof indices of the vector components that are to be returned. - ind
- Indices of the vectors whose components are to be retrieved (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thecomponent_indices[j]-th component of theind[i]-th vector of the array.
-
copy(ind=None, deep=False)[source]¶ Returns a copy of a subarray.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in array are copied (i.e.indis specified).Parameters
- ind
- Indices of the vectors that are to be copied (see class documentation).
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dot(other, ind=None, o_ind=None)[source]¶ Returns the inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
l1_norm(ind=None)[source]¶ The l1-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
l2_norm(ind=None)[source]¶ The l2-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
lincomb(coefficients, ind=None)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self). - ind
- Indices of the vectors which are linear combined (see class documentation).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other, ind=None, o_ind=None)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
remove(ind=None)[source]¶ Remove vectors from the array.
Parameters
- ind
- Indices of the vectors that are to be removed (see class documentation).
-
replace(other, ind=None, o_ind=None, remove_from_other=False)[source]¶ Replace vectors of the array.
Parameters
- other
- A
VectorArraycontaining the replacement vectors. - ind
- Indices of the vectors that are to be replaced (see class documentation). Repeated indices are forbidden.
- o_ind
- Indices of the replacement vectors (see class documentation).
len(ind)has to agree withlen(o_ind). Repeated indices are allowed. - remove_from_other
- If
True, the new vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
scal(alpha, ind=None)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self[ind] = alpha*self[ind]
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied. - ind
- Indices of the vectors of
selfthat are to be scaled (see class documentation). Repeated indices are forbidden.
-
sup_norm(ind=None)[source]¶ The l-infinity–norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
pymor.vectorarrays.constructions.cat_arrays(vector_arrays)[source]¶ Return a new
VectorArraywhich a concatenation of the arrays invector_arrays.
-
class
pymor.vectorarrays.interfaces.VectorArrayInterface[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceInterface for vector arrays.
A vector array should be thought of as a list of (possibly high-dimensional) vectors. While the vectors themselves will be inaccessible in general (e.g. because they are managed by an external PDE solver code), operations on the vectors like addition can be performed via the interface.
It is moreover assumed that the number of vectors is small enough such that scalar data associated to each vector can be handled on the Python side. As such, methods like
l2_normorgramianwill always returnNumPy arrays.An implementation of the interface via
NumPy arraysis given byNumpyVectorArray. In general, it is the implementors decision how memory is allocated internally (e.g. continuous block of memory vs. list of pointers to the individual vectors.) Thus, no general assumptions can be made on the costs of operations like appending to or removing vectors from the array. As a hint for ‘continuous block of memory’ implementations,VectorArrayconstructors should provide areservekeyword argument which allows to specify to what size the array is assumed to grow.Most methods provide
indand/oro_indarguments which are used to specify on which vectors the method is supposed to operate. Ifind(o_ind) isNonethe whole array is selected. Otherwise,indcan be a single index inrange(len(self)), alistof indices or a one-dimensionalNumPy arrayof indices. An index can be repeated in which case the corresponding vector is selected several times.Methods
Attributes
VectorArrayInterfacedata,dim,space,subtypeBasicInterfacelocked,logger,logging_disabled,name,uid-
data¶ Implementors can provide a
dataproperty which returns aNumPy arrayof shape(len(v), v.dim)containing the data stored in the array. Access should be assumed to be slow and is mainly intended for debugging / visualization purposes or to once transfer data to pyMOR and further process it using NumPy. In the case ofNumpyVectorArray, an actual view of the internally usedNumPy arrayis returned, so changing it, will alter theVectorArray. Thus, you cannot assume to own the data returned to you, in general.
-
dim¶ The dimension of the vectors in the array.
-
space¶ VectorSpacearray the array belongs to.
-
subtype¶ Can be any Python object. Two arrays are compatible (e.g. can be added) if they are instances of the same class and have equal subtypes. A valid subtype has to be provided to
make_arrayand the resulting array will be of that subtype. By default, the subtype of an array is simplyNone. ForNumpyVectorArray, the subtype is a single integer denoting the dimension of the array. Subtypes for other array classes could, e.g., include a socket for communication with a specific PDE solver instance.
-
__add__(other)[source]¶ The pairwise sum of two
VectorArrays.
-
__iadd__(other)[source]¶ In-place pairwise addition of
VectorArrays.
-
__isub__(other)[source]¶ In-place pairwise difference of
VectorArrays.
-
__radd__(other)¶ The pairwise sum of two
VectorArrays.
-
__sub__(other)[source]¶ The pairwise difference of two
VectorArrays.
-
amax(ind=None)[source]¶ The maximum absolute value of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose maximum absolute value is to be calculated (see class documentation).
Returns
- max_ind
NumPy arraycontaining for each vector an index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its components.
-
append(other, o_ind=None, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - o_ind
- Indices of the vectors that are to be appended (see class documentation).
- remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x, ind=None, x_ind=None)[source]¶ BLAS AXPY operation.
This method forms the sum
self[ind] = alpha*x[x_ind] + self[ind]
If the length of
x(x_ind) is 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofself(ind) andx(x_ind) have to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands. - ind
- Indices of the vectors of
selfthat are to be added (see class documentation). Repeated indices are forbidden. - x_ind
- Indices of the vectors in
xthat are to be added (see class documentation). Repeated indices are allowed.
-
check_ind(ind)[source]¶ Check if
indis an admissable list of indices in the sense of the class documentation.
-
check_ind_unique(ind)[source]¶ Check if
indis an admissable list of non-repeated indices in the sense of the class documentation.
-
components(component_indices, ind=None)[source]¶ Extract components of the vectors contained in the array.
Parameters
- component_indices
- List or 1D
NumPy arrayof indices of the vector components that are to be returned. - ind
- Indices of the vectors whose components are to be retrieved (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thecomponent_indices[j]-th component of theind[i]-th vector of the array.
-
copy(ind=None, deep=False)[source]¶ Returns a copy of a subarray.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in array are copied (i.e.indis specified).Parameters
- ind
- Indices of the vectors that are to be copied (see class documentation).
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dot(other, ind=None, o_ind=None)[source]¶ Returns the inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
empty(reserve=0)[source]¶ Create an empty
VectorArrayof the samesubtype.Parameters
- reserve
- Hint for the backend to which length the array will grow.
Returns
An empty
VectorArray.
-
l1_norm(ind=None)[source]¶ The l1-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
l2_norm(ind=None)[source]¶ The l2-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
lincomb(coefficients, ind=None)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self). - ind
- Indices of the vectors which are linear combined (see class documentation).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
classmethod
make_array(subtype=None, count=0, reserve=0)[source]¶ Create a
VectorArrayof null vectors.Parameters
- subtype
- The
subtype, the created array should have. What a valid subtype is, is determined by the respective array implementation. - count
- The number of null vectors to create. For
count == 0, an empty array is returned. - reserve
- A hint for the backend to which length the array will grow.
-
pairwise_dot(other, ind=None, o_ind=None)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
remove(ind=None)[source]¶ Remove vectors from the array.
Parameters
- ind
- Indices of the vectors that are to be removed (see class documentation).
-
replace(other, ind=None, o_ind=None, remove_from_other=False)[source]¶ Replace vectors of the array.
Parameters
- other
- A
VectorArraycontaining the replacement vectors. - ind
- Indices of the vectors that are to be replaced (see class documentation). Repeated indices are forbidden.
- o_ind
- Indices of the replacement vectors (see class documentation).
len(ind)has to agree withlen(o_ind). Repeated indices are allowed. - remove_from_other
- If
True, the new vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
scal(alpha, ind=None)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self[ind] = alpha*self[ind]
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied. - ind
- Indices of the vectors of
selfthat are to be scaled (see class documentation). Repeated indices are forbidden.
-
sup_norm(ind=None)[source]¶ The l-infinity–norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
zeros(count=1)[source]¶ Create a
VectorArrayof null vectors of the samesubtype.Parameters
- count
- The number of vectors.
Returns
A
VectorArraycontainingcountvectors whith each component zero.
-
-
class
pymor.vectorarrays.interfaces.VectorSpace(space_type, subtype=None)[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceClass describing a vector space.
A vector space is simply the combination of a
VectorArraytype and asubtype. This data is exactly sufficient to construct new arrays using themake_arraymethod (see the implementation ofzeros).A
VectorArrayUis contained in a vector spacespace, iftype(U) == space.type and U.subtype == space.subtype
Methods
Attributes
VectorSpacedim,subtype,typeBasicInterfacelocked,logger,logging_disabled,name,uid-
type¶ The type of
VectorArraysin the space.
-
subtype¶ The subtype used to construct arrays of the given space.
-
__contains__(other)[source]¶ A
VectorArrayis contained in the space, iff it is an instance of its type and has the same subtype.
-
__str__()¶ x.__repr__() <==> repr(x)
-
empty(reserve=0)[source]¶ Create an empty
VectorArrayParameters
- reserve
- Hint for the backend to which length the array will grow.
Returns
An empty
VectorArray.
-
zeros(count=1)[source]¶ Create a
VectorArrayof null vectorsParameters
- count
- The number of vectors.
Returns
A
VectorArraycontainingcountvectors with each component zero.
-
-
class
pymor.vectorarrays.list.CopyOnWriteVector[source]¶ Bases:
pymor.vectorarrays.list.VectorInterfaceMethods
CopyOnWriteVectoraxpy,copy,from_instance,scalVectorInterfaceamax,components,dot,l1_norm,l2_norm,make_zeros,sup_normBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
VectorInterfacedim,subtypeBasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.vectorarrays.list.ListVectorArray(vectors, subtype=(), copy=True)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorArrayInterfaceVectorArrayimplementation via a Python list of vectors.The
subtypesaListVectorArraycan have are tuples(vector_type, vector_subtype)wherevector_typeis a subclass ofVectorInterfaceandvector_subtypeis a valid subtype forvector_type.Parameters
Methods
Attributes
ListVectorArraydata,dim,subtypeVectorArrayInterfacespaceBasicInterfacelocked,logger,logging_disabled,name,uid-
amax(ind=None)[source]¶ The maximum absolute value of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose maximum absolute value is to be calculated (see class documentation).
Returns
- max_ind
NumPy arraycontaining for each vector an index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its components.
-
append(other, o_ind=None, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - o_ind
- Indices of the vectors that are to be appended (see class documentation).
- remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x, ind=None, x_ind=None)[source]¶ BLAS AXPY operation.
This method forms the sum
self[ind] = alpha*x[x_ind] + self[ind]
If the length of
x(x_ind) is 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofself(ind) andx(x_ind) have to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands. - ind
- Indices of the vectors of
selfthat are to be added (see class documentation). Repeated indices are forbidden. - x_ind
- Indices of the vectors in
xthat are to be added (see class documentation). Repeated indices are allowed.
-
components(component_indices, ind=None)[source]¶ Extract components of the vectors contained in the array.
Parameters
- component_indices
- List or 1D
NumPy arrayof indices of the vector components that are to be returned. - ind
- Indices of the vectors whose components are to be retrieved (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thecomponent_indices[j]-th component of theind[i]-th vector of the array.
-
copy(ind=None, deep=False)[source]¶ Returns a copy of a subarray.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in array are copied (i.e.indis specified).Parameters
- ind
- Indices of the vectors that are to be copied (see class documentation).
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dot(other, ind=None, o_ind=None)[source]¶ Returns the inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
l1_norm(ind=None)[source]¶ The l1-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
l2_norm(ind=None)[source]¶ The l2-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
lincomb(coefficients, ind=None)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self). - ind
- Indices of the vectors which are linear combined (see class documentation).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other, ind=None, o_ind=None)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
remove(ind=None)[source]¶ Remove vectors from the array.
Parameters
- ind
- Indices of the vectors that are to be removed (see class documentation).
-
replace(other, ind=None, o_ind=None, remove_from_other=False)[source]¶ Replace vectors of the array.
Parameters
- other
- A
VectorArraycontaining the replacement vectors. - ind
- Indices of the vectors that are to be replaced (see class documentation). Repeated indices are forbidden.
- o_ind
- Indices of the replacement vectors (see class documentation).
len(ind)has to agree withlen(o_ind). Repeated indices are allowed. - remove_from_other
- If
True, the new vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
scal(alpha, ind=None)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self[ind] = alpha*self[ind]
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied. - ind
- Indices of the vectors of
selfthat are to be scaled (see class documentation). Repeated indices are forbidden.
-
sup_norm(ind=None)[source]¶ The l-infinity–norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
-
class
pymor.vectorarrays.list.NumpyVector(instance, dtype=None, copy=False, order=None, subok=False)[source]¶ Bases:
pymor.vectorarrays.list.CopyOnWriteVectorVector stored in a NumPy 1D-array.
Methods
NumpyVectoramax,components,dot,from_instance,l1_norm,l2_norm,make_zerosCopyOnWriteVectoraxpy,copy,scalVectorInterfacesup_normBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
NumpyVectordata,dim,subtypeBasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.vectorarrays.list.VectorInterface[source]¶ Bases:
pymor.core.interfaces.BasicInterfaceInterface for vectors.
This Interface is intended to be used in conjunction with
ListVectorArray. All pyMOR algorithms operate onVectorArraysinstead of single vectors! All methods of the interface have a direct counterpart in theVectorArrayinterface.Methods
VectorInterfaceamax,axpy,components,copy,dot,l1_norm,l2_norm,make_zeros,scal,sup_normBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
VectorInterfacedim,subtypeBasicInterfacelocked,logger,logging_disabled,name,uid
Wrapper classes for building MPI distributed VectorArrays.
This module contains several wrapper classes which allow to
transform single rank VectorArrays into MPI distributed
VectorArrays which can be used on rank 0 like ordinary
VectorArrays. Similar classes are provided for handling
Vectors.
The implementations are based on the event loop provided
by pymor.tools.mpi.
-
class
pymor.vectorarrays.mpi.MPIVector(cls, subtype, obj_id)[source]¶ Bases:
pymor.vectorarrays.list.VectorInterfaceMPI distributed Vector.
Given a single-rank implementation of
VectorInterfacecls, this wrapper class uses the event loop frompymor.tools.mpito build MPI distributed vector where on each MPI rank an instance ofclsis used to manage the local data.Instances of
MPIVectorcan be used on rank 0 in conjunction withListVectorArraylike any other (non-distributed) Vector class.Note, however, that the implementation of
clsneeds to be MPI aware. For instance,cls.dotmust perform the needed MPI communication to sum up the local inner products and return the sum on rank 0.Default implementations for all communication requiring interface methods are provided by
MPIVectorAutoComm(also seeMPIVectorNoComm).Note that resource cleanup is handled by
object.__del__. Please be aware of the peculiarities of destructors in Python!Parameters
- cls
- The class of the
VectorInterfaceimplementation used on every MPI rank. - subtype
tupleof the different subtypes ofclson the MPI ranks. Alternatively, the length of subtype may be 1, in which case the same subtype is assumed for all ranks.- obj_id
ObjectIdof the MPI distributed instances ofclswrapped by this object.
Methods
MPIVectoramax,axpy,components,copy,dot,l1_norm,l2_norm,make_zeros,scalVectorInterfacesup_normBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
MPIVectordim,subtypeBasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.vectorarrays.mpi.MPIVectorArray(cls, subtype, obj_id)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorArrayInterfaceMPI distributed
VectorArray.Given a single-rank
VectorArrayimplementationcls, this wrapper class uses the event loop frompymor.tools.mpito build MPI distributed vector arrays where on each MPI rank an instance ofclsis used to manage the local data.Instances of
MPIVectorArraycan be used on rank 0 like any other (non-distributed)VectorArray.Note, however, that the implementation of
clsneeds to be MPI aware. For instance,cls.dotmust perform the needed MPI communication to sum up the local inner products and return the sums on rank 0.Default implementations for all communication requiring interface methods are provided by
MPIVectorArrayAutoComm(also seeMPIVectorArrayNoComm).Note that resource cleanup is handled by
object.__del__. Please be aware of the peculiarities of destructors in Python!Parameters
- cls
- The class of the
VectorArrayimplementation used on every MPI rank. - subtype
tupleof the different subtypes ofclson the MPI ranks. Alternatively, the length of subtype may be 1, in which case the same subtype is assumed for all ranks.- obj_id
ObjectIdof the MPI distributed instances ofclswrapped by this array.
Methods
Attributes
MPIVectorArraydim,subtypeVectorArrayInterfacedata,spaceBasicInterfacelocked,logger,logging_disabled,name,uid-
amax(ind=None)[source]¶ The maximum absolute value of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose maximum absolute value is to be calculated (see class documentation).
Returns
- max_ind
NumPy arraycontaining for each vector an index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its components.
-
append(other, o_ind=None, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - o_ind
- Indices of the vectors that are to be appended (see class documentation).
- remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x, ind=None, x_ind=None)[source]¶ BLAS AXPY operation.
This method forms the sum
self[ind] = alpha*x[x_ind] + self[ind]
If the length of
x(x_ind) is 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofself(ind) andx(x_ind) have to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands. - ind
- Indices of the vectors of
selfthat are to be added (see class documentation). Repeated indices are forbidden. - x_ind
- Indices of the vectors in
xthat are to be added (see class documentation). Repeated indices are allowed.
-
components(component_indices, ind=None)[source]¶ Extract components of the vectors contained in the array.
Parameters
- component_indices
- List or 1D
NumPy arrayof indices of the vector components that are to be returned. - ind
- Indices of the vectors whose components are to be retrieved (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thecomponent_indices[j]-th component of theind[i]-th vector of the array.
-
copy(ind=None, deep=False)[source]¶ Returns a copy of a subarray.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in array are copied (i.e.indis specified).Parameters
- ind
- Indices of the vectors that are to be copied (see class documentation).
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dot(other, ind=None, o_ind=None)[source]¶ Returns the inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
l1_norm(ind=None)[source]¶ The l1-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
l2_norm(ind=None)[source]¶ The l2-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
lincomb(coefficients, ind=None)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self). - ind
- Indices of the vectors which are linear combined (see class documentation).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other, ind=None, o_ind=None)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
remove(ind=None)[source]¶ Remove vectors from the array.
Parameters
- ind
- Indices of the vectors that are to be removed (see class documentation).
-
replace(other, ind=None, o_ind=None, remove_from_other=False)[source]¶ Replace vectors of the array.
Parameters
- other
- A
VectorArraycontaining the replacement vectors. - ind
- Indices of the vectors that are to be replaced (see class documentation). Repeated indices are forbidden.
- o_ind
- Indices of the replacement vectors (see class documentation).
len(ind)has to agree withlen(o_ind). Repeated indices are allowed. - remove_from_other
- If
True, the new vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
scal(alpha, ind=None)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self[ind] = alpha*self[ind]
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied. - ind
- Indices of the vectors of
selfthat are to be scaled (see class documentation). Repeated indices are forbidden.
-
class
pymor.vectorarrays.mpi.MPIVectorArrayAutoComm(cls, subtype, obj_id)[source]¶ Bases:
pymor.vectorarrays.mpi.MPIVectorArrayMPI distributed
VectorArray.This is a subclass of
MPIVectorArraywhich provides default implementations for all communication requiring interface methods for the case when the wrapped array is not MPI aware.Note, however, that depending on the discretization these default implementations might lead to wrong results (for instance in the presence of shared DOFs).
Methods
Attributes
MPIVectorArrayAutoCommdimMPIVectorArraysubtypeVectorArrayInterfacedata,spaceBasicInterfacelocked,logger,logging_disabled,name,uid-
amax(ind=None)[source]¶ The maximum absolute value of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose maximum absolute value is to be calculated (see class documentation).
Returns
- max_ind
NumPy arraycontaining for each vector an index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its components.
-
components(component_indices, ind=None)[source]¶ Extract components of the vectors contained in the array.
Parameters
- component_indices
- List or 1D
NumPy arrayof indices of the vector components that are to be returned. - ind
- Indices of the vectors whose components are to be retrieved (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thecomponent_indices[j]-th component of theind[i]-th vector of the array.
-
dot(other, ind=None, o_ind=None)[source]¶ Returns the inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
l1_norm(ind=None)[source]¶ The l1-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
l2_norm(ind=None)[source]¶ The l2-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
pairwise_dot(other, ind=None, o_ind=None)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
-
class
pymor.vectorarrays.mpi.MPIVectorArrayNoComm(cls, subtype, obj_id)[source]¶ Bases:
pymor.vectorarrays.mpi.MPIVectorArrayMPI distributed
VectorArray.This is a subclass of
MPIVectorArraywhich overrides all communication requiring interface methods to raiseNotImplementedError.This is mainly useful as a security measure when wrapping arrays for which simply calling the respective method on the wrapped arrays would lead to wrong results and
MPIVectorArrayAutoCommcannot be used either (for instance in the presence of shared DOFs).Methods
Attributes
MPIVectorArrayNoCommdimMPIVectorArraysubtypeVectorArrayInterfacedata,spaceBasicInterfacelocked,logger,logging_disabled,name,uid-
amax(ind=None)[source]¶ The maximum absolute value of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose maximum absolute value is to be calculated (see class documentation).
Returns
- max_ind
NumPy arraycontaining for each vector an index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its components.
-
components(component_indices, ind=None)[source]¶ Extract components of the vectors contained in the array.
Parameters
- component_indices
- List or 1D
NumPy arrayof indices of the vector components that are to be returned. - ind
- Indices of the vectors whose components are to be retrieved (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thecomponent_indices[j]-th component of theind[i]-th vector of the array.
-
dot(other, ind=None, o_ind=None)[source]¶ Returns the inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
l1_norm(ind=None)[source]¶ The l1-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
l2_norm(ind=None)[source]¶ The l2-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
pairwise_dot(other, ind=None, o_ind=None)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
-
class
pymor.vectorarrays.mpi.MPIVectorAutoComm(cls, subtype, obj_id)[source]¶ Bases:
pymor.vectorarrays.mpi.MPIVectorMPI distributed Vector.
This is a subclass of
MPIVectorwhich provides default implementations for all communication requiring interface methods for the case when the wrapped vector is not MPI aware.Note, however, that depending on the discretization these default implementations might lead to wrong results (for instance in the presence of shared DOFs).
Methods
MPIVectorAutoCommamax,components,dot,l1_norm,l2_normMPIVectoraxpy,copy,make_zeros,scalVectorInterfacesup_normBasicInterfacedisable_logging,enable_logging,has_interface_name,implementor_names,implementors,lock,unlock,__setattr__Attributes
MPIVectorAutoCommdimMPIVectorsubtypeBasicInterfacelocked,logger,logging_disabled,name,uid
-
class
pymor.vectorarrays.mpi.MPIVectorNoComm[source]¶ Bases:
objectMPI distributed Vector.
This is a subclass of
MPIVectorwhich overrides all communication requiring interface methods to raiseNotImplementedError.This is mainly useful as a security measure when wrapping vectors for which simply calling the respective method on the wrapped vectors would lead to wrong results and
MPIVectorAutoCommcannot be used either (for instance in the presence of shared DOFs).Methods
MPIVectorNoCommamax,components,dot,l1_norm,l2_norm,pairwise_dotAttributes
MPIVectorNoCommdim
-
class
pymor.vectorarrays.numpy.NumpyVectorArray(instance, dtype=None, copy=False, order=None, subok=False)[source]¶ Bases:
pymor.vectorarrays.interfaces.VectorArrayInterfaceVectorArrayimplementation viaNumPy arrays.This is the default
VectorArraytype used by allOperatorsin pyMOR’s discretization toolkit. Moreover, all reducedOperatorsare based onNumpyVectorArray.Note that this class is just a thin wrapper around the underlying
NumPy array. Thus, while operations likeaxpyordotwill be quite efficient, removing or appending vectors will be costly.Methods
Attributes
NumpyVectorArraydata,dim,imag,real,subtypeVectorArrayInterfacespaceBasicInterfacelocked,logger,logging_disabled,name,uid-
amax(ind=None)[source]¶ The maximum absolute value of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose maximum absolute value is to be calculated (see class documentation).
Returns
- max_ind
NumPy arraycontaining for each vector an index at which the maximum is attained.- max_val
NumPy arraycontaining for each vector the maximum absolute value of its components.
-
append(other, o_ind=None, remove_from_other=False)[source]¶ Append vectors to the array.
Parameters
- other
- A
VectorArraycontaining the vectors to be appended. - o_ind
- Indices of the vectors that are to be appended (see class documentation).
- remove_from_other
- If
True, the appended vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
axpy(alpha, x, ind=None, x_ind=None)[source]¶ BLAS AXPY operation.
This method forms the sum
self[ind] = alpha*x[x_ind] + self[ind]
If the length of
x(x_ind) is 1, the samexvector is used for all vectors inself. Otherwise, the lengths ofself(ind) andx(x_ind) have to agree. Ifalphais a scalar, eachxvector is multiplied with the same factoralpha. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the coefficients for eachxvector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inxare multiplied. - x
- A
VectorArraycontaining the x-summands. - ind
- Indices of the vectors of
selfthat are to be added (see class documentation). Repeated indices are forbidden. - x_ind
- Indices of the vectors in
xthat are to be added (see class documentation). Repeated indices are allowed.
-
components(component_indices, ind=None)[source]¶ Extract components of the vectors contained in the array.
Parameters
- component_indices
- List or 1D
NumPy arrayof indices of the vector components that are to be returned. - ind
- Indices of the vectors whose components are to be retrieved (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i, j]is thecomponent_indices[j]-th component of theind[i]-th vector of the array.
-
copy(ind=None, deep=False)[source]¶ Returns a copy of a subarray.
All
VectorArrayimplementations in pyMOR have copy-on-write semantics: if not specified otherwise by settingdeeptoTrue, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.Note that for
NumpyVectorArray, a deep copy is always performed when only some vectors in array are copied (i.e.indis specified).Parameters
- ind
- Indices of the vectors that are to be copied (see class documentation).
- deep
- Ensure that an actual copy of the array data is made (see above).
Returns
A copy of the
VectorArray.
-
dot(other, ind=None, o_ind=None)[source]¶ Returns the inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
l1_norm(ind=None)[source]¶ The l1-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
l2_norm(ind=None)[source]¶ The l2-norms of the vectors contained in the array.
Parameters
- ind
- Indices of the vectors whose norms are to be calculated (see class documentation).
Returns
A
NumPy arrayresultsuch thatresult[i]contains the norm ofself[ind[i]].
-
lincomb(coefficients, ind=None)[source]¶ Returns linear combinations of the vectors contained in the array.
Parameters
- coefficients
- A
NumPy arrayof dimension 1 or 2 containing the linear coefficients.coefficients.shape[-1]has to agree withlen(self). - ind
- Indices of the vectors which are linear combined (see class documentation).
Returns
A
VectorArrayresultsuch thatresult[i] = ∑ self[j] * coefficients[i,j]in case
coefficientsis of dimension 2, otherwiselen(result) == 1andresult[0] = ∑ self[j] * coefficients[j].
-
pairwise_dot(other, ind=None, o_ind=None)[source]¶ Returns the pairwise inner products between
VectorArrayelements.Parameters
- other
- A
VectorArraycontaining the second factors. - ind
- Indices of the vectors whose inner products are to be taken (see class documentation).
- o_ind
- Indices of the vectors in
otherwhose inner products are to be taken (see class documentation).
-
remove(ind=None)[source]¶ Remove vectors from the array.
Parameters
- ind
- Indices of the vectors that are to be removed (see class documentation).
-
replace(other, ind=None, o_ind=None, remove_from_other=False)[source]¶ Replace vectors of the array.
Parameters
- other
- A
VectorArraycontaining the replacement vectors. - ind
- Indices of the vectors that are to be replaced (see class documentation). Repeated indices are forbidden.
- o_ind
- Indices of the replacement vectors (see class documentation).
len(ind)has to agree withlen(o_ind). Repeated indices are allowed. - remove_from_other
- If
True, the new vectors are removed fromother. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
-
scal(alpha, ind=None)[source]¶ BLAS SCAL operation (in-place scalar multiplication).
This method calculates
self[ind] = alpha*self[ind]
If
alphais a scalar, each vector is multiplied by this scalar. Otherwise,alphahas to be a one-dimensionalNumPy arrayof the same length asself(ind) containing the factors for each vector.Parameters
- alpha
- The scalar coefficient or one-dimensional
NumPy arrayof coefficients with which the vectors inselfare multiplied. - ind
- Indices of the vectors of
selfthat are to be scaled (see class documentation). Repeated indices are forbidden.
-
-
pymor.vectorarrays.numpy.NumpyVectorSpace(dim)[source]¶ Shorthand for
VectorSpace(NumpyVectorArray, dim).
Demo Applications¶
pymordemos package¶
Submodules¶
analyze_pickle module¶
Analyze pickled data demo.
- Usage:
- analyze_pickle.py histogram [–detailed=DETAILED_DATA] [–error-norm=NORM] REDUCED_DATA SAMPLES analyze_pickle.py convergence [–detailed=DETAILED_DATA] [–error-norm=NORM] [–ndim=NDIM] REDUCED_DATA SAMPLES analyze_pickle.py (-h | –help)
This demo loads a pickled reduced discretization, solves for random parameters, estimates the reduction errors and then visualizes these estimates. If the detailed discretization and the reconstructor are also provided, the estimated error is visualized in comparison to the real reduction error.
The needed data files are created by the thermal block demo, by setting the ‘–pickle’ option.
- Arguments:
REDUCED_DATA File containing the pickled reduced discretization.
SAMPLES Number of parameter samples to test with.
- Options:
--detailed=DETAILED_DATA File containing the high-dimensional discretization and the reconstructor. --error-norm=NORM Name of norm in which to compute the errors. --ndim=NDIM Number of reduced basis dimensions for which to estimate the error.
burgers module¶
Burgers demo.
Solves a two-dimensional Burgers-type equation. See pymor.analyticalproblems.burgers for more details.
- Usage:
- burgers.py [-hp] [–grid=NI] [–grid-type=TYPE] [–initial-data=TYPE] [–lxf-lambda=VALUE] [–nt=COUNT]
- [–not-periodic] [–num-flux=FLUX] [–vx=XSPEED] [–vy=YSPEED] EXP
- Arguments:
- EXP Exponent
- Options:
--grid=NI Use grid with (2*NI)*NI elements [default: 60]. --grid-type=TYPE Type of grid to use (rect, tria) [default: rect]. --initial-data=TYPE Select the initial data (sin, bump) [default: sin] --lxf-lambda=VALUE Parameter lambda in Lax-Friedrichs flux [default: 1]. --nt=COUNT Number of time steps [default: 100]. --not-periodic Solve with dirichlet boundary conditions on left and bottom boundary. --num-flux=FLUX Numerical flux to use (lax_friedrichs, engquist_osher) [default: lax_friedrichs]. -h, --help Show this message. --vx=XSPEED Speed in x-direction [default: 1]. --vy=YSPEED Speed in y-direction [default: 1].
burgers_ei module¶
Burgers with EI demo.
Model order reduction of a two-dimensional Burgers-type equation (see pymor.analyticalproblems.burgers) using the reduced basis method with empirical operator interpolation.
- Usage:
- burgers_ei.py [options] EXP_MIN EXP_MAX EI_SNAPSHOTS EISIZE SNAPSHOTS RBSIZE
- Arguments:
EXP_MIN Minimal exponent
EXP_MAX Maximal exponent
EI_SNAPSHOTS Number of snapshots for empirical interpolation.
EISIZE Number of interpolation DOFs.
SNAPSHOTS Number of snapshots for basis generation.
RBSIZE Size of the reduced basis
- Options:
--cache-region=REGION Name of cache region to use for caching solution snapshots (NONE, MEMORY, DISK, PERSISTENT) [default: DISK] --grid=NI Use grid with (2*NI)*NI elements [default: 60]. --grid-type=TYPE Type of grid to use (rect, tria) [default: rect]. --initial-data=TYPE Select the initial data (sin, bump) [default: sin] --lxf-lambda=VALUE Parameter lambda in Lax-Friedrichs flux [default: 1]. --not-periodic Solve with dirichlet boundary conditions on left and bottom boundary. --nt=COUNT Number of time steps [default: 100]. --num-flux=FLUX Numerical flux to use (lax_friedrichs, engquist_osher) [default: lax_friedrichs]. -h, --help Show this message. -p, --plot-err Plot error. --plot-ei-err Plot empirical interpolation error. --plot-error-landscape Calculate and show plot of reduction error vs. basis sizes. --plot-error-landscape-N=COUNT Number of basis sizes to test [default: 10] --plot-error-landscape-M=COUNT Number of collateral basis sizes to test [default: 10] --plot-solutions Plot some example solutions. --test=COUNT Use COUNT snapshots for stochastic error estimation [default: 10]. --vx=XSPEED Speed in x-direction [default: 1]. --vy=YSPEED Speed in y-direction [default: 1]. --ipython-engines=COUNT If positive, the number of IPython cluster engines to use for parallel greedy search. If zero, no parallelization is performed. [default: 0] --ipython-profile=PROFILE IPython profile to use for parallelization.
elliptic module¶
Simple demonstration of solving the Poisson equation in 2D using pyMOR’s builtin discretizations.
- Usage:
- elliptic.py [–fv] [–rect] PROBLEM-NUMBER DIRICHLET-NUMBER NEUMANN-NUMBER NEUMANN-COUNT
- Arguments:
PROBLEM-NUMBER {0,1}, selects the problem to solve
DIRICHLET-NUMBER {0,1,2}, selects the Dirichlet data function
NEUMANN-NUMBER {0,1}, selects the Neumann data function
- NEUMANN-COUNT 0: no neumann boundary
- 1: right edge is neumann boundary 2: right+top edges are neumann boundary 3: right+top+bottom edges are neumann boundary
- Options:
-h, --help Show this message. --fv Use finite volume discretization instead of finite elements. --rect Use RectGrid instead of TriaGrid.
elliptic2 module¶
Simple demonstration of solving the Poisson equation in 2D using pyMOR’s builtin discretizations.
- Usage:
- elliptic2.py [–fv] PROBLEM-NUMBER N
- Arguments:
PROBLEM-NUMBER {0,1}, selects the problem to solve
N Triangle count per direction
- Options:
-h, --help Show this message. --fv Use finite volume discretization instead of finite elements.
elliptic_oned module¶
Proof of concept for solving the Poisson equation in 1D using linear finite elements and our grid interface
- Usage:
- elliptic_oned.py [–fv] PROBLEM-NUMBER N
- Arguments:
PROBLEM-NUMBER {0,1}, selects the problem to solve
N Grid interval count
- Options:
-h, --help Show this message. --fv Use finite volume discretization instead of finite elements.
elliptic_unstructured module¶
Simple demonstration of solving the Poisson equation in 2D on a circular sector domain of radius 1 using an unstructured mesh.
Note that Gmsh (http://geuz.org/gmsh/) is required for meshing.
- Usage:
- elliptic_unstructured.py [–fv] ANGLE NUM_POINTS CLSCALE
- Arguments:
ANGLE The angle of the circular sector.
NUM_POINTS The number of points that form the arc of the circular sector.
CLSCALE Mesh element size scaling factor.
- Options:
-h, --help Show this message. --fv Use finite volume discretization instead of finite elements.
parabolic module¶
Simple demonstration of solving the heat equation using pyMOR’s builtin discretizations.
- Usage:
- parabolic.py [-h] [–help] [–fv] [–rect] [–grid=NI] [–nt=COUNT] TOP
- Arguments:
- TOP The heat diffusion coefficient for the top bars.
- Options:
-h, --help Show this message. --fv Use finite volume discretization instead of finite elements. --rect Use RectGrid instead of TriaGrid. --grid=NI Use grid with NIxNI intervals [default: 100]. --nt=COUNT Number of time steps [default: 10].
parabolic_mor module¶
Reduced basis approximation of the heat equation.
- Usage:
- parabolic_mor.py [options] BACKEND ALG SNAPSHOTS RBSIZE TEST
- Arguments:
BACKEND Discretization toolkit to use (pymor, fenics).
- ALG The model reduction algorithm to use
- (greedy, adaptive_greedy, pod).
- SNAPSHOTS greedy/pod: number of training set parameters
- adaptive_greedy: size of validation set.
RBSIZE Size of the reduced basis.
TEST Number of test parameters for reduction error estimation.
thermalblock module¶
Thermalblock demo.
- Usage:
- thermalblock.py [options] XBLOCKS YBLOCKS SNAPSHOTS RBSIZE thermalblock.py -h | –help
- Arguments:
XBLOCKS Number of blocks in x direction.
YBLOCKS Number of blocks in y direction.
SNAPSHOTS naive: ignored
- greedy/pod: Number of training_set parameters per block
- (in total SNAPSHOTS^(XBLOCKS * YBLOCKS) parameters).
adaptive_greedy: size of validation set.
RBSIZE Size of the reduced basis
- Options:
--adaptive-greedy-rho=RHO See pymor.algorithms.adaptivegreedy [default: 1.1]. --adaptive-greedy-gamma=GAMMA See pymor.algorithms.adaptivegreedy [default: 0.2]. --adaptive-greedy-theta=THETA See pymor.algorithms.adaptivegreedy [default: 0.] --alg=ALG The model reduction algorithm to use (naive, greedy, adaptive_greedy, pod) [default: greedy]. --cache-region=REGION Name of cache region to use for caching solution snapshots (none, memory, disk, persistent) [default: none]. --estimator-norm=NORM Norm (euclidean, h1) in which to calculate the residual [default: h1]. --extension-alg=ALG Basis extension algorithm (trivial, gram_schmidt, h1_gram_schmidt) to be used [default: h1_gram_schmidt]. --fenics Use FEniCS discretization. --grid=NI Use grid with 4*NI*NI elements [default: 100]. -h, --help Show this message. --ipython-engines=COUNT If positive, the number of IPython cluster engines to use for parallel greedy search. If zero, no parallelization is performed. [default: 0] --ipython-profile=PROFILE IPython profile to use for parallelization. --list-vector-array Solve using ListVectorArray[NumpyVector] instead of NumpyVectorArray. --order=ORDER Polynomial order of the Lagrange finite elements to use in FEniCS discretization [default: 1]. --pickle=PREFIX Pickle reduced discretizaion, as well as reconstructor and high-dimensional discretization to files with this prefix. --plot-err Plot error. --plot-solutions Plot some example solutions. --plot-error-sequence Plot reduction error vs. basis size. --pod-product=PROD Inner product w.r.t. with to compute the pod (euclidean, h1) [default: h1]. --reductor=RED Reductor (error estimator) to choose (traditional, residual_basis) [default: residual_basis] --test=COUNT Use COUNT snapshots for stochastic error estimation [default: 10]. --greedy-without-estimator Do not use error estimator for basis generation.
-
pymordemos.thermalblock.discretize_fenics(xblocks, yblocks, grid_num_intervals, element_order)[source]¶
-
pymordemos.thermalblock.discretize_pymor(xblocks, yblocks, grid_num_intervals, use_list_vector_array)[source]¶
-
pymordemos.thermalblock.reduce_adaptive_greedy(d, reductor, validation_mus, extension_alg_name, max_extensions, use_estimator, rho, gamma, theta, pool)[source]¶
-
pymordemos.thermalblock.reduce_greedy(d, reductor, snapshots_per_block, extension_alg_name, max_extensions, use_estimator, pool)[source]¶
-
pymordemos.thermalblock.reduce_pod(d, reductor, snapshots_per_block, product_name, basis_size)[source]¶
thermalblock_adaptive module¶
Modified thermalblock demo using adaptive greedy basis generation algorithm.
- Usage:
- thermalblock_adaptive.py [options] RBSIZE thermalblock_adaptive.py -h | –help
- Arguments:
- RBSIZE Size of the reduced basis
- Options:
-h, --help Show this message. --estimator-norm=NORM Norm (trivial, h1) in which to calculate the residual [default: h1]. --without-estimator Do not use error estimator for basis generation. --extension-alg=ALG Basis extension algorithm (trivial, gram_schmidt, h1_gram_schmidt) to be used [default: h1_gram_schmidt]. --grid=NI Use grid with 2*NI*NI elements [default: 100]. --pickle=PREFIX Pickle reduced discretizaion, as well as reconstructor and high-dimensional discretization to files with this prefix. -p, --plot-err Plot error. --plot-solutions Plot some example solutions. --plot-error-sequence Plot reduction error vs. basis size. --reductor=RED Reductor (error estimator) to choose (traditional, residual_basis) [default: residual_basis] --test=COUNT Use COUNT snapshots for stochastic error estimation [default: 10]. --ipython-engines=COUNT If positive, the number of IPython cluster engines to use for parallel greedy search. If zero, no parallelization is performed. [default: 0] --ipython-profile=PROFILE IPython profile to use for parallelization. --cache-region=REGION Name of cache region to use for caching solution snapshots (NONE, MEMORY, DISK, PERSISTENT) [default: NONE] --list-vector-array Solve using ListVectorArray[NumpyVector] instead of NumpyVectorArray. --visualize-refinement Visualize the training set refinement indicators. --validation-mus Size of validation set. [default: 0] --rho=VALUE Maximum allowed ratio between error on validation set and on training set [default: 1.1]. --gamma=VALUE Weight factor for age penalty term in refinement indicators [default: 0.2]. --theta=VALUE Ratio of elements to refine [default: 0.].
thermalblock_gui module¶
Thermalblock with GUI demo
- Usage:
- thermalblock_gui.py [-h] [–estimator-norm=NORM] [–grid=NI] [–testing]
- [–help] XBLOCKS YBLOCKS SNAPSHOTS RBSIZE
- Arguments:
XBLOCKS Number of blocks in x direction.
YBLOCKS Number of blocks in y direction.
- SNAPSHOTS Number of snapshots for basis generation per component.
- In total SNAPSHOTS^(XBLOCKS * YBLOCKS).
RBSIZE Size of the reduced basis
- Options:
--estimator-norm=NORM Norm (trivial, h1) in which to calculate the residual [default: h1]. --grid=NI Use grid with 2*NI*NI elements [default: 60]. --testing load the gui and exit right away (for functional testing) -h, --help Show this message.
-
class
pymordemos.thermalblock_gui.AllPanel(parent, reduced_sim, detailed_sim)[source]¶ Bases:
object
-
class
pymordemos.thermalblock_gui.DetailedSim(args)[source]¶ Bases:
pymordemos.thermalblock_gui.SimBaseMethods
DetailedSimsolve
-
class
pymordemos.thermalblock_gui.ParamRuler(parent, sim)[source]¶ Bases:
objectMethods
ParamRulerenable
-
class
pymordemos.thermalblock_gui.ReducedSim(args)[source]¶ Bases:
pymordemos.thermalblock_gui.SimBaseMethods
ReducedSimsolve
thermalblock_simple module¶
Simplified version of the thermalblock demo.
- Usage:
- thermalblock_simple.py [options] MODEL ALG SNAPSHOTS RBSIZE TEST
- Arguments:
MODEL High-dimensional model (pymor, fenics).
- ALG The model reduction algorithm to use
- (naive, greedy, adaptive_greedy, pod).
SNAPSHOTS naive: ignored
- greedy/pod: Number of training_set parameters per block
- (in total SNAPSHOTS^(XBLOCKS * YBLOCKS) parameters).
adaptive_greedy: size of validation set.
RBSIZE Size of the reduced basis.
TEST Number of parameters for stochastic error estimation.
-
pymordemos.thermalblock_simple.reduce_adaptive_greedy(d, reductor, validation_mus, basis_size)[source]¶