Skip to content

Honor a shifted detector in 2d parallel beam on the CPU backend - #1730

Open
GuoCheng24 wants to merge 3 commits into
odlgroup:masterfrom
GuoCheng24:fix/parallel-2d-detector-offset-cpu
Open

GuoCheng24 wants to merge 3 commits into
odlgroup:masterfrom
GuoCheng24:fix/parallel-2d-detector-offset-cpu

Conversation

@GuoCheng24

Copy link
Copy Markdown

Fixes #359.

What goes wrong

For a 2D parallel-beam geometry on astra_impl='cpu', astra_projection_geometry builds ASTRA's non-vector 'parallel' geometry, which is parametrized by a pixel width, a pixel count and the angles only. A detector partition that is not centered on the origin therefore loses its offset with no warning: the projection comes out identical to the unshifted one. The TODO: change to parallel_vec when available above that branch predates ASTRA 1.8.3, which added parallel_vec; astra_projector already accepts it.

The 'cuda' branch stopped being affected when it moved to 'parallel3d_vec', so on current master the two backends disagree on the same geometry object. Measured on master with a Shepp–Logan phantom, 128², 200 angles, 183 bins, detector shifted by 1 and 4 bins (relative L∞ change of the sinogram):

backend 1 bin 4 bins
astra_cpu 0.000e+00 0.000e+00
astra_cuda 5.500e-01 9.804e-01
skimage 4.632e-01 9.364e-01

What this changes

  • astra_parallel_2d_geom_to_vec, the parallel-beam sibling of astra_conebeam_2d_geom_to_vec, with the same rot_minus_90 convention.
  • In the 'cpu' branch, 'parallel_vec' is used only when the detector is actually off-center (|shift| > 1e-6 pixel). A centered detector keeps the existing code path, so nobody's numbers move: with the patch the full tomo suite goes from 458 passed / 26 skipped to 467 / 28 — exactly the new tests, no existing test changes status. If the detector is shifted and ASTRA is too old for parallel_vec, a NotImplementedError now says so instead of dropping the shift.

After the patch astra_cpu gives the same 5.500e-01 / 9.804e-01 as astra_cuda; the two agree to 8e-4 at every offset tried, which is the same figure they show at zero offset.

Tests

test_detector_shifts_2d exists but uses FanBeamGeometry, which reaches ASTRA through 'fanflat_vec' and was never affected, so nothing caught this. Added:

  • test_detector_shifts_2d_parallel (ray_trafo_test): asserts the shift reaches the projector at all — on the unpatched code this fails with assert 0.0 > 0.04, the two sinograms being bit-identical — then that the projection is shifted by exactly k bins and that back-projection is unaffected. Runs on astra_cpu, astra_cuda and skimage (numpy spaces).
  • test_proj_geom_parallel_2d_shifted_detector and a parallel-2d case in test_geom_to_vec (astra_setup_test).

All three fail on the unpatched code and pass with it. Found while building an operator-mismatch test bed on LoDoPaB, where a guard requiring every mismatch axis to change the sinogram reported a centre-of-rotation change of exactly 0.0.

ASTRA's non-vector 'parallel' geometry is parametrized by a pixel width, a
pixel count and the angles, so it cannot represent a detector that is shifted
away from the origin. `astra_projection_geometry` built it unconditionally for
2d parallel beam, which meant the offset in the detector partition was dropped
without a warning: the projection came out identical to the unshifted one and
read as robustness (odlgroupgh-359, open since 2016; ASTRA has supported
'parallel_vec' since >1.8.3).

The 'cuda' branch stopped being affected when it moved to 'parallel3d_vec',
so the two backends currently disagree: the same geometry gives different
physics depending on `astra_impl`, silently. This restores agreement.

'parallel_vec' is used only when the detector is actually off-center, so a
centered detector keeps the original code path and its numerical results. If
the detector is shifted and ASTRA is too old for 'parallel_vec', a
NotImplementedError now says so rather than discarding the shift.

