File: antsAI.cxx

package info (click to toggle)
ants 2.5.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,672 kB
  • sloc: cpp: 85,685; sh: 15,850; perl: 863; xml: 115; python: 111; makefile: 68
file content (1890 lines) | stat: -rw-r--r-- 71,401 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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
#include "antsAllocImage.h"
#include "antsCommandIterationUpdate.h"
#include "antsCommandLineParser.h"
#include "antsUtilities.h"
#include "ReadWriteData.h"

#include "itkAffineTransform.h"
#include "itkConjugateGradientLineSearchOptimizerv4.h"
#include "itkEuler2DTransform.h"
#include "itkEuler3DTransform.h"
#include "itkCenteredTransformInitializer.h"
#include "itkCorrelationImageToImageMetricv4.h"
#include "itkImageMaskSpatialObject.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToImageMetricv4.h"
#include "itkJointHistogramMutualInformationImageToImageMetricv4.h"
#include "itkLandmarkBasedTransformInitializer.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkMattesMutualInformationImageToImageMetricv4.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkMultiScaleLaplacianBlobDetectorImageFilter.h"
#include "itkMultiStartOptimizerv4.h"
#include "itkRegistrationParameterScalesFromPhysicalShift.h"
#include "itkRigid2DTransform.h"
#include "itkSimilarity2DTransform.h"
#include "itkSimilarity3DTransform.h"
#include "itkTranslationTransform.h"
#include "itkVersorRigid3DTransform.h"
#include "itkTransformFileWriter.h"

#include "vnl/vnl_cross.h"
#include "vnl/vnl_inverse.h"

