File: elxCoreMainGTestUtilities.h

package info (click to toggle)
elastix 5.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 42,480 kB
  • sloc: cpp: 68,403; lisp: 4,118; python: 1,013; xml: 182; sh: 177; makefile: 33
file content (516 lines) | stat: -rw-r--r-- 17,619 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
/*=========================================================================
 *
 *  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.
 *
 *=========================================================================*/

#ifndef elxCoreMainGTestUtilities_h
#define elxCoreMainGTestUtilities_h

#include <elxBaseComponent.h> // For elx.
#include <elxParameterObject.h>
#include <elxConversion.h>

#include <itkDeref.h>
#include <itkImage.h>
#include <itkImageBase.h>
#include <itkImageBufferRange.h>
#include <itkImageRegionRange.h>
#include <itkIndex.h>
#include <itkSize.h>

#include <algorithm> // For fill and transform.
#include <array>
#include <cmath> // For round.
#include <initializer_list>
#include <iterator> // For begin and end.
#include <map>
#include <numeric> // For iota.
#include <random>
#include <string>
#include <type_traits> // For is_pointer, is_same, and integral_constant.
#include <vector>

// GoogleTest header file:
#include <gtest/gtest.h>


namespace elastix
{
namespace CoreMainGTestUtilities
{

/// Eases passing a type as argument to a generic lambda.
template <typename TNested>
struct TypeHolder
{
  using Type = TNested;
};

/// Simple exception class, to be used by unit tests.
class Exception : public std::exception
{
  const char * m_message = "";

public:
  explicit Exception(const char * const message)
    : m_message(message)
  {}

