File: elxSplineKernelTransform.hxx

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 (459 lines) | stat: -rw-r--r-- 15,034 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
/*=========================================================================
 *
 *  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 elxSplineKernelTransform_hxx
#define elxSplineKernelTransform_hxx

#include "elxSplineKernelTransform.h"
#include "itkTransformixInputPointFileReader.h"
#include <vnl/vnl_math.h>
#include "itkTimeProbe.h"
#include <cstdint> // For int64_t.

namespace elastix
{

/**
 * ********************* Constructor ****************************
 */

template <class TElastix>
SplineKernelTransform<TElastix>::SplineKernelTransform()
{
  this->SetKernelType("unknown");
} // end Constructor


/*
 * ******************* SetKernelType ***********************
 */

template <class TElastix>
bool
SplineKernelTransform<TElastix>::SetKernelType(const std::string & kernelType)
{
  this->m_SplineKernelType = kernelType;

  /** According to VTK documentation the R2logR version is
   * appropriate for 2D and the normal for 3D
   * \todo: understand why
   */
  if constexpr (SpaceDimension == 2)
  {
    /** only one variant for 2D possible: */
    this->m_KernelTransform = TPRKernelTransformType::New();
  }
  else
  {
    /** 3D: choose between different spline types.
     * \todo: devise one for 4D
     */
    if (kernelType == "ThinPlateSpline")
    {
      this->m_KernelTransform = TPKernelTransformType::New();
    }
    //     else if ( kernelType == "ThinPlateR2LogRSpline" )
    //     {
    //       this->m_KernelTransform = TPRKernelTransformType::New();
    //     }
    else if (kernelType == "VolumeSpline")
    {
      this->m_KernelTransform = VKernelTransformType::New();
    }
    else if (kernelType == "ElasticBodySpline")
    {
      this->m_KernelTransform = EBKernelTransformType::New();
    }
    else if (kernelType == "ElasticBodyReciprocalSpline")
    {
      this->m_KernelTransform = EBRKernelTransformType::New();
    }
    else
    {
      /** unknown kernelType */
      this->m_KernelTransform = KernelTransformType::New();
      return false;
    }
  }

  this->SetCurrentTransform(this->m_KernelTransform);
  return true;

} // end SetKernelType()


/*
 * ******************* BeforeAll ***********************
 */

template <class TElastix>
int
SplineKernelTransform<TElastix>::BeforeAll()
{
  /** Check if -fp is given */
  /** If the optional command "-fp" is given in the command
   * line arguments, then and only then we continue.
   */
  // fp used to be ipp, added in elastix 4.5
  std::string ipp = this->GetConfiguration()->GetCommandLineArgument("-ipp");
  std::string fp = this->GetConfiguration()->GetCommandLineArgument("-fp");

  // Backwards compatibility stuff:
  if (!ipp.empty())
  {
    log::warn("WARNING: -ipp is deprecated, use -fp instead.");
    fp = ipp;
  }

  /** Is the fixed landmark file specified? */
  if (ipp.empty() && fp.empty())
  {
    log::error(std::ostringstream{} << "ERROR: -fp should be given for " << this->elxGetClassName()
                                    << " in order to define the fixed image (source) landmarks.");
    return 1;
  }
  else
  {
    log::info(std::ostringstream{} << "-fp       " << fp);
  }

  /** Check if -mp is given. If the optional command "-mp"
   * is given in the command line arguments, then we print it.
   */
  std::string mp = this->GetConfiguration()->GetCommandLineArgument("-mp");

  /** Is the moving landmark file specified? */
  if (mp.empty())
  {
    log::info("-mp       unspecified, assumed equal to -fp");
  }
  else
  {
    log::info(std::ostringstream{} << "-mp       " << mp);
  }

  return 0;

} // end BeforeAll()


/*
 * ******************* BeforeRegistration ***********************
 */

template <class TElastix>
void
SplineKernelTransform<TElastix>::BeforeRegistration()
{
  /** Determine type of spline. */
  std::string kernelType = "ThinPlateSpline";
  this->GetConfiguration()->ReadParameter(kernelType, "SplineKernelType", this->GetComponentLabel(), 0, -1);
  bool knownType = this->SetKernelType(kernelType);
  if (!knownType)
  {
    log::error(std::ostringstream{} << "ERROR: The kernel type " << kernelType << " is not supported.");
    itkExceptionMacro("ERROR: unable to configure " << this->GetComponentLabel());
  }

  /** Interpolating or approximating spline. */
  double splineRelaxationFactor = 0.0;
  this->GetConfiguration()->ReadParameter(
    splineRelaxationFactor, "SplineRelaxationFactor", this->GetComponentLabel(), 0, -1);
  this->m_KernelTransform->SetStiffness(splineRelaxationFactor);

  /** Set the Poisson ratio; default = 0.3 = steel. */
  if (kernelType == "ElasticBodySpline" || kernelType == "ElastixBodyReciprocalSpline")
  {
    double poissonRatio = 0.3;
    this->GetConfiguration()->ReadParameter(poissonRatio, "SplinePoissonRatio", this->GetComponentLabel(), 0, -1);
    this->m_KernelTransform->SetPoissonRatio(poissonRatio);
  }

  /** Set the matrix inversion method (one of {SVD, QR}). */
  std::string matrixInversionMethod = "SVD";
  this->GetConfiguration()->ReadParameter(matrixInversionMethod, "TPSMatrixInversionMethod", 0, true);
  this->m_KernelTransform->SetMatrixInversionMethod(matrixInversionMethod);

  /** Load fixed image (source) landmark positions. */
  this->DetermineSourceLandmarks();

  /** Load moving image (target) landmark positions. */
  bool movingLandmarksGiven = this->DetermineTargetLandmarks();

  /** Set all parameters to identity if no moving landmarks were given. */
  if (!movingLandmarksGiven)
  {
    this->m_KernelTransform->SetIdentity();
  }

  /** Set the initial parameters in this->m_Registration. */
  this->m_Registration->GetAsITKBaseType()->SetInitialTransformParameters(this->GetParameters());

  /** \todo: builtin some multiresolution in this transform. */

} // end BeforeRegistration()


