Skip to content

BUG: Fix axis order in image_from_xarray origin/spacing - #6937

Merged
hjmjohnson merged 1 commit into
InsightSoftwareConsortium:mainfrom
SID-6921:fix-image-from-xarray-axis-order
Oct 17, 2026
Merged

hjmjohnson merged 1 commit into
InsightSoftwareConsortium:mainfrom
SID-6921:fix-image-from-xarray-axis-order

Conversation

@SID-6921

@SID-6921 SID-6921 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Fix image_from_xarray() assigning origin/spacing to the wrong axes for 4D (t, z, y, x) images; the per-axis loop iterated an incorrectly-ordered variable instead of the already-computed canonical order. Adds a 4D coordinate test to catch this.

Root cause

image_dims is built by alphabetically sorting a set, while ordered_dims
(computed just above it) already holds the correct canonical
(t, z, y, x) order used elsewhere in the same function for the values
transpose. The origin/spacing loop iterated image_dims instead of
ordered_dims. The two orderings coincide whenever no t dimension is
present (3D/2D), which is why the existing tests passed, but diverge for
4D data, silently assigning each axis's origin/spacing to the wrong
dimension.

AI assistance
  • Tool: Claude Code
  • Role: code review / bug hunting in Wrapping/Generators/Python/itk/support
  • Contribution: found the image_dims vs ordered_dims divergence by
    tracing the 4D axis-ordering logic, proposed the one-line fix, and
    added the regression test
  • All changes were reviewed and verified locally before committing
Test results

Reproduced the ordering bug and verified the fix in isolation (no local
ITK Python build available) by extracting the axis-ordering logic from
image_from_xarray into a standalone script with mock coordinate data:

  • 4D (t, z, y, x) case: before fix, SetOrigin/SetSpacing order was
    scrambled (e.g. origin (100.0, 30.0, 20.0, 10.0) instead of the
    expected (30.0, 20.0, 10.0, 100.0)); after the fix, output matches
    expected (x, y, z, t) order exactly.
  • 3D (z, y, x) case: output unchanged before/after, confirming no
    regression for the common case.
  • Added test_xarray.py coverage asserting GetOrigin()/GetSpacing()
    on a round-tripped 4D array with distinct per-axis coordinates, which
    the existing 4D test did not check.

image_from_xarray() iterated the alphabetically-sorted image_dims
list to assign per-axis origin/spacing values, while ordered_dims
holds the correct canonical (t, z, y, x) order already computed
earlier in the function. The two orderings coincide for dims
without "t", masking the bug, but diverge once a "t" dimension is
present, scrambling origin/spacing onto the wrong axes for 4D
images. Iterate ordered_dims instead, and add a 4D coordinate
test to catch this.
@github-actions github-actions Bot added type:Bug Inconsistencies or issues which will cause an incorrect result under some or all circumstances area:Python wrapping Python bindings for a class type:Testing Ensure that the purpose of a class is met/the results on a wide set of test cases are correct labels Oct 8, 2026
@SID-6921
SID-6921 marked this pull request as ready for review October 8, 2026 16:23
Copilot AI balanced review requested due to automatic review settings October 8, 2026 16:23

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@greptile-apps

greptile-apps Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Fixes axis ordering in xarray to image conversion.

The PR appears safe to merge; the geometry now follows the correct image axes.

What we checked:

  • Geometry follows pixel axes: The loop uses the same axis order as the pixel data. It excludes the trailing channel dimension and reverses the geometry into ITK order.
Summary

Fixes image_from_xarray() so 4D origin and spacing follow the same axis order as the pixel data.

  • Uses ordered_dims instead of alphabetically sorted dimensions.
  • Adds distinct coordinates and geometry checks to the existing 4D test.
  • No actionable issues found. Tests were not run during this review.

Reviews (1) · Last reviewed commit: "BUG: Fix axis order in image_from_xarray..." · Reviewed by Greptile

@N-Dekker

N-Dekker commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

@SID-6921 Thanks for your PR! Honestly I'm not familiar with xarray, but it sounds like a serious bug. Do you also think so? Or is it rarely a problem, in practice?

As far as I can see, the specific for l_index, dim loop in image_from_xarray was introduced with commit cf75807 (May 3, 2022, included with ITK 5.3), so does that mean that the bug is there for more than 4 years already?

@SID-6921

SID-6921 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Yes, it's at least that old. I checked: the image_dims.sort(reverse=True) / ordered_dims = (...)[-image_dimension:] split already existed in itk/support/extras.py before your May 2022 commit moved it verbatim into xarray.py. The divergence predates the refactor; it just moved house.

On severity: it only misfires when all four dims (t, z, y, x) are present. For 2D/3D subsets, reverse-alphabetical order happens to match the canonical order by coincidence, which is exactly why nobody caught it. The 3D tests all pass. So the practical impact is: build a true 4D image from xarray (e.g. a time-resolved volume) through this path, and you get correct pixel data but origin/spacing silently assigned to the wrong axes, no error raised. That's a real bug when you hit it, but the surface is narrow. It only bites 4D-with-named-time-axis usage of a function whose own docstring already calls it experimental.

@hjmjohnson

Copy link
Copy Markdown
Member

Thanks @SID-6921, this is a good partial step in the right direction. The fix is correct, and on the ITK 5.4.7 wheel the new asserts fail before your change and pass after it; a 4D round trip through xarray_from_image now keeps origin and spacing too. Follow-ups on CI coverage (ITK's CI currently never runs test_xarray.py) and on robustness cases not yet covered are in #6950.

What was checked locally

Isolated venv, ITK 5.4.7 wheel (wraps 4D unsigned char), xarray 2026.9.0, comparing the shipped image_from_xarray with only this PR's one-line change:

Check Before After
This PR's test_xarray.py fails at the new spacing assert passes
4D round trip image to xarray to image origin and spacing scrambled preserved
4D DataArray stored in x,y,z,t order scrambled correct
3D (z,y,x) with coords correct unchanged
dims (t,y,x) ValueError ValueError (tracked in #6950)

@hjmjohnson
hjmjohnson merged commit 8ec4229 into InsightSoftwareConsortium:main Oct 17, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:Python wrapping Python bindings for a class type:Bug Inconsistencies or issues which will cause an incorrect result under some or all circumstances type:Testing Ensure that the purpose of a class is met/the results on a wide set of test cases are correct

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants