Commit 10674bc
authored
Fix division by zero in Warp for singleton spatial dimensions (#8946)
### Description
`Warp.forward` (native `grid_sample` path) normalizes grid coordinates
with:
```python
grid[..., i] = grid[..., i] * 2 / (dim - 1) - 1
```
When a spatial dimension has size 1 — a **single-slice volume** `(B, C,
1, H, W)` or a single-row/column image `(B, C, 1, W)` / `(B, C, H, 1)` —
`dim - 1 == 0`, so the normalization divides by zero and produces
`inf`/`nan` coordinates. With `padding_mode="zeros"`, even a **zero
displacement field** then yields:
- `nan` output for 2D single-row/column inputs, and
- all-zeros output for 3D single-slice inputs,
instead of returning the input image unchanged.
#### Fix
Clamp the denominator to 1 so the lone voxel maps to `-1`. This mirrors
the guard MONAI already applies in
`monai.networks.utils.normalize_transform`, which performs the identical
`align_corners=True` normalization and clamps the size with `norm[norm
<= 1.0] = 2.0` to avoid exactly this division by zero. Non-singleton
dimensions are numerically unchanged.
```python
grid[..., i] = grid[..., i] * 2 / max(dim - 1, 1) - 1
```
#### Verification
Added `test_singleton_spatial_dim` (2D single-row, 2D single-column, 3D
single-slice). With a zero displacement field the warped output now
equals the input and contains no `nan`. The test fails on the current
code and passes with the fix; the existing `Warp` tests are unaffected.
### Types of changes
<!--- Put an `x` in all the boxes that apply, and remove the not
applicable items -->
- [x] Non-breaking change (fix or new feature that would not break
existing functionality).
- [x] New tests added to cover the changes.
- [x] Quick tests passed locally by running `./runtests.sh --quick
--unittests --disttests`.
- [x] In-line docstrings updated.
---------
Signed-off-by: VenkateswarluNagineni <venkates2002@tamu.edu>1 parent 36a6f0b commit 10674bc
2 files changed
Lines changed: 27 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
155 | 155 | | |
156 | 156 | | |
157 | 157 | | |
158 | | - | |
| 158 | + | |
| 159 | + | |
| 160 | + | |
| 161 | + | |
159 | 162 | | |
160 | 163 | | |
161 | 164 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
12 | 12 | | |
13 | 13 | | |
14 | 14 | | |
| 15 | + | |
15 | 16 | | |
16 | 17 | | |
17 | 18 | | |
| |||
138 | 139 | | |
139 | 140 | | |
140 | 141 | | |
| 142 | + | |
| 143 | + | |
| 144 | + | |
| 145 | + | |
| 146 | + | |
| 147 | + | |
| 148 | + | |
| 149 | + | |
| 150 | + | |
| 151 | + | |
| 152 | + | |
| 153 | + | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
| 159 | + | |
| 160 | + | |
| 161 | + | |
| 162 | + | |
| 163 | + | |
141 | 164 | | |
142 | 165 | | |
143 | 166 | | |
| |||
0 commit comments