Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion petsctools/options.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from __future__ import annotations

import weakref
import contextlib
import functools
import itertools
import numbers
import types
import warnings
import weakref
from functools import cached_property
from typing import Any, Iterable

Expand Down Expand Up @@ -280,6 +282,15 @@ def get_default_options(default_options_set: DefaultOptionSet,
return default_options


_native_petsc_option_types = (
bool,
str,
types.NoneType,
numbers.Number,
)
"""Types that are allowed to be directly passed as PETSc options."""


class OptionsManager:
"""Class that helps with managing setting PETSc options.

Expand Down Expand Up @@ -419,6 +430,14 @@ def __init__(self, parameters: dict,
# Convert nested dicts
parameters = flatten_parameters(parameters)

if appmngr is None:
appmngr = AppContextManager()
Comment thread
connorjward marked this conversation as resolved.
Outdated

# Replace any Python objects in the parameters dict with appctx entries
for key, value in parameters.items():
if not isinstance(value, _native_petsc_option_types):
parameters[key] = appmngr.add(value)

# If no prefix is provided generate a default prefix
# and ignore any command line options
if options_prefix is None:
Expand Down
27 changes: 15 additions & 12 deletions tests/test_appctx.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ def apply(self, pc, x, y):

@pytest.mark.skipnopetsc4py
@pytest.mark.parametrize("use_prefix", ["with_prefix", "without_prefix"])
def test_appctx_context_manager(use_prefix):
@pytest.mark.parametrize("implicit_appmngr", [False, True])
def test_appctx_context_manager(use_prefix, implicit_appmngr):
PETSc = petsctools.init()
n = 4
sizes = (n, n)
Expand All @@ -40,19 +41,21 @@ def test_appctx_context_manager(use_prefix):
ksp = PETSc.KSP().create()
ksp.setOperators(mat, mat)

appmngr = petsctools.AppContextManager()
parameters = {
'ksp_type': 'preonly',
'pc_type': 'python',
'pc_python_type': f'{__name__}.JacobiTestPC',
'jacobi_use_prefixed_appctx': use_prefix == "with_prefix",
}
if implicit_appmngr:
appmngr = None
parameters['jacobi_scale'] = diag
else:
appmngr = petsctools.AppContextManager()
parameters['jacobi_scale'] = appmngr.add(diag)

petsctools.set_from_options(
ksp,
parameters={
'ksp_type': 'preonly',
'pc_type': 'python',
'pc_python_type': f'{__name__}.JacobiTestPC',
'jacobi_scale': appmngr.add(diag),
'jacobi_use_prefixed_appctx': use_prefix == "with_prefix",
},
options_prefix="myksp",
appmngr=appmngr,
ksp, parameters=parameters, options_prefix="myksp", appmngr=appmngr
)

x, b = mat.createVecs()
Expand Down
Loading