-
Notifications
You must be signed in to change notification settings - Fork 274
Restore statistical padding modes #1499
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
Merged
Merged
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9e58e09
Restore statistical padding modes
fepegar 20699a4
Deduplicate padding mode definitions
fepegar b165e82
Simplify statistic padding modes tuple
fepegar 0b4378f
Preserve statistical padding precision
fepegar 167eaf7
Type padding modes consistently
fepegar 1e46a25
Move padding helpers to shared module
fepegar 11e0a45
Validate padding tensor dimensions
fepegar 5cb47f4
Validate forwarded padding modes
fepegar 79e565c
Share quantile computation across transforms
fepegar 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| """Shared spatial padding helpers.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import warnings | ||
| from typing import Literal | ||
| from typing import get_args | ||
|
|
||
| import torch | ||
| from torch import Tensor | ||
|
|
||
| from ...types import TypeSixInts | ||
| from ..intensity.normalize import _quantile | ||
|
|
||
| #: Accepted padding modes. | ||
| PaddingMode = Literal[ | ||
| "constant", | ||
| "reflect", | ||
| "replicate", | ||
| "circular", | ||
| "mean", | ||
| "median", | ||
| "minimum", | ||
| ] | ||
|
|
||
| _PADDING_MODES: tuple[PaddingMode, ...] = get_args(PaddingMode) | ||
| _STATISTIC_PADDING_MODES = "mean", "median", "minimum" | ||
|
|
||
|
|
||
| def parse_padding_mode(padding_mode: str) -> PaddingMode: | ||
| """Validate and return a padding mode.""" | ||
| if padding_mode not in _PADDING_MODES: | ||
| msg = f"padding_mode must be one of {_PADDING_MODES}, got {padding_mode!r}" | ||
| raise ValueError(msg) | ||
| return padding_mode | ||
|
|
||
|
|
||
| def _compute_padding_statistic( | ||
| data: Tensor, | ||
| padding_mode: PaddingMode, | ||
| ) -> Tensor: | ||
| """Compute one whole-volume padding statistic per batch element.""" | ||
| flat = data.flatten(start_dim=1) | ||
| if padding_mode == "minimum": | ||
| return flat.amin(dim=1) | ||
|
|
||
| if not torch.is_floating_point(data): | ||
| warnings.warn( | ||
| f'The constant value computed for padding mode "{padding_mode}"' | ||
| " might be truncated in the output, as the data type of the input" | ||
| " image is not float. Consider converting the image to a floating" | ||
| " point type before applying this transform.", | ||
| RuntimeWarning, | ||
| stacklevel=4, | ||
| ) | ||
|
|
||
| float_flat = flat if data.dtype in (torch.float32, torch.float64) else flat.float() | ||
| if padding_mode == "mean": | ||
| statistic = float_flat.mean(dim=1) | ||
| else: | ||
| statistic = torch.stack( | ||
| [_quantile(values, 0.5) for values in float_flat], | ||
| ) | ||
| return statistic.to(data.dtype) | ||
|
|
||
|
|
||
| def pad_tensor( | ||
| data: Tensor, | ||
| padding: TypeSixInts, | ||
| padding_mode: PaddingMode, | ||
| fill: float, | ||
| ) -> Tensor: | ||
| """Pad a 4D image tensor or 5D image batch.""" | ||
| if data.ndim not in (4, 5): | ||
| msg = f"Expected a 4D or 5D image tensor, got {data.ndim}D" | ||
| raise ValueError(msg) | ||
| i0, i1, j0, j1, k0, k1 = padding | ||
| pad_arg = k0, k1, j0, j1, i0, i1 | ||
| if padding_mode not in _STATISTIC_PADDING_MODES: | ||
| return torch.nn.functional.pad( | ||
| data, | ||
| pad_arg, | ||
| mode=padding_mode, | ||
| value=fill, | ||
| ) | ||
|
|
||
| is_unbatched = data.ndim == 4 | ||
| batch = data.unsqueeze(0) if is_unbatched else data | ||
| statistic = _compute_padding_statistic(batch, padding_mode) | ||
| padded = torch.nn.functional.pad(batch, pad_arg) | ||
| interior = torch.ones( | ||
| (1, 1, *batch.shape[-3:]), | ||
| dtype=torch.bool, | ||
| device=batch.device, | ||
| ) | ||
| interior = torch.nn.functional.pad(interior, pad_arg) | ||
| fill_values = statistic.reshape(-1, 1, 1, 1, 1) | ||
| result = torch.where(interior, padded, fill_values) | ||
| return result[0] if is_unbatched else result | ||
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
Oops, something went wrong.
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.