Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
schema_version: 1
title: Image metrics keep the fixed image values of sampled points
summary: |
With a sampled point set and a linear fixed transform, `ImageToImageMetricv4`
now keeps the fixed image value of each sample after the first evaluation,
instead of interpolating the fixed image again on every evaluation. An edit of
the fixed image or fixed mask image buffer in place is seen only after
`Modified()` is called on that image.
details: |
The kept values are recomputed when the fixed image, fixed interpolator, fixed
mask, fixed transform (including the transforms inside a composite transform)
or sampled point set is modified, so code that changes these objects through
their setters gets the same results as before. Only code that writes into an
image buffer directly, for example through `GetBufferPointer()` or an image
iterator, between two evaluations of the same metric must call `Modified()`.
Few users should notice: registration methods do not write into the fixed
image during a run, and the usual image filters and readers mark their
output modified.

This applies to metrics whose sparse threader uses the default
`ProcessVirtualPoint()`: mean squares, Mattes mutual information, joint
histogram mutual information and Demons. Correlation and ANTS neighborhood
correlation, and fixed transforms that are not linear, such as displacement
fields, evaluate every point as before.
actions:
- After writing into the fixed image or fixed mask image buffer in place, call `Modified()` on that image before the metric is evaluated again.
- A threader that overrides `ProcessVirtualPoint()` without calling the superclass should override `UsesFixedSampleCache()` to return false, so that the metric does not allocate the cache.
categories:
- ResultsChange
- Performance
environment:
- cxx
impact: low
pr: 7223
examples:
- language: cpp
before: |
fixedImage->GetBufferPointer()[0] = 0;
metric->GetValueAndDerivative(value, derivative);
after: |
fixedImage->GetBufferPointer()[0] = 0;
fixedImage->Modified();
metric->GetValueAndDerivative(value, derivative);
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,13 @@ class ITK_TEMPLATE_EXPORT ANTSNeighborhoodCorrelationImageToImageMetricv4GetValu
*
* */

/** Reads the fixed image with TransformAndEvaluateFixedPoint(), not with the fixed sample cache. */
bool
UsesFixedSampleCache() const override
{
return false;
}

/** Method called by the threaders to process the given virtual point. This
* in turn calls \c TransformAndEvaluateFixedPoint, \c
* TransformAndEvaluateMovingPoint, and \c ProcessPoint.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,13 @@ class ITK_TEMPLATE_EXPORT CorrelationImageToImageMetricv4GetValueAndDerivativeTh
void
AfterThreadedExecution() override;

/** Reads the fixed image with TransformAndEvaluateFixedPoint(), not with the fixed sample cache. */
bool
UsesFixedSampleCache() const override
{
return false;
}

/** Overload to avoid execution of adding entries to m_MeasurePerThread
Comment thread
hjmjohnson marked this conversation as resolved.
Resolved
* StorePointDerivativeResult() after this function calls ProcessPoint().
* Method called by the threaders to process the given virtual point. This
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ class ITK_TEMPLATE_EXPORT CorrelationImageToImageMetricv4HelperThreader
using typename Superclass::MovingOutputPointType;

protected:
/** Reads the fixed image with TransformAndEvaluateFixedPoint(), not with the fixed sample cache. */
bool
UsesFixedSampleCache() const override
{
return false;
}

CorrelationImageToImageMetricv4HelperThreader();
~CorrelationImageToImageMetricv4HelperThreader() override = default;

Expand Down
54 changes: 54 additions & 0 deletions Modules/Registration/Metricsv4/include/itkImageToImageMetricv4.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
#include "itkDefaultConvertPixelTraits.h"
#include "itkDefaultImageToImageMetricTraitsv4.h"

#include <cstdint>

