pymor.tools package

Submodules

context module


class pymor.tools.context.NoContext[source]

Bases: object

counter module


class pymor.tools.counter.Counter(start=0)[source]

Bases: object

Methods

Counter inc

deprecated module


class pymor.tools.deprecated.Deprecated(alt='no alternative given')[source]

Bases: object

This 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.

__call__(func)[source]

Call self as a function.

__get__(obj, ownerClass=None)[source]

Return a wrapper that binds self as a method of obj (!)

docopt module

MIT License Copyright (c) 2012 Vladimir Keleshev, <vladimir@keleshev.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


class pymor.tools.docopt.AnyOptions(*children)[source]

Bases: pymor.tools.docopt.Optional

Marker/placeholder for [options] shortcut.

Attributes

Pattern either

class pymor.tools.docopt.Argument(name, value=None)[source]

Bases: pymor.tools.docopt.ChildPattern

Methods

Argument parse, single_match
ChildPattern flat, match
Pattern fix, fix_identities, fix_repeating_arguments

Attributes

Pattern either

class pymor.tools.docopt.ChildPattern(name, value=None)[source]

Bases: pymor.tools.docopt.Pattern

Attributes

Pattern either
__repr__()[source]

Return repr(self).


class pymor.tools.docopt.Command(name, value=False)[source]

Bases: pymor.tools.docopt.Argument

Methods

Command single_match
Argument parse
ChildPattern flat, match
Pattern fix, fix_identities, fix_repeating_arguments

Attributes

Pattern either

class pymor.tools.docopt.Dict[source]

Bases: dict

Methods

dict clear, copy, fromkeys, get, items, keys, pop, popitem, setdefault, update, values, __contains__, __getitem__, __new__, __sizeof__
__repr__()[source]

Return repr(self).


class pymor.tools.docopt.DocoptExit(message='')[source]

Bases: SystemExit

Exit in case user invoked program with incorrect arguments.

Methods

BaseException with_traceback, __new__

Attributes

DocoptExit usage
SystemExit code
BaseException args

class pymor.tools.docopt.DocoptLanguageError[source]

Bases: Exception

Error in construction of usage-message by developer.

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.tools.docopt.Either(*children)[source]

Bases: pymor.tools.docopt.ParentPattern

Attributes

Pattern either

class pymor.tools.docopt.OneOrMore(*children)[source]

Bases: pymor.tools.docopt.ParentPattern

Attributes

Pattern either

class pymor.tools.docopt.Option(short=None, long=None, argcount=0, value=False)[source]

Bases: pymor.tools.docopt.ChildPattern

Methods

Option parse, single_match
ChildPattern flat, match
Pattern fix, fix_identities, fix_repeating_arguments

Attributes

Option name
Pattern either
__repr__()[source]

Return repr(self).


class pymor.tools.docopt.Optional(*children)[source]

Bases: pymor.tools.docopt.ParentPattern

Attributes

Pattern either

class pymor.tools.docopt.ParentPattern(*children)[source]

Bases: pymor.tools.docopt.Pattern

Attributes

Pattern either
__repr__()[source]

Return repr(self).


class pymor.tools.docopt.Pattern[source]

Bases: object

Attributes

Pattern either
__eq__(other)[source]

Return self==value.

__hash__()[source]

Return hash(self).

either

Transform pattern into an equivalent, with only top-level Either.

fix_identities(uniq=None)[source]

Make pattern-tree tips point to same object if they are equal.

fix_repeating_arguments()[source]

Fix elements that should accumulate/increment values.


class pymor.tools.docopt.Required(*children)[source]

Bases: pymor.tools.docopt.ParentPattern

Attributes

Pattern either

class pymor.tools.docopt.TokenStream(source, error)[source]

Bases: list

Methods

TokenStream current, move
list append, clear, copy, count, extend, index, insert, pop, remove, reverse, sort, __getitem__, __new__, __reversed__, __sizeof__

pymor.tools.docopt.docopt(doc, argv=None, help=True, version=None, options_first=False)[source]

Parse argv based on command-line interface described in doc.

docopt creates your command-line interface based on its description that you pass as doc. Such description can contain –options, <positional-argument>, commands, which could be [optional], (required), (mutually | exclusive) or repeated…

Parameters

