`DenseFieldTransform.map()` wraps or raises for on-grid points outside the field

Open Beginner friendly
#306 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
78/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
numpy, python

Research direction

Start at the fast path in nitransforms/nonlinear.py around lines 185-191, where on-grid points are rounded to voxel indices and used to index the field with no bounds check, then compare it with the interpolation path used 0.01 mm off-grid. Run the reproduction snippet from the issue to see index -1 wrapping and index n raising IndexError. Done when both assertions pass and on-grid points outside the grid give the same result as the off-grid path.

Written by the indexing model from the issue text.

Description

When every point falls on a voxel center, map() takes a fast path:

https://github.com/nipy/nitransforms/blob/06537caee1e5908e7faada275187a0568982b549/nitransforms/nonlinear.py#L185-L191

That rounds points to voxel indices and indexes the field with them, without checking bounds. A point one voxel before the grid gets index -1 and wraps to the last voxel. A point one voxel past the grid gets index n and raises IndexError. Shifting 0.01 mm off the grid switches to the interpolation path, with the correct result.

Reproduction

import nibabel as nb
import numpy as np
from nitransforms.nonlinear import DenseFieldTransform

# 21^3 grid of 4 mm voxels spanning -40..40 mm; +100 mm x-shift in the last x slab only
deltas = np.zeros((21, 21, 21, 3), dtype="float32")
deltas[-1, ..., 0] = 100.0
affine = nb.affines.from_matvec(np.eye(3) * 4, [-40] * 3)
xfm = DenseFieldTransform(nb.Nifti1Image(deltas, affine))

# 0.01 mm off-grid, one voxel before the grid start: no displacement
assert np.allclose(xfm.map([[-44.01, 0, 0]]), [[-44.01, 0, 0]])
# On-grid, one voxel before the grid start
assert np.allclose(xfm.map([[-44.0, 0, 0]]), [[-44.0, 0, 0]])

The first assertion passes, second fails:

>>> xfm.map([[-44.01, 0, 0]])
array([[-44.01,   0.  ,   0.  ]])
>>> xfm.map([[-44.0, 0, 0]])
array([[140.,   0.,   0.]])
Dominant language
Python
Stars
36
Forks
18
Avg merge
1h 24m
Merged PRs (30d)
1

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from nipy/nitransforms

All issues in nipy/nitransforms

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.