namespace itk
{
/** \class ImageToImageMetricv4
Expand Down Expand Up @@ -711,6 +713,25 @@ class ITK_TEMPLATE_EXPORT ImageToImageMetricv4
FixedImagePointType & mappedFixedPoint,
FixedImagePixelType & mappedFixedPixelValue) const;

/**
* TransformAndEvaluateFixedPoint() for the sample \c sampleIndex of the virtual sampled point set.
* With a sampled point set and a fixed transform made only of linear transforms, the result for
* each sample is kept, so that later evaluations do not interpolate the fixed image again. The
* samples are filled during the first evaluation, each by the work unit that processes it, and
* are recomputed when the fixed image, fixed interpolator, fixed mask, fixed transform or
* sampled point set is modified.
*/
bool
TransformAndEvaluateFixedSample(SizeValueType sampleIndex,
const VirtualPointType & virtualPoint,
FixedImagePointType & mappedFixedPoint,
FixedImagePixelType & mappedFixedPixelValue) const;

/** Enables, sizes or clears the fixed sample cache of TransformAndEvaluateFixedSample(). The threader
* calls it before each evaluation, with \c used false when its ProcessVirtualPoint() does not read the cache. */
void
UpdateFixedSampleCache(bool used) const;

/** Transform and evaluate a point from VirtualImage domain to MovingImage domain. */
bool
TransformAndEvaluateMovingPoint(const VirtualPointType & virtualPoint,
Expand Down Expand Up @@ -892,6 +913,39 @@ class ITK_TEMPLATE_EXPORT ImageToImageMetricv4
/** Flag to know if derivative should be calculated */
mutable bool m_ComputeDerivative{};

/** Newest MTime of \c transform and its sub-transforms; false if any is not linear. */
static bool
InspectFixedTransform(const FixedTransformType * transform, ModifiedTimeType & time, bool & identity);

// State of a sample in the fixed sample cache.
enum class FixedSampleState : std::uint8_t
{
Unknown,
Valid,
Invalid
};

// Objects whose modification clears the fixed sample cache, and their modified times.
struct FixedSampleCacheKey
{
std::vector<const Object *> Objects{};
std::vector<ModifiedTimeType> Times{};
SizeValueType NumberOfSamples{};

bool
operator==(const FixedSampleCacheKey & other) const
{
return Objects == other.Objects && Times == other.Times && NumberOfSamples == other.NumberOfSamples;
}
};

mutable bool m_FixedSampleCacheIsEnabled{};
mutable FixedSampleCacheKey m_FixedSampleCacheKey{};
mutable std::vector<FixedSampleState> m_FixedSampleStates{};
mutable std::vector<FixedImagePixelType> m_FixedSampleValues{};
/** Mapped fixed points; empty when the fixed transform is the identity, which maps each point to itself. */
mutable std::vector<FixedImagePointType> m_FixedSamplePoints{};

/** Only floating-point images are currently supported. To support integer images,
* several small changes must be made */
/** @ITKStartGrouping */
Expand Down
131 changes: 131 additions & 0 deletions Modules/Registration/Metricsv4/include/itkImageToImageMetricv4.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputat
itkDebugMacro("Initialize: ComputeMovingImageGradientFilterImage");
this->ComputeMovingImageGradientFilterImage();
}

/* Initialize() can change what the fixed samples map to, so start with an empty cache. */
this->m_FixedSampleCacheIsEnabled = false;
this->m_FixedSampleCacheKey = FixedSampleCacheKey{};
}

template <typename TFixedImage,
Expand Down Expand Up @@ -280,6 +284,92 @@ ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputat
}
}

template <typename TFixedImage,
typename TMovingImage,
typename TVirtualImage,
typename TInternalComputationValueType,
typename TMetricTraits>
bool
ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputationValueType, TMetricTraits>::
InspectFixedTransform(const FixedTransformType * transform, ModifiedTimeType & time, bool & identity)
{
time = std::max(time, transform->GetMTime());
if constexpr (VirtualImageDimension == FixedImageDimension)
{
using ScalarType = typename FixedTransformType::ScalarType;
if (dynamic_cast<const IdentityTransform<ScalarType, FixedImageDimension> *>(transform) != nullptr)
{
return true;
}
// A composite transform keeps its modified time when one of its transforms is modified.
using MultiTransformType = MultiTransform<ScalarType, FixedImageDimension, FixedImageDimension>;
if (const auto * const multiTransform = dynamic_cast<const MultiTransformType *>(transform))
{
for (SizeValueType n = 0; n < multiTransform->GetNumberOfTransforms(); ++n)
{
if (!InspectFixedTransform(multiTransform->GetNthTransformConstPointer(n), time, identity))
{
return false;
}
}
return true;
}
}
identity = false;
return transform->GetTransformCategory() == FixedTransformType::TransformCategoryEnum::Linear;
}