Tests: `test_detector_shifts_2d` covers fan beam only, which reaches ASTRA
through 'fanflat_vec' and was never affected, so nothing caught this. Adds
`test_detector_shifts_2d_parallel`, which asserts the shift reaches the
projector at all before checking that the projection is shifted by exactly the
expected number of bins, and `test_proj_geom_parallel_2d_shifted_detector`
plus a `astra_parallel_2d_geom_to_vec` case in `test_geom_to_vec`. All three
fail on the unpatched code.
@GuoCheng24 GuoCheng24 mentioned this pull request Sep 8, 2026
@leftaroundabout

Copy link
Copy Markdown
Contributor

Thanks for the contribution. This seems like it fills a feature that was missing mostly due to oversight, and should be included. We definitely don't want a requested shift to be silently ignored!

A couple of details should be considered though:

  • As you say, the Cuda backend wasn't affected, but not so much because it had already implemented the vector-shift-2D version but rather because it uses the somewhat hacky trick of casting everything to 3D. I remember this was because Astra didn't have a Cuda 2D version then, but is this still the best approach today?
    It would be cleanest and most future-proof to keep the CPU and Cuda versions in the same code as much as possible.
  • I'm not sure I agree to keep the existing code path for the centered detector case, in particular not with a abs(det_shift) <= 1e-6 * det_width condition.
    How big is the discrepancy between using the old version and the new one with a shift that happens to be zero? Is it about numerical precision or rather performance? For what use case would it be important to keep exactly the old behaviour?
    If we decide to special-case this, I'd rather do it with an actual det_shift == 0 check. Presumably users who want the unshifted behaviour would put in an exact literal zero there, whereas if somebody runs a whole series of reconstructions with different shifts it's better to not trigger the special case even when passing through zero. Don't want to get a strange discontinuity at a magical value of $10^{-6}$.

@GuoCheng24

Copy link
Copy Markdown
Author

Thanks — both points taken, and the second one is now measured rather than argued.

The centered-detector special case is gone. You were right to push back; I kept the old path out of caution, not evidence. Measured on ASTRA 2.5.0 (Shepp–Logan 256², 360 angles, 363 bins, detector partition exactly centered), 'parallel' against 'parallel_vec':

proj type max abs diff / max sinogram mean relative runtime
linear 6.2e-04 5.9e-07 1.02x
line 6.5e-04 7.7e-07 1.02x
strip 6.2e-04 4.8e-06 1.01x

So: not a performance question at all, and the accuracy question resolves as float32 accumulation order rather than geometry. Regressing the residual on the detector-direction gradient — the shape it would have if the two geometries disagreed by a sub-pixel offset — gives an implied shift of −8.4e-07 pixels (−0.85 nm on a 1.01 mm pixel) with R² = 0.0000, residual mean −6.9e-10, correlation with the gradient −0.005. For scale, a real half-pixel shift changes the sinogram by 1.4e-02, i.e. 340× more than the difference between the two code paths. There is no use case I can construct that needs the old numbers, so parallel_vec is now used unconditionally, with NotImplementedError if ASTRA is too old for it — no magic threshold and no discontinuity.

The two geometry tests that asserted 'parallel' for the CPU backend are updated; the tomo suite is 467 passed / 28 skipped / 1 xfailed, unchanged from before this patch except for the 9 new test parametrizations.

On the CUDA path and keeping the two backends in one place — I agree, and it looks achievable now: ASTRA 2.5.0's CUDA projector accepts the 2D 'parallel_vec' geometry directly, offset included.

2D parallel_vec, centered      linear  OK   sum=2948.8701
2D parallel_vec, centered      cuda    OK   sum=2948.8696
2D parallel_vec, 4-pixel shift linear  OK   sum=2948.8701
2D parallel_vec, 4-pixel shift cuda    OK   sum=2948.8691
   CUDA responds to the shift:      relative change 9.4e-01
   CUDA vs CPU at the same shift:   relative difference 8.0e-04

