Skip to content
Draft
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
8d680b1
appctx
JHopeCollins Jul 17, 2025
321fefa
Merge branch 'main' into JHopeCollins/appctx
JHopeCollins Aug 18, 2025
54cd6db
AppContext in __init__
JHopeCollins Aug 18, 2025
4604f3d
Merge branch 'main' into JHopeCollins/appctx
JHopeCollins Aug 27, 2025
c7e366a
Hide AppContext internal keys from user
JHopeCollins Aug 27, 2025
913eb56
updates
JHopeCollins Aug 27, 2025
cfe9954
appctx docstrings
JHopeCollins Aug 28, 2025
ec9c900
test appctx
JHopeCollins Aug 28, 2025
0a4ba8f
tidy up appctx keygen
JHopeCollins Aug 28, 2025
8104028
review comments - hide key from user completely
JHopeCollins Sep 3, 2025
d231b36
move import to top of test file
JHopeCollins Sep 3, 2025
36587cc
Update petsctools/appctx.py
JHopeCollins Sep 4, 2025
3c1b6cf
appctx: hide key_from_option from user.
JHopeCollins Sep 4, 2025
5975b82
global appctx stack
JHopeCollins Sep 10, 2025
d51cd25
numpy import inside test
JHopeCollins Sep 10, 2025
0c54caa
Merge branch 'main' into JHopeCollins/appctx
JHopeCollins Apr 22, 2026
3e7928b
use petsc.vec.norm rather than numpy.allclose for test
JHopeCollins Apr 22, 2026
660475a
trailing whitespace
JHopeCollins Apr 28, 2026
e042462
attach the appctx directly to the OptionsManager
JHopeCollins Apr 28, 2026
ffb03ef
Separate global AppContext and scoped AppContextManager
JHopeCollins Apr 29, 2026
f893063
AppContext()[option] = value?
JHopeCollins Apr 29, 2026
65f166a
make the AppContextKey a helpfully named string
JHopeCollins Apr 29, 2026
b66867e
appctx demo
JHopeCollins May 12, 2026
814967f
numpy for tests and demos
JHopeCollins May 12, 2026
813504c
tidy up appctx demo
JHopeCollins May 12, 2026
e1d3597
appctx exception
JHopeCollins May 12, 2026
f0d6db2
lint
JHopeCollins May 12, 2026
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
1 change: 1 addition & 0 deletions petsctools/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .appctx import AppContext # noqa: F401
from .config import ( # noqa: F401
MissingPetscException,
get_config,
Expand Down
84 changes: 84 additions & 0 deletions petsctools/appctx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import itertools
from functools import cached_property
from petsctools.exceptions import PetscToolsAppctxException


class _AppContextKey(int):
pass
Comment thread
JHopeCollins marked this conversation as resolved.
Outdated


class AppContext:
Comment thread
connorjward marked this conversation as resolved.
"""

.. code-block:: python3

appctx = AppContext()
some_data = MyCustomObject()

opts = OptionsManager(
parameters={
'pc_type': 'python',
'pc_python_type': 'MyCustomPC',
'custompc_somedata': appctx.add(some_data)},
options_prefix="")

with opts.inserted_options():
data = appctx.get('custompc_somedata')

"""

def __init__(self):
self._count = itertools.count()
self._data = {}
self._missing_key = self._keygen()

def _keygen(self, key=None):
return _AppContextKey(next(self._count) if key is None else key)

def _option_to_key(self, option):
key = self.options_object.getInt(option, self.missing_key)
print(f"_option_to_key: {key = }")
return self._keygen(key)

@property
def missing_key(self):
"""
Key instance representing a missing AppContext entry.
"""
# PETSc requires the default value for Options.getObj()
# to be the correct type, so we need a dummy key.
return self._missing_key

def add(self, val):
"""
Add a value to the application context and
return the autogenerated key for that value.

The autogenerated key should the value for the
corresponding entry in the solver_parameters dictionary.
"""
key = self._keygen()
self._data[key] = val
print(f"add: {key = }")
return key

def __getitem__(self, option):
"""
Return the value with the key saved in `PETSc.Options()[option]`.
"""
try:
return self._data[self._option_to_key(option)]
except KeyError:
raise PetscToolsAppctxException(
f"AppContext does not have an entry for {option}")

def get(self, option, default=None):
key = self._option_to_key(option)
if key == self.missing_key:
Comment thread
JHopeCollins marked this conversation as resolved.
Outdated
return default
return self._data[key]

@cached_property
def options_object(self):
from petsc4py import PETSc
return PETSc.Options()
4 changes: 4 additions & 0 deletions petsctools/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ class PetscToolsNotInitialisedException(PetscToolsException):
"""Exception raised when petsctools should have been initialised."""


class PetscToolsAppctxException(PetscToolsException):
"""Exception raised when the Appctx is missing an entry."""


class PetscToolsWarning(UserWarning):
"""Generic base class for petsctools warnings."""
24 changes: 24 additions & 0 deletions tests/test_options.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import petsctools
Comment thread
JHopeCollins marked this conversation as resolved.

PETSc = petsctools.init()

appctx = petsctools.AppContext()
reynolds = 10

opts = petsctools.OptionsManager(
parameters={
'fieldsplit_1_pc_type': 'python',
'fieldsplit_1_pc_python_type': 'firedrake.MassInvPC',
'fieldsplit_1_mass_reynolds': appctx.add(reynolds)},
options_prefix="")

with opts.inserted_options():
re = appctx.get('fieldsplit_1_mass_reynolds')
print(f"{re = }")
re = appctx['fieldsplit_1_mass_reynolds']
print(f"{re = }")

re = appctx.get('fieldsplit_0_mass_reynolds', 20)
print(f"{re = }")
re = appctx['fieldsplit_0_mass_reynolds']
print(f"{re = }")
Loading