  const char *
  what() const noexcept override
  {
    return m_message;
  }
};


/// Expect the specified condition to be false, and throw an exception if it is true.
#define ELX_GTEST_EXPECT_FALSE_AND_THROW_EXCEPTION_IF(condition)                                                       \
  if (condition)                                                                                                       \
  {                                                                                                                    \
    EXPECT_FALSE(true) << "Expected to be false: " #condition;                                                         \
    throw ::elastix::CoreMainGTestUtilities::Exception("Exception thrown because " #condition);                        \
  }                                                                                                                    \
  static_assert(true, "Expect a semi-colon ';' at the end of a macro call")

template <typename TSmartPointer>
decltype(auto)
DerefSmartPointer(const TSmartPointer & ptr)
{
  static_assert(!std::is_pointer_v<TSmartPointer>, "For raw pointers, use itk::Deref instead!");

  if (ptr == nullptr)
  {
    throw Exception("DerefSmartPointer error: the (smart) pointer should not be null!");
  }
  return *ptr;
}


/// Returns a reference to the front of the specified container. Throws an
/// `Exception` instead, when the container is empty.
template <typename T>
decltype(T().front())
Front(T & container)
{
  if (container.empty())
  {
    throw Exception("Front error: the container should be non-empty!");
  }
  return container.front();
}


template <typename T>
itk::SmartPointer<T>
CheckNew()
{
  static_assert(std::is_same<decltype(T::New()), itk::SmartPointer<T>>{},
                "T::New() must return an itk::SmartPointer<T>!");

  const auto ptr = T::New();
  if (ptr == nullptr)
  {
    throw Exception("New() error: should not return null!");
  }
  return ptr;
}

/// Fills the specified image region with pixel values 1.
template <typename TPixel, unsigned int VImageDimension>
void
FillImageRegion(itk::Image<TPixel, VImageDimension> & image,
                const itk::Index<VImageDimension> &   regionIndex,
                const itk::Size<VImageDimension> &    regionSize)
{
  const itk::ImageRegionRange<itk::Image<TPixel, VImageDimension>> imageRegionRange{
    image, itk::ImageRegion<VImageDimension>{ regionIndex, regionSize }
  };
  std::fill(std::begin(imageRegionRange), std::end(imageRegionRange), 1);
}


// Converts the specified strings to a vector of double.
// Assumes that each string represents a floating point number.
inline std::vector<double>
ConvertStringsToVectorOfDouble(const std::vector<std::string> & strings)
{
  std::vector<double> vectorOfDouble(strings.size());

  std::transform(strings.cbegin(), strings.cend(), vectorOfDouble.begin(), [](const std::string & str) {
    std::size_t index{};
    const auto  result = std::stod(str, &index);

    // Test that all characters have been processed, by std::stod.
    EXPECT_EQ(index, str.size());
    return result;
  });

  return vectorOfDouble;
}


// Converts the specified vector of double to itk::Offset, by rounding each element.
template <std::size_t VDimension>
itk::Offset<VDimension>
ConvertToOffset(const std::vector<double> & doubles)
{
  ELX_GTEST_EXPECT_FALSE_AND_THROW_EXCEPTION_IF(doubles.size() != VDimension);

  itk::Offset<VDimension> result;
  std::size_t             i{};

  for (const double value : doubles)
  {
    const auto roundedValue = std::round(value);

    EXPECT_GE(roundedValue, std::numeric_limits<itk::OffsetValueType>::min());
    EXPECT_LE(roundedValue, std::numeric_limits<itk::OffsetValueType>::max());

    result[i] = static_cast<itk::OffsetValueType>(roundedValue);
    ++i;
  }

  return result;
}


std::map<std::string, std::vector<std::string>> inline CreateParameterMap(
  std::initializer_list<std::pair<std::string, std::vector<std::string>>> initializerList)
{
  std::map<std::string, std::vector<std::string>> result;

  for (const auto & pair : initializerList)
  {
    EXPECT_TRUE(result.insert(pair).second);
  }
  return result;
}


std::map<std::string, std::vector<std::string>> inline CreateParameterMap(
  std::initializer_list<std::pair<std::string, std::string>> initializerList)
{
  std::map<std::string, std::vector<std::string>> result;

  for (const auto & pair : initializerList)
  {
    EXPECT_TRUE(result.insert({ pair.first, { pair.second } }).second);
  }
  return result;
}


template <unsigned VImageDimension>
std::map<std::string, std::vector<std::string>>
CreateParameterMap(std::initializer_list<std::pair<std::string, std::string>> initializerList)
{
  std::map<std::string, std::vector<std::string>> result = CreateParameterMap(initializerList);

  for (const auto & key : { "FixedImageDimension", "MovingImageDimension" })
  {
    EXPECT_TRUE(result.insert({ key, { std::to_string(VImageDimension) } }).second);
  }
  return result;
}


ParameterObject::Pointer inline CreateParameterObject(
  std::initializer_list<std::pair<std::string, std::string>> initializerList)
{
  const auto parameterObject = ParameterObject::New();
  parameterObject->SetParameterMap(CreateParameterMap(initializerList));
  return parameterObject;
}


ParameterObject::Pointer inline CreateParameterObject(const ParameterObject::ParameterMapType & parameterMap)
{
  const auto parameterObject = ParameterObject::New();
  parameterObject->SetParameterMap(parameterMap);
  return parameterObject;
}


inline std::vector<double>
GetTransformParametersFromMaps(const std::vector<ParameterObject::ParameterMapType> & transformParameterMaps)
{
  // For the time being, only support a single parameter map here.
  EXPECT_EQ(transformParameterMaps.size(), 1);

  if (transformParameterMaps.empty())
  {
    throw Exception("Error: GetTransformParametersFromMaps should not return an empty ParameterMap!");
  }

  const auto & transformParameterMap = transformParameterMaps.front();
  const auto   found = transformParameterMap.find("TransformParameters");

  if (found == transformParameterMap.cend())
  {
    throw Exception("Error: GetTransformParametersFromMaps did not find TransformParameters!");
  }
  return ConvertStringsToVectorOfDouble(found->second);
}


template <typename TFilter>
std::vector<double>
GetTransformParametersFromFilter(TFilter & filter)
{
  const auto   transformParameterObject = filter.GetTransformParameterObject();
  const auto & transformParameterMaps = itk::Deref(transformParameterObject).GetParameterMaps();
  return GetTransformParametersFromMaps(transformParameterMaps);
}


// ITK's RecursiveSeparableImageFilter "requires a minimum of four pixels along the dimension to be processed", at
// https://github.com/InsightSoftwareConsortium/ITK/blob/v5.3.0/Modules/Filtering/ImageFilterBase/include/itkRecursiveSeparableImageFilter.hxx#L226
constexpr itk::SizeValueType minimumImageSizeValue{ 4 };


// The image domain. ITK calls it the "geometry" of an image. ("The geometry of an image is defined by its position,
// orientation, spacing, and extent", according to https://itk.org/Doxygen52/html/classitk_1_1ImageBase.html#details).
// The elastix manual (elastix-5.1.0-manual.pdf, January 16, 2023) simply calls it "the
// Size/Spacing/Origin/Index/Direction settings".
template <unsigned int VDimension>
struct ImageDomain
{
  using ImageBaseType = itk::ImageBase<VDimension>;

  using DirectionType = typename ImageBaseType::DirectionType;
  using IndexType = typename ImageBaseType::IndexType;
  using SizeType = typename ImageBaseType::SizeType;
  using SpacingType = typename ImageBaseType::SpacingType;
  using PointType = typename ImageBaseType::PointType;

  DirectionType direction{ DirectionType::GetIdentity() };
  IndexType     index{};
  SizeType      size{};
  SpacingType   spacing{ itk::MakeFilled<SpacingType>(1.0) };
  PointType     origin{};

  // Default-constructor
  ImageDomain() = default;

  // Explicit constructor
  explicit ImageDomain(const SizeType & initialSize)
    : size(initialSize)
  {}

  explicit ImageDomain(const ImageBaseType & image)
    : direction(image.GetDirection())
    , index(image.GetLargestPossibleRegion().GetIndex())
    , size(image.GetLargestPossibleRegion().GetSize())
    , spacing(image.GetSpacing())
    , origin(image.GetOrigin())
  {}

  // Constructor, allowing to explicitly specify all the settings of the domain.
  ImageDomain(const DirectionType & initialDirection,
              const IndexType &     initialIndex,
              const SizeType &      initialSize,
              const SpacingType &   initialSpacing,
              const PointType &     initialOrigin)
    : direction(initialDirection)
    , index(initialIndex)
    , size(initialSize)
    , spacing(initialSpacing)
    , origin(initialOrigin)
  {}

  // Puts the domain settings into the specified image.
  void
  ToImage(itk::ImageBase<VDimension> & image) const
  {
    image.SetDirection(direction);
    image.SetRegions({ index, size });
    image.SetSpacing(spacing);
    image.SetOrigin(origin);
  }

  // Returns the data of this image domain as an elastix/transformix parameter map.
  ParameterObject::ParameterMapType
  AsParameterMap() const
  {
    return {
      // Parameters in alphabetic order:
      { "Direction", elx::Conversion::ToVectorOfStrings(direction) },
      { "Index", elx::Conversion::ToVectorOfStrings(index) },
      { "Origin", elx::Conversion::ToVectorOfStrings(origin) },
      { "Size", elx::Conversion::ToVectorOfStrings(size) },
      { "Spacing", elx::Conversion::ToVectorOfStrings(spacing) },
    };
  }

  friend bool
  operator==(const ImageDomain & lhs, const ImageDomain & rhs)
  {
    return lhs.direction == rhs.direction && lhs.index == rhs.index && lhs.size == rhs.size &&
           lhs.spacing == rhs.spacing && lhs.origin == rhs.origin;
  }

  friend bool
  operator!=(const ImageDomain & lhs, const ImageDomain & rhs)
  {
    return !(lhs == rhs);
  }
};


template <typename TRandomNumberEngine>
int
GenerateRandomSign(TRandomNumberEngine & randomNumberEngine)
{
  return (randomNumberEngine() % 2 == 0) ? -1 : 1;
}


template <unsigned int VImageDimension>
auto
CreateRandomImageDomain(std::mt19937 & randomNumberEngine)
{
  using ImageDomainType = ImageDomain<VImageDimension>;

  const auto createRandomDirection = [&randomNumberEngine] {
    using DirectionType = typename ImageDomainType::DirectionType;
    auto randomDirection = DirectionType::GetIdentity();

    // For now, just a single random rotation
    const auto randomRotation = std::uniform_real_distribution<>{ -M_PI, M_PI }(randomNumberEngine);
    const auto cosRandomRotation = std::cos(randomRotation);
    const auto sinRandomRotation = std::sin(randomRotation);

    randomDirection[0][0] = cosRandomRotation;
    randomDirection[0][1] = sinRandomRotation;
    randomDirection[1][0] = -sinRandomRotation;
    randomDirection[1][1] = cosRandomRotation;

    return randomDirection;
  };
  const auto createRandomIndex = [&randomNumberEngine] {
    typename ImageDomainType::IndexType randomIndex{};
    // Originally tried `std::uniform_int_distribution<itk::IndexValueType>` with
    // `std::numeric_limits<itk::IndexValueType>`, but that caused errors from ImageSamplerBase::CropInputImageRegion(),
    // saying "ERROR: the bounding box of the mask lies entirely out of the InputImageRegion!"
    std::generate(randomIndex.begin(), randomIndex.end(), [&randomNumberEngine] {
      return std::uniform_int_distribution{ std::numeric_limits<int>::min() / 2,
                                            std::numeric_limits<int>::max() / 2 }(randomNumberEngine);
    });
    return randomIndex;
  };
  const auto createRandomSmallImageSize = [&randomNumberEngine] {
    typename ImageDomainType::SizeType randomImageSize{};
    std::generate(randomImageSize.begin(), randomImageSize.end(), [&randomNumberEngine] {
      return std::uniform_int_distribution<itk::SizeValueType>{ minimumImageSizeValue,
                                                                2 * minimumImageSizeValue }(randomNumberEngine);
    });
    return randomImageSize;
  };
  const auto createRandomSpacing = [&randomNumberEngine] {
    typename ImageDomainType::SpacingType randomSpacing{};
    std::generate(randomSpacing.begin(), randomSpacing.end(), [&randomNumberEngine] {
      // Originally tried the maximum interval from std::numeric_limits<itk::SpacePrecisionType>::min() to
      // std::numeric_limits<itk::SpacePrecisionType>::max(), but that caused errors during inverse matrix computation.
      return std::uniform_real_distribution<itk::SpacePrecisionType>{ 0.1, 10.0 }(randomNumberEngine);
    });
    return randomSpacing;
  };
  const auto createRandomPoint = [&randomNumberEngine] {
    typename ImageDomainType::PointType randomPoint{};
    std::generate(randomPoint.begin(), randomPoint.end(), [&randomNumberEngine] {
      // Originally tried an interval up to `std::numeric_limits<itk::SpacePrecisionType>::max() / 2.0`, but that caused
      // errors from ImageSamplerBase::CropInputImageRegion(), saying "ERROR: the bounding box of the mask lies entirely
      // out of the InputImageRegion!"
      return std::uniform_real_distribution<itk::SpacePrecisionType>{
        std::numeric_limits<int>::min(), std::numeric_limits<int>::max()
      }(randomNumberEngine);
    });
    return randomPoint;
  };

  return ImageDomainType{ createRandomDirection(),
                          createRandomIndex(),
                          createRandomSmallImageSize(),
                          createRandomSpacing(),
                          createRandomPoint() };
}


// Creates a test image, filled with zero.
template <typename TPixel, unsigned VImageDimension>
auto
CreateImage(const itk::Size<VImageDimension> & imageSize)
{
  const auto image = itk::Image<TPixel, VImageDimension>::New();
  image->SetRegions(imageSize);
  image->AllocateInitialized();
  return image;
}

// Creates a test image, filled with zero.
template <typename TPixel, unsigned VImageDimension>
auto
CreateImage(const ImageDomain<VImageDimension> & imageDomain)
{
  const auto image = itk::Image<TPixel, VImageDimension>::New();
  imageDomain.ToImage(*image);
  image->AllocateInitialized();
  return image;
}


// Creates a test image, filled with a sequence of natural numbers, 1, 2, 3, ..., N.
template <typename TPixel, unsigned VImageDimension>
auto
CreateImageFilledWithSequenceOfNaturalNumbers(const ImageDomain<VImageDimension> & imageDomain)
{
  using ImageType = itk::Image<TPixel, VImageDimension>;
  const auto image = ImageType::New();
  imageDomain.ToImage(*image);
  image->Allocate();
  const itk::ImageBufferRange<ImageType> imageBufferRange{ *image };
  std::iota(imageBufferRange.begin(), imageBufferRange.end(), TPixel{ 1 });
  return image;
}


// Creates a test image, filled with a sequence of natural numbers, 1, 2, 3, ..., N.
template <typename TPixel, unsigned VImageDimension>
auto
CreateImageFilledWithSequenceOfNaturalNumbers(const itk::Size<VImageDimension> & imageSize)
{
  return CreateImageFilledWithSequenceOfNaturalNumbers<TPixel>(ImageDomain<VImageDimension>{ imageSize });
}


std::string
GetDataDirectoryPath();

// Returns CMAKE_CURRENT_BINARY_DIR: the path to Core Main GTesting subdirectory of the elastix build tree (without
// trailing slash).
std::string
GetCurrentBinaryDirectoryPath();

// Returns the name of a test defined by `GTEST_TEST(TestSuiteName, TestName)` as "TestSuiteName_TestName_Test".
std::string
GetNameOfTest(const testing::Test &);

} // namespace CoreMainGTestUtilities
} // namespace elastix


#endif