So astra_parallel_2d_geom_to_vec could serve both branches and the parallel3d_vec cast could go, which would also remove astra_parallel_2d_geom_to_parallel3d_vec and the 12-element ODL_TO_ASTRA_INDEX_PERMUTATIONS round-trip for this case. I have left it out of this PR because it changes the numbers of every existing 2D CUDA user (the 8.0e-04 above is the size of that change) and deserves its own before/after, but I am happy to do it here if you would rather have the unification in one go — or as a follow-up PR with the CUDA path measured the same way. Your call on the scope.

Drops the centered-detector special case from the first version of this patch,
per review. Measured on ASTRA 2.5.0 (Shepp-Logan 256^2, 360 angles, 363 bins,
exactly centered detector), 'parallel' against 'parallel_vec':

  proj type   max |delta| / max sinogram   mean rel.   runtime
  linear      6.2e-04                      5.9e-07     1.02x
  line        6.5e-04                      7.7e-07     1.02x
  strip       6.2e-04                      4.8e-06     1.01x

The difference is float32 accumulation order, not geometry: regressing the
residual on the detector-direction gradient gives an implied sub-pixel shift of
-8.4e-07 pixels (-0.85 nm on a 1.01 mm pixel) with R^2 = 0.0000, residual mean
-6.9e-10 and correlation with the gradient -0.005. For scale, a real half-pixel
shift changes the sinogram by 1.4e-02, i.e. 340x more. So there is no accuracy
or performance reason to keep the old path, and no discontinuity to introduce.

If ASTRA is too old for 'parallel_vec', 2d parallel beam now raises
NotImplementedError instead of silently dropping any shift.
@leftaroundabout

Copy link
Copy Markdown
Contributor

Alright, this looks like very meticulous work - assuming the numbers are correct, which I still need to double-check.

The unconditional version in astra_projection_geometry is much cleaner, though it must be noted that completely removing the 'parallel' version effectively pins us to Astra >=2.0. (What I had in mind was actually rather to use 'parallel_vec' always if available; we could still have a fallback based purely on the Astra version and then assert(det_shift==0) there.)
But Astra 2.0 was released in 2021, so honestly there might not be a need to support older versions at all.

Regarding the Cuda path, yes it's probably better to do that in a separate PR.

@GuoCheng24

Copy link
Copy Markdown
Author

Done — 'parallel_vec' when ASTRA has it, otherwise the old 'parallel' path with a NotImplementedError if the detector is shifted, which is the one thing that path was never able to express. No version floor added.

On whether the fallback is needed at all, two facts that may let you delete it:

  • odl's own feature table already puts this at 'par2d_vec_geometry': '>1.8.3', not >=2.0. The comment above the entry says it is a "development version, will be in the next release after 1.8.3" and cites astra-toolbox#54 — so ASTRA 1.9, 2019.
  • pyproject.toml already asks for astra-toolbox>=2.4 in the all extra (added in f6b7f27). Nothing odl installs for itself can reach the fallback; it exists only for a user who brings an ASTRA from 2018 or earlier and asks for a shifted detector.

So I am happy either way — the fallback is eleven lines and costs nothing, or it goes and the floor becomes explicit. Your call; I have left it in.

The new test reaches that branch by reporting the feature as absent, since no installable ASTRA does. It fails on the cpu backend when the fallback is removed, and asserts the shifted case raises rather than quietly returning a 'parallel' geometry.

Full src/odl/test/applications/tomo/ on ASTRA 2.5.0: 469 passed, 28 skipped, 1 xfailed — the same as master apart from the eleven new parametrizations.

Understood on the CUDA path being a separate PR. I will open it with the same before/after treatment: the parallel3d_vec cast can go, astra_parallel_2d_geom_to_parallel3d_vec and its 12-element ODL_TO_ASTRA_INDEX_PERMUTATIONS round-trip with it, and the number that matters for review is the size of the change it makes to existing 2D CUDA users — 8.0e-04 relative on the phantom I measured, which I will pin down properly across geometries before opening it.

