Skip to content

Commit

Permalink
Fix lazy rand affine (#6774)
Browse files Browse the repository at this point in the history
Fixes #6773.

### Description

Call `rand_affine_grid()` once before call
`rand_affine_grid.get_transformation_matrix()`, since its documented as
"Get the most recently applied transformation matrix", or the `.affine`
attribute will not be set.
Also, set `randomize=False` here since randomization if performed in the
beginning of the function.

### 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).
- [ ] Integration tests passed locally by running `./runtests.sh -f -u
--net --coverage`.
- [ ] Quick tests passed locally by running `./runtests.sh --quick
--unittests --disttests`.

---------

Signed-off-by: function2 <[email protected]>
Co-authored-by: Wenqi Li <[email protected]>
  • Loading branch information
function2-llx and wyli authored Jul 28, 2023
1 parent e2fa53b commit 5feb353
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 0 deletions.
2 changes: 2 additions & 0 deletions monai/transforms/spatial/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -2523,6 +2523,8 @@ def __call__(
img = convert_to_tensor(img, track_meta=get_track_meta())
if lazy_:
if self._do_transform:
if grid is None:
self.rand_affine_grid(sp_size, randomize=randomize, lazy=True)
affine = self.rand_affine_grid.get_transformation_matrix()
else:
affine = convert_to_dst_type(torch.eye(len(sp_size) + 1), img, dtype=self.rand_affine_grid.dtype)[0]
Expand Down
1 change: 1 addition & 0 deletions monai/transforms/spatial/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -1141,6 +1141,7 @@ def __call__(
grid = self.rand_affine.get_identity_grid(sp_size, lazy=lazy_)
if self._do_transform: # add some random factors
grid = self.rand_affine.rand_affine_grid(sp_size, grid=grid, lazy=lazy_)
grid = 0 if grid is None else grid # always provide a grid to self.rand_affine

for key, mode, padding_mode in self.key_iterator(d, self.mode, self.padding_mode):
# do the transform
Expand Down
1 change: 1 addition & 0 deletions tests/test_rand_affine.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ def test_rand_affine(self, input_param, input_data, expected_val):
g = RandAffine(**input_param)
g.set_random_state(123)
result = g(**input_data)
g.rand_affine_grid.affine = torch.eye(4, dtype=torch.float64) # reset affine
test_resampler_lazy(g, result, input_param, input_data, seed=123)
if input_param.get("cache_grid", False):
self.assertTrue(g._cached_grid is not None)
Expand Down

0 comments on commit 5feb353

Please sign in to comment.