/**
 * ************************* DetermineSourceLandmarks *********************
 */

template <class TElastix>
void
SplineKernelTransform<TElastix>::DetermineSourceLandmarks()
{
  /** Load the fixed image landmarks. */
  log::info(std::ostringstream{} << "Loading fixed image landmarks for " << this->GetComponentLabel() << ":"
                                 << this->elxGetClassName() << ".");

  // fp used to be ipp
  std::string ipp = this->GetConfiguration()->GetCommandLineArgument("-ipp");
  std::string fp = this->GetConfiguration()->GetCommandLineArgument("-fp");
  if (fp.empty())
  {
    fp = ipp; // backwards compatibility, added in elastix 4.5
  }
  PointSetPointer landmarkPointSet; // default-constructed (null)
  this->ReadLandmarkFile(fp, landmarkPointSet, true);

  /** Set the fp as source landmarks. */
  itk::TimeProbe timer;
  timer.Start();
  log::info("  Setting the fixed image landmarks (requiring large matrix inversion) ...");
  this->m_KernelTransform->SetSourceLandmarks(landmarkPointSet);
  timer.Stop();
  log::info(std::ostringstream{} << "  Setting the fixed image landmarks took: "
                                 << Conversion::SecondsToDHMS(timer.GetMean(), 6));

} // end DetermineSourceLandmarks()


/**
 * ************************* DetermineTargetLandmarks *********************
 */

template <class TElastix>
bool
SplineKernelTransform<TElastix>::DetermineTargetLandmarks()
{
  /** The moving landmark file name. */
  std::string mp = this->GetConfiguration()->GetCommandLineArgument("-mp");
  if (mp.empty())
  {
    return false;
  }

  /** Load the moving image landmarks. */
  log::info(std::ostringstream{} << "Loading moving image landmarks for " << this->GetComponentLabel() << ":"
                                 << this->elxGetClassName() << ".");

  PointSetPointer landmarkPointSet;
  this->ReadLandmarkFile(mp, landmarkPointSet, false);

  /** Set the mp as target landmarks. */
  itk::TimeProbe timer;
  timer.Start();
  log::info("  Setting the moving image landmarks ...");
  this->m_KernelTransform->SetTargetLandmarks(landmarkPointSet);
  timer.Stop();
  log::info(std::ostringstream{} << "  Setting the moving image landmarks took: "
                                 << Conversion::SecondsToDHMS(timer.GetMean(), 6));

  return true;

} // end DetermineTargetLandmarks()


/**
 * ************************* ReadLandmarkFile *********************
 */