And please do double-check the numbers; every figure in the previous comment is one command on a stock ASTRA 2.5.0, and I would rather you find a mistake than take my word for it.

…hift there

Per review: use 'parallel_vec' when ASTRA provides it, otherwise fall back to the
non-vector 'parallel' geometry, which can only express a centered detector, and
raise NotImplementedError rather than flatten a shift it cannot represent. This
drops the version floor the unconditional version would have introduced.

On the floor itself, in case it makes the fallback unnecessary: odl's own feature
table puts 'par2d_vec_geometry' at '>1.8.3', not >=2.0 - the entry cites
astra-toolbox#54 and says it landed in the release after 1.8.3, i.e. ASTRA 1.9
(2019). And pyproject.toml already asks for astra-toolbox>=2.4 in the 'all'
extra, so nothing odl installs itself can reach the fallback. It is only for a
user who brings an ASTRA from 2018 or earlier.

The new test reaches that branch by reporting the feature as absent, since no
ASTRA anyone would install can: with the fallback removed it fails on the cpu
backend, and the shifted case must raise rather than return a 'parallel' geometry.
@GuoCheng24

Copy link
Copy Markdown
Author

Before opening the CUDA PR I measured what it would cost and how far it reaches, and the second part is larger than the geometry function suggests — so this is a scope question for you rather than a patch.

The numbers say the change is safe. Comparing the current path (parallel3d_vec + cuda3d with ProjectionKernel='2d_weighting') against a true 2d path (parallel_vec + the 2d cuda projector, with the CPU volume-geometry convention), on ASTRA 2.5.0, RTX 4090, random x and random y for the adjoint test:

case ⟨Ax,y⟩/⟨x,Aᵀy⟩ now same, 2d path forward rel. diff backprojection rel. diff
centered 256² / 360 ang / 363 det 1.000015 1.000015 1.3e-04 6.1e-05
detector +4 px 1.000013 1.000013 1.9e-04 7.3e-05
detector −2.5 px 1.000020 1.000020 1.3e-04 6.4e-05
non-square 256×192 1.000003 1.000003 1.5e-04 7.2e-05
32 angles 0.999989 0.999989 8.2e-05 3.0e-04

The adjoint ratio is identical to six decimals in every case, and forward sums agree to 1.000000, so astra_cuda_fp_scaling_factor and astra_cuda_bp_scaling_factor would not need to change. Existing 2d CUDA users would see their numbers move by about 1e-4 relative, i.e. float32 accumulation order, the same size as the CPU change in this PR.

But it is not a geometry swap. cuda3d refuses the 2d geometry outright:

ValueError: projector type cuda3d not in the set
['line', 'linear', 'strip', 'cuda', 'distance_driven'] of valid types for geometry type parallel_vec

so the 2d branch of astra_cuda.py has to move off the 3d machinery with it: astra_projector(..., 'cuda3d', ndim=3, override_2D=True) becomes the 2d cuda projector, FP3D_CUDA/BP3D_CUDA become their 2d counterparts, astra.data3d becomes data2d, and the [None] axis added and removed around every 2d call goes away. On top of that the two backends currently use different volume-geometry conventions for the same 2d space — astra_volume_geometry flips the sign of the x extent for 'cpu' and does not for 'cuda' — which is exactly what the two different vector helpers compensate for, so unifying the projection geometry means unifying that too.

And fan beam 2d has the same shape (astra_fanflat_2d_geom_to_conebeam_vec → 'cone_vec' + cuda3d), so doing only parallel beam would leave the file half-converted.

That is a bigger change to a core backend than I would push on you unasked, and it moves every 2d CUDA user by 1e-4, so: do you want it as one PR covering parallel and fan beam together, parallel only, or not at all for now? I am happy to do any of the three — the measurement above is the part I wanted you to have either way, and every figure in it is one script on a stock ASTRA 2.5.0.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parallel 2d bug

2 participants