template <typename TFixedImage,
typename TMovingImage,
typename TVirtualImage,
typename TInternalComputationValueType,
typename TMetricTraits>
void
ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputationValueType, TMetricTraits>::
UpdateFixedSampleCache(const bool used) const
{
ModifiedTimeType transformTime{};
bool identity = true;
if (!used || !this->m_UseSampledPointSet || this->m_VirtualSampledPointSet.IsNull() ||
!InspectFixedTransform(this->m_FixedTransform.GetPointer(), transformTime, identity))
{
if (this->m_FixedSampleCacheIsEnabled)
{
this->m_FixedSampleCacheIsEnabled = false;
this->m_FixedSampleCacheKey = FixedSampleCacheKey{};
std::vector<FixedSampleState>().swap(this->m_FixedSampleStates);
std::vector<FixedImagePixelType>().swap(this->m_FixedSampleValues);
std::vector<FixedImagePointType>().swap(this->m_FixedSamplePoints);
}
return;
}

FixedSampleCacheKey key;
for (const Object * const object : { static_cast<const Object *>(this->m_FixedImage.GetPointer()),
static_cast<const Object *>(this->m_FixedInterpolator.GetPointer()),
static_cast<const Object *>(this->m_FixedImageMask.GetPointer()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Moved masks keep old decisions

UpdateFixedSampleCache() misses changes to the mask's world transform. After an evaluation, a caller can move the mask through GetModifiableObjectToWorldTransform() and call GetObjectToWorldTransformInverse() to refresh its inverse, as documented. Neither call changes the mask's GetMTime(), so the key still matches. The metric then reuses old mask decisions and returns values and derivatives based on the mask's previous position.

Include the mask transforms' modified times in the key and add a test for this path.

static_cast<const Object *>(this->m_VirtualSampledPointSet.GetPointer()),
// SetPoint() modifies the points container, not the point set.
static_cast<const Object *>(this->m_VirtualSampledPointSet->GetPoints()) })
Comment thread
hjmjohnson marked this conversation as resolved.
Resolved
{
key.Objects.push_back(object);
key.Times.push_back(object != nullptr ? object->GetMTime() : ModifiedTimeType{});
Comment thread
hjmjohnson marked this conversation as resolved.
Resolved
}
key.Objects.push_back(this->m_FixedTransform.GetPointer());
key.Times.push_back(transformTime);
key.NumberOfSamples = this->m_VirtualSampledPointSet->GetNumberOfPoints();

if (this->m_FixedSampleCacheIsEnabled && key == this->m_FixedSampleCacheKey)
{
return;
}
this->m_FixedSampleStates.assign(key.NumberOfSamples, FixedSampleState::Unknown);
this->m_FixedSampleValues.resize(key.NumberOfSamples);
this->m_FixedSamplePoints.resize(identity ? 0 : key.NumberOfSamples);
Comment thread
hjmjohnson marked this conversation as resolved.
Resolved
this->m_FixedSampleCacheKey = std::move(key);
this->m_FixedSampleCacheIsEnabled = true;
}

template <typename TFixedImage,
typename TMovingImage,
typename TVirtualImage,
Expand Down Expand Up @@ -321,6 +411,47 @@ ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputat
return pointIsValid;
}

template <typename TFixedImage,
typename TMovingImage,
typename TVirtualImage,
typename TInternalComputationValueType,
typename TMetricTraits>
bool
ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputationValueType, TMetricTraits>::
TransformAndEvaluateFixedSample(const SizeValueType sampleIndex,
const VirtualPointType & virtualPoint,
FixedImagePointType & mappedFixedPoint,
FixedImagePixelType & mappedFixedPixelValue) const
{
if (!this->m_FixedSampleCacheIsEnabled)
{
return this->TransformAndEvaluateFixedPoint(virtualPoint, mappedFixedPoint, mappedFixedPixelValue);
}
FixedSampleState & state = this->m_FixedSampleStates[sampleIndex];
if (state == FixedSampleState::Unknown)
{
const bool pointIsValid =
this->TransformAndEvaluateFixedPoint(virtualPoint, mappedFixedPoint, mappedFixedPixelValue);
this->m_FixedSampleValues[sampleIndex] = mappedFixedPixelValue;
if (!this->m_FixedSamplePoints.empty())
{
this->m_FixedSamplePoints[sampleIndex] = mappedFixedPoint;
}
state = pointIsValid ? FixedSampleState::Valid : FixedSampleState::Invalid;
return pointIsValid;
}
if (this->m_FixedSamplePoints.empty())
{
this->LocalTransformPoint(virtualPoint, mappedFixedPoint);
}
else
{
mappedFixedPoint = this->m_FixedSamplePoints[sampleIndex];
}
mappedFixedPixelValue = this->m_FixedSampleValues[sampleIndex];
return state == FixedSampleState::Valid;
}