template <class TElastix>
void
SplineKernelTransform<TElastix>::ReadLandmarkFile(const std::string & filename,
                                                  PointSetPointer &   landmarkPointSet,
                                                  const bool          landmarksInFixedImage)
{
  /** Typedef's. */
  using IndexType = typename FixedImageType::IndexType;
  using IndexValueType = typename IndexType::IndexValueType;

  /** Construct a landmark file reader and read the points. */
  auto landmarkReader = itk::TransformixInputPointFileReader<PointSetType>::New();
  landmarkReader->SetFileName(filename);
  try
  {
    landmarkReader->Update();
  }
  catch (const itk::ExceptionObject & err)
  {
    log::error(std::ostringstream{} << "  Error while opening landmark file.\n" << err);
    itkExceptionMacro("ERROR: unable to configure " << this->GetComponentLabel());
  }

  /** Some user-feedback. */
  if (landmarkReader->GetPointsAreIndices())
  {
    log::info("  Landmarks are specified as image indices.");
  }
  else
  {
    log::info("  Landmarks are specified in world coordinates.");
  }
  const unsigned int nrofpoints = landmarkReader->GetNumberOfPoints();
  log::info(std::ostringstream{} << "  Number of specified input points: " << nrofpoints);

  /** Get the set of input points. */
  landmarkPointSet = landmarkReader->GetOutput();

  /** Convert from index to point if necessary */
  landmarkPointSet->DisconnectPipeline();
  if (landmarkReader->GetPointsAreIndices())
  {
    /** Get handles to the fixed and moving images. */
    typename FixedImageType::Pointer  fixedImage = this->GetElastix()->GetFixedImage();
    typename MovingImageType::Pointer movingImage = this->GetElastix()->GetMovingImage();

    InputPointType landmarkPoint;
    landmarkPoint.Fill(0.0f);
    IndexType landmarkIndex;
    for (unsigned int j = 0; j < nrofpoints; ++j)
    {
      /** The read point from the inputPointSet is actually an index
       * Cast to the proper type.
       */
      landmarkPointSet->GetPoint(j, &landmarkPoint);
      for (unsigned int d = 0; d < SpaceDimension; ++d)
      {
        landmarkIndex[d] = static_cast<IndexValueType>(itk::Math::Round<std::int64_t>(landmarkPoint[d]));
      }

      /** Compute the input point in physical coordinates and replace the point. */
      if (landmarksInFixedImage)
      {
        fixedImage->TransformIndexToPhysicalPoint(landmarkIndex, landmarkPoint);
      }
      else
      {
        movingImage->TransformIndexToPhysicalPoint(landmarkIndex, landmarkPoint);
      }
      landmarkPointSet->SetPoint(j, landmarkPoint);
    }
  }

  /** Apply initial transform if necessary, for fixed image landmarks only. */
  if (const auto * const initialTransform = this->Superclass1::GetInitialTransform();
      initialTransform != nullptr && landmarksInFixedImage && this->GetUseComposition())
  {
    InputPointType inputPoint;
    inputPoint.Fill(0.0f);
    for (unsigned int j = 0; j < nrofpoints; ++j)
    {
      landmarkPointSet->GetPoint(j, &inputPoint);
      inputPoint = initialTransform->TransformPoint(inputPoint);
      landmarkPointSet->SetPoint(j, inputPoint);
    }
  }

} // end ReadLandmarkFile()


/**
 * ************************* ReadFromFile ************************
 */

template <class TElastix>
void
SplineKernelTransform<TElastix>::ReadFromFile()
{
  /** Read kernel type. */
  std::string kernelType = "unknown";
  bool        skret = this->GetConfiguration()->ReadParameter(kernelType, "SplineKernelType", 0);
  if (skret)
  {
    this->SetKernelType(kernelType);
  }
  else
  {
    log::error("ERROR: the SplineKernelType is not given in the transform parameter file.");
    itkExceptionMacro("ERROR: unable to configure transform.");
  }

  /** Interpolating or approximating spline. */
  double splineRelaxationFactor = 0.0;
  this->GetConfiguration()->ReadParameter(
    splineRelaxationFactor, "SplineRelaxationFactor", this->GetComponentLabel(), 0, -1);
  this->m_KernelTransform->SetStiffness(splineRelaxationFactor);

  /** Set the Poisson ratio; default = 0.3 = steel. */
  double poissonRatio = 0.3;
  this->GetConfiguration()->ReadParameter(poissonRatio, "SplinePoissonRatio", this->GetComponentLabel(), 0, -1);
  this->m_KernelTransform->SetPoissonRatio(poissonRatio);

  /** Read number of parameters. */
  unsigned int numberOfParameters = 0;
  this->GetConfiguration()->ReadParameter(numberOfParameters, "NumberOfParameters", 0);

  /** Read source landmarks. */
  std::vector<CoordRepType> fixedImageLandmarks(numberOfParameters, CoordRepType{});
  bool                      retfil = this->GetConfiguration()->ReadParameter(
    fixedImageLandmarks, "FixedImageLandmarks", 0, numberOfParameters - 1, true);
  if (!retfil)
  {
    log::error("ERROR: the FixedImageLandmarks are not given in the transform parameter file.");
    itkExceptionMacro("ERROR: unable to configure transform.");
  }

  /** Convert to fixedParameters type and set in transform. */
  ParametersType fixedParams(numberOfParameters);
  for (unsigned int i = 0; i < numberOfParameters; ++i)
  {
    fixedParams[i] = fixedImageLandmarks[i];
  }
  this->m_KernelTransform->SetFixedParameters(fixedParams);

  /** Call the ReadFromFile from the TransformBase.
   * This must be done after setting the source landmarks and the
   * splinekerneltype, because later the ReadFromFile from
   * TransformBase calls SetParameters.
   */
  this->Superclass2::ReadFromFile();

} // ReadFromFile()


/**
 * ************************* CustomizeTransformParameterMap ************************
 */

template <class TElastix>
auto
SplineKernelTransform<TElastix>::CreateDerivedTransformParameterMap() const -> ParameterMapType
{
  auto & itkTransform = *m_KernelTransform;

  return { { "SplineKernelType", { m_SplineKernelType } },
           { "SplinePoissonRatio", { Conversion::ToString(itkTransform.GetPoissonRatio()) } },
           { "SplineRelaxationFactor", { Conversion::ToString(itkTransform.GetStiffness()) } },
           { "FixedImageLandmarks", Conversion::ToVectorOfStrings(itkTransform.GetFixedParameters()) } };

} // end CustomizeTransformParameterMap()


} // end namespace elastix

#endif // end #ifndef elxSplineKernelTransform_hxx