File: CreateDTICohort.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 (1166 lines) | stat: -rw-r--r-- 42,963 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

#include "antsUtilities.h"
#include <algorithm>

#include "antsCommandLineParser.h"
#include "antsAllocImage.h"
#include "itkArray2D.h"
#include "itkDecomposeTensorFunction.h"
#include "itkDiffusionTensor3D.h"
#include "itkImageDuplicator.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"
#include "itkLabelImageToShapeLabelMapFilter.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkNumericSeriesFileNames.h"
#include "itkTimeProbe.h"
#include "itkVariableSizeMatrix.h"

#include <itksys/SystemTools.hxx>

#include "vnl/vnl_matrix.h"
#include "vnl/vnl_vector.h"

#include <iomanip>

#include <string>
#include <algorithm>
#include <vector>
#include <fstream>

namespace ants
{
template <typename TensorType>
double
CalculateFractionalAnisotropy(TensorType tensor)
{
  typename TensorType::EigenValuesArrayType   eigenvalues;
  typename TensorType::EigenVectorsMatrixType eigenvectors;

  tensor.ComputeEigenAnalysis(eigenvalues, eigenvectors);

  if (eigenvalues[0] < 0)
  {
    eigenvalues[0] = eigenvalues[1];
  }
  if (TensorType::Dimension == 3 && eigenvalues[2] < 0)
  {
    eigenvalues[2] = eigenvalues[1];
  }

  double fa = 0.0;
  double mean = tensor.GetTrace() / static_cast<double>(TensorType::Dimension);

  double numerator = 0.0;
  double denominator = 0.0;
  for (unsigned int d = 0; d < TensorType::Dimension; d++)
  {
    numerator += static_cast<double>(itk::Math::sqr(static_cast<double>(eigenvalues[d]) - mean));
    denominator += static_cast<double>(itk::Math::sqr(eigenvalues[d]));
  }
  fa = std::sqrt((3.0 * numerator) / (2.0 * denominator));

  return fa;
}

template <typename TensorType>
double
CalculateMeanDiffusivity(TensorType tensor)
{
  typename TensorType::EigenValuesArrayType   eigenvalues;
  typename TensorType::EigenVectorsMatrixType eigenvectors;

  tensor.ComputeEigenAnalysis(eigenvalues, eigenvectors);

  if (eigenvalues[0] < 0)
  {
    eigenvalues[0] = eigenvalues[1];
  }
  if (TensorType::Dimension == 3 && eigenvalues[2] < 0)
  {
    eigenvalues[2] = eigenvalues[1];
  }

  double mean = tensor.GetTrace() / static_cast<double>(TensorType::Dimension);

  return mean;
}

template <unsigned int ImageDimension>
int
CreateDTICohort(itk::ants::CommandLineParser * parser)
{
  using RealType = float;
  using TensorType = itk::SymmetricSecondRankTensor<RealType, ImageDimension>;
  using MatrixType = itk::VariableSizeMatrix<typename TensorType::ValueType>;

  using ImageType = itk::Image<RealType, ImageDimension>;

  using LabelType = unsigned int;
  using MaskImageType = itk::Image<LabelType, ImageDimension>;
  typename MaskImageType::Pointer maskImage = nullptr;

  using TensorImageType = itk::Image<TensorType, ImageDimension>;
  typename TensorImageType::Pointer inputAtlas = nullptr;

  using TensorReaderType = itk::ImageFileReader<TensorImageType>;
  typename TensorReaderType::Pointer reader = TensorReaderType::New();

  using DecomposerType = itk::DecomposeTensorFunction<MatrixType, typename MatrixType::ValueType, MatrixType>;
  typename DecomposerType::Pointer decomposer = DecomposerType::New();

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

  //
  // Get the input DTI atlas
  //
  typename itk::ants::CommandLineParser::OptionType::Pointer inputAtlasOption = parser->GetOption("dti-atlas");
  if (inputAtlasOption && inputAtlasOption->GetNumberOfFunctions())
  {
    std::string inputFile = inputAtlasOption->GetFunction(0)->GetName();
    reader->SetFileName(inputFile.c_str());

    inputAtlas = reader->GetOutput();
    inputAtlas->Update();
    inputAtlas->DisconnectPipeline();
  }
  else
  {
    std::cout << "ERROR:  Input DTI atlas not specified." << std::endl;
    return EXIT_FAILURE;
  }

  //
  // Get the number of output images and duplicate the atlas for each cohort.
  //
  std::string  outputDirectory("./");
  std::string  rootOutputFileName("outputDWI");
  unsigned int numberOfControls = 10;
  unsigned int numberOfExperimentals = 10;

  typename itk::ants::CommandLineParser::OptionType::Pointer outputOption = parser->GetOption("output");
  if (outputOption && outputOption->GetNumberOfFunctions())
  {
    if (outputOption->GetFunction(0)->GetNumberOfParameters() > 0)
    {
      outputDirectory = outputOption->GetFunction(0)->GetParameter(0);
      outputDirectory += std::string("/");
    }
    if (outputOption->GetFunction(0)->GetNumberOfParameters() > 1)
    {
      rootOutputFileName = outputOption->GetFunction(0)->GetParameter(1);
    }
    if (outputOption->GetFunction(0)->GetNumberOfParameters() > 2)
    {
      numberOfControls = parser->Convert<unsigned int>(outputOption->GetFunction(0)->GetParameter(2));
    }
    if (outputOption->GetFunction(0)->GetNumberOfParameters() > 3)
    {
      numberOfExperimentals = parser->Convert<unsigned int>(outputOption->GetFunction(0)->GetParameter(3));
    }
  }
  else
  {
    std::cout << "ERROR:  No output specified." << std::endl;
    return EXIT_FAILURE;
  }

  //
  // Get the label mask.  If not specified, create one from the DTI atlas.
  //
  typename itk::ants::CommandLineParser::OptionType::Pointer maskImageOption = parser->GetOption("label-mask-image");
  RealType                                                   lowerThresholdFunction = 0.2;
  if (maskImageOption && maskImageOption->GetNumberOfFunctions())
  {
    std::string inputFile = maskImageOption->GetFunction(0)->GetName();
    using ReaderType = itk::ImageFileReader<MaskImageType>;
    typename ReaderType::Pointer maskreader = ReaderType::New();
    maskreader->SetFileName(inputFile.c_str());
    try
    {
      maskImage = maskreader->GetOutput();
      maskImage->Update();
      maskImage->DisconnectPipeline();
    }
    catch (...)
    {
      lowerThresholdFunction = parser->Convert<RealType>(maskImageOption->GetFunction(0)->GetName());
    }
  }
  if (maskImage.IsNull())
  {
    std::cout << "Mask not read.  Creating mask by thresholding "
              << "the FA of the DTI atlas at >= " << lowerThresholdFunction << "." << std::endl
              << std::endl;

    typename ImageType::Pointer faImage = AllocImage<ImageType>(inputAtlas, 0.0);

    itk::ImageRegionIterator<TensorImageType> ItA(inputAtlas, inputAtlas->GetLargestPossibleRegion());
    itk::ImageRegionIterator<ImageType>       ItF(faImage, faImage->GetLargestPossibleRegion());
    for (ItA.GoToBegin(), ItF.GoToBegin(); !ItA.IsAtEnd(); ++ItA, ++ItF)
    {
      ItF.Set(CalculateFractionalAnisotropy<TensorType>(ItA.Get()));
    }

    using ThresholderType = itk::BinaryThresholdImageFilter<ImageType, MaskImageType>;
    typename ThresholderType::Pointer thresholder = ThresholderType::New();
    thresholder->SetInput(faImage);
    thresholder->SetInsideValue(1);
    thresholder->SetOutsideValue(0);
    thresholder->SetLowerThreshold(lowerThresholdFunction);
    thresholder->SetUpperThreshold(2.0);

    maskImage = thresholder->GetOutput();
    maskImage->Update();
    maskImage->DisconnectPipeline();
  }

  //
  // Get label information for pathology option
  //
  using LabelMapFilterType = itk::LabelImageToShapeLabelMapFilter<MaskImageType>;
  typename LabelMapFilterType::Pointer labelMapper = LabelMapFilterType::New();
  labelMapper->SetInput(maskImage);
  labelMapper->ComputeOrientedBoundingBoxOff();
  labelMapper->ComputePerimeterOff();
  labelMapper->SetBackgroundValue(-1); // include 0 in output
  labelMapper->Update();
  auto labelObjects = labelMapper->GetOutput()->GetLabelObjects();

  unsigned int totalMaskVolume = 0;
  for (unsigned int n = 0; n < labelObjects.size(); n++)
  {
    totalMaskVolume += static_cast<unsigned int>(labelObjects[n]->GetNumberOfPixels());
  }

  // Fill in default values per label:
  //    column 1:  percentage change in longitudinal eigenvalue
  //    column 2:  percentage change in average of transverse eigenvalue(s)
  //    column 3:  percentage of affected voxels
  itk::Array2D<RealType> pathologyParameters(labelObjects.size(), 3);
  for (unsigned int i = 0; i < labelObjects.size(); i++)
  {
    pathologyParameters(i, 0) = 0.0;
    pathologyParameters(i, 1) = 0.0;
    pathologyParameters(i, 2) = 0.0;
  }

  /**
   * labels
   */
  typename itk::ants::CommandLineParser::OptionType::Pointer pathologyOption = parser->GetOption("pathology");
  if (pathologyOption && pathologyOption->GetNumberOfFunctions())
  {
    if (pathologyOption->GetNumberOfFunctions() == 1 && (pathologyOption->GetFunction(0)->GetName()).empty())
    {
      float pathologyDeltaEig1 = 0.0;
      float pathologyDeltaEig2_Eig3 = 0.0;
      float percentageVoxels = 0.0;

      if (pathologyOption->GetFunction(0)->GetNumberOfParameters() > 0)
      {
        pathologyDeltaEig1 = parser->Convert<float>(pathologyOption->GetFunction(0)->GetParameter(0));
      }
      if (pathologyOption->GetFunction(0)->GetNumberOfParameters() > 1)
      {
        pathologyDeltaEig2_Eig3 = parser->Convert<float>(pathologyOption->GetFunction(0)->GetParameter(1));
      }
      if (pathologyOption->GetFunction(0)->GetNumberOfParameters() > 2)
      {
        percentageVoxels = parser->Convert<float>(pathologyOption->GetFunction(0)->GetParameter(2));
      }
      for (unsigned int n = 0; n < labelObjects.size(); n++)
      {
        RealType percentage = percentageVoxels;
        if (percentage > itk::NumericTraits<RealType>::OneValue())
        {
          percentage /= static_cast<RealType>(labelObjects[n]->GetNumberOfPixels());
          std::cout << "WARNING:  Percentage of affected voxels must be less than or equal to 1." << std::endl;
          std::cout << "          Dividing by size of region, percentage = " << percentage << std::endl;
        }

        pathologyParameters(n, 0) = pathologyDeltaEig1;
        pathologyParameters(n, 1) = pathologyDeltaEig2_Eig3;
        pathologyParameters(n, 2) = percentage;
      }
    }
    else
    {
      for (unsigned int n = 0; n < pathologyOption->GetNumberOfFunctions(); n++)
      {
        auto whichClass = parser->Convert<LabelType>(pathologyOption->GetFunction(n)->GetName());

        auto it = labelObjects.begin();

        for (it = labelObjects.begin(); it != labelObjects.end(); ++it)
        {
          if ((*it)->GetLabel() == whichClass)
          {
            break;
          }
        }

        if (it == labelObjects.end())
        {
          continue;
        }

        float pathologyDeltaEig1 = 0.1;
        float pathologyDeltaEig2_Eig3 = 0.1;
        float percentageVoxels = 1.0;

        if (pathologyOption->GetFunction(n)->GetNumberOfParameters() > 0)
        {
          pathologyDeltaEig1 = parser->Convert<float>(pathologyOption->GetFunction(n)->GetParameter(0));
        }
        if (pathologyOption->GetFunction(n)->GetNumberOfParameters() > 1)
        {
          pathologyDeltaEig2_Eig3 = parser->Convert<float>(pathologyOption->GetFunction(n)->GetParameter(1));
        }
        if (pathologyOption->GetFunction(n)->GetNumberOfParameters() > 2)
        {
          percentageVoxels = parser->Convert<float>(pathologyOption->GetFunction(n)->GetParameter(2));
        }

        RealType percentage = percentageVoxels;
        if (percentage > itk::NumericTraits<RealType>::OneValue())
        {
          percentage /= static_cast<RealType>((*it)->GetNumberOfPixels());
          std::cout << "WARNING:  Percentage of affected voxels must be less than or equal to 1." << std::endl;
          std::cout << "          Dividing by size of region, percentage = " << percentage << std::endl;
        }
        pathologyParameters(it - labelObjects.begin(), 0) = pathologyDeltaEig1;
        pathologyParameters(it - labelObjects.begin(), 1) = pathologyDeltaEig2_Eig3;
        pathologyParameters(it - labelObjects.begin(), 2) = percentage;
      }
    }
  }

  /**
   * Perform PCA decomposition on input registered population
   */
  bool applyISV = false;

  typename MatrixType::InternalMatrixType                    ISV(1, 1);
  typename itk::ants::CommandLineParser::OptionType::Pointer populationOption =
    parser->GetOption("registered-population");
  if (populationOption && populationOption->GetNumberOfFunctions())
  {
    std::cout << "--- Modeling intersubject variability ---" << std::endl << std::endl;

    std::vector<std::string> imageNames;

    std::string filename = populationOption->GetFunction(0)->GetName();

    std::string imageFile;

    std::fstream str(filename.c_str());
    while (str >> imageFile)
    {
      imageNames.push_back(imageFile);
    }

    str.close();

    MatrixType M;
    MatrixType Mt;
    MatrixType E;
    MatrixType Lambda;
    M.SetSize(imageNames.size(), 2 * totalMaskVolume);
    M.Fill(0);
    for (unsigned int k = 0; k < imageNames.size(); k++)
    {
      std::cout << "Processing " << imageNames[k] << " (" << k + 1 << " of " << imageNames.size() << ")." << std::endl;
      typename TensorReaderType::Pointer tensorReader = TensorReaderType::New();
      tensorReader->SetFileName(imageNames[k].c_str());
      tensorReader->Update();

      unsigned int count = 0;

      itk::ImageRegionIterator<TensorImageType> It(tensorReader->GetOutput(),
                                                   tensorReader->GetOutput()->GetLargestPossibleRegion());
      itk::ImageRegionIterator<MaskImageType>   ItM(maskImage, maskImage->GetLargestPossibleRegion());
      for (It.GoToBegin(), ItM.GoToBegin(); !It.IsAtEnd(); ++It, ++ItM)
      {
        if (ItM.Get() != 0)
        {
          TensorType tensor = It.Get();

          typename TensorType::EigenValuesArrayType   eigenvalues;
          typename TensorType::EigenVectorsMatrixType eigenvectors;
          tensor.ComputeEigenAnalysis(eigenvalues, eigenvectors);

          if (eigenvalues[0] < 0)
          {
            eigenvalues[0] = eigenvalues[1];
          }
          if (ImageDimension == 3 && eigenvalues[2] < 0)
          {
            eigenvalues[2] = eigenvalues[1];
          }

          if (ImageDimension == 2)
          {
            M(k, count) = eigenvalues[1];
            M(k, totalMaskVolume + count) = eigenvalues[0];
          }
          else
          {
            M(k, count) = eigenvalues[2];
            M(k, totalMaskVolume + count) = static_cast<RealType>(0.5) * (eigenvalues[0] + eigenvalues[1]);
          }
          ++count;
        }
      }
    }

    std::cout << std::endl;
    // Now that the matrix M has been calculated, we need to subtract out
    // the longitudinal mean before performing PCA
    for (unsigned int i = 0; i < M.Cols(); i++)
    {
      RealType columnAverage = 0.0;
      for (unsigned int j = 0; j < M.Rows(); j++)
      {
        columnAverage += M(j, i);
      }
      columnAverage /= static_cast<RealType>(M.Rows());
      for (unsigned int j = 0; j < M.Rows(); j++)
      {
        M(j, i) -= columnAverage;
      }
    }
    // Perform PCA decomposition

    MatrixType MMt = M;
    MMt *= M.GetTranspose();
    decomposer->EvaluateSymmetricEigenDecomposition(MMt, Lambda, E);

    ISV = (M.GetTranspose() * E.GetVnlMatrix()) / std::sqrt(static_cast<float>(imageNames.size()));

    applyISV = true;
  }

  //
  // Get DWI parameters
  //
  typename ImageType::Pointer       b0Image = nullptr;
  unsigned int                      numberOfDirections = 0;
  std::vector<vnl_vector<RealType>> directions;
  std::vector<RealType>             bvalues;

  vnl_vector<RealType> direction(ImageDimension);

  // Add a B0 value at direction 0
  direction.fill(0.0);
  directions.push_back(direction);
  bvalues.push_back(0);

  typename itk::ants::CommandLineParser::OptionType::Pointer dwiOption = parser->GetOption("dwi-parameters");
  if (dwiOption && dwiOption->GetNumberOfFunctions() && dwiOption->GetFunction(0)->GetNumberOfParameters() > 1)
  {
    using ReaderType = itk::ImageFileReader<ImageType>;
    typename ReaderType::Pointer reader2 = ReaderType::New();
    reader2->SetFileName(dwiOption->GetFunction(0)->GetParameter(0));
    reader2->Update();
    b0Image = reader2->GetOutput();
    b0Image->DisconnectPipeline();

    std::string  directionsFileName = dwiOption->GetFunction(0)->GetParameter(1);
    std::fstream str(directionsFileName.c_str());

    if (dwiOption->GetFunction(0)->GetNumberOfParameters() > 2)
    {
      bvalues.push_back(parser->Convert<RealType>(dwiOption->GetFunction(0)->GetParameter(2)));

      str >> numberOfDirections;
    }

    RealType x = 0.0;

    unsigned int count = 0;
    while (str >> x)
    {
      direction[count % ImageDimension] = x;
      ++count;
      if (count % ImageDimension == 0)
      {
        directions.push_back(direction);
        if (dwiOption->GetFunction(0)->GetNumberOfParameters() < 3)
        {
          str >> x;
          bvalues.push_back(x);
        }
        else
        {
          bvalues.push_back(bvalues[1]);
        }
      }
    }

    if (dwiOption->GetFunction(0)->GetNumberOfParameters() < 3)
    {
      if (bvalues.size() != directions.size())
      {
        std::cout << "ERROR:  Number of bvalues does not match the number of directions." << std::endl;
        return EXIT_FAILURE;
      }
    }
    else
    {
      if (numberOfDirections != directions.size() - 1)
      {
        std::cout << "ERROR:  Number of directions does not match the data file." << std::endl;
        return EXIT_FAILURE;
      }
    }
  }
  else
  {
    std::cout << "ERROR:  No DWI parameters specified." << std::endl;
    return EXIT_FAILURE;
  }

  //
  // Get Rician noise parameter
  //
  RealType noiseSigma = 0;

  typename itk::ants::CommandLineParser::OptionType::Pointer noiseOption = parser->GetOption("noise-sigma");
  if (noiseOption && noiseOption->GetNumberOfFunctions())
  {
    noiseSigma = parser->Convert<RealType>(noiseOption->GetFunction()->GetName());
  }

  //
  // Create the simulated diffusion-weighted images.  For each image, we
  // perform the following steps:
  //   1. Copy the atlas
  //   2. Construct new DTI
  //     2a. Apply pathology (only for the experimentals).
  //     2b. Introduce subject intervariability
  //   3. For each direction, write new DWI
  //     3a. Use DTI from 2 to reconstruct DWI in current direction
  //     3b. Add Rician noise
  //
  itksys::SystemTools::MakeDirectory(outputDirectory.c_str());

  itk::Array2D<RealType> meanFAandMD(labelObjects.size(), 5);
  meanFAandMD.Fill(0.0);
  for (unsigned n = 0; n <= numberOfControls + numberOfExperimentals; n++)
  {
    if (n == 0)
    {
      std::cout << "--- Calculating regional average FA and MD values (original and "
                << "pathology + intersubject variability) ---" << std::endl
                << std::endl;
    }
    else if (n <= numberOfControls)
    {
      if (n == 1)
      {
        std::cout << std::endl << "--- Writing images ---" << std::endl << std::endl;
      }
      std::cout << "Writing control " << n << " (of " << numberOfControls << ") DWI images." << std::endl;
    }
    else
    {
      std::cout << "Writing experimental " << n - numberOfControls << " (of " << numberOfExperimentals
                << ") DWI images." << std::endl;
    }

    // copy atlas
    using DuplicatorType = itk::ImageDuplicator<TensorImageType>;
    typename DuplicatorType::Pointer duplicator = DuplicatorType::New();
    duplicator->SetInputImage(inputAtlas);
    duplicator->Update();

    typename TensorImageType::Pointer dti = duplicator->GetOutput();

    // If we are to apply intersubject variability, we calculate random
    // projection.
    vnl_vector<RealType> eigenISVProjection(1);
    if (applyISV)
    {
      vnl_vector<RealType> R(ISV.cols());
      for (float & d : R)
      {
        d = randomizer->GetNormalVariate(0.0, 1.0);
      }
      eigenISVProjection = ISV * R;
    }

    //
    // Iterate through the image to apply pathology and inter-subject variability
    //
    unsigned long count = 0;

    itk::ImageRegionIterator<TensorImageType> It(dti, dti->GetLargestPossibleRegion());
    itk::ImageRegionIterator<MaskImageType>   ItM(maskImage, maskImage->GetLargestPossibleRegion());
    for (It.GoToBegin(), ItM.GoToBegin(); !It.IsAtEnd(); ++It, ++ItM)
    {
      LabelType  label = ItM.Get();
      TensorType tensor = It.Get();

      typename TensorType::EigenValuesArrayType   eigenvalues;
      typename TensorType::EigenVectorsMatrixType eigenvectors;
      tensor.ComputeEigenAnalysis(eigenvalues, eigenvectors);

      if (eigenvalues[0] < 0)
      {
        eigenvalues[0] = eigenvalues[1];
      }
      if (ImageDimension == 3 && eigenvalues[2] < 0)
      {
        eigenvalues[2] = eigenvalues[1];
      }

      auto it = labelObjects.begin();

      for (it = labelObjects.begin(); it != labelObjects.end(); ++it)
      {
        if ((*it)->GetLabel() == label)
        {
          break;
        }
      }

      if (it == labelObjects.end())
      {
        std::cout << "ERROR:  unknown label." << std::endl;
      }

      unsigned int labelIndex = it - labelObjects.begin();

      typename TensorType::EigenValuesArrayType newEigenvalues;

      //
      // Only apply pathology to a certain fraction of the voxels for a
      // particular label.  We "throw the dice" to determine whether or not
      // to apply to the current voxel.
      //
      RealType pathologyLongitudinalChange = 0.0;
      RealType pathologyTransverseChange = 0.0;
      if ((n == 0 || n > numberOfControls) &&
          static_cast<RealType>(randomizer->GetUniformVariate(0.0, 1.0)) <= pathologyParameters(labelIndex, 2))
      {
        pathologyLongitudinalChange = pathologyParameters(labelIndex, 0);
        pathologyTransverseChange = pathologyParameters(labelIndex, 1);
      }

      //
      // Apply intersubject variability
      //
      RealType isvLongitudinalProjection = 0.0;
      RealType isvTransverseProjection = 0.0;
      if (label != 0 && applyISV)
      {
        isvLongitudinalProjection = eigenISVProjection(count);
        isvTransverseProjection = eigenISVProjection(totalMaskVolume + count);
        count++;
      }

      //
      // Reconstruct the tensor
      //
      if (ImageDimension == 2)
      {
        newEigenvalues[1] = eigenvalues[1] + eigenvalues[1] * pathologyLongitudinalChange + isvLongitudinalProjection;
        newEigenvalues[0] =
          eigenvalues[0] * (itk::NumericTraits<RealType>::OneValue() + eigenvalues[0]) * pathologyTransverseChange +
          isvTransverseProjection;
        if (newEigenvalues[0] >= newEigenvalues[1])
        {
          newEigenvalues[0] = newEigenvalues[1] - static_cast<RealType>(1.0e-6);
        }
      }
      else
      {
        newEigenvalues[2] = eigenvalues[2] + eigenvalues[2] * pathologyLongitudinalChange + isvLongitudinalProjection;
        RealType eigenAverage = static_cast<RealType>(0.5) * (eigenvalues[1] + eigenvalues[0]);
        newEigenvalues[1] = (static_cast<RealType>(2.0) * eigenAverage *
                               (itk::NumericTraits<RealType>::OneValue() + pathologyTransverseChange) +
                             isvTransverseProjection) /
                            (eigenvalues[0] / eigenvalues[1] + itk::NumericTraits<RealType>::OneValue());
        if (newEigenvalues[1] >= newEigenvalues[2])
        {
          newEigenvalues[1] = newEigenvalues[2] - static_cast<RealType>(1.0e-6);
        }
        newEigenvalues[0] = (eigenvalues[0] / eigenvalues[1]) * newEigenvalues[1];
      }
      for (unsigned int d = 0; d < ImageDimension; d++)
      {
        if (std::isnan(newEigenvalues[d]))
        {
          newEigenvalues[d] = 0.0;
        }
      }

      if (newEigenvalues[0] < 0)
      {
        newEigenvalues[0] = newEigenvalues[1];
      }
      if (ImageDimension == 3 && newEigenvalues[2] < itk::NumericTraits<RealType>::ZeroValue())
      {
        newEigenvalues[2] = newEigenvalues[1];
      }

      typename TensorType::MatrixType eigenvalueMatrix;
      eigenvalueMatrix.Fill(0.0);
      for (unsigned int d = 0; d < ImageDimension; d++)
      {
        eigenvalueMatrix(d, d) = newEigenvalues[d];
      }

      typename TensorType::MatrixType D(eigenvectors.GetTranspose());
      D *= eigenvalueMatrix;
      D *= eigenvectors;

      TensorType newTensor;
      for (unsigned int i = 0; i < ImageDimension; i++)
      {
        for (unsigned int j = i; j < ImageDimension; j++)
        {
          newTensor(i, j) = D(i, j);
        }
      }

      if (label != 0 && n == 0)
      {
        meanFAandMD(labelIndex, 0) += static_cast<RealType>(CalculateFractionalAnisotropy<TensorType>(tensor));
        meanFAandMD(labelIndex, 1) += static_cast<RealType>(CalculateMeanDiffusivity<TensorType>(tensor));
        meanFAandMD(labelIndex, 2) += static_cast<RealType>(CalculateFractionalAnisotropy<TensorType>(newTensor));
        meanFAandMD(labelIndex, 3) += static_cast<RealType>(CalculateMeanDiffusivity<TensorType>(newTensor));
        meanFAandMD(labelIndex, 4)++;
      }
      else if (n != 0)
      {
        It.Set(newTensor);
      }
    }

    if (n == 0)
    {
      std::cout << "   " << std::left << std::setw(7) << "Region" << std::left << std::setw(15) << "FA (original)"
                << std::left << std::setw(15) << "FA (path+isv)" << std::left << std::setw(15) << "FA (prop. change)"
                << std::left << std::setw(15) << "MD (original)" << std::left << std::setw(15) << "MD (path+isv)"
                << std::left << std::setw(15) << "MD (prop. change)" << std::endl;
      for (unsigned int l = 1; l < labelObjects.size(); l++)
      {
        std::cout << "   " << std::left << std::setw(7) << labelObjects[l]->GetLabel() << std::left << std::setw(15)
                  << meanFAandMD(l, 0) / meanFAandMD(l, 4) << std::left << std::setw(15)
                  << meanFAandMD(l, 2) / meanFAandMD(l, 4) << std::left << std::setw(15)
                  << (meanFAandMD(l, 2) - meanFAandMD(l, 0)) / meanFAandMD(l, 0) << std::left << std::setw(15)
                  << meanFAandMD(l, 1) / meanFAandMD(l, 4) << std::left << std::setw(15)
                  << meanFAandMD(l, 3) / meanFAandMD(l, 4) << std::left << std::setw(15)
                  << (meanFAandMD(l, 3) - meanFAandMD(l, 1)) / meanFAandMD(l, 1) << std::endl;
      }
    }
    else
    {
      std::string which;
      if (n <= numberOfControls)
      {
        which = std::string("Control");
      }
      else
      {
        which = std::string("Experimental");
      }

      std::stringstream istream;
      if (n <= numberOfControls)
      {
        istream << n;
      }
      else
      {
        istream << (n - numberOfControls);
      }
      std::string dwiSeriesFileNames =
        outputDirectory + which + istream.str() + rootOutputFileName + std::string("Direction%03d.nii.gz");

      itk::NumericSeriesFileNames::Pointer dwiFileNamesCreator = itk::NumericSeriesFileNames::New();
      dwiFileNamesCreator->SetStartIndex(0);
      dwiFileNamesCreator->SetEndIndex(directions.size() - 1);
      dwiFileNamesCreator->SetSeriesFormat(dwiSeriesFileNames.c_str());
      std::vector<std::string> dwiImageNames = dwiFileNamesCreator->GetFileNames();
      for (unsigned int d = 0; d < directions.size(); d++)
      {
        vnl_vector<RealType> bk = directions[d];
        RealType             bvalue = bvalues[d];

        std::cout << "  Applying direction " << d << " (of " << directions.size() - 1 << "): [" << bk << "]"
                  << ", bvalue = " << bvalue << std::endl;

        typename ImageType::Pointer dwi = AllocImage<ImageType>(dti, 0);

        itk::ImageRegionConstIterator<ImageType> ItB(b0Image, b0Image->GetLargestPossibleRegion());
        itk::ImageRegionIterator<ImageType>      ItD(dwi, dwi->GetLargestPossibleRegion());
        for (It.GoToBegin(), ItB.GoToBegin(), ItD.GoToBegin(); !It.IsAtEnd(); ++It, ++ItB, ++ItD)
        {
          TensorType tensor = It.Get();
          for (unsigned int i = 0; i < tensor.GetNumberOfComponents(); i++)
          {
            if (std::isnan(tensor[i]))
            {
              tensor[i] = 0.0;
            }
          }

          vnl_matrix<RealType> D(ImageDimension, ImageDimension);
          for (unsigned int i = 0; i < ImageDimension; i++)
          {
            for (unsigned int j = 0; j < ImageDimension; j++)
            {
              D(i, j) = tensor(i, j);
            }
          }

          vnl_vector<RealType> bkD = bk * D;

          RealType signal = ItB.Get() * std::exp(-bvalue * inner_product(bkD, bk));

          // Add Rician noise
          RealType realNoise = 0.0;
          RealType imagNoise = 0.0;
          if (noiseSigma > itk::NumericTraits<RealType>::ZeroValue())
          {
            realNoise = randomizer->GetNormalVariate(0.0, itk::Math::sqr(noiseSigma));
            imagNoise = randomizer->GetNormalVariate(0.0, itk::Math::sqr(noiseSigma));
          }
          RealType realSignal = signal + realNoise;
          RealType imagSignal = imagNoise;

          std::complex<RealType> noisySignal(realSignal, imagSignal);

          RealType finalSignal = std::sqrt(std::norm(noisySignal));

          if (signal <= ItB.Get())
          {
            ItD.Set(finalSignal);
          }
        }
        using WriterType = itk::ImageFileWriter<ImageType>;
        typename WriterType::Pointer writer = WriterType::New();
        writer->SetFileName(dwiImageNames[d].c_str());
        writer->SetInput(dwi);
        writer->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, the program tries to ") +
                              std::string("infer the dimensionality from the input image.");

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

  {
    std::string description =
      std::string("A diffusion tensor atlas image is required input for ") + std::string("creating the cohort. ");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("dti-atlas");
    option->SetShortName('a');
    option->SetUsageOption(0, "inputDTIAtlasFileName");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("A mask image can be specified which determines the region(s). ") +
                              std::string("to which the simulated pathology operations are applied. ") +
                              std::string("See also the option '--pathology'.  If no mask is specified ") +
                              std::string("one is created by thresholding the atlas FA map at 0.2 unless  ") +
                              std::string("a lower threshold is specified.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("label-mask-image");
    option->SetShortName('x');
    option->SetUsageOption(0, "maskImageFileName");
    option->SetUsageOption(1, "lowerThresholdFunction");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("This parameter characterizes the Rician noise in the original DWI") +
                              std::string("images.  Van Hecke uses the noise-estimation method of Sijbers et ") +
                              std::string("al. \"Automatic estimation of the noise variance from the ") +
                              std::string("histogram of a magnetic resonance image\", Phys. Med. Biol. ") +
                              std::string("52:1335-1348, 2007.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("noise-sigma");
    option->SetShortName('n');
    option->SetUsageOption(0, "<noiseSigma=18>");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("The user can specify the simulated pathology in a given ") +
                              std::string("area using a label mask. If no label is prepended to ") +
                              std::string("parameters, the specified parameters are applied to all labels.") +
                              std::string("Pathology is simulated by changing the eigenvalues. Typically ") +
                              std::string("this involves a decrease in the largest eigenvalue and an ") +
                              std::string("increase in the average of the remaining eigenvalues. ") +
                              std::string("Change is specified as a proportion of the current eigenvalues. ") +
                              std::string("However, care is taken ") +
                              std::string("to ensure that diffusion direction does not change. ") +
                              std::string("Additionally, one can specify the number of voxels affected ") +
                              std::string("in each region or one can specify the proportion of voxels ") +
                              std::string("affected.  Default is to change all voxels.  Note that the ") +
                              std::string("proportions must be specified in the range [0,1]. For ") +
                              std::string("dimension=3 where the average transverse diffusion eigenvalues ") +
                              std::string("are altered, this change is propagated to the distinct eigenvalues ") +
                              std::string("by forcing the ratio to be the same before the change. ");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("pathology");
    option->SetUsageOption(0,
                           "label[<propChangeEig1=-0.05>,<propChangeAvgEig2andEig3=0.05>,<numberOfVoxels="
                           "all or propOfVoxels>]");
    option->SetShortName('p');
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("This option specifies the parameters of the output ") +
                              std::string("diffusion-weighted images including the directions and ") +
                              std::string("b-values.  The directions are specified using a direction ") +
                              std::string("file which has as its first line the number of directions.") +
                              std::string("Each successive three lines contains the x, y, and z ") +
                              std::string("directions, respectively, and a single b-value. ") +
                              std::string("Note that several direction files of this format are ") +
                              std::string("distributed with the Camino DTI toolkit ") +
                              std::string("(http://web4.cs.ucl.ac.uk/research/medic/camino/pmwiki/pmwiki.php).  ") +
                              std::string("Alternatively, one can specify a scheme file where each direction ") +
                              std::string("is specified followed by a b-value for that direction, i.e. ") +
                              std::string("<x1> <y1> <z1> <bvalue1> ... <xN><yN><zN><bvalueN>.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("dwi-parameters");
    option->SetShortName('w');
    option->SetUsageOption(0, "[B0Image,directionFile,bvalue]");
    option->SetUsageOption(1, "[B0Image,schemeFile]");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("If one wants to introduce inter-subject variability") +
                              std::string("a registered DTI population to the DTI atlas is ") +
                              std::string("required.  This variability is modeled by a PCA ") +
                              std::string("decomposition on a combination of the first eigenvalue ") +
                              std::string("image and the average of the second and third eigenvalues.") +
                              std::string("The registered image file names are specified using ") +
                              std::string("a text file ") +
                              std::string("where each line is the name of an individual DTI.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("registered-population");
    option->SetShortName('r');
    option->SetUsageOption(0, "textFileWithFileNames.txt");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("The output consists of a set of diffusion-weighted images ") +
                              std::string("for each subject.  Each file name is prepended with the ") +
                              std::string("word 'Control' or 'Experimental'.  The number of control ") +
                              std::string("and experimental subjects can be also be specified on the ") +
                              std::string("command line.  Default is 10 for each group.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("output");
    option->SetShortName('o');
    option->SetUsageOption(0,
                           "[outputDirectory,fileNameSeriesRootName,<numberOfControls=10>,<numberOfExperimentals=10>]");
    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);
    option->AddFunction(std::string("0"));
    parser->AddOption(option);
  }

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

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

// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int
CreateDTICohort(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(), "CreateDTICohort");

  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 );

  itk::ants::CommandLineParser::Pointer parser = itk::ants::CommandLineParser::New();

  parser->SetCommand(argv[0]);

  std::string commandDescription = std::string("CreateDTICohort implements the work of Van Hecke et al. (") +
                                   std::string("On the construction of a ground truth framework for ") +
                                   std::string("evaluating voxl-based diffusion tensor MRI analysis ") +
                                   std::string("methods, Neuroimage 46:692-707, 2009) to create ") +
                                   std::string("simulated DTI data sets.  The only ") +
                                   std::string("difference is that all registrations (both for the input ") +
                                   std::string("population and for the output population) are assumed to ") +
                                   std::string("take place outside of this program.");

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

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

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

  // Get dimensionality
  unsigned int dimension = 3;

  itk::ants::CommandLineParser::OptionType::Pointer dimOption = parser->GetOption("image-dimensionality");
  if (dimOption && dimOption->GetNumberOfFunctions())
  {
    dimension = parser->Convert<unsigned int>(dimOption->GetFunction()->GetName());
  }
  else
  {
    // Read in the first intensity image to get the image dimension.
    std::string filename;

    itk::ants::CommandLineParser::OptionType::Pointer imageOption = parser->GetOption("dti-atlas");
    if (imageOption && imageOption->GetNumberOfFunctions())
    {
      if (imageOption->GetFunction(0)->GetNumberOfParameters() > 0)
      {
        filename = imageOption->GetFunction(0)->GetParameter(0);
      }
      else
      {
        filename = imageOption->GetFunction(0)->GetName();
      }
    }
    else
    {
      std::cout << "No input atlas was specified.  Specify a dti atlas"
                << " with the -a option" << std::endl;
      return EXIT_FAILURE;
    }
    itk::ImageIOBase::Pointer imageIO =
      itk::ImageIOFactory::CreateImageIO(filename.c_str(), itk::IOFileModeEnum::ReadMode);
    dimension = imageIO->GetNumberOfDimensions();
  }

  std::cout << std::endl << "Creating DTI cohort for " << dimension << "-dimensional images." << std::endl << std::endl;

  switch (dimension)
  {
    case 2:
    {
      return CreateDTICohort<2>(parser);
    }
    break;
    case 3:
    {
      return CreateDTICohort<3>(parser);
    }
    break;
    default:
      std::cout << "Unsupported dimension" << std::endl;
      return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
} // namespace ants