Skip to content

GetInverseTransform() should not return base class type #6686

Closed

Description

@dzenanz

GetInverseTransform() should return the most derived class.

Description

This is not satisfied for many classes, see PR #6685 which demonstrates the problem.

Versions

main, and probably all the other versions too.

Additional information

Taken from repro PR:

ERROR: GetInverseTransform() did not preserve concrete type for AzimuthElevationToCartesianTransform
  Expected type: AzimuthElevationToCartesianTransform
  Actual type: AffineTransform
GetInverseTransform() returned null for BSplineTransform 
ERROR: GetInverseTransform() did not preserve concrete type for Euler3DTransform
  Expected type: Euler3DTransform
  Actual type: MatrixOffsetTransformBase
ERROR: GetInverseTransform() did not preserve concrete type for FixedCenterOfRotationAffineTransform
  Expected type: FixedCenterOfRotationAffineTransform
  Actual type: ScalableAffineTransform
ERROR: GetInverseTransform() did not preserve concrete type for QuaternionRigidTransform
  Expected type: QuaternionRigidTransform
  Actual type: MatrixOffsetTransformBase
ERROR: GetInverseTransform() did not preserve concrete type for ScaleLogarithmicTransform
  Expected type: ScaleLogarithmicTransform
  Actual type: ScaleTransform
ERROR: GetInverseTransform() did not preserve concrete type for Similarity3DTransform
  Expected type: Similarity3DTransform
  Actual type: MatrixOffsetTransformBase
ERROR: GetInverseTransform() did not preserve concrete type for VersorRigid3DTransform
  Expected type: VersorRigid3DTransform
  Actual type: MatrixOffsetTransformBase
ERROR: GetInverseTransform() did not preserve concrete type for VersorTransform
  Expected type: VersorTransform
  Actual type: MatrixOffsetTransformBase

