-
Notifications
You must be signed in to change notification settings - Fork 0
Adding overload for DirichletBC #49
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
finsberg
wants to merge
24
commits into
main
Choose a base branch
from
finsberg/dirichlet-bc
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
350f8b2
Add beginning of dirichlebc
finsberg 9db8d73
Try using the .g function instead
finsberg 424be4c
New attempt to implement overload for dirichletbc inspired by irksome
finsberg 4e651ac
Add fix to FunctionAssigner to work with dirichlet bc
finsberg 621b2ee
Formatting
finsberg b438d67
Cleanup
finsberg c3171bf
Merge remote-tracking branch 'origin/main' into finsberg/dirichlet-bc
finsberg 5b11d6d
Add fix for hessian computations
finsberg c9d5222
Merge pull request #53 from scientificcomputing/finsberg/hessian
finsberg 35ae6f5
Merge remote-tracking branch 'origin/main' into finsberg/dirichlet-bc
finsberg b7a8bcc
Add missing scatter_forward
finsberg c8b33f9
Fix after API change in https://github.com/FEniCS/dolfinx/pull/4342
finsberg 588c591
Fall back to old initialization of DirichletBC if new one fails with …
finsberg f8a8f97
Do not recreate tlm matrix in every evaluation - memory blows up
finsberg 67a58f9
Fix annotation kwargs bug in dirichletbc
finsberg bf7e5de
Make private properties in DirichletBlock
finsberg 7dc50ca
Merge remote-tracking branch 'origin/main' into finsberg/dirichlet-bc
finsberg 710bdb3
Apply suggestion from @jorgensd
finsberg 1aefccd
Apply suggestions from code review
finsberg a84dfa6
Remove try-except in DirichletBC and check version instead
finsberg 46c796c
Assert block is DirichletBC block
finsberg 6395090
More docs to dirichletbc and fix solver
finsberg e944c17
Fix type annotation in dirichletbc
finsberg 67fd237
Fix type annotations
finsberg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import dolfinx | ||
| import numpy as np | ||
| import numpy.typing as npt | ||
| from pyadjoint.block import Block | ||
|
|
||
|
|
||
| class DirichletBCBlock(Block): | ||
| """A block representing a DirichletBC in the adjoint framework. | ||
|
|
||
| Args: | ||
| value: The value of the Dirichlet BC. | ||
| dofs: An array of degree-of-freedom indices in `V` where the BC should be applied. | ||
| V: The function space associated with the Dirichlet BC. | ||
| ad_block_tag: An optional tag to identify this block in the adjoint framework. | ||
|
|
||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| value: dolfinx.fem.Function | dolfinx.fem.Constant, | ||
| dofs: npt.NDArray[np.int32], | ||
| V: dolfinx.fem.FunctionSpace | None = None, | ||
| ad_block_tag: str | None = None, | ||
| ): | ||
| super().__init__(ad_block_tag=ad_block_tag) | ||
| self._dofs = dofs | ||
| self._V = V | ||
| self.add_dependency(value) | ||
|
|
||
| @property | ||
| def dofs(self): | ||
| return self._dofs | ||
|
|
||
| @property | ||
| def V(self): | ||
| return self._V | ||
|
|
||
| def prepare_recompute_component(self, inputs, relevant_outputs): | ||
| return inputs[0] if inputs else None | ||
|
|
||
| def recompute_component(self, inputs, block_variable, idx, prepared): | ||
| return block_variable.saved_output |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| __all__ = ["Function", "Constant"] | ||
| __all__ = ["Function", "Constant", "dirichletbc"] | ||
|
|
||
| from .dirichletbc import dirichletbc | ||
| from .function import Constant, Function |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| from typing import Any | ||
|
|
||
| import dolfinx | ||
| import numpy as np | ||
| import numpy.typing as npt | ||
| import pyadjoint | ||
| from packaging.version import Version | ||
| from pyadjoint.overloaded_type import FloatingType | ||
|
|
||
| from ..blocks.dirichletbc import DirichletBCBlock | ||
| from .function import Function | ||
|
|
||
|
|
||
| class DirichletBC(dolfinx.fem.DirichletBC, FloatingType): | ||
| """A class overloading :py:class:`dolfinx.fem.DirichletBC` to support | ||
| it being used as a control variable in the adjoint framework. | ||
|
|
||
| Args: | ||
| g: The value of the Dirichlet BC. | ||
| dofs: An array of degree-of-freedom indices in `V` where the BC should be applied. | ||
| **kwargs: Additional keyword arguments to pass to the | ||
| :py:func:`pyadjoint.overloaded_type.FloatingType` constructor. | ||
|
|
||
| """ | ||
|
|
||
| def __init__(self, g: Function, dofs: npt.NDArray[np.int32], **kwargs): | ||
| dtype = g.dtype | ||
|
|
||
| cpp_bc: ( | ||
| dolfinx.cpp.fem.DirichletBC_float32 | ||
| | dolfinx.cpp.fem.DirichletBC_float64 | ||
| | dolfinx.cpp.fem.DirichletBC_complex64 | ||
| | dolfinx.cpp.fem.DirichletBC_complex128 | ||
| ) | ||
| if np.issubdtype(dtype, np.float32): | ||
| assert isinstance(g._cpp_object, dolfinx.cpp.fem.Function_float32) | ||
| cpp_bc = dolfinx.cpp.fem.DirichletBC_float32(g._cpp_object, dofs) | ||
| elif np.issubdtype(dtype, np.float64): | ||
| assert isinstance(g._cpp_object, dolfinx.cpp.fem.Function_float64) | ||
| cpp_bc = dolfinx.cpp.fem.DirichletBC_float64(g._cpp_object, dofs) | ||
| elif np.issubdtype(dtype, np.complex64): | ||
| assert isinstance(g._cpp_object, dolfinx.cpp.fem.Function_complex64) | ||
| cpp_bc = dolfinx.cpp.fem.DirichletBC_complex64(g._cpp_object, dofs) | ||
| elif np.issubdtype(dtype, np.complex128): | ||
| assert isinstance(g._cpp_object, dolfinx.cpp.fem.Function_complex128) | ||
| cpp_bc = dolfinx.cpp.fem.DirichletBC_complex128(g._cpp_object, dofs) | ||
| else: | ||
| raise NotImplementedError(f"Type {dtype} not supported.") | ||
|
|
||
| bc_kwargs: dict[str, Any] = {} | ||
| # If dolfinx-version is 0.12 we need to pass the following | ||
| # due to https://github.com/FEniCS/dolfinx/pull/4342/ | ||
| if Version(dolfinx.__version__).minor >= 11: | ||
| bc_kwargs["V"] = g.function_space | ||
| bc_kwargs["g"] = g | ||
|
|
||
| super().__init__(cpp_bc, **bc_kwargs) | ||
|
|
||
| annotate = kwargs.pop("annotate", True) | ||
| annotate = annotate and pyadjoint.annotate_tape() | ||
|
|
||
| FloatingType.__init__( | ||
| self, | ||
| g, | ||
| dtype=dtype, | ||
| block_class=kwargs.pop("block_class", DirichletBCBlock), | ||
|
jorgensd marked this conversation as resolved.
|
||
| _ad_floating_active=False, | ||
| _ad_args=kwargs.pop("_ad_args", (g, dofs)), | ||
| annotate=annotate, | ||
| **kwargs, | ||
| ) | ||
|
|
||
| if annotate: | ||
| self._ad_annotate_block() | ||
|
|
||
| def _ad_create_checkpoint(self): | ||
| return self | ||
|
|
||
| def _ad_restore_at_checkpoint(self, checkpoint): | ||
| return self | ||
|
|
||
|
|
||
| def dirichletbc(value: Function, dofs: npt.NDArray[np.int32], **kwargs) -> DirichletBC: | ||
| """Overloaded DirichletBC constructor that creates an adjoint-aware DirichletBC | ||
|
|
||
| Args: | ||
| value: The value of the Dirichlet BC. Should be a :py:class:`dolfinx_adjoint.Function`. | ||
| This means you can also pass in a :py:class:`dolfinx_adjoint.Constant` but not | ||
| a :py:class:`dolfinx.fem.Constant`. | ||
| dofs: An array of degree-of-freedom indices in `V` where the BC should be applied. | ||
| **kwargs: Additional keyword arguments to pass to the | ||
| :py:class:`dolfinx_adjoint.types.dirichletbc.DirichletBC` constructor. | ||
|
|
||
|
|
||
| """ | ||
| assert isinstance(value, Function), "value must be a dolfinx_adjoint.Function" | ||
| return DirichletBC(value, dofs, **kwargs) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.