File: elxConversion.cxx

package info (click to toggle)
elastix 5.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 45,644 kB
  • sloc: cpp: 85,720; lisp: 4,118; python: 1,045; sh: 200; xml: 182; makefile: 33
file content (507 lines) | stat: -rw-r--r-- 13,358 bytes parent folder | download | duplicates (2)
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
/*=========================================================================
 *
 *  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.
 *
 *=========================================================================*/

#include "elxConversion.h"

#include <itkNumberToString.h>
#include <itkOptimizerParameters.h>

#include <double-conversion.h>

// Standard C++ header files:
#include <cassert>
#include <cmath>   // For fmod, fpclassify and FP_SUBNORMAL.
#include <iomanip> // For setprecision.
#include <limits>
#include <numeric> // For accumulate.
#include <regex>
#include <sstream>     // For ostringstream.
#include <type_traits> // For is_floating_point.


namespace
{

template <typename TFloatingPoint>
TFloatingPoint
ConvertStringToFloatingPoint(const double_conversion::StringToDoubleConverter &, const char *, int, int *);

template <>
float
ConvertStringToFloatingPoint(const double_conversion::StringToDoubleConverter & converter,
                             const char * const                                 buffer,
                             const int                                          length,
                             int * const                                        processed_characters_count)
{
  return converter.StringToFloat(buffer, length, processed_characters_count);
}

template <>
double
ConvertStringToFloatingPoint(const double_conversion::StringToDoubleConverter & converter,
                             const char * const                                 buffer,
                             const int                                          length,
                             int * const                                        processed_characters_count)
{
  return converter.StringToDouble(buffer, length, processed_characters_count);
}


template <typename TFloatingPoint>
bool
StringToFloatingPointValue(const std::string & str, TFloatingPoint & value)
{
  static_assert(std::is_floating_point_v<TFloatingPoint>, "This function template only supports floating point types.");

  using NumericLimits = std::numeric_limits<TFloatingPoint>;

  if (str == "NaN")
  {
    value = NumericLimits::quiet_NaN();
    return true;
  }
  if (str == "Infinity")
  {
    value = NumericLimits::infinity();
    return true;
  }
  if (str == "-Infinity")
  {
    value = -NumericLimits::infinity();
    return true;
  }
  const auto numberOfChars = str.size();

  if (numberOfChars > std::numeric_limits<int>::max())
  {
    return false;
  }

  constexpr auto double_NaN = std::numeric_limits<double>::quiet_NaN();
  int            processed_characters_count{};

  const double_conversion::StringToDoubleConverter converter(0, double_NaN, double_NaN, "inf", "nan");

  const auto conversionResult = ConvertStringToFloatingPoint<TFloatingPoint>(
    converter, str.c_str(), static_cast<int>(numberOfChars), &processed_characters_count);

  if (std::isnan(conversionResult) || (processed_characters_count != static_cast<int>(numberOfChars)))
  {
    // Conversion failed: the result is NaN (while `str` is not
    // "NaN"), or the converter did not process all characters.
    return false;
  }
  value = conversionResult;
  return true;
}


template <typename TChar>
bool
StringToCharValue(const std::string & str, TChar & value)
{
  static_assert(sizeof(TChar) < sizeof(int), "StringToValueCharType only supports character types smaller than int");

  int temp{};

  if (elastix::Conversion::StringToValue<int>(str, temp))
  {
    // Check that `temp` can be copied losslessly to `value`.
    if ((temp >= std::numeric_limits<TChar>::lowest()) && (temp <= std::numeric_limits<TChar>::max()))
    {
      value = static_cast<TChar>(temp);
      return true;
    }
  }
  return false;
}


} // namespace