Activity

  1. added
    type:Style
    on Jul 22, 2026
  2. hjmjohnson commented on Jul 23, 2026

    @hjmjohnson
    Member

    @dzenanz I started some analysis. I think the plan is pretty clear for how to make this work. It can not be 100% "Inverse is the same type", because sometimes an inverse does not exist (i.e. bspline).

    Proposed plan to make GetInverseTransform() preserve the concrete (most-derived) type, turning the failing repro in #6685 into a tiered regression test.

    Root cause (one sentence): Transform::InvertTransform(const TTransform&) does TTransform::New(), deducing TTransform from the static type at the call site; MatrixOffsetTransformBase::GetInverseTransform() calls InvertTransform(*this) where *this is statically the base, so every derived class that doesn't override GetInverseTransform() inherits a parent-typed inverse.

    Good news: MatrixOffsetTransformBase::GetInverse() already writes the inverse matrix and calls the virtual ComputeMatrixParameters(), which the constrained subclasses override to re-extract their own params (Euler angles, versor, log-scales). So the per-class fix is essentially a one-line override — no new inverse math — with the real work being round-trip precision tests.

    Per-transform bucket analysis (the 9 failing cases)
    Bucket Transforms Fixable to same-type? Notes
    A — inherit MatrixOffset inverse Euler3DTransform, QuaternionRigidTransform, Similarity3DTransform, VersorRigid3DTransform, VersorTransform Yes Inverse of a rigid/similarity is representable in the same constrained parameterization; virtual ComputeMatrixParameters() re-extracts it
    B — inherit intermediate-concrete inverse FixedCenterOfRotationAffineTransform (→ScalableAffine), ScaleLogarithmicTransform (→Scale) Yes ScaleLogarithmic needs a positive-scale guard (log domain)
    C — not same-type AzimuthElevationToCartesianTransform (→Affine), BSplineTransform (→null) No Nonlinear / no closed-form global inverse — recommend exempting; see open question

    Per-class fix is:

    InverseTransformBasePointer
    GetInverseTransform() const override
    {
      return Superclass::InvertTransform(*this);
    }

    Because InvertTransform(*this) deduces TTransform = Self inside the derived class's own method body, constructs Self::New(), and the inherited GetInverse(MatrixOffsetTransformBase*) binds to it (Liskov), with virtual ComputeMatrixParameters() re-deriving the constrained parameters.

    Phased plan
    • Phase 0 — design sign-off (gate): this touches a documented contract. The base-class GetInverseTransform() Doxygen currently states the inverse type need not match ("allows one to return a numeric inverse transform instead"). Update that doc to say concrete transforms should preserve type when representable.
    • Phase 1 — Bucket A (5 classes): add the one-line override.
    • Phase 2 — Bucket B (2 classes): add the override; add the positive-scale guard for ScaleLogarithmicTransform.
    • Phase 3 — Bucket C (exempt): leave BSplineTransform returning null and AzimuthElevation returning affine; add a short Doxygen note explaining why (pending the open question below).
    • Phase 4 — test rework (itkTestTransformGetInverse.cxx): replace the single hard type-assertion with a tiered, per-transform expectation — Tier 1 (A/B) asserts concrete type and a numerical round-trip (forward∘inverse ≈ identity); Tier 2 (C) asserts only numerical correctness / allows null.
    • Phase 5 — local validation: build the Transform test driver, run the full Core/Transform suite; re-run transform IO/serialization tests since the written concrete-class type string changes for inverses.
    • Phase 6 — packaging: split into a small PR series for reviewability (contract+harness → Bucket A → Bucket B+C docs), each crediting @dzenanz as co-author and building on Inverse transform should be the same type as the original #6685.
    Open questions / risks
    1. Bucket C intent: the issue title says "most derived class" universally. Do you want BSplineTransform (no closed-form inverse) and AzimuthElevationToCartesianTransform (nonlinear) exempted, or should the test simply skip them? They cannot return a same-typed exact inverse.
    2. Serialization compatibility: written inverse transforms (.tfm/.h5) now record the derived type string — may affect stored-file round-trip tests.
    3. Precision: constrained re-extraction (ComputeMatrixParameters()) can warn/throw on near-degenerate rotations or non-positive scales; each class needs a targeted numerical test, not just a dynamic_cast.
  3. self-assigned this
    on Jul 23, 2026
  4. hjmjohnson commented on Jul 23, 2026

    @hjmjohnson
    Member

    Downstream audit update — I swept a ~280-repo / 13 GB ITK-consumer forest (ANTs, BRAINSTools, RTK, elastix, MITK, TubeTK, Slicer + extensions, SimpleITK, …) for the open risk "contract break for downstream code that relied on dynamic_cast to the parent type of an inverse." No affected call site exists. The fix returns a more-derived inverse, and every consumer either uses the inverse through a base pointer or upcasts to an ancestor — both of which a more-derived object still satisfies. The residual concern is serialization baselines, not casting.

    Method

    rg "GetInverseTransform" across all consumers (excluding ITK itself) → 32 hits in 20 files. Each inspected in context; plus a targeted sweep for typeid on any inverse and for sibling-type downcasts (the only patterns that would break). 20/20 files classified below.

    Cast sites — all upcasts to an ancestor, all safe
    Site Cast Verdict
    ANTs/Examples/antsApplyTransforms.cxx:677 dynamic_cast<MatrixOffsetTransformType*>(inv) upcast → derived still casts
    ANTs/Examples/itkantsRegistrationHelper.h:1429 dynamic_cast<TransformType*>(inv) upcast to template base
    ANTs/Examples/itkantsRegistrationHelper.hxx:4059,4065 dynamic_cast<MatrixOffsetTransformBaseType*>(inv) upcast
    BRAINSTools/BRAINSCommonLib/GenericTransformImage.cxx:551 static_cast<MatrixOffsetTransformBase<double,3,3>*>(inv) static upcast — well-defined
    TubeTK/src/Filtering/itktubeResampleTubesFilter.hxx:143 C-style (MatrixOffsetTransformType*)ivT upcast
    RTK/src/rtkOraGeometryReader.cxx:203 stored as base InverseTransformBasePointer no downcast

    Three of these (antsApplyTransforms, itkantsRegistrationHelper.hxx, GenericTransformImage) already do a defensive "cast inverse to MatrixOffsetTransformBase, read GetMatrix(), rebuild a fresh affine" — written precisely because the inverse currently returns a generic parent. They keep working unchanged; the derived type still exposes GetMatrix().

    Non-cast consumers (polymorphic via base pointer) and non-consumers

    Base-pointer only (safe): antsDisplacementAndVelocityField…Update.h, antsMotionCorr.cxx, antsRegistrationTemplateHeader.h, itkMeanSquaresPointSetToPointSetIntensityMetricv4.hxx, BRAINSFitHelperTemplate.hxx, BRAINSConstellationLandmarksTransform.cxx, MITK QmitkRegistrationManipulationWidget.cpp, RTK rtkZengBackProjectionImageFilter.hxx, SphinxExamples RegisterTwoPointSets/Code.cxx, TubeTK itktubeMergeAdjacentImagesFilter.hxx, TubeTK itkImageToImageRegistrationHelper.hxx.

    Own GetInverseTransform() overrides (not consumers): elastix itkAdvancedIdentityTransform.h, TubeTK itkSimilarity2DTransform.hxx.

    typeid/sibling-cast sweep: zero hits — the one failure mode that would break (exact-type check or cast to a sibling) does not exist in the forest.

    Residual risk: serialization baselines (not casting)

    The forest writes inverses to disk — ANTs/Examples/antsRegistrationTemplateHeader.h:1430 (WriteTransform of the inverse composite) and BRAINSTools/…/GenericTransformImage.cxx. After the fix the recorded transform-type string changes (e.g. MatrixOffsetTransformBase_double_3_3 → Euler3DTransform_double_3_3). Factory-based readers handle any registered type, but stored regression baselines that string/byte-compare .tfm/.h5 files in ANTs/BRAINSTools could flag a diff. This is the item to verify when the fix lands; it matches the serialization risk already listed in the plan above.

    Net: open risk #1 ("contract break for downstream dynamic_cast to parent inverse type") can be downgraded to no forest call site affected. Open risk #2 (serialization baselines) stands and should gate the Phase-5 validation.

  5. hjmjohnson commented on Jul 23, 2026

    @hjmjohnson
    Member

    Key de-risking finding: the fix is an existing in-tree pattern applied inconsistently, not a new contract. ITK's own Similarity2DTransform::GetInverseTransform() is literally return Superclass::InvertTransform(*this); — and the entire 2D transform family already overrides GetInverseTransform() and already passes the #6685 test. The failing transforms are all their 3D counterparts, which simply never got the override. This is a 2D-vs-3D consistency gap.

    Evidence — 2D family already fixed, 3D family not

    Transforms that override GetInverseTransform() in Modules/Core/Transform/include and pass the test:
    Rigid2DTransform, Euler2DTransform, Similarity2DTransform, CenteredRigid2DTransform, CenteredSimilarity2DTransform, CenteredEuler3DTransform, AffineTransform, ScalableAffineTransform, ScaleTransform, TranslationTransform, IdentityTransform, kernel transforms.

    Transforms that inherit (parent-typed inverse → fail #6685): Euler3DTransform, QuaternionRigidTransform, Similarity3DTransform, VersorRigid3DTransform, VersorTransform (Bucket A); FixedCenterOfRotationAffineTransform, ScaleLogarithmicTransform (Bucket B).

    The canonical in-tree implementation (itkSimilarity2DTransform.hxx):

    Similarity2DTransform<TParametersValueType>::GetInverseTransform() const -> InverseTransformBasePointer
    {
      return Superclass::InvertTransform(*this);
    }

    This is exactly the one-line override proposed for each failing 3D class. CenteredEuler3DTransform already overrides it too — so even within 3D the treatment is inconsistent, not absent by design.

    Independent downstream confirmation (from the forest audit)

    Two downstream projects reinvented the same idiom, confirming it is the accepted shape:

    • TubeTK src/Registration/itkSimilarity2DTransform.hxx (a fork of the ITK class) — older idiom, functionally identical to InvertTransform:
      Pointer inv = New();
      if (this->GetInverse(inv)) return inv.GetPointer();
      return nullptr;
      Production proof the pattern yields a correct same-typed inverse for a constrained (rotation+scale+translation) transform.
    • elastix Common/Transforms/itkAdvancedIdentityTransform.h — return this->New().GetPointer(); for the identity case.
    Precision caveat this surfaces

    TubeTK's Similarity2DTransform::SetMatrix() throws on a non-orthogonal matrix (orthogonality tolerance check). Constrained re-extraction (ComputeMatrixParameters()) can therefore fail/throw for near-degenerate inverses. The tiered regression test (Phase 4) must expect/tolerate exceptions for such inputs rather than assume GetInverse always succeeds — it is not a pure dynamic_cast check.

    Impact on the plan: Phase 0 (design sign-off) is lighter than first stated — this makes the 3D family consistent with the already-shipped 2D family and with CenteredEuler3DTransform, rather than introducing a new API contract. The base-class Doxygen "type need not match" note documents the fallback (e.g. numeric inverses), not the intended default for transforms that can represent their own inverse.

  6. hjmjohnson commented on Jul 23, 2026

    @hjmjohnson
    Member

    Implementation status — local work complete and verified. The fix is implemented, built, and tested locally; it is not yet pushed or proposed as a PR (awaiting maintainer direction on the design + the two open questions below).

    Completion stages

    Phase Status Notes
    0 — Design sign-off ⏳ pending maintainers Fix reframed as 2D→3D consistency, not a new contract (see prior comment). Base-class Doxygen note left as-is for now.
    1 — Bucket A (5 rigid/versor/similarity) ✅ done One-line GetInverseTransform() override each
    2 — Bucket B (2 classes) ✅ done FixedCenterOfRotationAffineTransform, ScaleLogarithmicTransform
    3 — Bucket C (exempt) ✅ done BSpline (null) + AzimuthElevation (affine) documented + test-exempted
    4 — Test rework ✅ done itkTestTransformGetInverse asserts concrete-type preservation, parameterized expectSameType
    5 — Local build + test ✅ done Green with fix; proven to fail without it
    6 — Packaging / PR ⛔ not started Gated on explicit human request
    What changed (15 files, +114/-3)

    Each of the 7 classes gains, in the header:

    using typename Superclass::InverseTransformBasePointer;
    
    /** Return an inverse of this transform. */
    InverseTransformBasePointer
    GetInverseTransform() const override;

    and in the .hxx:

    template <...>
    auto
    ClassName<...>::GetInverseTransform() const -> InverseTransformBasePointer
    {
      return Superclass::InvertTransform(*this);
    }

    Classes: Euler3DTransform, QuaternionRigidTransform, Similarity3DTransform, VersorRigid3DTransform, VersorTransform, FixedCenterOfRotationAffineTransform, ScaleLogarithmicTransform.

    Implementation note: unlike the 2D siblings, these classes did not re-export InverseTransformBasePointer, so an explicit using typename Superclass::InverseTransformBasePointer; is required — unqualified names from a template-dependent base are not found by two-phase lookup.

    Local verification
    • ITKTransformTestDriver built clean against main.
    • itkTestTransformGetInverse: exit 0 with the fix; all 28 instantiations pass including the two exempted (BSpline, AzimuthElevation).
    • Non-vacuity proven: reverting just the Euler3DTransform override reproduces the exact failure and exit 1:
      ERROR: GetInverseTransform() did not preserve concrete type for Euler3DTransform; got MatrixOffsetTransformBase
      
    • pre-commit run clean (clang-format wrapped one long signature line).

    Open questions still needing a maintainer decision

    1. Bucket C intent — OK to exempt BSplineTransform (null) and AzimuthElevationToCartesianTransform (affine approximation), or should the test skip them differently? They cannot return an exact same-typed inverse.
    2. Serialization baselines — inverses written to disk now record the derived type string; ANTs/BRAINSTools stored-transform baselines may need regeneration (the only downstream impact the forest audit surfaced).

    No PR has been opened. On your go-ahead (and a decision on Q1/Q2), this becomes a small draft PR series crediting @dzenanz.

  7. hjmjohnson commented on Jul 23, 2026

    @hjmjohnson
    Member

    Phase 6 done — draft PR #6689 is open (crediting @dzenanz as co-author, includes the migration-guide note). Phases 1–6 complete; the two open questions (Bucket C exemption, serialization baselines) are surfaced for reviewers in the PR body. Phase 0 design confirmation is the remaining gate.

  8. dzenanz commented on Jul 23, 2026

    @dzenanz
    MemberAuthor

    We can keep the two "problematic" cases as is: AzimuthElevationToCartesianTransform (→Affine), BSplineTransform (→null). Maybe we can be less stringent on these 2 in the existing inversion test, or move them to a new test.

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

Metadata

Metadata

Assignees

Labels

type:Style

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions