File: elxOpenCLMovingGenericPyramid.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 (357 lines) | stat: -rw-r--r-- 11,594 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
/*=========================================================================
 *
 *  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 elxOpenCLMovingGenericPyramid_hxx
#define elxOpenCLMovingGenericPyramid_hxx

#include "elxOpenCLSupportedImageTypes.h"
#include "elxOpenCLMovingGenericPyramid.h"

// GPU includes
#include "itkGPUImageFactory.h"
#include "itkOpenCLLogger.h"

// GPU factory includes
#include "itkGPURecursiveGaussianImageFilterFactory.h"
#include "itkGPUCastImageFilterFactory.h"
#include "itkGPUShrinkImageFilterFactory.h"
#include "itkGPUResampleImageFilterFactory.h"
#include "itkGPUIdentityTransformFactory.h"
#include "itkGPULinearInterpolateImageFunctionFactory.h"

namespace elastix
{

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

template <class TElastix>
OpenCLMovingGenericPyramid<TElastix>::OpenCLMovingGenericPyramid()
  : m_GPUPyramidReady(true)
  , m_GPUPyramidCreated(true)
  , m_ContextCreated(false)
  , m_UseOpenCL(true)
{
  // Based on the Insight Journal paper:
  // http://insight-journal.org/browse/publication/884
  // it is not beneficial to create pyramids for 2D images with OpenCL.
  // There are also small extra overhead and potential problems may appear.
  // To avoid it, we simply run it on CPU for 2D images.
  if constexpr (ImageDimension <= 2)
  {
    log::warn(
      std::ostringstream{} << "WARNING: Creating the moving pyramid with OpenCL for 2D images is not beneficial.\n"
                           << "  The OpenCLMovingGenericPyramid is switching back to CPU mode.");
    return;
  }

  // Check if the OpenCL context has been created.
  itk::OpenCLContext::Pointer context = itk::OpenCLContext::GetInstance();
  this->m_ContextCreated = context->IsCreated();
  if (this->m_ContextCreated)
  {
    try
    {
      this->m_GPUPyramid = GPUPyramidType::New();
    }
    catch (itk::ExceptionObject & e)
    {
      log::error(std::ostringstream{} << "ERROR: Exception during GPU moving generic pyramid creation: " << e);
      this->SwitchingToCPUAndReport(true);
      this->m_GPUPyramidCreated = false;
    }
  }
  else
  {
    this->SwitchingToCPUAndReport(false);
  }
} // end Constructor


/**
 * ******************* BeforeGenerateData ***********************
 */

template <class TElastix>
void
OpenCLMovingGenericPyramid<TElastix>::BeforeGenerateData()
{
  // Local GPU input image
  GPUInputImagePointer gpuInputImage;

  if (this->m_GPUPyramidReady)
  {
    // Create GPU input image
    try
    {
      gpuInputImage = GPUInputImageType::New();
      gpuInputImage->GraftITKImage(this->GetInput());
      gpuInputImage->AllocateGPU();
      gpuInputImage->GetGPUDataManager()->SetCPUBufferLock(true);
      gpuInputImage->GetGPUDataManager()->SetGPUDirtyFlag(true);
      gpuInputImage->GetGPUDataManager()->UpdateGPUBuffer();
    }
    catch (itk::ExceptionObject & e)
    {
      log::error(std::ostringstream{} << "ERROR: Exception during creating GPU input image for moving generic pyramid: "
                                      << e);
      this->SwitchingToCPUAndReport(true);
    }
  }

  if (this->m_GPUPyramidReady)
  {
    // Set the m_GPUResampler properties the same way as Superclass1
    this->m_GPUPyramid->SetNumberOfLevels(this->GetNumberOfLevels());
    this->m_GPUPyramid->SetRescaleSchedule(this->GetRescaleSchedule());
    this->m_GPUPyramid->SetSmoothingSchedule(this->GetSmoothingSchedule());
    this->m_GPUPyramid->SetUseShrinkImageFilter(this->GetUseShrinkImageFilter());
    this->m_GPUPyramid->SetComputeOnlyForCurrentLevel(this->GetComputeOnlyForCurrentLevel());
  }

  if (this->m_GPUPyramidReady)
  {
    try
    {
      this->m_GPUPyramid->SetInput(gpuInputImage);
    }
    catch (itk::ExceptionObject & e)
    {
      log::error(std::ostringstream{} << "ERROR: Exception during setting GPU moving generic pyramid: " << e);
      this->SwitchingToCPUAndReport(true);
    }
  }
} // end BeforeGenerateData()