namespace elastix
{

/**
 * ****************** SecondsToDHMS ****************************
 */

std::string
Conversion::SecondsToDHMS(const double totalSeconds, const unsigned int precision)
{
  /** Define days, hours, minutes. */
  const std::size_t secondsPerMinute = 60;
  const std::size_t secondsPerHour = 60 * secondsPerMinute;
  const std::size_t secondsPerDay = 24 * secondsPerHour;

  /** Convert total seconds. */
  auto              iSeconds = static_cast<std::size_t>(totalSeconds);
  const std::size_t days = iSeconds / secondsPerDay;

  iSeconds %= secondsPerDay;
  const std::size_t hours = iSeconds / secondsPerHour;

  iSeconds %= secondsPerHour;
  const std::size_t minutes = iSeconds / secondsPerMinute;

  // iSeconds %= secondsPerMinute;
  // const std::size_t seconds = iSeconds;
  const double dSeconds = fmod(totalSeconds, 60.0);

  /** Create a string in days, hours, minutes and seconds. */
  bool               nonzero = false;
  std::ostringstream make_string;
  if (days != 0)
  {
    make_string << days << "d";
    nonzero = true;
  }
  if (hours != 0 || nonzero)
  {
    make_string << hours << "h";
    nonzero = true;
  }
  if (minutes != 0 || nonzero)
  {
    make_string << minutes << "m";
  }
  make_string << std::showpoint << std::fixed << std::setprecision(precision);
  make_string << dSeconds << "s";

  /** Return a value. */
  return make_string.str();

} // end SecondsToDHMS()


/**
 ******************* ObjectPtrToString ****************************
 */

std::string
Conversion::ObjectPtrToString(itk::Object * const objectPtr)
{
  const void * const voidPtr{ objectPtr };
  std::ostringstream outputStringStream{};
  outputStringStream << voidPtr;
  return outputStringStream.str();
}


/**
 * ****************** ToOptimizerParameters ****************************
 */

itk::OptimizerParameters<double>
Conversion::ToOptimizerParameters(const std::vector<double> & stdVector)
{
  return itk::OptimizerParameters<double>(stdVector.data(), stdVector.size());
};


/**
 * ****************** ToString ****************************
 */

std::string
Conversion::ParameterMapToString(const ParameterMapType & parameterMap, const ParameterMapStringFormat format)
{
  std::string result;

  if (format == ParameterMapStringFormat::Toml)
  {
    const auto parameterValueToTomlValue = [](const std::string & parameterValue) {
      // Use the same representation in TOML as in elastix for booleans and numbers.
      if (parameterValue == BoolToString(false) || parameterValue == BoolToString(true) || IsNumber(parameterValue))
      {
        return parameterValue;
      }
      else
      {
        return '"' + parameterValue + '"';
      }
    };

    for (const auto & parameter : parameterMap)
    {
      result.append(parameter.first).append(" = ");

      const auto & parameterValues = parameter.second;

      if (parameterValues.size() == 1)
      {
        result.append(parameterValueToTomlValue(parameterValues.front()));
      }
      else
      {
        result.push_back('[');

        if (!parameterValues.empty())
        {
          result.append(parameterValueToTomlValue(parameterValues.front()));

          const std::size_t numberOfParameterValues = parameterValues.size();

          for (std::size_t i{ 1 }; i < numberOfParameterValues; ++i)
          {
            result.append(", ").append(parameterValueToTomlValue(parameterValues[i]));
          }
        }
        result.push_back(']');
      }
      result.push_back('\n');
    }
  }
  else
  {
    const auto expectedNumberOfChars = std::accumulate(
      parameterMap.cbegin(),
      parameterMap.cend(),
      std::size_t{},
      [](const std::size_t numberOfChars, const std::pair<std::string, ParameterValuesType> & parameter) {
        return numberOfChars +
               std::accumulate(parameter.second.cbegin(),
                               parameter.second.cend(),
                               // Two parentheses and a linebreak are added for each parameter.
                               parameter.first.size() + 3,
                               [](const std::size_t numberOfCharsPerParameter, const std::string & value) {
                                 // A space character is added for each of the values.
                                 // Plus two double-quotes, if the value is not a number.
                                 return numberOfCharsPerParameter + value.size() +
                                        (Conversion::IsNumber(value) ? 1 : 3);
                               });
      });

    result.reserve(expectedNumberOfChars);

    for (const auto & parameter : parameterMap)
    {
      result.push_back('(');
      result.append(parameter.first);

      for (const auto & value : parameter.second)
      {
        result.push_back(' ');

        if (Conversion::IsNumber(value))
        {
          result.append(value);
        }
        else
        {
          result.push_back('"');
          result.append(value);
          result.push_back('"');
        }
      }
      result.append(")\n");
    }

    // Assert that the correct number of characters was reserved.
    assert(result.size() == expectedNumberOfChars);
  }

  return result;
}


std::string
Conversion::ToString(const double scalar)
{
  return itk::NumberToString<double>{}(scalar);
}


std::string
Conversion::ToString(const float scalar)
{
  return itk::NumberToString<float>{}(scalar);
}


bool
Conversion::IsNumber(const std::string & str)
{
  auto       iter = str.cbegin();
  const auto end = str.cend();

  if (iter == end)
  {
    return false;
  }
  if (*iter == '-')
  {
    // Skip minus sign.
    ++iter;

    if (iter == end)
    {
      return false;
    }
  }

  const auto isDigit = [](const char ch) { return (ch >= '0') && (ch <= '9'); };

  if (!(isDigit(*iter) && isDigit(str.back())))
  {
    // Any number must start and end with a digit.
    return false;
  }
  ++iter;

  const auto numberOfChars = end - iter;
  const auto numberOfDigits = std::count_if(iter, end, isDigit);

  if (numberOfDigits == numberOfChars)
  {
    // Whole (integral) number, e.g.: 1234567890
    return true;
  }

  if ((std::find(iter, end, '.') != end) && (numberOfDigits == (numberOfChars - 1)))
  {
    // Decimal notation, e.g.: 12345.67890
    return true;
  }
  // Scientific notation, e.g.: -1.23e-89 (Note: `iter` has already parsed the optional minus sign and the first digit.
  return std::regex_match(iter, end, std::regex("(\\.\\d+)?e[+-]\\d+"));
}


std::string
Conversion::ToNativePathNameSeparators(const std::string & pathName)
{
  constexpr char separators[] = { '/', '\\' };

  constexpr auto nativateSeparatorIndex =
#ifdef _WIN32
    1;
#else
    0;
#endif

  constexpr char nativeSeparator = separators[nativateSeparatorIndex];
  constexpr char nonNativeSeparator = separators[1 - nativateSeparatorIndex];

  auto result = pathName;
  std::replace(result.begin(), result.end(), nonNativeSeparator, nativeSeparator);
  return result;
}

/**
 * **************** StringToValue ***************
 */

bool
Conversion::StringToValue(const std::string & str, std::string & value)
{
  value = str;
  return true;
} // end StringToValue()


bool
Conversion::StringToValue(const std::string & str, float & value)
{
  return StringToFloatingPointValue(str, value);
}


bool
Conversion::StringToValue(const std::string & str, double & value)
{
  return StringToFloatingPointValue(str, value);
}


bool
Conversion::StringToValue(const std::string & str, char & value)
{
  return StringToCharValue(str, value);
}


bool
Conversion::StringToValue(const std::string & str, signed char & value)
{
  return StringToCharValue(str, value);
}


bool
Conversion::StringToValue(const std::string & str, unsigned char & value)
{
  return StringToCharValue(str, value);
}


bool
Conversion::StringToValue(const std::string & str, bool & value)
{
  if (str == "false")
  {
    value = false;
    return true;
  }
  if (str == "true")
  {
    value = true;
    return true;
  }
  return false;
}


bool
Conversion::StringToValue(const std::string & str, itk::Object *& value)
{
  void *     voidPtr{};
  const bool hasSucceeded = StringToValue<void *>(str, voidPtr);
  value = static_cast<itk::Object *>(voidPtr);
  return hasSucceeded;
}


ParameterMapStringFormat
Conversion::StringToParameterMapStringFormat(const std::string & str)
{
  if (str.empty() || str == "txt")
  {
    return ParameterMapStringFormat::LegacyTxt;
  }
  if (str == "TOML")
  {
    return ParameterMapStringFormat::Toml;
  }
  itkGenericExceptionMacro("Failed to convert to the following string to ParameterMapStringFormat: \"" << str << '"');
}

std::string
Conversion::CreateParameterMapFileNameExtension(const ParameterMapStringFormat format)
{
  switch (format)
  {
    case ParameterMapStringFormat::LegacyTxt:
      return ".txt";
    case ParameterMapStringFormat::Toml:
      return ".toml";
  }
  itkGenericExceptionMacro("Failed to create a file name extension for '" << static_cast<int>(format) << '\'');
}

} // end namespace elastix