From 3316dbaaa2ea3590342d659e142e612dfc1cc01e Mon Sep 17 00:00:00 2001 From: Niels Viggo Stark Madsen <90676486+Voggo@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:59:39 +0100 Subject: [PATCH] BUG: Preserve work units of sub-metrics in CombinationImageToImageMetric `CombinationImageToImageMetric::Initialize()` saved the number of work units of the combination metric itself, and assigned that number to each sub-metric after the `Initialize()` of the sub-metric. When the number of work units of a sub-metric was different from the number of the combination metric, the per-work-unit data of the sub-metric (allocated during its `Initialize()`) no longer matched the number of work units its threader would use. When the sub-metric then had fewer work units than the combination metric, `ThreadedGetValueAndDerivative` accessed its per-work-unit data out of bounds. This occurred for a multi-metric registration with the "-threads" option (`ElastixRegistrationMethod::SetNumberOfThreads`), using an ITK that has TBB as its default threader: "-threads N" sets the number of work units of each sub-metric to N, while the combination metric then has 16 x N work units by default. It caused a segmentation fault in `ParzenWindowHistogramImageToImageMetric::ThreadedComputePDFs`. Fixed by saving and restoring the number of work units of the sub-metric itself. Added a GoogleTest unit test, `CombinationImageToImageMetric.InitializePreservesNumberOfWorkUnitsOfSubMetric`. --- Common/GTesting/CMakeLists.txt | 2 + .../itkCombinationImageToImageMetricGTest.cxx | 107 ++++++++++++++++++ .../itkCombinationImageToImageMetric.hxx | 2 +- 3 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 Common/GTesting/itkCombinationImageToImageMetricGTest.cxx diff --git a/Common/GTesting/CMakeLists.txt b/Common/GTesting/CMakeLists.txt index 7b2e1c1c7..2390a774f 100644 --- a/Common/GTesting/CMakeLists.txt +++ b/Common/GTesting/CMakeLists.txt @@ -10,6 +10,7 @@ set(ELX_COMMON_GTEST_SOURCES elxTransformIOGTest.cxx itkAdvancedImageToImageMetricGTest.cxx itkAdvancedMeanSquaresImageToImageMetricGTest.cxx + itkCombinationImageToImageMetricGTest.cxx itkComputeImageExtremaFilterGTest.cxx itkCorrespondingPointsEuclideanDistancePointMetricGTest.cxx itkGridScheduleComputerGTest.cxx @@ -60,6 +61,7 @@ endif() target_include_directories(CommonGTest PRIVATE ${elastix_SOURCE_DIR}/Components/Metrics + ${elastix_SOURCE_DIR}/Components/Registrations ${elastix_SOURCE_DIR}/Components/ResampleInterpolators ${elastix_SOURCE_DIR}/Components/Resamplers ${elastix_SOURCE_DIR}/Components/Transforms diff --git a/Common/GTesting/itkCombinationImageToImageMetricGTest.cxx b/Common/GTesting/itkCombinationImageToImageMetricGTest.cxx new file mode 100644 index 000000000..b05b8d715 --- /dev/null +++ b/Common/GTesting/itkCombinationImageToImageMetricGTest.cxx @@ -0,0 +1,107 @@ +/*========================================================================= + * + * Copyright UMC Utrecht and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +// First include the header file to be tested: +#include "MultiMetricMultiResolutionRegistration/itkCombinationImageToImageMetric.h" + +#include "AdvancedMeanSquares/itkAdvancedMeanSquaresImageToImageMetric.h" +#include "itkAdvancedTranslationTransform.h" +#include "itkImageFullSampler.h" +#include "GTesting/elxCoreMainGTestUtilities.h" +#include "elxGTestUtilities.h" +#include "elxDefaultConstruct.h" +#include +#include +#include + +// The template to be tested. +using itk::CombinationImageToImageMetric; + +using elx::CoreMainGTestUtilities::CreateImageFilledWithSequenceOfNaturalNumbers; +using elx::CoreMainGTestUtilities::minimumImageSizeValue; +using elx::GTestUtilities::InitializeMetric; +using elx::GTestUtilities::ValueAndDerivative; + + +// Tests that Initialize() preserves the number of work units of a sub-metric, and that the combination metric then +// yields the same value and derivative as the sub-metric by itself. A sub-metric allocates its per-work-unit data +// during its own Initialize(), so its number of work units should not be changed afterwards. +GTEST_TEST(CombinationImageToImageMetric, InitializePreservesNumberOfWorkUnitsOfSubMetric) +{ + static constexpr auto imageDimension = 2U; + using PixelType = float; + using ImageType = itk::Image; + using SizeType = itk::Size; + using SubMetricType = itk::AdvancedMeanSquaresImageToImageMetric; + + const auto fixedImage = + CreateImageFilledWithSequenceOfNaturalNumbers(SizeType::Filled(minimumImageSizeValue)); + const auto movingImage = + CreateImageFilledWithSequenceOfNaturalNumbers(SizeType::Filled(minimumImageSizeValue + 1)); + + const itk::ThreadIdType defaultNumberOfWorkUnits = + elx::DefaultConstruct>{}.GetNumberOfWorkUnits(); + + // Test both less and more work units than the default number of the combination metric. + for (const itk::ThreadIdType numberOfWorkUnits : { itk::ThreadIdType{ 1 }, defaultNumberOfWorkUnits + 1 }) + { + elx::DefaultConstruct> transform{}; + elx::DefaultConstruct> interpolator{}; + + const auto createSubMetric = [numberOfWorkUnits] { + const auto subMetric = SubMetricType::New(); + subMetric->SetUseMultiThread(true); + subMetric->SetNumberOfWorkUnits(numberOfWorkUnits); + return subMetric; + }; + + elx::DefaultConstruct> imageSampler{}; + const auto subMetric = createSubMetric(); + subMetric->SetImageSampler(&imageSampler); + + elx::DefaultConstruct> combinationMetric{}; + combinationMetric.SetNumberOfMetrics(1); + combinationMetric.SetMetric(subMetric, 0); + combinationMetric.SetMetricWeight(1.0, 0); + combinationMetric.SetUseAllMetrics(); + combinationMetric.SetFixedImage(fixedImage); + combinationMetric.SetMovingImage(movingImage); + combinationMetric.SetTransform(&transform); + combinationMetric.SetInterpolator(&interpolator); + combinationMetric.SetFixedImageRegion(fixedImage->GetBufferedRegion()); + combinationMetric.Initialize(); + + EXPECT_EQ(subMetric->GetNumberOfWorkUnits(), numberOfWorkUnits); + + elx::DefaultConstruct> expectedImageSampler{}; + const auto expectedMetric = createSubMetric(); + InitializeMetric(*expectedMetric, + *fixedImage, + *movingImage, + expectedImageSampler, + transform, + interpolator, + fixedImage->GetBufferedRegion()); + + const auto expected = ValueAndDerivative::FromCostFunction(*expectedMetric, transform.GetParameters()); + const auto actual = ValueAndDerivative::FromCostFunction(combinationMetric, transform.GetParameters()); + + EXPECT_EQ(actual.value, expected.value); + EXPECT_EQ(actual.derivative, expected.derivative); + } +} diff --git a/Components/Registrations/MultiMetricMultiResolutionRegistration/itkCombinationImageToImageMetric.hxx b/Components/Registrations/MultiMetricMultiResolutionRegistration/itkCombinationImageToImageMetric.hxx index b6be0fbaa..b34c1e109 100644 --- a/Components/Registrations/MultiMetricMultiResolutionRegistration/itkCombinationImageToImageMetric.hxx +++ b/Components/Registrations/MultiMetricMultiResolutionRegistration/itkCombinationImageToImageMetric.hxx @@ -591,7 +591,7 @@ CombinationImageToImageMetric::Initialize() { // The NumberOfThreadsPerMetric is changed after Initialize() so we save it before and then // set it on. - unsigned nrOfThreadsPerMetric = this->GetNumberOfWorkUnits(); + const ThreadIdType nrOfThreadsPerMetric = testPtr1->GetNumberOfWorkUnits(); testPtr1->Initialize(); testPtr1->SetNumberOfWorkUnits(nrOfThreadsPerMetric); }