/**
 * ******************* GenerateData ***********************
 */

template <class TElastix>
void
OpenCLMovingGenericPyramid<TElastix>::GenerateData()
{
  if (!this->m_ContextCreated || !this->m_GPUPyramidCreated || !this->m_UseOpenCL || !this->m_GPUPyramidReady)
  {
    // Switch to CPU version
    Superclass1::GenerateData();
    return;
  }

  // First execute BeforeGenerateData to configure GPU pyramid
  this->BeforeGenerateData();
  if (!this->m_GPUPyramidReady)
  {
    Superclass1::GenerateData();
    return;
  }

  bool computedUsingOpenCL = true;

  // Register factories
  this->RegisterFactories();
  try
  {
    // Perform GPU pyramid execution
    this->m_GPUPyramid->Update();
  }
  catch (itk::OpenCLCompileError & e)
  {
    // First log then report OpenCL compile error
    itk::OpenCLLogger::Pointer logger = itk::OpenCLLogger::GetInstance();
    logger->Write(itk::LoggerBase::PriorityLevelEnum::CRITICAL, e.GetDescription());

    log::error(std::ostringstream{}
               << "ERROR: OpenCL program has not been compiled during updating GPU moving pyramid calculation.\n"
               << "  Please check the '" << logger->GetLogFileName() << "' in output directory.");
    computedUsingOpenCL = false;
  }
  catch (itk::ExceptionObject & e)
  {
    log::error(std::ostringstream{} << "ERROR: Exception during updating GPU moving pyramid calculation: " << e);
    computedUsingOpenCL = false;
  }
  catch (...)
  {
    log::error("ERROR: Unknown exception during updating GPU moving pyramid calculation.");
    computedUsingOpenCL = false;
  }

  // Unregister factories
  this->UnregisterFactories();

  if (computedUsingOpenCL)
  {
    // Graft outputs
    const auto numberOfLevels = this->GetNumberOfLevels();
    for (unsigned int i = 0; i < numberOfLevels; i++)
    {
      this->GraftNthOutput(i, this->m_GPUPyramid->GetOutput(i));
    }

    // Report OpenCL device to the log
    this->ReportToLog();
  }
  else
  {
    log::warn(std::ostringstream{} << "WARNING: The moving pyramid computation with OpenCL failed due to the error.\n"
                                   << "  The OpenCLMovingGenericPyramid is switching back to CPU mode.");
    Superclass1::GenerateData();
  }
} // end GenerateData()


/**
 * ******************* RegisterFactories ***********************
 */

