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
|
/*=========================================================================
*
* 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.
*
*=========================================================================*/
/** If running on a Windows-system, include "windows.h".
* This is to set the priority, but which does not work on cygwin.
*/
#if defined(_WIN32) && !defined(__CYGWIN__)
# include <windows.h>
#else
# include <dlfcn.h>
#endif
#include "elxMainBase.h"
#include "elxComponentLoader.h"
#include "elxMacro.h"
#include "itkMultiThreaderBase.h"
#ifdef ELASTIX_USE_OPENCL
# include "itkOpenCLContext.h"
# include "itkOpenCLSetup.h"
#endif
#include <cstdlib>
#include <sstream>
namespace elastix
{
/**
* ********************* Constructor ****************************
*/
MainBase::MainBase() = default;
/**
* ********************* GetMutableComponentDatabase ****************************
*/
ComponentDatabase &
MainBase::GetMutableComponentDatabase()
{
// Improved thread-safety by using C++11 "magic statics".
static const auto staticComponentDatabase = [] {
const auto componentDatabase = ComponentDatabase::New();
const auto componentLoader = ComponentLoader::New();
componentLoader->SetComponentDatabase(componentDatabase);
if (componentLoader->LoadComponents() != 0)
{
log::error("Loading components failed");
}
return componentDatabase; // SmartPointer
}();
return *staticComponentDatabase;
} // end GetMutableComponentDatabase
/**
* ********************* GetComponentDatabase ****************************
*/
const ComponentDatabase &
MainBase::GetComponentDatabase()
{
return GetMutableComponentDatabase();
} // end GetComponentDatabase()
/**
* ********************** Destructor ****************************
*/
MainBase::~MainBase()
{
#ifdef ELASTIX_USE_OPENCL
itk::OpenCLContext::Pointer context = itk::OpenCLContext::GetInstance();
if (context->IsCreated())
{
context->Release();
}
#endif
} // end Destructor
/**
* **************************** Run *****************************
*/
int
MainBase::Run(const ArgumentMapType & argmap)
{
/** Initialize the configuration object with the
* command line parameters entered by the user.
*/
if (m_Configuration->Initialize(argmap) != 0)
{
log::error("ERROR: Something went wrong during initialization of the configuration object.");
}
return this->Run();
} // end Run()
/**
* **************************** Run *****************************
*/
int
MainBase::Run(const ArgumentMapType & argmap, const ParameterMapType & inputMap)
{
/** Initialize the configuration object with the
* command line parameters entered by the user.
*/
if (m_Configuration->Initialize(argmap, inputMap) != 0)
{
log::error("ERROR: Something went wrong during initialization of the configuration object.");
}
return this->Run();
} // end Run()
/**
* ************************* GetElastixBase ***************************
*/
ElastixBase &
MainBase::GetElastixBase() const
{
/** Convert ElastixAsObject to a pointer to an ElastixBase. */
const auto elastixBase = dynamic_cast<ElastixBase *>(m_Elastix.GetPointer());
if (elastixBase == nullptr)
{
itkExceptionMacro("Probably GetElastixBase() is called before having called Run()");
}
return *elastixBase;
} // end GetElastixBase()
/**
* ************************* TryLoadComponentPlugin ***************************
*/
bool
MainBase::TryLoadComponentPlugin(const ComponentDescriptionType & componentName)
{
// Only lazy-load for IMPACT (keep it minimal).
if (componentName != "Impact")
{
return false;
}
// Try CUDA first, then CPU.
const std::vector<std::string> pluginCandidates = { "ImpactMetricCuda", "ImpactMetric" };
// Keep the most recent loader error, to report something useful at the end.
std::string lastError;
for (const auto & pluginName : pluginCandidates)
{
// Note: this is the symbol name exported by the plugin (extern "C").
const std::string installSymbol = "ImpactMetricInstallComponent";
#if defined(_WIN32) && !defined(__CYGWIN__)
const std::string libFileName = pluginName + ".dll";
HMODULE handle = LoadLibraryA(libFileName.c_str());
if (!handle)
{
lastError = "LoadLibrary failed for " + libFileName;
continue;
}
using InstallFunc = int (*)(elastix::ComponentDatabase *);
auto fn = reinterpret_cast<InstallFunc>(GetProcAddress(handle, installSymbol.c_str()));
if (!fn)
{
lastError = "GetProcAddress failed for symbol " + installSymbol + " in " + libFileName;
continue;
}
#else
// Linux and MacOS have the same convention for plugin file names.
const std::string libFileName = "lib" + pluginName + ".so";
dlerror(); // clear any old error state
void * handle = dlopen(libFileName.c_str(), RTLD_NOW | RTLD_LOCAL);
if (!handle)
{
const char * e = dlerror();
lastError = std::string("dlopen failed for ") + libFileName + ": " + (e ? e : "");
continue;
}
dlerror(); // clear before dlsym
using InstallFunc = int (*)(elastix::ComponentDatabase *);
auto fn = reinterpret_cast<InstallFunc>(dlsym(handle, installSymbol.c_str()));
if (const char * e = dlerror())
{
lastError = std::string("dlsym failed for symbol ") + installSymbol + " in " + libFileName + ": " + e;
continue;
}
if (!fn)
{
lastError = "dlsym returned null for symbol " + installSymbol + " in " + libFileName;
continue;
}
#endif
const int ret = fn(&GetMutableComponentDatabase());
if (ret != 0)
{
lastError = "InstallComponent returned non-zero (" + std::to_string(ret) + ") for " + libFileName;
continue;
}
log::info(std::ostringstream{} << "Lazy-loaded IMPACT plugin '" << pluginName << "'.");
return true;
}
log::error(
std::ostringstream{} << "IMPACT requested but could not be loaded.\n"
<< "Tried plugins: ImpactMetricCuda, ImpactMetric\n"
<< "Last error: " << (lastError.empty() ? "(none)" : lastError) << "\n"
<< "Hint: ensure the plugin is on the loader search path and that the corresponding LibTorch "
<< "dependencies are available (LD_LIBRARY_PATH / PATH).");
return false;
} // TryLoadComponentPlugin()
MainBase::ObjectPointer
MainBase::CreateComponent(const ComponentDescriptionType & name)
{
/** 1) Try to create the component from the already installed database. */
if (const PtrToCreator creator = GetComponentDatabase().GetCreator(name, m_DBIndex))
{
if (const ObjectPointer component = creator())
{
return component;
}
}
/** 2) Not found: try to lazy-load a plugin that may provide this component,
* and retry exactly once.
*/
if (TryLoadComponentPlugin(name))
{
if (const PtrToCreator creator = GetComponentDatabase().GetCreator(name, m_DBIndex))
{
if (const ObjectPointer component = creator())
{
return component;
}
}
}
/** 3) Still not available: give a clear and fatal error. */
itkExceptionMacro("The following component could not be created: " << name);
} // end CreateComponent()
/**
* *********************** CreateComponents *****************************
*/
MainBase::ObjectContainerPointer
MainBase::CreateComponents(const std::string & key,
const ComponentDescriptionType & defaultComponentName,
int & errorcode,
bool mandatoryComponent)
{
ComponentDescriptionType componentName = defaultComponentName;
unsigned int componentnr = 0;
ObjectContainerPointer objectContainer = ObjectContainerType::New();
objectContainer->Initialize();
/** Read the component name.
* If the user hasn't specified any component names, use
* the default, and give a warning.
*/
bool found = m_Configuration->ReadParameter(componentName, key, componentnr, true);
/** If the default equals "" (so no default), the mandatoryComponent
* flag is true, and not component was given by the user,
* then elastix quits.
*/
if (!found && (defaultComponentName.empty()))
{
if (mandatoryComponent)
{
log::error(std::ostringstream{} << "ERROR: the following component has not been specified: " << key);
errorcode = 1;
return objectContainer;
}
else
{
/* Just return an empty container without nagging. */
errorcode = 0;
return objectContainer;
}
}
/** Try creating the specified component. */
try
{
objectContainer->CreateElementAt(componentnr) = this->CreateComponent(componentName);
}
catch (const itk::ExceptionObject & excp)
{
log::error(std::ostringstream{} << "ERROR: error occurred while creating " << key << " " << componentnr << ".\n"
<< excp);
errorcode = 1;
return objectContainer;
}
/** Check if more than one component name is given. */
while (found)
{
++componentnr;
found = m_Configuration->ReadParameter(componentName, key, componentnr, false);
if (found)
{
try
{
objectContainer->CreateElementAt(componentnr) = this->CreateComponent(componentName);
}
catch (const itk::ExceptionObject & excp)
{
log::error(std::ostringstream{} << "ERROR: error occurred while creating " << key << " " << componentnr << ".\n"
<< excp);
errorcode = 1;
return objectContainer;
}
} // end if
} // end while
return objectContainer;
} // end CreateComponents()
/**
* *********************** SetProcessPriority *************************
*/
void
MainBase::SetProcessPriority() const
{
/** If wanted, set the priority of this process high or below normal. */
std::string processPriority = m_Configuration->GetCommandLineArgument("-priority");
if (processPriority == "high")
{
#if defined(_WIN32) && !defined(__CYGWIN__)
SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
#endif
}
else if (processPriority == "abovenormal")
{
#if defined(_WIN32) && !defined(__CYGWIN__)
SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
#endif
}
else if (processPriority == "normal")
{
#if defined(_WIN32) && !defined(__CYGWIN__)
SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS);
#endif
}
else if (processPriority == "belownormal")
{
#if defined(_WIN32) && !defined(__CYGWIN__)
SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
}
else if (processPriority == "idle")
{
#if defined(_WIN32) && !defined(__CYGWIN__)
SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS);
#endif
}
else if (!processPriority.empty())
{
log::warn("Unsupported -priority value. Specify one of <high, abovenormal, normal, belownormal, idle, ''>.");
}
} // end SetProcessPriority()
/**
* *********************** SetMaximumNumberOfThreads *************************
*/
void
MainBase::SetMaximumNumberOfThreads() const
{
/** Get the number of threads from the command line. */
std::string maximumNumberOfThreadsString = m_Configuration->GetCommandLineArgument("-threads");
/** If supplied, set the maximum number of threads. */
if (!maximumNumberOfThreadsString.empty())
{
const int maximumNumberOfThreads = atoi(maximumNumberOfThreadsString.c_str());
itk::MultiThreaderBase::SetGlobalMaximumNumberOfThreads(maximumNumberOfThreads);
// The following statement (getting and setting GlobalDefaultNumberOfThreads) may look redundant, but it's not
// (using ITK 5.4.0)! The Set function ensures that GlobalDefaultNumberOfThreads <= GlobalMaximumNumberOfThreads.
// (GlobalDefaultNumberOfThreads is important, as ITK uses this number when constructing the ThreadPool.)
itk::MultiThreaderBase::SetGlobalDefaultNumberOfThreads(itk::MultiThreaderBase::GetGlobalDefaultNumberOfThreads());
}
} // end SetMaximumNumberOfThreads()
} // end namespace elastix
|