namespace ants
{

// ##########################################################################
//      Transform traits to generalize the different linear transforms
// ##########################################################################

template <typename TComputeType, unsigned int ImageDimension>
class RigidTransformTraits
{
  // Don't worry about the fact that the default option is the
  // affine Transform, that one will not actually be instantiated.
public:
  using TransformType = itk::AffineTransform<TComputeType, ImageDimension>;
};

template <typename TComputeType, unsigned int ImageDimension>
class LandmarkRigidTransformTraits
{
  // Don't worry about the fact that the default option is the
  // affine Transform, that one will not actually be instantiated.
public:
  using TransformType = itk::AffineTransform<TComputeType, ImageDimension>;
};

template <>
class RigidTransformTraits<double, 2>
{
public:
  using TransformType = itk::Euler2DTransform<double>;
};

template <>
class RigidTransformTraits<float, 2>
{
public:
  using TransformType = itk::Euler2DTransform<float>;
};

template <>
class RigidTransformTraits<double, 3>
{
public:
  // typedef itk::VersorRigid3DTransform<double>    TransformType;
  // typedef itk::QuaternionRigidTransform<double>  TransformType;
  using TransformType = itk::Euler3DTransform<double>;
};

template <>
class RigidTransformTraits<float, 3>
{
public:
  // typedef itk::VersorRigid3DTransform<float>    TransformType;
  // typedef itk::QuaternionRigidTransform<float>  TransformType;
  using TransformType = itk::Euler3DTransform<float>;
};

template <>
class LandmarkRigidTransformTraits<double, 2>
{
public:
  using TransformType = itk::Rigid2DTransform<double>;
};

template <>
class LandmarkRigidTransformTraits<float, 2>
{
public:
  using TransformType = itk::Rigid2DTransform<float>;
};

template <>
class LandmarkRigidTransformTraits<double, 3>
{
public:
  using TransformType = itk::VersorRigid3DTransform<double>;
};

template <>
class LandmarkRigidTransformTraits<float, 3>
{
public:
  using TransformType = itk::VersorRigid3DTransform<float>;
};

template <typename TComputeType, unsigned int ImageDimension>
class SimilarityTransformTraits
{
  // Don't worry about the fact that the default option is the
  // affine Transform, that one will not actually be instantiated.
public:
  using TransformType = itk::AffineTransform<TComputeType, ImageDimension>;
};

template <>
class SimilarityTransformTraits<double, 2>
{
public:
  using TransformType = itk::Similarity2DTransform<double>;
};

template <>
class SimilarityTransformTraits<float, 2>
{
public:
  using TransformType = itk::Similarity2DTransform<float>;
};

template <>
class SimilarityTransformTraits<double, 3>
{
public:
  using TransformType = itk::Similarity3DTransform<double>;
};

template <>
class SimilarityTransformTraits<float, 3>
{
public:
  using TransformType = itk::Similarity3DTransform<float>;
};

// ##########################################################################
// ##########################################################################
template <typename TImage, typename TGradientImage, typename TInterpolator, typename TReal>
TReal
PatchCorrelation(itk::NeighborhoodIterator<TImage> fixedNeighborhood,
                 itk::NeighborhoodIterator<TImage> movingNeighborhood,
                 std::vector<unsigned int>         activeIndex,
                 std::vector<TReal>                weights,
                 typename TGradientImage::Pointer  fixedGradientImage,
                 typename TGradientImage::Pointer  movingGradientImage,
                 typename TInterpolator::Pointer   movingInterpolator)
{
  using RealType = TReal;
  using ImageType = TImage;

  const unsigned int ImageDimension = ImageType::ImageDimension;

  using PointType = typename ImageType::PointType;
  using GradientPixelType = itk::CovariantVector<RealType, ImageDimension>;
  using VectorType = vnl_vector<RealType>;
  using IndexType = typename ImageType::IndexType;

  unsigned int           numberOfIndices = activeIndex.size();
  std::vector<PointType> movingImagePatchPoints;
  VectorType             fixedSamples(numberOfIndices, 0);
  VectorType             movingSamples(numberOfIndices, 0);

  vnl_matrix<RealType> fixedGradientMatrix(numberOfIndices, ImageDimension, 0.0);
  vnl_matrix<RealType> movingGradientMatrix(numberOfIndices, ImageDimension, 0.0);

  PointType movingPointCentroid(0.0);

  RealType weight = itk::NumericTraits<RealType>::OneValue() / static_cast<RealType>(numberOfIndices);
  for (unsigned int i = 0; i < numberOfIndices; i++)
  {
    fixedSamples[i] = fixedNeighborhood.GetPixel(activeIndex[i]);
    movingSamples[i] = movingNeighborhood.GetPixel(activeIndex[i]);

    IndexType fixedIndex = fixedNeighborhood.GetIndex(activeIndex[i]);
    IndexType movingIndex = movingNeighborhood.GetIndex(activeIndex[i]);

    if (fixedGradientImage->GetRequestedRegion().IsInside(fixedIndex) &&
        movingGradientImage->GetRequestedRegion().IsInside(movingIndex))
    {
      GradientPixelType fixedGradient = fixedGradientImage->GetPixel(fixedIndex) * weights[i];
      GradientPixelType movingGradient = movingGradientImage->GetPixel(movingIndex) * weights[i];
      for (unsigned int j = 0; j < ImageDimension; j++)
      {
        fixedGradientMatrix(i, j) = fixedGradient[j];
        movingGradientMatrix(i, j) = movingGradient[j];
      }
      PointType movingPoint(0.0);
      movingGradientImage->TransformIndexToPhysicalPoint(movingIndex, movingPoint);
      for (unsigned int d = 0; d < ImageDimension; d++)
      {
        movingPointCentroid[d] += movingPoint[d] * static_cast<typename PointType::CoordRepType>(weight);
      }
      movingImagePatchPoints.push_back(movingPoint);
    }
    else
    {
      return 0.0;
    }
  }

  fixedSamples -= fixedSamples.mean();
  movingSamples -= movingSamples.mean();

  RealType fixedSd = std::sqrt(fixedSamples.squared_magnitude());

  // compute patch orientation

  vnl_matrix<RealType> fixedCovariance = fixedGradientMatrix.transpose() * fixedGradientMatrix;
  vnl_matrix<RealType> movingCovariance = movingGradientMatrix.transpose() * movingGradientMatrix;

  vnl_symmetric_eigensystem<RealType> fixedImagePrincipalAxes(fixedCovariance);
  vnl_symmetric_eigensystem<RealType> movingImagePrincipalAxes(movingCovariance);

  vnl_vector<RealType> fixedPrimaryEigenVector;
  vnl_vector<RealType> fixedSecondaryEigenVector;
  vnl_vector<RealType> fixedTertiaryEigenVector;
  vnl_vector<RealType> movingPrimaryEigenVector;
  vnl_vector<RealType> movingSecondaryEigenVector;

  vnl_matrix<RealType> B;

  if (ImageDimension == 2)
  {
    fixedPrimaryEigenVector = fixedImagePrincipalAxes.get_eigenvector(1);
    movingPrimaryEigenVector = movingImagePrincipalAxes.get_eigenvector(1);

    B = outer_product(movingPrimaryEigenVector, fixedPrimaryEigenVector);
  }
  else if (ImageDimension == 3)
  {
    fixedPrimaryEigenVector = fixedImagePrincipalAxes.get_eigenvector(2);
    fixedSecondaryEigenVector = fixedImagePrincipalAxes.get_eigenvector(1);

    movingPrimaryEigenVector = movingImagePrincipalAxes.get_eigenvector(2);
    movingSecondaryEigenVector = movingImagePrincipalAxes.get_eigenvector(1);

    B = outer_product(movingPrimaryEigenVector, fixedPrimaryEigenVector) +
        outer_product(movingSecondaryEigenVector, fixedSecondaryEigenVector);
  }

  vnl_svd<RealType>    wahba(B);
  vnl_matrix<RealType> A = wahba.V() * wahba.U().transpose();

  bool patchIsInside = true;
  for (unsigned int i = 0; i < numberOfIndices; i++)
  {
    PointType            movingImagePoint = movingImagePatchPoints[i];
    vnl_vector<RealType> movingImageVector(ImageDimension, 0.0);
    for (unsigned int d = 0; d < ImageDimension; d++)
    {
      movingImagePoint[d] -= movingPointCentroid[d];
      movingImageVector[d] = movingImagePoint[d];
    }

    vnl_vector<RealType> movingImagePointRotated = A * movingImageVector;
    for (unsigned int d = 0; d < ImageDimension; d++)
    {
      movingImagePoint[d] =
        static_cast<typename PointType::CoordRepType>(movingImagePointRotated[d]) + movingPointCentroid[d];
    }
    if (movingInterpolator->IsInsideBuffer(movingImagePoint))
    {
      movingSamples[i] = movingInterpolator->Evaluate(movingImagePoint);
    }
    else
    {
      patchIsInside = false;
      break;
    }
  }

  RealType correlation = 0.0;
  if (patchIsInside)
  {
    movingSamples -= movingSamples.mean();
    RealType movingSd = std::sqrt(movingSamples.squared_magnitude());
    correlation = inner_product(fixedSamples, movingSamples) / (fixedSd * movingSd);

    if (std::isnan(correlation) || std::isinf(correlation))
    {
      correlation = 0.0;
    }
  }

  return correlation;
}

template <typename TImage, typename TBlobFilter>
void
GetBlobCorrespondenceMatrix(typename TImage::Pointer            fixedImage,
                            typename TImage::Pointer            movingImage,
                            typename TBlobFilter::BlobsListType fixedBlobs,
                            typename TBlobFilter::BlobsListType movingBlobs,
                            float                               sigma,
                            unsigned int                        radiusValue,
                            vnl_matrix<float> &                 correspondenceMatrix)
{
  using ImageType = TImage;
  using RealType = float;
  using IndexType = typename ImageType::IndexType;
  using NeighborhoodIteratorType = itk::NeighborhoodIterator<ImageType>;

  const unsigned int ImageDimension = ImageType::ImageDimension;

  using GradientVectorType = itk::CovariantVector<RealType, ImageDimension>;
  using GradientImageType = itk::Image<GradientVectorType, ImageDimension>;
  using GradientImageFilterType = itk::GradientRecursiveGaussianImageFilter<ImageType, GradientImageType>;
  using GradientImageFilterPointer = typename GradientImageFilterType::Pointer;

  typename GradientImageFilterType::Pointer fixedGradientFilter = GradientImageFilterType::New();
  fixedGradientFilter->SetInput(fixedImage);
  fixedGradientFilter->SetSigma(sigma);

  typename GradientImageType::Pointer fixedGradientImage = fixedGradientFilter->GetOutput();
  fixedGradientImage->Update();
  fixedGradientImage->DisconnectPipeline();

  GradientImageFilterPointer movingGradientFilter = GradientImageFilterType::New();
  movingGradientFilter->SetInput(movingImage);
  movingGradientFilter->SetSigma(sigma);

  typename GradientImageType::Pointer movingGradientImage = movingGradientFilter->GetOutput();
  movingGradientImage->Update();
  movingGradientImage->DisconnectPipeline();

  correspondenceMatrix.set_size(fixedBlobs.size(), movingBlobs.size());
  correspondenceMatrix.fill(0);

  typename NeighborhoodIteratorType::RadiusType radius;
  radius.Fill(radiusValue);

  NeighborhoodIteratorType ItF(radius, fixedImage, fixedImage->GetLargestPossibleRegion());
  NeighborhoodIteratorType ItM(radius, movingImage, movingImage->GetLargestPossibleRegion());

  IndexType zeroIndex;
  zeroIndex.Fill(radiusValue);
  ItF.SetLocation(zeroIndex);

  std::vector<unsigned int> activeIndex;
  std::vector<RealType>     weights;
  RealType                  weightSum = 0.0;
  for (unsigned int i = 0; i < ItF.Size(); i++)
  {
    IndexType index = ItF.GetIndex(i);
    RealType  distance = 0.0;
    for (unsigned int j = 0; j < ImageDimension; j++)
    {
      distance += itk::Math::sqr(index[j] - zeroIndex[j]);
    }
    distance = std::sqrt(distance);
    if (distance <= radiusValue)
    {
      activeIndex.push_back(i);
      RealType weight = std::exp(-distance / itk::Math::sqr(radiusValue));
      weights.push_back(weight);
      weightSum += (weight);
    }
  }
  for (float & weight : weights)
  {
    weight /= weightSum;
  }

  using ScalarInterpolatorType = itk::LinearInterpolateImageFunction<ImageType, RealType>;
  typename ScalarInterpolatorType::Pointer movingInterpolator = ScalarInterpolatorType::New();
  movingInterpolator->SetInputImage(movingImage);

  for (unsigned int i = 0; i < fixedBlobs.size(); i++)
  {
    IndexType fixedIndex = fixedBlobs[i]->GetCenter();
    if (fixedImage->GetPixel(fixedIndex) > static_cast<typename ImageType::PixelType>(1.0e-4))
    {
      ItF.SetLocation(fixedIndex);
      for (unsigned int j = 0; j < movingBlobs.size(); j++)
      {
        IndexType movingIndex = movingBlobs[j]->GetCenter();
        if (movingImage->GetPixel(movingIndex) > static_cast<typename ImageType::PixelType>(1.0e-4))
        {
          ItM.SetLocation(movingIndex);

          RealType correlation = PatchCorrelation<ImageType, GradientImageType, ScalarInterpolatorType, RealType>(
            ItF, ItM, activeIndex, weights, fixedGradientImage, movingGradientImage, movingInterpolator);

          if (correlation < itk::NumericTraits<RealType>::ZeroValue())
          {
            correlation = itk::NumericTraits<RealType>::ZeroValue();
          }

          correspondenceMatrix(i, j) = correlation;
        }
      }
    }
  }
}

template <typename TImage, typename TTransform>
typename TTransform::Pointer
GetTransformFromFeatureMatching(typename TImage::Pointer fixedImage,
                                typename TImage::Pointer movingImage,
                                unsigned int             numberOfBlobsToExtract,
                                unsigned int             numberOfBlobsToMatch)
{
  using RealType = float;
  using ImageType = TImage;
  using TransformType = TTransform;
  using PointType = typename ImageType::PointType;

  /////////////////////////////////////////////////////////////////
  //
  //         Values taken from Brian in ImageMath.cxx
  //
  /////////////////////////////////////////////////////////////////

  unsigned int radiusValue = 20;
  RealType     gradientSigma = 1.0;
  RealType     maxRadiusDifferenceAllowed = 0.25;
  RealType     distancePreservationThreshold = 0.1;
  RealType     minimumNumberOfNeighborhoodNodes = 3;

  RealType     minScale = std::pow(1.0, 1.0);
  RealType     maxScale = std::pow(2.0, 10.0);
  unsigned int stepsPerOctave = 10;

  ///////////////////////////////////////////////////////////////

  using BlobFilterType = itk::MultiScaleLaplacianBlobDetectorImageFilter<ImageType>;
  using BlobPointer = typename BlobFilterType::BlobPointer;
  using BlobPairType = std::pair<BlobPointer, BlobPointer>;
  using BlobsListType = typename BlobFilterType::BlobsListType;

  typename BlobFilterType::Pointer blobFixedImageFilter = BlobFilterType::New();
  blobFixedImageFilter->SetStartT(minScale);
  blobFixedImageFilter->SetEndT(maxScale);
  blobFixedImageFilter->SetStepsPerOctave(stepsPerOctave);
  blobFixedImageFilter->SetNumberOfBlobs(numberOfBlobsToExtract);
  blobFixedImageFilter->SetInput(fixedImage);
  blobFixedImageFilter->Update();

  BlobsListType fixedImageBlobs = blobFixedImageFilter->GetBlobs();

  typename BlobFilterType::Pointer blobMovingImageFilter = BlobFilterType::New();
  blobMovingImageFilter->SetStartT(minScale);
  blobMovingImageFilter->SetEndT(maxScale);
  blobMovingImageFilter->SetStepsPerOctave(stepsPerOctave);
  blobMovingImageFilter->SetNumberOfBlobs(numberOfBlobsToExtract);
  blobMovingImageFilter->SetInput(movingImage);
  blobMovingImageFilter->Update();

  BlobsListType movingImageBlobs = blobMovingImageFilter->GetBlobs();

  if (movingImageBlobs.empty() || fixedImageBlobs.empty())
  {
    std::cerr << "The moving image or fixed image blobs list is empty." << std::endl;
    return nullptr;
  }

  vnl_matrix<RealType> correspondenceMatrix;

  /////////////////////////////////////////////////////////////////
  //
  //         Get the correspondence matrix based on local image patches
  //
  /////////////////////////////////////////////////////////////////

  GetBlobCorrespondenceMatrix<ImageType, BlobFilterType>(
    fixedImage, movingImage, fixedImageBlobs, movingImageBlobs, gradientSigma, radiusValue, correspondenceMatrix);

  /////////////////////////////////////////////////////////////////
  //
  //         Pick the first numberOfBlobsToMatch pairs based on the correlation matrix
  //
  /////////////////////////////////////////////////////////////////

  std::vector<BlobPairType> blobPairs;

  BlobPointer bestBlob = nullptr;

  unsigned int matchPoint = 1;
  unsigned int fixedCount = 0;
  while ((matchPoint <= numberOfBlobsToMatch) && (fixedCount < fixedImageBlobs.size()))
  {
    unsigned int maxPair = correspondenceMatrix.arg_max();
    auto         maxRow = static_cast<unsigned int>(maxPair / correspondenceMatrix.cols());
    unsigned int maxCol = maxPair - maxRow * correspondenceMatrix.cols();
    BlobPointer  fixedBlob = fixedImageBlobs[maxRow];
    bestBlob = movingImageBlobs[maxCol];

    if (bestBlob && bestBlob->GetObjectRadius() > 1)
    {
      if (static_cast<RealType>(std::fabs(bestBlob->GetObjectRadius() - fixedBlob->GetObjectRadius())) <
          maxRadiusDifferenceAllowed)
      {
        if (fixedImage->GetPixel(fixedBlob->GetCenter()) > static_cast<typename ImageType::PixelType>(1.0e-4) &&
            movingImage->GetPixel(bestBlob->GetCenter()) > static_cast<typename ImageType::PixelType>(1.0e-4))
        {
          BlobPairType blobPairing = std::make_pair(fixedBlob, bestBlob);
          blobPairs.push_back(blobPairing);
          matchPoint++;
        }
      }
    }
    correspondenceMatrix.set_row(maxRow, correspondenceMatrix.get_row(0).fill(0));
    correspondenceMatrix.set_column(maxCol, correspondenceMatrix.get_column(0).fill(0));
    fixedCount++;
  }

  /////////////////////////////////////////////////////////////////
  //
  //         For every blob pair compute the relative distance from its
  //         neighbors in both the fixed and moving images.
  //
  /////////////////////////////////////////////////////////////////

  vnl_matrix<RealType> distanceRatios(blobPairs.size(), blobPairs.size(), 0.0);
  for (unsigned int i = 0; i < blobPairs.size(); i++)
  {
    PointType fixedPoint(0.0);
    fixedImage->TransformIndexToPhysicalPoint(blobPairs[i].first->GetCenter(), fixedPoint);

    PointType movingPoint(0.0);
    movingImage->TransformIndexToPhysicalPoint(blobPairs[i].second->GetCenter(), movingPoint);

    for (unsigned int j = 0; j < blobPairs.size(); j++)
    {
      PointType fixedNeighborPoint(0.0);
      fixedImage->TransformIndexToPhysicalPoint(blobPairs[j].first->GetCenter(), fixedNeighborPoint);

      PointType movingNeighborPoint(0.0);
      movingImage->TransformIndexToPhysicalPoint(blobPairs[j].second->GetCenter(), movingNeighborPoint);

      distanceRatios(i, j) = distanceRatios(j, i) = fixedNeighborPoint.SquaredEuclideanDistanceTo(movingNeighborPoint) /
                                                    fixedPoint.SquaredEuclideanDistanceTo(movingPoint);
    }
  }

  /////////////////////////////////////////////////////////////////
  //
  //         Keep those blob pairs which have close to the same
  //         distance in both the fixed and moving images.
  //
  /////////////////////////////////////////////////////////////////

  typename TransformType::Pointer transform = TransformType::New();

  using TransformInitializerType = itk::LandmarkBasedTransformInitializer<TransformType, ImageType, ImageType>;

  using PointsContainerType = typename TransformInitializerType::LandmarkPointContainer;
  PointsContainerType fixedLandmarks;
  PointsContainerType movingLandmarks;

  for (unsigned int i = 0; i < blobPairs.size(); i++)
  {
    unsigned int neighborhoodCount = 0;
    for (unsigned int j = 0; j < blobPairs.size(); j++)
    {
      if ((j != i) &&
          (std::fabs(distanceRatios(i, j) - itk::NumericTraits<RealType>::OneValue()) < distancePreservationThreshold))
      {
        neighborhoodCount++;
      }
    }
    if (neighborhoodCount >= minimumNumberOfNeighborhoodNodes)
    {
      PointType fixedPoint(0.0);
      fixedImage->TransformIndexToPhysicalPoint(blobPairs[i].first->GetCenter(), fixedPoint);
      fixedLandmarks.push_back(fixedPoint);

      PointType movingPoint(0.0);
      movingImage->TransformIndexToPhysicalPoint(blobPairs[i].second->GetCenter(), movingPoint);
      movingLandmarks.push_back(movingPoint);
    }
  }

  /////////////////////////////////////////////////////////////////
  //
  //         Compute initial transform from the landmarks
  //
  /////////////////////////////////////////////////////////////////

  typename TransformInitializerType::Pointer transformInitializer = TransformInitializerType::New();
  transformInitializer->SetFixedLandmarks(fixedLandmarks);
  transformInitializer->SetMovingLandmarks(movingLandmarks);

  transformInitializer->SetTransform(transform);
  transformInitializer->InitializeTransform();

  return transform;
}

template <unsigned int ImageDimension>
int
antsAI(itk::ants::CommandLineParser * parser)
{
  using RealType = double;
  using PixelType = float;
  using FloatType = float;

  using VectorType = itk::Vector<FloatType, ImageDimension>;
  using ImageType = itk::Image<PixelType, ImageDimension>;

  using AffineTransformType = itk::AffineTransform<RealType, ImageDimension>;
  using RigidTransformType = typename RigidTransformTraits<RealType, ImageDimension>::TransformType;
  using SimilarityTransformType = typename SimilarityTransformTraits<RealType, ImageDimension>::TransformType;
  using LandmarkRigidTransformType = typename LandmarkRigidTransformTraits<RealType, ImageDimension>::TransformType;

  enum SamplingStrategyType
  {
    NONE,
    REGULAR,
    RANDOM
  };

  bool                                              verbose = false;
  itk::ants::CommandLineParser::OptionType::Pointer verboseOption = parser->GetOption("verbose");
  if (verboseOption && verboseOption->GetNumberOfFunctions())
  {
    verbose = parser->Convert<bool>(verboseOption->GetFunction(0)->GetName());
  }

  /////////////////////////////////////////////////////////////////
  //
  //         Read in the metric type and fixed/moving images
  //
  /////////////////////////////////////////////////////////////////

  typename ImageType::Pointer fixedImage;
  typename ImageType::Pointer movingImage;

  std::string          metric;
  unsigned int         numberOfBins = 32;
  SamplingStrategyType samplingStrategy = NONE;
  RealType             samplingPercentage = 1.0;

  itk::ants::CommandLineParser::OptionType::Pointer metricOption = parser->GetOption("metric");
  if (metricOption && metricOption->GetNumberOfFunctions())
  {
    metric = metricOption->GetFunction(0)->GetName();
    ConvertToLowerCase(metric);
    if (metricOption->GetFunction(0)->GetNumberOfParameters() < 2)
    {
      if (verbose)
      {
        std::cerr << "Fixed and/or moving images not specified." << std::endl;
      }
      return EXIT_FAILURE;
    }
    ReadImage<ImageType>(fixedImage, (metricOption->GetFunction(0)->GetParameter(0)).c_str());
    ReadImage<ImageType>(movingImage, (metricOption->GetFunction(0)->GetParameter(1)).c_str());

    if (metricOption->GetFunction(0)->GetNumberOfParameters() > 2)
    {
      numberOfBins = parser->Convert<unsigned int>(metricOption->GetFunction(0)->GetParameter(2));
    }
    if (metricOption->GetFunction(0)->GetNumberOfParameters() > 3)
    {
      std::string samplingStrategyString = metricOption->GetFunction(0)->GetParameter(3);
      ConvertToLowerCase(samplingStrategyString);
      if (std::strcmp(samplingStrategyString.c_str(), "none") == 0)
      {
        samplingStrategy = NONE;
      }
      else if (std::strcmp(samplingStrategyString.c_str(), "regular") == 0)
      {
        samplingStrategy = REGULAR;
      }
      else if (std::strcmp(samplingStrategyString.c_str(), "random") == 0)
      {
        samplingStrategy = RANDOM;
      }
      else
      {
        if (verbose)
        {
          std::cerr << "Unrecognized sampling strategy." << std::endl;
        }
        return EXIT_FAILURE;
      }
    }
    if (metricOption->GetFunction(0)->GetNumberOfParameters() > 4)
    {
      samplingPercentage = parser->Convert<RealType>(metricOption->GetFunction(0)->GetParameter(4));
    }
  }
  else
  {
    std::cerr << "Input metric not specified." << std::endl;
    return EXIT_FAILURE;
  }

  /////////////////////////////////////////////////////////////////
  //
  //         Read in convergence options
  //
  /////////////////////////////////////////////////////////////////

  unsigned int numberOfIterations = 0;
  unsigned int convergenceWindowSize = 5;
  RealType     convergenceThreshold = 1e-6;

  itk::ants::CommandLineParser::OptionType::Pointer convergenceOption = parser->GetOption("convergence");
  if (convergenceOption && convergenceOption->GetNumberOfFunctions())
  {
    if (convergenceOption->GetFunction(0)->GetNumberOfParameters() == 0)
    {
      numberOfIterations = parser->Convert<unsigned int>(convergenceOption->GetFunction(0)->GetName());
    }
    else
    {
      numberOfIterations = parser->Convert<unsigned int>(convergenceOption->GetFunction(0)->GetParameter(0));
      if (convergenceOption->GetFunction(0)->GetNumberOfParameters() > 1)
      {
        convergenceThreshold = parser->Convert<RealType>(convergenceOption->GetFunction(0)->GetParameter(1));
      }
      if (convergenceOption->GetFunction(0)->GetNumberOfParameters() > 2)
      {
        convergenceWindowSize = parser->Convert<unsigned int>(convergenceOption->GetFunction(0)->GetParameter(2));
      }
    }
  }


  /////////////////////////////////////////////////////////////////
  //
  //         Get the transform
  //
  /////////////////////////////////////////////////////////////////

  std::string transform = "";
  // std::string outputTransformTypeName = "";
  RealType learningRate = 0.1;
  RealType searchFactor = 20.0 * itk::Math::pi / 180.0;
  RealType arcFraction = 1.0;

  itk::ants::CommandLineParser::OptionType::Pointer searchFactorOption = parser->GetOption("search-factor");
  if (searchFactorOption && searchFactorOption->GetNumberOfFunctions())
  {
    if (searchFactorOption->GetFunction(0)->GetNumberOfParameters() == 0)
    {
      searchFactor = parser->Convert<RealType>(searchFactorOption->GetFunction(0)->GetName()) * itk::Math::pi / 180.0;
    }
    if (searchFactorOption->GetFunction(0)->GetNumberOfParameters() > 0)
    {
      searchFactor =
        parser->Convert<RealType>(searchFactorOption->GetFunction(0)->GetParameter(0)) * itk::Math::pi / 180.0;
    }
    if (searchFactorOption->GetFunction(0)->GetNumberOfParameters() > 1)
    {
      arcFraction = parser->Convert<RealType>(searchFactorOption->GetFunction(0)->GetParameter(1));
    }
  }

  std::vector<RealType> translationSearchGrid;

  RealType translationSearchStepSize = 25.0;

  for (unsigned int i = 0; i < ImageDimension; i++)
  {
    translationSearchGrid.push_back(0.0);
  }

  itk::ants::CommandLineParser::OptionType::Pointer translationSearchGridOption =
    parser->GetOption("translation-search-grid");
  if (translationSearchGridOption && translationSearchGridOption->GetNumberOfFunctions())
  {

    translationSearchStepSize = parser->Convert<RealType>(translationSearchGridOption->GetFunction(0)->GetParameter(0));

    if (translationSearchGridOption->GetFunction(0)->GetNumberOfParameters() > 1)
    {
      translationSearchGrid =
        parser->ConvertVector<RealType>(translationSearchGridOption->GetFunction(0)->GetParameter(1));
    }
  }

  itk::ants::CommandLineParser::OptionType::Pointer transformOption = parser->GetOption("transform");
  if (transformOption && transformOption->GetNumberOfFunctions())
  {
    transform = transformOption->GetFunction(0)->GetName();
    ConvertToLowerCase(transform);
    if (transformOption->GetFunction(0)->GetNumberOfParameters() > 0)
    {
      learningRate = parser->Convert<RealType>(transformOption->GetFunction(0)->GetParameter(0));
    }
  }

  typename AffineTransformType::Pointer     affineSearchTransform = AffineTransformType::New();
  typename RigidTransformType::Pointer      rigidSearchTransform = RigidTransformType::New();
  typename SimilarityTransformType::Pointer similaritySearchTransform = SimilarityTransformType::New();

  typename AffineTransformType::Pointer initialTransform = AffineTransformType::New();
  initialTransform->SetIdentity();

  bool initialTransformInitializedWithImages = false;

  unsigned int numberOfTransformParameters = 0;
  if (strcmp(transform.c_str(), "affine") == 0)
  {
    numberOfTransformParameters = AffineTransformType::ParametersDimension;
    // outputTransformTypeName = std::string( "Affine" );
  }
  else if (strcmp(transform.c_str(), "rigid") == 0)
  {
    numberOfTransformParameters = RigidTransformType::ParametersDimension;
    // outputTransformTypeName = std::string( "Rigid" );
  }
  else if (strcmp(transform.c_str(), "similarity") == 0)
  {
    numberOfTransformParameters = SimilarityTransformType::ParametersDimension;
    // outputTransformTypeName = std::string( "Similarity" );
  }
  else if (strcmp(transform.c_str(), "aligngeometriccenters") == 0 ||
           strcmp(transform.c_str(), "aligncentersofmass") == 0)
  {
    using TransformInitializerType = itk::CenteredTransformInitializer<AffineTransformType, ImageType, ImageType>;
    typename TransformInitializerType::Pointer initializer = TransformInitializerType::New();

    initializer->SetTransform(initialTransform);

    initializer->SetFixedImage(fixedImage);
    initializer->SetMovingImage(movingImage);

    if (strcmp(transform.c_str(), "aligngeometriccenters") == 0)
    {
      initializer->GeometryOn();
    }
    else // strcmp( transform.c_str(), "aligncentersofmass" ) == 0
    {
      initializer->MomentsOn();
    }
    initializer->InitializeTransform();

    initialTransformInitializedWithImages = true;

    // outputTransformTypeName = std::string( "Translation" );
  }
  else
  {
    if (verbose)
    {
      std::cerr << "Unrecognized transform option." << std::endl;
    }
    return EXIT_FAILURE;
  }

  /////////////////////////////////////////////////////////////////
  //
  //         Align the images using center of mass and principal axes
  //         or feature blobs if the initial transform hasn't already
  //         been initialized.
  //
  /////////////////////////////////////////////////////////////////

  itk::Vector<RealType, ImageDimension> axis1(0.0);
  itk::Vector<RealType, ImageDimension> axis2(0.0);
  axis1[0] = 1.0;
  axis2[1] = 1.0;

  RealType bestScale = 1.0;

  if (initialTransformInitializedWithImages == false)
  {
    constexpr unsigned int minimumNumberOfBlobs = 3; // should a different min number of blobs be expected?

    unsigned int                                      numberOfBlobsToExtract = 0;
    unsigned int                                      numberOfBlobsToMatch = 0;
    itk::ants::CommandLineParser::OptionType::Pointer blobsOption = parser->GetOption("align-blobs");
    if (blobsOption && blobsOption->GetNumberOfFunctions())
    {
      if (blobsOption->GetFunction(0)->GetNumberOfParameters() == 0)
      {
        numberOfBlobsToExtract = parser->Convert<unsigned int>(blobsOption->GetFunction(0)->GetName());
        numberOfBlobsToMatch = numberOfBlobsToExtract;
      }
      if (blobsOption->GetFunction(0)->GetNumberOfParameters() > 0)
      {
        numberOfBlobsToExtract = parser->Convert<unsigned int>(blobsOption->GetFunction(0)->GetParameter(0));
        numberOfBlobsToMatch = numberOfBlobsToExtract;
      }
      if (blobsOption->GetFunction(0)->GetNumberOfParameters() > 1)
      {
        numberOfBlobsToMatch = parser->Convert<unsigned int>(blobsOption->GetFunction(0)->GetParameter(1));
      }
      if (numberOfBlobsToExtract < minimumNumberOfBlobs)
      {
        std::cerr << "Please specify a greater number of blobs (>=" << minimumNumberOfBlobs << ")." << std::endl;
        return EXIT_FAILURE;
      }
    }

    if (numberOfBlobsToExtract >= minimumNumberOfBlobs)
    {
      if (strcmp(transform.c_str(), "affine") == 0)
      {
        typename AffineTransformType::Pointer initialAffineTransform =
          GetTransformFromFeatureMatching<ImageType, AffineTransformType>(
            fixedImage, movingImage, numberOfBlobsToExtract, numberOfBlobsToMatch);

        initialTransform->SetOffset(initialAffineTransform->GetOffset());
        initialTransform->SetMatrix(initialAffineTransform->GetMatrix());
      }
      else // RigidTransform or SimilarityTransform
      {

        typename LandmarkRigidTransformType::Pointer initialRigidTransform =
          GetTransformFromFeatureMatching<ImageType, LandmarkRigidTransformType>(
            fixedImage, movingImage, numberOfBlobsToExtract, numberOfBlobsToMatch);

        initialTransform->SetOffset(initialRigidTransform->GetOffset());
        initialTransform->SetMatrix(initialRigidTransform->GetMatrix());
      }
    }
    else
    {
      bool doAlignPrincipalAxes = false;

      itk::ants::CommandLineParser::OptionType::Pointer axesOption = parser->GetOption("align-principal-axes");
      if (axesOption && axesOption->GetNumberOfFunctions())
      {
        doAlignPrincipalAxes = parser->Convert<bool>(axesOption->GetFunction(0)->GetName());
      }

      using ImageMomentsCalculatorType = typename itk::ImageMomentsCalculator<ImageType>;
      using MatrixType = typename ImageMomentsCalculatorType::MatrixType;

      typename ImageMomentsCalculatorType::Pointer fixedImageMomentsCalculator = ImageMomentsCalculatorType::New();
      typename ImageMomentsCalculatorType::Pointer movingImageMomentsCalculator = ImageMomentsCalculatorType::New();

      fixedImageMomentsCalculator->SetImage(fixedImage);
      fixedImageMomentsCalculator->Compute();
      VectorType fixedImageCenterOfGravity = fixedImageMomentsCalculator->GetCenterOfGravity();
      MatrixType fixedImagePrincipalAxes = fixedImageMomentsCalculator->GetPrincipalAxes();

      movingImageMomentsCalculator->SetImage(movingImage);
      movingImageMomentsCalculator->Compute();
      VectorType movingImageCenterOfGravity = movingImageMomentsCalculator->GetCenterOfGravity();
      MatrixType movingImagePrincipalAxes = movingImageMomentsCalculator->GetPrincipalAxes();

      // RealType bestScale = 1.0; // movingImageMomentsCalculator->GetTotalMass() /
      // fixedImageMomentsCalculator->GetTotalMass();

      typename AffineTransformType::OutputVectorType translation;
      itk::Point<RealType, ImageDimension>           center;
      for (unsigned int i = 0; i < ImageDimension; i++)
      {
        translation[i] = movingImageCenterOfGravity[i] - fixedImageCenterOfGravity[i];
        center[i] = fixedImageCenterOfGravity[i];
      }
      initialTransform->SetTranslation(translation);

      /** Solve Wahba's problem --- http://en.wikipedia.org/wiki/Wahba%27s_problem */

      vnl_vector<RealType> fixedPrimaryEigenVector;
      vnl_vector<RealType> fixedSecondaryEigenVector;
      vnl_vector<RealType> fixedTertiaryEigenVector;
      vnl_vector<RealType> movingPrimaryEigenVector;
      vnl_vector<RealType> movingSecondaryEigenVector;

      vnl_matrix<RealType> B;

      if (ImageDimension == 2)
      {
        fixedPrimaryEigenVector = fixedImagePrincipalAxes.GetVnlMatrix().get_row(1).as_ref();
        movingPrimaryEigenVector = movingImagePrincipalAxes.GetVnlMatrix().get_row(1).as_ref();

        B = outer_product(movingPrimaryEigenVector, fixedPrimaryEigenVector);
      }
      else if (ImageDimension == 3)
      {
        fixedPrimaryEigenVector = fixedImagePrincipalAxes.GetVnlMatrix().get_row(2).as_ref();
        fixedSecondaryEigenVector = fixedImagePrincipalAxes.GetVnlMatrix().get_row(1).as_ref();

        movingPrimaryEigenVector = movingImagePrincipalAxes.GetVnlMatrix().get_row(2).as_ref();
        movingSecondaryEigenVector = movingImagePrincipalAxes.GetVnlMatrix().get_row(1).as_ref();

        B = outer_product(movingPrimaryEigenVector, fixedPrimaryEigenVector) +
            outer_product(movingSecondaryEigenVector, fixedSecondaryEigenVector);
      }

      if (doAlignPrincipalAxes)
      {
        vnl_svd<RealType>    wahba(B);
        vnl_matrix<RealType> A = wahba.V() * wahba.U().transpose();
        A = vnl_inverse(A);
        RealType det = vnl_determinant(A);

        if (det < 0.0)
        {
          if (verbose)
          {
            std::cout << "Bad determinant = " << det << std::endl;
            std::cout << "  det( V ) = " << vnl_determinant(wahba.V()) << std::endl;
            std::cout << "  det( U ) = " << vnl_determinant(wahba.U()) << std::endl;
          }
          vnl_matrix<RealType> I(A);
          I.set_identity();
          for (unsigned int i = 0; i < ImageDimension; i++)
          {
            if (A(i, i) < 0.0)
            {
              I(i, i) = -1.0;
            }
          }
          A = A * I.transpose();
          det = vnl_determinant(A);

          if (verbose)
          {
            std::cout << "New determinant = " << det << std::endl;
          }
        }
        initialTransform->SetMatrix(typename AffineTransformType::MatrixType(A));
      }
      initialTransform->SetCenter(center);

      if (ImageDimension == 2)
      {
        fixedTertiaryEigenVector = fixedSecondaryEigenVector;
        fixedSecondaryEigenVector = fixedPrimaryEigenVector;
      }
      if (ImageDimension == 3)
      {
        fixedTertiaryEigenVector = vnl_cross_3d(fixedPrimaryEigenVector, fixedSecondaryEigenVector);
      }

      for (unsigned int d = 0; d < ImageDimension; d++)
      {
        axis1[d] = fixedTertiaryEigenVector[d];
        axis2[d] = fixedSecondaryEigenVector[d];
      }
    }
  }
  /////////////////////////////////////////////////////////////////
  //
  //         Write the output if the number of iterations == 0
  //
  /////////////////////////////////////////////////////////////////

  if (numberOfIterations == 0)
  {
    itk::ants::CommandLineParser::OptionType::Pointer outputOption = parser->GetOption("output");
    if (outputOption && outputOption->GetNumberOfFunctions())
    {
      std::string outputName = std::string("");
      if (outputOption->GetFunction(0)->GetNumberOfParameters() == 0)
      {
        outputName = outputOption->GetFunction(0)->GetName();
      }
      else
      {
        outputName = outputOption->GetFunction(0)->GetParameter(0);
      }
      using TransformWriterType = itk::TransformFileWriter;
      typename TransformWriterType::Pointer transformWriter = TransformWriterType::New();

      if (strcmp(transform.c_str(), "affine") == 0)
      {
        typename AffineTransformType::Pointer bestAffineTransform = AffineTransformType::New();
        bestAffineTransform->SetCenter(initialTransform->GetCenter());
        bestAffineTransform->SetMatrix(initialTransform->GetMatrix());
        bestAffineTransform->SetOffset(initialTransform->GetOffset());
        transformWriter->SetInput(bestAffineTransform);
      }
      else if (strcmp(transform.c_str(), "rigid") == 0)
      {
        typename RigidTransformType::Pointer bestRigidTransform = RigidTransformType::New();
        bestRigidTransform->SetCenter(initialTransform->GetCenter());
        bestRigidTransform->SetMatrix(initialTransform->GetMatrix());
        bestRigidTransform->SetOffset(initialTransform->GetOffset());
        transformWriter->SetInput(bestRigidTransform);
      }
      else if (strcmp(transform.c_str(), "similarity") == 0)
      {
        typename SimilarityTransformType::Pointer bestSimilarityTransform = SimilarityTransformType::New();
        bestSimilarityTransform->SetCenter(initialTransform->GetCenter());
        bestSimilarityTransform->SetMatrix(initialTransform->GetMatrix());
        bestSimilarityTransform->SetOffset(initialTransform->GetOffset());
        transformWriter->SetInput(bestSimilarityTransform);
      }
      else if (initialTransformInitializedWithImages == true)
      {
        using TranslationTransformType = itk::TranslationTransform<RealType, ImageDimension>;
        typename TranslationTransformType::Pointer bestTranslationTransform = TranslationTransformType::New();
        bestTranslationTransform->SetOffset(initialTransform->GetOffset());
        transformWriter->SetInput(bestTranslationTransform);
      }

      transformWriter->SetFileName(outputName.c_str());
#if ITK_VERSION_MAJOR >= 5
      transformWriter->SetUseCompression(true);
#endif
      transformWriter->Update();
    }

    return EXIT_SUCCESS;
  }

  /////////////////////////////////////////////////////////////////
  //
  //         Read in the masks
  //
  /////////////////////////////////////////////////////////////////

  using ImageMaskSpatialObjectType = itk::ImageMaskSpatialObject<ImageDimension>;
  using MaskImageType = typename ImageMaskSpatialObjectType::ImageType;

  typename MaskImageType::Pointer fixedMask = nullptr;
  typename MaskImageType::Pointer movingMask = nullptr;

  itk::ants::CommandLineParser::OptionType::Pointer maskOption = parser->GetOption("masks");
  if (maskOption && maskOption->GetNumberOfFunctions())
  {
    if (maskOption->GetFunction(0)->GetNumberOfParameters() == 0)
    {
      ReadImage<MaskImageType>(fixedMask, (maskOption->GetFunction(0)->GetName()).c_str());
    }
    else if (maskOption->GetFunction(0)->GetNumberOfParameters() == 1)
    {
      ReadImage<MaskImageType>(fixedMask, (maskOption->GetFunction(0)->GetParameter(0)).c_str());
    }
    else if (maskOption->GetFunction(0)->GetNumberOfParameters() == 2)
    {
      ReadImage<MaskImageType>(fixedMask, (maskOption->GetFunction(0)->GetParameter(0)).c_str());
      ReadImage<MaskImageType>(movingMask, (maskOption->GetFunction(0)->GetParameter(1)).c_str());
    }
  }

  typename ImageMaskSpatialObjectType::Pointer fixedMaskSpatialObject = nullptr;
  if (fixedMask.IsNotNull())
  {
    fixedMaskSpatialObject = ImageMaskSpatialObjectType::New();
    fixedMaskSpatialObject->SetImage(const_cast<MaskImageType *>(fixedMask.GetPointer()));
  }

  typename ImageMaskSpatialObjectType::Pointer movingMaskSpatialObject = nullptr;
  if (movingMask.IsNotNull())
  {
    movingMaskSpatialObject = ImageMaskSpatialObjectType::New();
    movingMaskSpatialObject->SetImage(const_cast<MaskImageType *>(movingMask.GetPointer()));
  }

  /////////////////////////////////////////////////////////////////
  //
  //         Set up the image metric
  //
  /////////////////////////////////////////////////////////////////

  using ImageMetricType = itk::ImageToImageMetricv4<ImageType, ImageType, ImageType, RealType>;
  typename ImageMetricType::Pointer imageMetric = nullptr;

  if (std::strcmp(metric.c_str(), "mattes") == 0)
  {
    if (verbose)
    {
      std::cout << "Using the Mattes MI metric (number of bins = " << numberOfBins << ")" << std::endl;
    }
    using MutualInformationMetricType =
      itk::MattesMutualInformationImageToImageMetricv4<ImageType, ImageType, ImageType, RealType>;
    typename MutualInformationMetricType::Pointer mutualInformationMetric = MutualInformationMetricType::New();
    // mutualInformationMetric = mutualInformationMetric;
    mutualInformationMetric->SetNumberOfHistogramBins(numberOfBins);
    mutualInformationMetric->SetUseMovingImageGradientFilter(true);
    mutualInformationMetric->SetUseFixedImageGradientFilter(true);

    imageMetric = mutualInformationMetric;
  }
  else if (std::strcmp(metric.c_str(), "mi") == 0)
  {
    if (verbose)
    {
      std::cout << "Using the joint histogram MI metric (number of bins = " << numberOfBins << ")" << std::endl;
    }
    using MutualInformationMetricType =
      itk::JointHistogramMutualInformationImageToImageMetricv4<ImageType, ImageType, ImageType, RealType>;
    typename MutualInformationMetricType::Pointer mutualInformationMetric = MutualInformationMetricType::New();
    // mutualInformationMetric = mutualInformationMetric;
    mutualInformationMetric->SetNumberOfHistogramBins(numberOfBins);
    mutualInformationMetric->SetUseMovingImageGradientFilter(true);
    mutualInformationMetric->SetUseFixedImageGradientFilter(true);
    mutualInformationMetric->SetVarianceForJointPDFSmoothing(1.0);

    imageMetric = mutualInformationMetric;
  }
  else if (std::strcmp(metric.c_str(), "gc") == 0)
  {
    if (verbose)
    {
      std::cout << "Using the global correlation metric " << std::endl;
    }
    using corrMetricType = itk::CorrelationImageToImageMetricv4<ImageType, ImageType, ImageType, RealType>;
    typename corrMetricType::Pointer corrMetric = corrMetricType::New();

    imageMetric = corrMetric;
  }
  else
  {
    if (verbose)
    {
      std::cerr << "ERROR: Unrecognized metric. " << std::endl;
    }
    return EXIT_FAILURE;
  }

  imageMetric->SetFixedImage(fixedImage);
  imageMetric->SetVirtualDomainFromImage(fixedImage);
  imageMetric->SetMovingImage(movingImage);
  imageMetric->SetFixedImageMask(fixedMaskSpatialObject);
  imageMetric->SetMovingImageMask(movingMaskSpatialObject);
  imageMetric->SetUseSampledPointSet(false);

  /** Sample the image domain **/

  if (samplingStrategy != NONE)
  {
    const typename ImageType::SpacingType oneThirdVirtualSpacing = fixedImage->GetSpacing() / 3.0;

    using MetricSamplePointSetType = typename ImageMetricType::FixedSampledPointSetType;
    typename MetricSamplePointSetType::Pointer samplePointSet = MetricSamplePointSetType::New();
    samplePointSet->Initialize();

    using SamplePointType = typename MetricSamplePointSetType::PointType;

    using RandomizerType = itk::Statistics::MersenneTwisterRandomVariateGenerator;
    typename RandomizerType::Pointer randomizer = RandomizerType::New();

    int antsRandomSeed = 1234;

    itk::ants::CommandLineParser::OptionType::Pointer randomSeedOption = parser->GetOption("random-seed");
    if (randomSeedOption && randomSeedOption->GetNumberOfFunctions())
    {
      antsRandomSeed = parser->Convert<int>(randomSeedOption->GetFunction(0)->GetName());
    }
    else
    {
      char * envSeed = getenv("ANTS_RANDOM_SEED");

      if (envSeed != nullptr)
      {
        antsRandomSeed = std::stoi(envSeed);
      }
    }

    if (antsRandomSeed != 0)
    {
      randomizer->SetSeed(antsRandomSeed);
    }

    unsigned long index = 0;

    switch (samplingStrategy)
    {
      case REGULAR:
      {
        const auto    sampleCount = static_cast<unsigned long>(std::ceil(1.0 / samplingPercentage));
        unsigned long count =
          sampleCount; // Start at sampleCount to keep behavior backwards identical, using first element.
        itk::ImageRegionConstIteratorWithIndex<ImageType> It(fixedImage, fixedImage->GetRequestedRegion());
        for (It.GoToBegin(); !It.IsAtEnd(); ++It)
        {
          if (count == sampleCount)
          {
            count = 0; // Reset counter
            SamplePointType point;
            fixedImage->TransformIndexToPhysicalPoint(It.GetIndex(), point);

            // randomly perturb the point within a voxel (approximately)
            for (unsigned int d = 0; d < ImageDimension; d++)
            {
              point[d] += static_cast<typename SamplePointType::CoordRepType>(randomizer->GetNormalVariate()) *
                          static_cast<typename SamplePointType::CoordRepType>(oneThirdVirtualSpacing[d]);
            }
            if (!fixedMaskSpatialObject || fixedMaskSpatialObject->IsInsideInWorldSpace(point))
            {
              samplePointSet->SetPoint(index, point);
              ++index;
            }
          }
          ++count;
        }
        break;
      }
      case RANDOM:
      {
        const unsigned long totalVirtualDomainVoxels = fixedImage->GetRequestedRegion().GetNumberOfPixels();
        const auto          sampleCount = static_cast<unsigned long>(static_cast<float>(totalVirtualDomainVoxels) *
                                                            static_cast<float>(samplingPercentage));
        itk::ImageRandomConstIteratorWithIndex<ImageType> ItR(fixedImage, fixedImage->GetRequestedRegion());
        ItR.SetNumberOfSamples(sampleCount);
        for (ItR.GoToBegin(); !ItR.IsAtEnd(); ++ItR)
        {
          SamplePointType point;
          fixedImage->TransformIndexToPhysicalPoint(ItR.GetIndex(), point);

          // randomly perturb the point within a voxel (approximately)
          for (unsigned int d = 0; d < ImageDimension; d++)
          {
            point[d] += static_cast<typename SamplePointType::CoordRepType>(randomizer->GetNormalVariate() *
                                                                            oneThirdVirtualSpacing[d]);
          }
          if (!fixedMaskSpatialObject || fixedMaskSpatialObject->IsInsideInWorldSpace(point))
          {
            samplePointSet->SetPoint(index, point);
            ++index;
          }
        }
        break;
      }
      case NONE:
        break;
    }
    imageMetric->SetFixedSampledPointSet(samplePointSet);
    imageMetric->SetUseSampledPointSet(true);
  }

  imageMetric->Initialize();

  if (strcmp(transform.c_str(), "affine") == 0)
  {
    imageMetric->SetMovingTransform(affineSearchTransform);
  }
  else if (strcmp(transform.c_str(), "rigid") == 0)
  {
    imageMetric->SetMovingTransform(rigidSearchTransform);
  }
  else if (strcmp(transform.c_str(), "similarity") == 0)
  {
    imageMetric->SetMovingTransform(similaritySearchTransform);
  }


  /////////////////////////////////////////////////////////////////
  //
  //         Set up the optimizer
  //
  /////////////////////////////////////////////////////////////////

  using RegistrationParameterScalesFromPhysicalShiftType =
    itk::RegistrationParameterScalesFromPhysicalShift<ImageMetricType>;
  typename RegistrationParameterScalesFromPhysicalShiftType::Pointer scalesEstimator =
    RegistrationParameterScalesFromPhysicalShiftType::New();
  scalesEstimator->SetMetric(imageMetric);
  scalesEstimator->SetTransformForward(true);

  typename RegistrationParameterScalesFromPhysicalShiftType::ScalesType movingScales(numberOfTransformParameters);
  scalesEstimator->EstimateScales(movingScales);

  using LocalOptimizerType = itk::ConjugateGradientLineSearchOptimizerv4;
  typename LocalOptimizerType::Pointer localOptimizer = LocalOptimizerType::New();
  localOptimizer->SetLowerLimit(0);
  localOptimizer->SetUpperLimit(2);
  localOptimizer->SetEpsilon(0.1);
  localOptimizer->SetMaximumLineSearchIterations(10);
  localOptimizer->SetLearningRate(learningRate);
  localOptimizer->SetMaximumStepSizeInPhysicalUnits(learningRate);
  localOptimizer->SetNumberOfIterations(numberOfIterations);
  localOptimizer->SetMinimumConvergenceValue(convergenceThreshold);
  localOptimizer->SetConvergenceWindowSize(convergenceWindowSize);
  localOptimizer->SetDoEstimateLearningRateOnce(true);
  localOptimizer->SetScales(movingScales);
  localOptimizer->SetMetric(imageMetric);

  using MultiStartOptimizerType = itk::MultiStartOptimizerv4;
  typename MultiStartOptimizerType::Pointer multiStartOptimizer = MultiStartOptimizerType::New();
  multiStartOptimizer->SetScales(movingScales);
  multiStartOptimizer->SetMetric(imageMetric);

  unsigned int trialCounter = 0;

  typename MultiStartOptimizerType::ParametersListType parametersList = multiStartOptimizer->GetParametersList();
  for (RealType angle1 = (itk::Math::pi * -arcFraction); angle1 <= (itk::Math::pi * arcFraction + 0.000001);
       angle1 += searchFactor)
  {
    if (ImageDimension == 2)
    {
      for (RealType translation1 = -1.0 * translationSearchGrid[0]; translation1 <= translationSearchGrid[0] + 0.000001;
           translation1 += translationSearchStepSize)
      {
        for (RealType translation2 = -1.0 * translationSearchGrid[1];
             translation2 <= translationSearchGrid[1] + 0.000001;
             translation2 += translationSearchStepSize)
        {
          typename AffineTransformType::OutputVectorType searchTranslation;
          searchTranslation[0] = translation1;
          searchTranslation[1] = translation2;

          affineSearchTransform->SetIdentity();
          affineSearchTransform->SetCenter(initialTransform->GetCenter());
          affineSearchTransform->SetMatrix(initialTransform->GetMatrix());
          affineSearchTransform->SetOffset(initialTransform->GetOffset());
          affineSearchTransform->Translate(searchTranslation, 1);
          affineSearchTransform->Rotate2D(angle1, 1);

          if (strcmp(transform.c_str(), "affine") == 0)
          {
            affineSearchTransform->Scale(bestScale);
            parametersList.push_back(affineSearchTransform->GetParameters());
          }
          else if (strcmp(transform.c_str(), "rigid") == 0)
          {
            rigidSearchTransform->SetIdentity();
            rigidSearchTransform->SetCenter(initialTransform->GetCenter());
            rigidSearchTransform->SetMatrix(affineSearchTransform->GetMatrix());
            rigidSearchTransform->SetOffset(initialTransform->GetOffset());

            parametersList.push_back(rigidSearchTransform->GetParameters());
          }
          else if (strcmp(transform.c_str(), "similarity") == 0)
          {
            similaritySearchTransform->SetIdentity();
            similaritySearchTransform->SetCenter(initialTransform->GetCenter());
            similaritySearchTransform->SetMatrix(affineSearchTransform->GetMatrix());
            similaritySearchTransform->SetOffset(initialTransform->GetOffset());
            similaritySearchTransform->SetScale(bestScale);

            similaritySearchTransform->SetScale(bestScale);

            parametersList.push_back(similaritySearchTransform->GetParameters());
          }
          trialCounter++;
        }
      }
    }
    if (ImageDimension == 3)
    {
      for (RealType angle2 = (itk::Math::pi * -arcFraction); angle2 <= (itk::Math::pi * arcFraction + 0.000001);
           angle2 += searchFactor)
      {
        for (RealType angle3 = (itk::Math::pi * -arcFraction); angle3 <= (itk::Math::pi * arcFraction + 0.000001);
             angle3 += searchFactor)
        {
          for (RealType translation1 = -1.0 * translationSearchGrid[0];
               translation1 <= translationSearchGrid[0] + 0.000001;
               translation1 += translationSearchStepSize)
          {
            for (RealType translation2 = -1.0 * translationSearchGrid[1];
                 translation2 <= translationSearchGrid[1] + 0.000001;
                 translation2 += translationSearchStepSize)
            {
              for (RealType translation3 = -1.0 * translationSearchGrid[2];
                   translation3 <= translationSearchGrid[2] + 0.000001;
                   translation3 += translationSearchStepSize)
              {
                typename AffineTransformType::OutputVectorType searchTranslation;
                searchTranslation[0] = translation1;
                searchTranslation[1] = translation2;
                searchTranslation[2] = translation3;

                affineSearchTransform->SetIdentity();
                affineSearchTransform->SetCenter(initialTransform->GetCenter());
                affineSearchTransform->SetOffset(initialTransform->GetOffset());
                affineSearchTransform->SetMatrix(initialTransform->GetMatrix());
                affineSearchTransform->Translate(searchTranslation, 0);
                affineSearchTransform->Rotate3D(axis1, angle1, 1);
                affineSearchTransform->Rotate3D(axis2, angle2, 1);
                affineSearchTransform->Rotate3D(axis1, angle3, 1);

                if (strcmp(transform.c_str(), "affine") == 0)
                {
                  affineSearchTransform->Scale(bestScale);
                  parametersList.push_back(affineSearchTransform->GetParameters());
                }
                else if (strcmp(transform.c_str(), "rigid") == 0)
                {
                  rigidSearchTransform->SetIdentity();
                  rigidSearchTransform->SetCenter(initialTransform->GetCenter());
                  rigidSearchTransform->SetOffset(initialTransform->GetOffset());
                  rigidSearchTransform->Translate(searchTranslation, 0);
                  rigidSearchTransform->SetMatrix(affineSearchTransform->GetMatrix());
                  parametersList.push_back(rigidSearchTransform->GetParameters());
                }
                else if (strcmp(transform.c_str(), "similarity") == 0)
                {
                  similaritySearchTransform->SetIdentity();
                  similaritySearchTransform->SetCenter(initialTransform->GetCenter());
                  similaritySearchTransform->SetOffset(initialTransform->GetOffset());
                  similaritySearchTransform->SetMatrix(affineSearchTransform->GetMatrix());
                  similaritySearchTransform->SetScale(bestScale);

                  parametersList.push_back(similaritySearchTransform->GetParameters());
                }
                trialCounter++;
              }
            }
          }
        }
      }
    }
  }

  multiStartOptimizer->SetParametersList(parametersList);
  multiStartOptimizer->SetLocalOptimizer(localOptimizer);

  if (verbose)
  {
    std::cout << "Starting optimizer with " << trialCounter << " starting points" << std::endl;

    using MultiStartObserverType = antsCommandIterationUpdate<MultiStartOptimizerType>;

    auto multiStartObserver = MultiStartObserverType::New();

    multiStartObserver->SetOptimizer(multiStartOptimizer);
  }

   multiStartOptimizer->StartOptimization();


  /////////////////////////////////////////////////////////////////
  //
  //         Write the output after convergence
  //
  /////////////////////////////////////////////////////////////////

  itk::ants::CommandLineParser::OptionType::Pointer outputOption = parser->GetOption("output");
  if (outputOption && outputOption->GetNumberOfFunctions())
  {
    std::string outputName = std::string("");
    if (outputOption->GetFunction(0)->GetNumberOfParameters() == 0)
    {
      outputName = outputOption->GetFunction(0)->GetName();
    }
    else
    {
      outputName = outputOption->GetFunction(0)->GetParameter(0);
    }

    using TransformWriterType = itk::TransformFileWriter;
    typename TransformWriterType::Pointer transformWriter = TransformWriterType::New();

    if (strcmp(transform.c_str(), "affine") == 0)
    {
      typename AffineTransformType::Pointer bestAffineTransform = AffineTransformType::New();
      bestAffineTransform->SetCenter(initialTransform->GetCenter());
      bestAffineTransform->SetParameters(multiStartOptimizer->GetBestParameters());
      transformWriter->SetInput(bestAffineTransform);
    }
    else if (strcmp(transform.c_str(), "rigid") == 0)
    {
      typename RigidTransformType::Pointer bestRigidTransform = RigidTransformType::New();
      bestRigidTransform->SetCenter(initialTransform->GetCenter());
      bestRigidTransform->SetParameters(multiStartOptimizer->GetBestParameters());
      transformWriter->SetInput(bestRigidTransform);
    }
    else if (strcmp(transform.c_str(), "similarity") == 0)
    {
      typename SimilarityTransformType::Pointer bestSimilarityTransform = SimilarityTransformType::New();
      bestSimilarityTransform->SetCenter(initialTransform->GetCenter());
      bestSimilarityTransform->SetParameters(multiStartOptimizer->GetBestParameters());
      transformWriter->SetInput(bestSimilarityTransform);
    }

    transformWriter->SetFileName(outputName.c_str());
    transformWriter->Update();
  }

  return EXIT_SUCCESS;
}

void
InitializeCommandLineOptions(itk::ants::CommandLineParser * parser)
{
  using OptionType = itk::ants::CommandLineParser::OptionType;

  {
    std::string description = std::string("This option forces the image to be treated as a specified-") +
                              std::string("dimensional image.  If not specified, we try to ") +
                              std::string("infer the dimensionality from the input image.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("dimensionality");
    option->SetShortName('d');
    option->SetUsageOption(0, "2/3");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("These image metrics are available:  ") +
      std::string("Mattes: Mattes mutual information (recommended), GC:  global correlation,  MI:  joint histogram mutual information");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("metric");
    option->SetShortName('m');
    option->SetUsageOption(1,
                           "Mattes[fixedImage,movingImage,<numberOfBins=32>,<samplingStrategy={None,Regular,Random}>,<"
                           "samplingPercentage=[0,1]>]");
    option->SetUsageOption(
      2, "GC[fixedImage,movingImage,<radius=NA>,<samplingStrategy={None,Regular,Random}>,<samplingPercentage=[0,1]>]");
    option->SetUsageOption(3,
                           "MI[fixedImage,movingImage,<numberOfBins=32>,<samplingStrategy={None,Regular,Random}>,<"
                           "samplingPercentage=[0,1]>]");

    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("Several transform options are available.  For the rigid, ") +
      std::string("affine, and similarity transforms, the gradientStep characterizes the gradient ") +
      std::string("descent optimization and is scaled appropriately for each transform using the ") +
      std::string("shift scales estimator. The other two transform types finds the simple translation ") +
      std::string("transform which aligns the specified image feature.  Note that the images are read ") +
      std::string("from the similarity metric option although the metric isn't actually used.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("transform");
    option->SetShortName('t');
    option->SetUsageOption(0, "Rigid[gradientStep]");
    option->SetUsageOption(1, "Affine[gradientStep]");
    option->SetUsageOption(2, "Similarity[gradientStep]");
    option->SetUsageOption(3, "AlignGeometricCenters");
    option->SetUsageOption(4, "AlignCentersOfMass");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Boolean indicating alignment by principal axes.  ") +
                              std::string("Alternatively, one can align using blobs (see -b option).");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("align-principal-axes");
    option->SetShortName('p');
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Boolean indicating alignment by a set of blobs.  ") +
                              std::string("Alternatively, one can align using blobs (see -p option).");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("align-blobs");
    option->SetShortName('b');
    option->SetUsageOption(0, "numberOfBlobsToExtract");
    option->SetUsageOption(1, "[numberOfBlobsToExtract,<numberOfBlobsToMatch=numberOfBlobsToExtract>]");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Incremental search factor (in degrees) which will ") +
                              std::string("sample the arc fraction around the principal axis or default axis.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("search-factor");
    option->SetShortName('s');
    option->SetUsageOption(0, "searchFactor");
    option->SetUsageOption(1, "[searchFactor=20,<arcFraction=1.0>]");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("Translation search grid in mm, which will ") +
      std::string("translate the moving image in each dimension in increments of the step size.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("translation-search-grid");
    option->SetShortName('g');
    option->SetUsageOption(0, "[stepSize=25, AxBxC=0x0x0]");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Number of iterations.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("convergence");
    option->SetShortName('c');
    option->SetUsageOption(0, "numberOfIterations");
    option->SetUsageOption(1, "[numberOfIterations,<convergenceThreshold=1e-6>,<convergenceWindowSize=10>]");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string         description = std::string("Image masks to limit voxels considered by the metric.");
    OptionType::Pointer option = OptionType::New();
    option->SetLongName("masks");
    option->SetShortName('x');
    option->SetUsageOption(0, "fixedImageMask");
    option->SetUsageOption(1, "[fixedImageMask,movingImageMask]");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Specify the output transform (output format an ITK .mat file). ");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("output");
    option->SetShortName('o');
    option->SetUsageOption(0, "outputFileName");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("Use a fixed seed for random number generation. ") +
      std::string("The default fixed seed is overwritten by this value. ") +
      std::string("The fixed seed can be any nonzero int value. If the specified seed is zero, ") +
      std::string("the system time will be used.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("random-seed");
    option->SetUsageOption(0, "seedValue");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Verbose output.");

    OptionType::Pointer option = OptionType::New();
    option->SetShortName('v');
    option->SetLongName("verbose");
    option->SetUsageOption(0, "(0)/1");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Print the help menu (short version).");

    OptionType::Pointer option = OptionType::New();
    option->SetShortName('h');
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Print the help menu.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("help");
    option->SetDescription(description);
    parser->AddOption(option);
  }
}

int
antsAI(std::vector<std::string> args, std::ostream * /*out_stream = nullptr */)
{

  // put the arguments coming in as 'args' into standard (argc,argv) format;
  // 'args' doesn't have the command name as first, argument, so add it manually;
  // 'args' may have adjacent arguments concatenated into one argument,
  // which the parser should handle

  args.insert(args.begin(), "antsAI");

  int     argc = args.size();
  char ** argv = new char *[args.size() + 1];
  for (unsigned int i = 0; i < args.size(); ++i)
  {
    // allocate space for the string plus a null character
    argv[i] = new char[args[i].length() + 1];
    std::strncpy(argv[i], args[i].c_str(), args[i].length());
    // place the null character in the end
    argv[i][args[i].length()] = '\0';
  }
  argv[argc] = nullptr;

  // class to automatically cleanup argv upon destruction
  class Cleanup_argv
  {
  public:
    Cleanup_argv(char ** argv_, int argc_plus_one_)
      : argv(argv_)
      , argc_plus_one(argc_plus_one_)
    {}

    ~Cleanup_argv()
    {
      for (unsigned int i = 0; i < argc_plus_one; ++i)
      {
        delete[] argv[i];
      }
      delete[] argv;
    }

  private:
    char **      argv;
    unsigned int argc_plus_one;
  };
  Cleanup_argv cleanup_argv(argv, argc + 1);

  // antscout->set_stream( out_stream );
  using ParserType = itk::ants::CommandLineParser;

  ParserType::Pointer parser = ParserType::New();
  parser->SetCommand(argv[0]);

  std::string commandDescription = std::string("Program to calculate the optimal") +
                                   std::string("linear transform parameters for aligning two images.");

  parser->SetCommandDescription(commandDescription);
  InitializeCommandLineOptions(parser);

  if (parser->Parse(argc, argv) == EXIT_FAILURE)
  {
    return EXIT_FAILURE;
  }

  bool                                              verbose = false;
  itk::ants::CommandLineParser::OptionType::Pointer verboseOption = parser->GetOption("verbose");
  if (verboseOption && verboseOption->GetNumberOfFunctions())
  {
    verbose = parser->Convert<bool>(verboseOption->GetFunction(0)->GetName());
  }

  if (argc == 1)
  {
    parser->PrintMenu(std::cout, 5, false);
    return EXIT_FAILURE;
  }
  else if (parser->GetOption("help")->GetFunction() &&
           parser->Convert<bool>(parser->GetOption("help")->GetFunction()->GetName()))
  {
    parser->PrintMenu(std::cout, 5, false);
    return EXIT_SUCCESS;
  }
  else if (parser->GetOption('h')->GetFunction() &&
           parser->Convert<bool>(parser->GetOption('h')->GetFunction()->GetName()))
  {
    parser->PrintMenu(std::cout, 5, true);
    return EXIT_SUCCESS;
  }

  unsigned int dimension = 3;

  ParserType::OptionType::Pointer dimOption = parser->GetOption("dimensionality");
  if (dimOption && dimOption->GetNumberOfFunctions())
  {
    dimension = parser->Convert<unsigned int>(dimOption->GetFunction(0)->GetName());
  }
  else
  {
    if (verbose)
    {
      std::cerr << "Image dimensionality not specified.  See command line option --dimensionality" << std::endl;
    }
    return EXIT_FAILURE;
  }

  switch (dimension)
  {
    case 2:
    {
      return antsAI<2>(parser);
      break;
    }
    case 3:
    {
      return antsAI<3>(parser);
      break;
    }
    default:
    {
      std::cerr << "Unrecognized dimensionality.  Please see help menu." << std::endl;
      return EXIT_FAILURE;
    }
  }
  return EXIT_SUCCESS;
}
} // namespace ants