template <class TElastix>
void
OpenCLMovingGenericPyramid<TElastix>::RegisterFactories()
{
  // Typedefs for factories
  using ImageFactoryType = itk::GPUImageFactory2<OpenCLImageTypes, OpenCLImageDimentions>;
  using RecursiveGaussianFactoryType =
    itk::GPURecursiveGaussianImageFilterFactory2<OpenCLImageTypes, OpenCLImageTypes, OpenCLImageDimentions>;
  using CastFactoryType = itk::GPUCastImageFilterFactory2<OpenCLImageTypes, OpenCLImageTypes, OpenCLImageDimentions>;
  using ShrinkFactoryType =
    itk::GPUShrinkImageFilterFactory2<OpenCLImageTypes, OpenCLImageTypes, OpenCLImageDimentions>;
  using ResampleFactoryType =
    itk::GPUResampleImageFilterFactory2<OpenCLImageTypes, OpenCLImageTypes, OpenCLImageDimentions>;
  using IdentityFactoryType = itk::GPUIdentityTransformFactory2<OpenCLImageDimentions>;
  using LinearFactoryType = itk::GPULinearInterpolateImageFunctionFactory2<OpenCLImageTypes, OpenCLImageDimentions>;

  // Create factories
  auto imageFactory = ImageFactoryType::New();
  auto recursiveFactory = RecursiveGaussianFactoryType::New();
  auto castFactory = CastFactoryType::New();
  auto shrinkFactory = ShrinkFactoryType::New();
  auto resampleFactory = ResampleFactoryType::New();
  auto identityFactory = IdentityFactoryType::New();
  auto linearFactory = LinearFactoryType::New();

  // Register factories
  itk::ObjectFactoryBase::RegisterFactory(imageFactory);
  itk::ObjectFactoryBase::RegisterFactory(recursiveFactory);
  itk::ObjectFactoryBase::RegisterFactory(castFactory);
  itk::ObjectFactoryBase::RegisterFactory(shrinkFactory);
  itk::ObjectFactoryBase::RegisterFactory(resampleFactory);
  itk::ObjectFactoryBase::RegisterFactory(identityFactory);
  itk::ObjectFactoryBase::RegisterFactory(linearFactory);

  // Append them
  this->m_Factories.push_back(imageFactory.GetPointer());
  this->m_Factories.push_back(recursiveFactory.GetPointer());
  this->m_Factories.push_back(castFactory.GetPointer());
  this->m_Factories.push_back(shrinkFactory.GetPointer());
  this->m_Factories.push_back(resampleFactory.GetPointer());
  this->m_Factories.push_back(identityFactory.GetPointer());
  this->m_Factories.push_back(linearFactory.GetPointer());

} // end RegisterFactories()


/**
 * ******************* UnregisterFactories ***********************
 */

template <class TElastix>
void
OpenCLMovingGenericPyramid<TElastix>::UnregisterFactories()
{
  for (std::vector<ObjectFactoryBasePointer>::iterator it = this->m_Factories.begin(); it != this->m_Factories.end();
       ++it)
  {
    itk::ObjectFactoryBase::UnRegisterFactory(*it);
  }
  this->m_Factories.clear();
} // end UnregisterFactories()


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

template <class TElastix>
void
OpenCLMovingGenericPyramid<TElastix>::BeforeRegistration()
{
  // Are we using a OpenCL enabled GPU for pyramid?
  this->m_UseOpenCL = true;
  this->m_Configuration->ReadParameter(this->m_UseOpenCL, "OpenCLMovingGenericImagePyramidUseOpenCL", 0);

} // end BeforeRegistration()


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

template <class TElastix>
void
OpenCLMovingGenericPyramid<TElastix>::ReadFromFile()
{
  // OpenCL pyramid specific.
  this->m_UseOpenCL = true;
  this->m_Configuration->ReadParameter(this->m_UseOpenCL, "OpenCLMovingGenericImagePyramidUseOpenCL", 0);

} // end ReadFromFile()


/**
 * ************************* SwitchingToCPUAndReport ************************
 */

template <class TElastix>
void
OpenCLMovingGenericPyramid<TElastix>::SwitchingToCPUAndReport(const bool configError)
{
  if (!configError)
  {
    log::warn(std::ostringstream{} << "WARNING: The OpenCL context could not be created.\n"
                                   << "  The OpenCLMovingGenericImagePyramid is switching back to CPU mode.");
  }
  else
  {
    log::warn(std::ostringstream{} << "WARNING: Unable to configure the GPU.\n"
                                   << "  The OpenCLMovingGenericImagePyramid is switching back to CPU mode.");
  }
  this->m_GPUPyramidReady = false;

} // end SwitchingToCPUAndReport()


/**
 * ************************* ReportToLog ************************************
 */

template <class TElastix>
void
OpenCLMovingGenericPyramid<TElastix>::ReportToLog()
{
  itk::OpenCLContext::Pointer context = itk::OpenCLContext::GetInstance();
  itk::OpenCLDevice           device = context->GetDefaultDevice();
  log::info(std::ostringstream{} << "  Moving pyramid was computed by " << device.GetName() << " from "
                                 << device.GetVendor() << ".");
} // end ReportToLog()


} // end namespace elastix

#endif // end #ifndef elxOpenCLMovingGenericPyramid_hxx