template <typename TFixedImage,
typename TMovingImage,
typename TVirtualImage,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ ImageToImageMetricv4GetValueAndDerivativeThreader<ThreadedIndexedContainerPartit
{
const VirtualPointType & virtualPoint = virtualSampledPointSet->GetPoint(i);
const auto virtualIndex = virtualImage->TransformPhysicalPointToIndex(virtualPoint);
this->m_GetValueAndDerivativePerThreadVariables[threadId].SampleIndex = i;
this->ProcessVirtualPoint(virtualIndex, virtualPoint, threadId);
this->m_GetValueAndDerivativePerThreadVariables[threadId].SampleIndex = Superclass::NoSampleIndex;
}
// Finalize per thread actions
this->m_Associate->FinalizeThread(threadId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,17 @@ class ITK_TEMPLATE_EXPORT ImageToImageMetricv4GetValueAndDerivativeThreaderBase
virtual void
StorePointDerivativeResult(const VirtualIndexType & virtualIndex, const ThreadIdType threadId);

/** Whether ProcessVirtualPoint() reads the fixed sample cache of the metric. Threaders that override
* ProcessVirtualPoint() without calling it return false, so that the metric does not allocate the cache. */
virtual bool
UsesFixedSampleCache() const
{
return true;
}

/** SampleIndex value outside the sparse loop. */
static constexpr SizeValueType NoSampleIndex = NumericTraits<SizeValueType>::max();

struct GetValueAndDerivativePerThreadStruct
{
/** Intermediary threaded metric value storage. */
Expand All @@ -182,6 +193,8 @@ class ITK_TEMPLATE_EXPORT ImageToImageMetricv4GetValueAndDerivativeThreaderBase
DerivativeType LocalDerivatives;
/** Intermediary threaded metric value storage. */
SizeValueType NumberOfValidPoints;
/** Index of the sample that the sparse loop is processing, or NoSampleIndex. */
SizeValueType SampleIndex{ NoSampleIndex };
/** Pre-allocated transform jacobian objects, for use as needed by derived
* classes for efficiency. */
JacobianType MovingTransformJacobian;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ ImageToImageMetricv4GetValueAndDerivativeThreaderBase<TDomainPartitioner,
this->m_GetValueAndDerivativePerThreadVariables =
make_unique_for_overwrite<AlignedGetValueAndDerivativePerThreadStruct[]>(numWorkUnitsUsed);

this->m_Associate->UpdateFixedSampleCache(this->UsesFixedSampleCache());

if (this->m_Associate->GetComputeDerivative())
{
for (ThreadIdType i = 0; i < numWorkUnitsUsed; ++i)
Expand Down Expand Up @@ -201,8 +203,13 @@ ImageToImageMetricv4GetValueAndDerivativeThreaderBase<TDomainPartitioner, TImage
* then we otherwise get when exceptions are caught in MultiThreaderBase. */
try
{
// The sparse loop sets the sample index, which lets the metric reuse the fixed results of the sample.
const SizeValueType sampleIndex = this->m_GetValueAndDerivativePerThreadVariables[threadId].SampleIndex;
pointIsValid =
this->m_Associate->TransformAndEvaluateFixedPoint(virtualPoint, mappedFixedPoint, mappedFixedPixelValue);
sampleIndex != NoSampleIndex
? this->m_Associate->TransformAndEvaluateFixedSample(
sampleIndex, virtualPoint, mappedFixedPoint, mappedFixedPixelValue)
: this->m_Associate->TransformAndEvaluateFixedPoint(virtualPoint, mappedFixedPoint, mappedFixedPixelValue);
if (pointIsValid && this->m_Associate->GetComputeDerivative() &&
this->m_Associate->GetGradientSourceIncludesFixed())
{
Expand Down
1 change: 1 addition & 0 deletions Modules/Registration/Metricsv4/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,7 @@ itk_add_test(

set(
ITKMetricsv4GTests
itkImageToImageMetricv4FixedSampleCacheGTest.cxx
itkImageToImageMetricv4WorkUnitsGTest.cxx
itkMattesMutualInformationImageToImageMetricv4GTest.cxx
)
Expand Down
Loading
Loading