You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
GetInverseTransform() should not return base class type #6686
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
@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 virtualComputeMatrixParameters(), 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)
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.
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.
Serialization compatibility: written inverse transforms (.tfm/.h5) now record the derived type string — may affect stored-file round-trip tests.
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.
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.
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
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.
Key de-risking finding: the fix is an existing in-tree pattern applied inconsistently, not a new contract. ITK's own Similarity2DTransform::GetInverseTransform() is literallyreturn 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 overrideGetInverseTransform() in Modules/Core/Transform/include and pass the test: Rigid2DTransform, Euler2DTransform, Similarity2DTransform, CenteredRigid2DTransform, CenteredSimilarity2DTransform, CenteredEuler3DTransform, AffineTransform, ScalableAffineTransform, ScaleTransform, TranslationTransform, IdentityTransform, kernel transforms.
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:
TubeTKsrc/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();
returnnullptr;
Production proof the pattern yields a correct same-typed inverse for a constrained (rotation+scale+translation) transform.
elastixCommon/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.
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.
usingtypename Superclass::InverseTransformBasePointer;
/** Return an inverse of this transform. */
InverseTransformBasePointer
GetInverseTransform() constoverride;
and in the .hxx:
template <...>
auto
ClassName<...>::GetInverseTransform() const -> InverseTransformBasePointer
{
returnSuperclass::InvertTransform(*this);
}
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
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.
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.
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.
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.
Activity
hjmjohnson commentedon Jul 23, 2026
@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&)doesTTransform::New(), deducingTTransformfrom the static type at the call site;MatrixOffsetTransformBase::GetInverseTransform()callsInvertTransform(*this)where*thisis statically the base, so every derived class that doesn't overrideGetInverseTransform()inherits a parent-typed inverse.Good news:
MatrixOffsetTransformBase::GetInverse()already writes the inverse matrix and calls the virtualComputeMatrixParameters(), 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)
Euler3DTransform,QuaternionRigidTransform,Similarity3DTransform,VersorRigid3DTransform,VersorTransformComputeMatrixParameters()re-extracts itFixedCenterOfRotationAffineTransform(→ScalableAffine),ScaleLogarithmicTransform(→Scale)AzimuthElevationToCartesianTransform(→Affine),BSplineTransform(→null)Per-class fix is:
Because
InvertTransform(*this)deducesTTransform = Selfinside the derived class's own method body, constructsSelf::New(), and the inheritedGetInverse(MatrixOffsetTransformBase*)binds to it (Liskov), with virtualComputeMatrixParameters()re-deriving the constrained parameters.Phased plan
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.ScaleLogarithmicTransform.BSplineTransformreturning null andAzimuthElevationreturning affine; add a short Doxygen note explaining why (pending the open question below).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.Core/Transformsuite; re-run transform IO/serialization tests since the written concrete-class type string changes for inverses.Open questions / risks
BSplineTransform(no closed-form inverse) andAzimuthElevationToCartesianTransform(nonlinear) exempted, or should the test simply skip them? They cannot return a same-typed exact inverse..tfm/.h5) now record the derived type string — may affect stored-file round-trip tests.ComputeMatrixParameters()) can warn/throw on near-degenerate rotations or non-positive scales; each class needs a targeted numerical test, not just adynamic_cast.hjmjohnson commentedon Jul 23, 2026
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_castto 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 fortypeidon 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
ANTs/Examples/antsApplyTransforms.cxx:677dynamic_cast<MatrixOffsetTransformType*>(inv)ANTs/Examples/itkantsRegistrationHelper.h:1429dynamic_cast<TransformType*>(inv)ANTs/Examples/itkantsRegistrationHelper.hxx:4059,4065dynamic_cast<MatrixOffsetTransformBaseType*>(inv)BRAINSTools/BRAINSCommonLib/GenericTransformImage.cxx:551static_cast<MatrixOffsetTransformBase<double,3,3>*>(inv)TubeTK/src/Filtering/itktubeResampleTubesFilter.hxx:143(MatrixOffsetTransformType*)ivTRTK/src/rtkOraGeometryReader.cxx:203InverseTransformBasePointerThree of these (
antsApplyTransforms,itkantsRegistrationHelper.hxx,GenericTransformImage) already do a defensive "cast inverse toMatrixOffsetTransformBase, readGetMatrix(), rebuild a fresh affine" — written precisely because the inverse currently returns a generic parent. They keep working unchanged; the derived type still exposesGetMatrix().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(WriteTransformof the inverse composite) andBRAINSTools/…/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/.h5files 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_castto 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.hjmjohnson commentedon Jul 23, 2026
Key de-risking finding: the fix is an existing in-tree pattern applied inconsistently, not a new contract. ITK's own
Similarity2DTransform::GetInverseTransform()is literallyreturn Superclass::InvertTransform(*this);— and the entire 2D transform family already overridesGetInverseTransform()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()inModules/Core/Transform/includeand 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):This is exactly the one-line override proposed for each failing 3D class.
CenteredEuler3DTransformalready 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:
src/Registration/itkSimilarity2DTransform.hxx(a fork of the ITK class) — older idiom, functionally identical toInvertTransform: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 assumeGetInversealways succeeds — it is not a puredynamic_castcheck.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.hjmjohnson commentedon Jul 23, 2026
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
GetInverseTransform()override eachFixedCenterOfRotationAffineTransform,ScaleLogarithmicTransformitkTestTransformGetInverseasserts concrete-type preservation, parameterizedexpectSameTypeWhat changed (15 files, +114/-3)
Each of the 7 classes gains, in the header:
and in the
.hxx:Classes:
Euler3DTransform,QuaternionRigidTransform,Similarity3DTransform,VersorRigid3DTransform,VersorTransform,FixedCenterOfRotationAffineTransform,ScaleLogarithmicTransform.Implementation note: unlike the 2D siblings, these classes did not re-export
InverseTransformBasePointer, so an explicitusing typename Superclass::InverseTransformBasePointer;is required — unqualified names from a template-dependent base are not found by two-phase lookup.Local verification
ITKTransformTestDriverbuilt clean againstmain.itkTestTransformGetInverse: exit 0 with the fix; all 28 instantiations pass including the two exempted (BSpline, AzimuthElevation).Euler3DTransformoverride reproduces the exact failure and exit 1:pre-commit runclean (clang-format wrapped one long signature line).Open questions still needing a maintainer decision
BSplineTransform(null) andAzimuthElevationToCartesianTransform(affine approximation), or should the test skip them differently? They cannot return an exact same-typed inverse.No PR has been opened. On your go-ahead (and a decision on Q1/Q2), this becomes a small draft PR series crediting @dzenanz.
hjmjohnson commentedon Jul 23, 2026
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.
ENH: GetInverseTransform() preserves concrete type for 3D transforms
DOC: Note 3D GetInverseTransform() concrete-type change in migration …
ENH: GetInverseTransform() preserves concrete type for 3D transforms
DOC: Note 3D GetInverseTransform() concrete-type change in migration …
dzenanz commentedon Jul 23, 2026
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.
ENH: GetInverseTransform() preserves concrete type for 3D transforms
DOC: Note 3D GetInverseTransform() concrete-type change in migration …
ENH: GetInverseTransform() preserves concrete type for 3D transforms
DOC: Note 3D GetInverseTransform() concrete-type change in migration …
ENH: GetInverseTransform() preserves concrete type for 3D transforms
DOC: Note 3D GetInverseTransform() concrete-type change in migration …
ENH: GetInverseTransform() preserves concrete type for 3D transforms
DOC: Note 3D GetInverseTransform() concrete-type change in migration …
ENH: GetInverseTransform() preserves concrete type for 3D transforms
DOC: Note 3D GetInverseTransform() concrete-type change in migration …
Merge pull request #6689 from hjmjohnson/enh-3d-transform-same-type-i…