petsctools package

Submodules

petsctools.citation module

Module containing functions for registering citations through PETSc.

The functions in this module may be used to record Bibtex citation information and then register that a particular citation is relevant for a particular computation. It hooks up with PETSc’s citation registration mechanism, so that running with -citations does the right thing.

Example usage:

petsctools.add_citation("key", "bibtex-entry-for-my-funky-method")

...

if using_funky_method:
    petsctools.cite("key")
petsctools.citation.add_citation(cite_key: str, entry: str) None

Add a paper to the database of possible citations.

Parameters:
  • cite_key – The key to use.

  • entry – The bibtex entry.

petsctools.citation.cite(cite_key: str) None

Cite a paper.

The paper should already have been added to the citations database using add_citation.

Parameters:

cite_key – The key of the relevant citation.

Raises:

KeyError : – If no such citation is found in the database.

petsctools.citation.print_citations_at_exit() None

Print citations at the end of the program.

petsctools.config module

exception petsctools.config.MissingPetscException

Bases: PetscToolsException

petsctools.config.get_blas_library()

Get the path to the BLAS library that PETSc links to.

petsctools.config.get_config()
petsctools.config.get_external_packages()

Return a list of PETSc external packages that are installed.

petsctools.config.get_petsc_arch()
petsctools.config.get_petsc_dir()
petsctools.config.get_petsc_dirs(*, prefix: str = '', subdir: str | None = None) tuple[str, str]

Return $PETSC_DIR and $PETSC_DIR/$PETSC_ARCH.

This function is useful for generating compiler arguments. For example

get_petsc_dirs(subdir="include", prefix="-I")

will return

("-I/path/to/petsc/include", "-I/path/to/petsc/mypetscarch/include")
Parameters:
  • prefix – Optional prefix to prepend to the paths.

  • subdir – Optional subdirectory to include in the returned paths.

Returns:

$PETSC_DIR and $PETSC_DIR/$PETSC_ARCH with appropriate sub-directories and prefixes.

Return type:

tuple

petsctools.config.get_petscconf_h()

Get dict of PETSc include variables from the file: $PETSC_DIR/$PETSC_ARCH/include/petscconf.h

The #define and PETSC_ prefix are dropped in the dictionary key.

The result is memoized to avoid constantly reading the file.

petsctools.config.get_petscvariables()

Return PETSc’s configuration information.

petsctools.exceptions module

exception petsctools.exceptions.PetscToolsException

Bases: Exception

Generic base class for petsctools exceptions.

exception petsctools.exceptions.PetscToolsNotInitialisedException

Bases: PetscToolsException

Exception raised when petsctools should have been initialised.

exception petsctools.exceptions.PetscToolsWarning

Bases: UserWarning

Generic base class for petsctools warnings.

petsctools.init module

exception petsctools.init.InvalidEnvironmentException

Bases: PetscToolsException

exception petsctools.init.InvalidPetscVersionException

Bases: PetscToolsException

petsctools.init.check_environment_matches_petsc4py_config()
petsctools.init.check_petsc_version(version_spec) None
petsctools.init.init(argv=None, *, version_spec='')

Initialise PETSc.

petsctools.options module

class petsctools.options.DefaultOptionSet(base_prefix: str, custom_prefix_endings: Iterable)

Bases: object

Defines a set of common default options shared by multiple PETSc objects.

Some solvers, e.g. PCFieldsplit, create multiple subsolvers whose prefixes differ only by the final characters, e.g. 'fieldsplit_0', 'fieldsplit_1'. It is often useful to be able to set default options for these subsolvers using the un-specialised prefix e.g. 'fieldsplit_ksp_type'. However, just grabbing all options with the 'fieldsplit' prefix will erroneously find options like '0_ksp_type' and '1_ksp_type' that were meant for a specific subsolver.

DefaultOptionSet defines a base prefix (e.g. 'fieldsplit') and a set of custom prefix endings (e.g. [0, 1]). If passed to an OptionsManager then any default options present in the global options database will be used if those options are not present either: in the parameters passed to the OptionsManager; or in the global PETSc.Options database with the options_prefix passed to the OptionsManager.

For example, to set up a fieldsplit solver you might have the following options, where both fields are to use ILU as the preconditioner but each field uses a different KSP type.

-fieldsplit_pc_type ilu
-fieldsplit_0_ksp_type preonly
-fieldsplit_1_ksp_type richardson

To create an OptionsManager for each field you would call:

default_options_set = DefaultOptionSet(
     base_prefix='fieldsplit',
     custom_prefix_endings=(0, 1))

fieldsplit_0_options = OptionsManager(
    parameters={},
     options_prefix="fieldsplit_0",
    default_options_set=default_options_set)

fieldsplit_1_options = OptionsManager(
    parameters={},
     options_prefix="fieldsplit_1",
    default_options_set=default_options_set)
Parameters:
  • base_prefix – The prefix for the default options, which is the beginning of each full custom prefix.

  • custom_prefix_endings – The ends of each individual custom prefix. Often a range of integers.

Notes

The base prefix and each custom prefix ending will be converted to a string and have an underscore appended if they do not already have one.

property base_prefix

The prefix for the default options.

property custom_prefix_endings

The ends of each individual custom prefix.

property custom_prefixes

The full custom prefixes.

class petsctools.options.OptionsManager(parameters: dict, options_prefix: str | None = None, default_prefix: str | None = None, default_options_set: DefaultOptionSet | None = None)

Bases: object

Class that helps with managing setting PETSc options.

The recommended way to use the OptionsManager is by using the attach_options(), set_from_options(), and inserted_options() free functions. These functions ensure that each OptionsManager is associated to a single PETSc object.

For detail on the previous approach of using OptionsManager as a mixin class (where the user takes responsibility for ensuring an association with a single PETSc object), see below.

To use the OptionsManager:

  1. Pass a PETSc object a parameters dictionary, and optionally an options prefix, to attach_options(). This will create an OptionsManager and set the prefix of the PETSc object, but will not yet set it up.

  2. Once the object is ready, pass it to set_from_options(), which will insert the solver options into PETSc.Options and call obj.setFromOptions.

  3. The inserted_options() context manager must be used when calling methods on the PETSc object within which solver options will be read, for example solve. This will insert the provided parameters into PETSc’s global options dictionary within the context manager, and remove them afterwards. This ensures that the global options dictionary will not grow indefinitely if many OptionsManager instances are used.

ksp = PETSc.KSP().create(comm=comm)
ksp.setOperators(mat)

attach_options(ksp, parameters=parameters,
               options_prefix=prefix)

# ...

set_from_options(ksp)

# ...

with inserted_options(ksp):
    ksp.solve(b, x)

To access the OptionsManager for a PETSc object directly use the get_options() function:

N = get_options(ksp).getInt(prefix+"N")

Using OptionsManager as a mixin class:

To use this, you must call its constructor with the parameters you want in the options database, and optionally a prefix to extract options from the global database.

You then call set_from_options(), passing the PETSc object you’d like to call setFromOptions on. Note that this will actually only call setFromOptions the first time (so really this parameters object is a once-per-PETSc-object thing).

So that the runtime monitors which look in the options database actually see options, you need to ensure that the options database is populated at the time of a SNESSolve or KSPSolve call. Do that using the OptionsManager.inserted_options() context manager.

If using as a mixin class, call the OptionsManager methods directly:

self.set_from_options(self.snes)

with self.inserted_options():
    self.snes.solve(...)

This ensures that the options database has the relevant entries for the duration of the with block, before removing them afterwards. This is a much more robust way of dealing with the fixed-size options database than trying to clear it out using destructors.

This object can also be used only to manage insertion and deletion into the PETSc options database, by using the context manager.

Parameters:
  • parameters – The dictionary of parameters to use.

  • options_prefix – The prefix to look up items in the global options database (may be None, in which case only entries from parameters will be considered. If no trailing underscore is provided, one is appended. Hence foo_ and foo are treated equivalently. As an exception, if the prefix is the empty string, no underscore is appended.

  • default_prefix – The base string to generate default prefixes. If options_prefix is not provided then a prefix is automatically generated with the form “{default_prefix}_{n}”, where n is a unique integer. Note that because the unique integer is not stable any options passed via the command line with a matching prefix will be ignored.

  • default_options_set – The prefix set for any default shared with other solvers. See DefaultOptionSet for more information.

count = count(0)
inserted_options()

Context manager inside which the petsc options database contains the parameters from this object.

property options_object
set_default_parameter(key: str, val: Any) None

Set a default parameter value.

Parameters:
  • key – The parameter name.

  • val – The parameter value.

  • options (Ensures that the right thing happens cleaning up the)

  • database.

set_from_options(petsc_obj)

Set up petsc_obj from the options database.

Parameters:

petsc_obj – The PETSc object to call setFromOptions on.

Raises PetscToolsWarning if this method has already been called.

Matt says: “Only ever call setFromOptions once”. This function ensures we do so.

petsctools.options.attach_options(obj: petsc4py.PETSc.Object, parameters: dict | None = None, options_prefix: str | None = None, default_prefix: str | None = None, default_options_set: DefaultOptionSet | None = None) None

Set up an OptionsManager and attach it to a PETSc Object.

Parameters:
  • obj – The object to attach an OptionsManager to.

  • parameters – The dictionary of parameters to use.

  • options_prefix – The options prefix to use for this object.

  • default_prefix – Base string for autogenerated default prefixes.

  • default_options_set – The prefix set for any default shared with other solvers.

petsctools.options.flatten_parameters(parameters, sep='_')

Flatten a nested parameters dict, joining keys with sep.

Parameters:
  • parameters – a dict to flatten.

  • sep – separator of keys.

Used to flatten parameter dictionaries with nested structure to a flat dict suitable to pass to PETSc. For example:

flatten_parameters({"a": {"b": {"c": 4}, "d": 2}, "e": 1}, sep="_")
=> {"a_b_c": 4, "a_d": 2, "e": 1}

If a “prefix” key already ends with the provided separator, then it is not used to concatenate the keys. Hence:

flatten_parameters({"a_": {"b": {"c": 4}, "d": 2}, "e": 1}, sep="_")
=> {"a_b_c": 4, "a_d": 2, "e": 1}
# rather than
=> {"a__b_c": 4, "a__d": 2, "e": 1}
petsctools.options.get_commandline_options() frozenset

Return the PETSc options passed on the command line.

petsctools.options.get_default_options(default_options_set: DefaultOptionSet, options: petsc4py.PETSc.Options | None = None) dict

Extract default options for subsolvers with similar prefixes.

Parameters:
  • default_options_set – The DefaultOptionSet which defines the shared options.

  • options – The PETSc.Options database to use. If not provided then the global database will be used.

Return type:

The dictionary of default options with the base prefix stripped.

See also

DefaultOptionSet

petsctools.options.get_options(obj: petsc4py.PETSc.Object) OptionsManager

Return the OptionsManager attached to this PETSc object.

Parameters:

obj – The object to get the OptionsManager from.

Return type:

The OptionsManager attached to the object.

Raises:

PetscToolsException – If the object does not have an OptionsManager.

petsctools.options.has_options(obj: petsc4py.PETSc.Object) bool

Return whether this PETSc object has an OptionsManager attached.

Parameters:

obj – The object which may have an OptionsManager.

Return type:

Whether the object has an OptionsManager.

petsctools.options.inserted_options(obj)

Context manager inside which the PETSc options database contains the parameters from this object’s OptionsManager.

Parameters:

obj – The object which may have been set from options.

Raises:

PetscToolsException – If the object does not have an OptionsManager.

petsctools.options.is_set_from_options(obj: petsc4py.PETSc.Object) bool

Return whether this PETSc object has been set by the OptionsManager.

Parameters:

obj – The object which may have been set from options.

Return type:

Whether the object has previously been set from options.

Raises:

PetscToolsException – If the object does not have an OptionsManager.

petsctools.options.petscobj2str(obj: petsc4py.PETSc.Object) str

Return a string with a PETSc object type and prefix.

Parameters:

obj – The object to stringify.

Return type:

The stringified name of the object

petsctools.options.set_default_parameter(obj: petsc4py.PETSc.Object, key: str, val: Any) None

Set a default parameter value in the OptionsManager of a PETSc object.

Parameters:
  • obj – The object to get the OptionsManager from.

  • key – The options parameter name

  • val – The options parameter value

Raises:

PetscToolsException – If the object does not have an OptionsManager.

petsctools.options.set_from_options(obj: petsc4py.PETSc.Object, parameters: dict | None = None, options_prefix: str | None = None, default_prefix: str | None = None, default_options_set: DefaultOptionSet | None = None) None

Set up a PETSc object from the options in its OptionsManager.

Calls obj.setOptionsPrefix and obj.setFromOptions whilst inside the inserted_options context manager, which ensures that all options from parameters are in the global PETSc.Options dictionary.

If neither parameters nor options_prefix are provided, assumes that attach_options has been called with obj. If either parameters and/or options_prefix are provided, then attach_options is called before setting up the obj.

Parameters:
  • obj – The PETSc object to call setFromOptions on.

  • parameters – The dictionary of parameters to use.

  • options_prefix – The options prefix to use for this object.

  • default_prefix – Base string for autogenerated default prefixes.

  • default_options_set – The prefix set for any default shared with other solvers.

Raises:

petsctools.pc module

class petsctools.pc.PCBase

Bases: ABC

Abstract base class for python type PETSc PCs.

This is a convenience base class that provides two common functionalities for python type preconditioners.

  1. Checking whether the PC operators are of python type.

    Often a python type preconditioner will rely on the Mat operators also being of python type. If the needs_python_amat and/or needs_python_pmat attributes are set then the type of the pc.getOperators() will be checked, and an error raised if they are not python type. If they are python type then their python contexts will be added as the attributes amat and/or pmat (e.g. A.getPythonContext()).

  2. Separating code to initialize and update the preconditioner.

    Often there are operations to set up the preconditioner which only need to be run once, and operations that are needed each time the preconditioner is updated. The setUp method will call the user implemented initialize method only on the first time it is called, but will call the update method on every subsequent call.

Inheriting classes should also set the prefix attribute. The attributes parent_prefix and full_prefix will then be set, where parent_prefix is the unqualified pc prefix and full_prefix is the qualified prefix of this context (i.e. pc.getOptionsPrefix() and parent_prefix+self.prefix).

Inheriting classes should implement the following methods:

  • initialize

  • update

  • apply

They should also set the following class attributes:

  • prefix

  • needs_python_amat (optional, defaults to False).

  • needs_python_pmat (optional, defaults to False).

Notes

The update method is not called on the first call to setUp(), so for some preconditioners it may be necessary to call update at the end of the initialize method.

If the prefix attribute does not end in an underscore ("_") then one will automatically be appended to the full_prefix attribute.

abstractmethod apply(pc, x, y)

Apply the preconditioner to x, putting the result in y.

Both x and y are PETSc Vecs, y is not guaranteed to be zero on entry.

applyTranspose(pc, x, y)

Apply the preconditioner transpose to x, putting the result in y.

Both x and y are PETSc Vecs, y is not guaranteed to be zero on entry.

abstractmethod initialize(pc)

Initialize any state in this preconditioner.

This method is only called on the first time that the setUp method is called.

needs_python_amat = False

Set this to True if the A matrix needs to be Python (matfree).

needs_python_pmat = False

Set this to False if the P matrix needs to be Python (matfree).

prefix = None

The options prefix of this PC.

setUp(pc)

Called by PETSc to update the PC.

The first time setUp is called, the initialize method will be called followed by the update method. In subsequent calls to setUp only the update method will be called.

abstractmethod update(pc)

Update any state in this preconditioner.

This method is called the on second and later times that the setUp method is called.

This method is not needed for all preconditioners and can often be a no-op.

view(pc, viewer=None)

Write a basic description of this PC.

petsctools.utils module

Module contents