-
Notifications
You must be signed in to change notification settings - Fork 2
Add tensor parameter containers #75
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
fnattino
wants to merge
14
commits into
main
Choose a base branch
from
tensor-param-template
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.
+609
−707
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
d302d4f
add tensor trait
fnattino ee1082b
add tensor param template
fnattino 52c2809
use new param template and trait in existing models
fnattino 72d8633
update assimilation and partitioning
fnattino 95387a8
add state and rate variable tensors
fnattino 2c934fc
add tensor variable containers in existing models
fnattino da73f9a
add info text for clearer errors
fnattino 86a586b
fix for afgen
fnattino b40d8d6
fix errors in tests
fnattino dacf9af
add tests for tensor containers
fnattino cfc786b
move function to extract paramter shapes to engine
fnattino 7e3fcc9
simplify broadcast
fnattino 0b72ed5
new engine cannot run with pcse models anymore
fnattino 8f79c4d
simplify all models with new parameter containers
fnattino 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from .states_rates import TensorParamTemplate | ||
| from .states_rates import TensorRatesTemplate | ||
| from .states_rates import TensorStatesTemplate | ||
|
|
||
| __all__ = ["TensorParamTemplate", "TensorRatesTemplate", "TensorStatesTemplate"] |
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,109 @@ | ||
| from pcse.base import ParamTemplate | ||
| from pcse.base import RatesTemplate | ||
| from pcse.base import StatesTemplate | ||
| from pcse.traitlets import HasTraits | ||
| from ..traitlets import Tensor | ||
| from ..utils import AfgenTrait | ||
|
|
||
|
|
||
| class TensorContainer(HasTraits): | ||
| def __init__(self, shape=None, do_not_broadcast=None, **variables): | ||
| """Container of tensor variables. | ||
| It includes functionality to broadcast variables to a common shape. This common shape can | ||
| be inferred from the container's tensor and AFGEN variables, or it can be set as an input | ||
| argument. | ||
| Args: | ||
| shape (tuple | torch.Size, optional): Shape to which the variables in the container | ||
| are broadcasted. If given, it should match the shape of all the input variables that | ||
| already have dimensions. Defaults to None. | ||
| do_not_broadcast (list, optional): Name of the variables that are not broadcasted | ||
| to the container shape. Defaults to None, which means that all variables are | ||
| broadcasted. | ||
| variables (dict): Collection of variables to initialize the container, as key-value | ||
| pairs. | ||
| """ | ||
| self._shape = () | ||
| self._do_not_broadcast = [] if do_not_broadcast is None else do_not_broadcast | ||
| HasTraits.__init__(self, **variables) | ||
| self._broadcast(shape) | ||
|
|
||
| def _broadcast(self, shape=None): | ||
| # Identify which variables should be broadcasted. Also check that the input shape is | ||
| # compatible with the existing variable shapes | ||
| vars_to_broadcast = self._get_vars_to_broadcast() | ||
| vars_shape = self._get_vars_shape() | ||
| if shape and vars_shape and vars_shape != shape: | ||
| raise ValueError(f"Input shape {shape} does not match variable shape {vars_shape}") | ||
| shape = tuple(shape or vars_shape) | ||
|
|
||
| # Broadcast all required variables to the identified shape. | ||
| for varname, var in vars_to_broadcast.items(): | ||
| try: | ||
| broadcasted = var.expand(shape) | ||
| except RuntimeError as error: | ||
| raise ValueError(f"Cannot broadcast {varname} to shape {shape}") from error | ||
| setattr(self, varname, broadcasted) | ||
|
|
||
| # Finally, update the shape of the container | ||
| self.shape = shape | ||
|
|
||
| def _get_vars_to_broadcast(self): | ||
| vars = {} | ||
| for varname, trait in self.traits().items(): | ||
| if varname not in self._do_not_broadcast: | ||
| if isinstance(trait, Tensor): | ||
| vars[varname] = getattr(self, varname) | ||
| return vars | ||
|
|
||
| def _get_vars_shape(self): | ||
| shape = () | ||
| for varname, trait in self.traits().items(): | ||
| if varname not in self._do_not_broadcast: | ||
| if isinstance(trait, Tensor) or isinstance(trait, AfgenTrait): | ||
| var = getattr(self, varname) | ||
| if not var.shape or shape == var.shape: | ||
| continue | ||
| elif var.shape and not shape: | ||
| shape = tuple(var.shape) | ||
| else: | ||
| raise ValueError( | ||
| f"Incompatible shapes within variables: {shape} and {var.shape}" | ||
| ) | ||
| return shape | ||
|
|
||
| @property | ||
| def shape(self): | ||
| """Base shape of the variables in the container.""" | ||
| return self._shape | ||
|
|
||
| @shape.setter | ||
| def shape(self, shape): | ||
| if self.shape and self.shape != shape: | ||
| raise ValueError(f"Container shape already set to {self.shape}") | ||
| self._shape = shape | ||
|
|
||
|
|
||
| class TensorParamTemplate(TensorContainer, ParamTemplate): | ||
| def __init__(self, parvalues, shape=None, do_not_broadcast=None): | ||
| self._shape = () | ||
| self._do_not_broadcast = [] if do_not_broadcast is None else do_not_broadcast | ||
| ParamTemplate.__init__(self, parvalues=parvalues) | ||
| self._broadcast(shape) | ||
|
|
||
|
|
||
| class TensorStatesTemplate(TensorContainer, StatesTemplate): | ||
| def __init__(self, kiosk=None, publish=None, shape=None, do_not_broadcast=None, **kwargs): | ||
| self._shape = () | ||
| self._do_not_broadcast = [] if do_not_broadcast is None else do_not_broadcast | ||
| StatesTemplate.__init__(self, kiosk=kiosk, publish=publish, **kwargs) | ||
| self._broadcast(shape) | ||
|
|
||
|
|
||
| class TensorRatesTemplate(TensorContainer, RatesTemplate): | ||
| def __init__(self, kiosk=None, publish=None, shape=None, do_not_broadcast=None): | ||
| self._shape = () | ||
| self._do_not_broadcast = [] if do_not_broadcast is None else do_not_broadcast | ||
| RatesTemplate.__init__(self, kiosk=kiosk, publish=publish) | ||
| self._broadcast(shape) |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Was this needed? Why cannot we leave it as a tensor with dtype bool?