doc : str
Description of your command-line interface.
argv : list of str, optional
Argument vector to be parsed. sys.argv[1:] is used if not provided.
help : bool (default: True)
Set to False to disable automatic help on -h or –help options.
version : any object
If passed, the object will be printed if –version is in argv.
options_first : bool (default: False)
Set to True to require options preceed positional arguments, i.e. to forbid options and positional arguments intermix.

Returns

args : dict
A dictionary, where keys are names of command-line elements such as e.g. “–verbose” and “<path>”, and values are the parsed values of those elements.

Example

>>> from docopt import docopt
>>> doc = '''
Usage:
    my_program tcp <host> <port> [--timeout=<seconds>]
    my_program serial <port> [--baud=<n>] [--timeout=<seconds>]
    my_program (-h | --help | --version)
Options:
-h, --help Show this screen and exit.
--baud=<n> Baudrate [default: 9600]

‘’’ >>> argv = [‘tcp’, ‘127.0.0.1’, ‘80’, ‘–timeout’, ‘30’] >>> docopt(doc, argv) {‘–baud’: ‘9600’,

‘–help’: False, ‘–timeout’: ‘30’, ‘–version’: False, ‘<host>’: ‘127.0.0.1’, ‘<port>’: ‘80’, ‘serial’: False, ‘tcp’: True}

See also


pymor.tools.docopt.extras(help, version, options, doc)[source]

pymor.tools.docopt.formal_usage(printable_usage)[source]

pymor.tools.docopt.parse_argv(tokens, options, options_first=False)[source]

Parse command-line argument vector.

If options_first:
argv ::= [ long | shorts ]* [ argument ]* [ ‘–’ [ argument ]* ] ;
else:
argv ::= [ long | shorts | argument ]* [ ‘–’ [ argument ]* ] ;

pymor.tools.docopt.parse_atom(tokens, options)[source]

atom ::= ‘(‘ expr ‘)’ | ‘[‘ expr ‘]’ | ‘options’ | long | shorts | argument | command ;


pymor.tools.docopt.parse_defaults(doc)[source]

pymor.tools.docopt.parse_expr(tokens, options)[source]

expr ::= seq ( ‘|’ seq )* ;


pymor.tools.docopt.parse_long(tokens, options)[source]

long ::= ‘–’ chars [ ( ‘ ‘ | ‘=’ ) chars ] ;


pymor.tools.docopt.parse_pattern(source, options)[source]

pymor.tools.docopt.parse_seq(tokens, options)[source]

seq ::= ( atom [ ‘…’ ] )* ;


pymor.tools.docopt.parse_shorts(tokens, options)[source]

shorts ::= ‘-‘ ( chars )* [ [ ‘ ‘ ] chars ] ;


pymor.tools.docopt.printable_usage(doc)[source]

floatcmp module


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 allclose method 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 arrays to 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)


pymor.tools.floatcmp.float_cmp_all(x, y, rtol=None, atol=None)[source]

Compare x and y for almost equality.

Returns True if all components of x are almost equal to the corresponding components of y.

See float_cmp.

formatrepr module


pymor.tools.formatrepr.format_repr(obj, max_width=120, verbosity=1)[source]

pymor.tools.formatrepr.indent_value(val, indent)[source]

pymor.tools.formatrepr.register_format_handler(cls, handler)[source]

frozendict module


class pymor.tools.frozendict.FrozenDict(*args, **kwargs)[source]

Bases: dict

An immutable dictionary.

Methods

dict copy, fromkeys, get, items, keys, values, __contains__, __getitem__, __sizeof__

Attributes

FrozenDict clear, pop, popitem, setdefault, update
static __new__(cls, *args, **kwargs)[source]

Create and return a new object. See help(type) for accurate signature.

__reduce__()[source]

Helper for pickle.

__repr__()[source]

Return repr(self).

inplace module

inverse module


pymor.tools.inverse.inv_transposed_two_by_two(A)[source]

Efficiently compute the tranposed inverses of a NumPy array of 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 array of 2x2-matrices

|  retval[i1,...,ik,m,n] = numpy.linalg.inv(A[i1,...,ik,:,:]).

io module


pymor.tools.io.SafeTemporaryFileName(name=None, parent_dir=None)[source]

Cross Platform safe equivalent of re-opening a NamedTemporaryFile Creates an automatically cleaned up temporary directory with a single file therein.

name: filename component, defaults to ‘temp_file’ dir: the parent dir of the new tmp dir. defaults to tempfile.gettempdir()


pymor.tools.io.load_matrix(path, key=None)[source]

mpi module

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: int

A handle to an MPI distributed object.

Methods

int bit_length, conjugate, from_bytes, to_bytes, __ceil__, __floor__, __new__, __round__, __sizeof__, __trunc__

Attributes

int denominator, imag, numerator, real

pymor.tools.mpi.call(method, *args, **kwargs)[source]

Execute method on all MPI ranks.

Assuming event_loop is running on all MPI ranks (except rank 0), this will execute method on all ranks (including rank 0) with positional arguments args and keyword arguments kwargs.

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 method on rank 0.


pymor.tools.mpi.event_loop()[source]

Launches an MPI-based event loop.

Events can be sent by either calling call on rank 0 to execute an arbitrary method on all ranks or by calling quit to 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 execute event_loop on 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 f with given arguments.

Intended to be used in conjunction with call. Arguments of type ObjectId are transparently mapped to the object they refer to.


pymor.tools.mpi.function_call_manage(f, *args, **kwargs)[source]

Execute the function f and manage the return value.

Intended to be used in conjunction with call. The return value of f is managed by calling manage_object and the corresponding ObjectId is returned. Arguments of type ObjectId are transparently mapped to the object they refer to.


pymor.tools.mpi.get_object(obj_id)[source]

Return the object referred to by obj_id.


pymor.tools.mpi.import_module(path)[source]

Import the module named by path.

Intended to be used in conjunction with call.


pymor.tools.mpi.manage_object(obj)[source]

Keep track of obj and return an ObjectId handle.


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 type ObjectId are transparently mapped to the object they refer to.

Parameters

obj_id
The ObjectId of 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 calling manage_object and the corresponding ObjectId is returned. Arguments of type ObjectId are transparently mapped to the object they refer to.

Parameters

obj_id
The ObjectId of 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_loop to terminate on all MPI ranks.


pymor.tools.mpi.remove_object(obj_id)[source]

Remove the object referred to by obj_id from the registry.


pymor.tools.mpi.run_code(code)[source]

Execute the code string code.

Intended to be used in conjunction with call.

pprint module


pymor.tools.pprint.format_array(array, compact_print=False)[source]

Creates a formatted string representation of a NumPy array.

Parameters

array
the NumPy array to be formatted
compact_print
If True, return a shorter version of string representation.

Returns

The string representation.

Defaults

compact_print (see pymor.core.defaults)

quadratures module


class pymor.tools.quadratures.GaussQuadratures[source]

Bases: object

Gauss quadrature on the interval [0, 1]

Attributes

GaussQuadratures a, order_map, orders, points, weights
classmethod iter_quadrature(order=None, npoints=None)[source]

iterates over a quadrature tuple wise

classmethod quadrature(order=None, npoints=None)[source]

returns tuple (P, W) where P is an array of Gauss points with corresponding weights W for the given integration order “order” or with “npoints” integration points

random module


pymor.tools.random.default_random_state(seed=42)[source]

Returns the default NumPy RandomState.

Parameters

seed
Seed to use for initializing the random state.

Returns

The default RandomState object.

Defaults

seed (see pymor.core.defaults)


pymor.tools.random.get_random_state(random_state=None, seed=None)[source]

Returns a NumPy RandomState.

Parameters

random_state
If specified, this state is returned.
seed
If specified, the seed to initialize a new random state.

Returns

Either the provided, a newly created or the default RandomState object.

relations module

table module


pymor.tools.table.format_table(rows, width='AUTO', title=None)[source]

timing module


class pymor.tools.timing.Timer(section, log=<Logger pymor.tools.timing (INFO)>)[source]

Bases: object

You 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

Timer start, stop
__call__(func)[source]

Call self as a function.


pymor.tools.timing.busywait(amount)[source]

vtkio module


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 Grid with triangular or rectilinear reference element.
data
VectorArray with either cell (ie one datapoint per codim 0 entity) or vertex (ie one datapoint per codim 2 entity) data in each array element.
codim
the codimension associated with the data
filename_base
common component for output files in timeseries
binary_vtk
if false, output files contain human readable inline ascii data, else appended binary
last_step
if set must be <= len(data) to restrict output of timeseries