-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComputeBValue.cpp
More file actions
executable file
·2231 lines (1643 loc) · 74 KB
/
ComputeBValue.cpp
File metadata and controls
executable file
·2231 lines (1643 loc) · 74 KB
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
/*-
* Copyright (c) 2018 Nathan Lay (enslay@gmail.com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*-
* Nathan Lay
* Imaging Biomarkers and Computer-Aided Diagnosis Laboratory
* National Institutes of Health
* March 2017
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdlib>
#include <cctype>
#include <memory>
#include <iostream>
#include <map>
#include <unordered_map>
#include <vector>
#include <string>
#include <utility>
#include "Common.h"
#include "ADVar.h"
#include "strcasestr.h"
#include "bsdgetopt.h"
// ITK stuff
#include "itkGDCMImageIO.h"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include "itkRGBPixel.h"
#include "itkRGBAPixel.h"
// VNL stuff
#include "vnl/vnl_cost_function.h"
#include "vnl/vnl_vector.h"
#include "vnl/vnl_cross.h"
#include "vnl/algo/vnl_lbfgsb.h"
#include "vnl/algo/vnl_cholesky.h"
void Usage(const char *p_cArg0) {
std::cerr << "Usage: " << p_cArg0 << " [-achkp] [-o outputPath] [-n seriesNumber] [-s BValueScaleFactor] [-A ADCImageFolder|ADCImageFile] [-I initialBValue] -b targetBValue mono|ivim|dk|dkivim diffusionFolder1|diffusionFile1[:bvalue] [diffusionFolder2|diffusionFile2[:bvalue] ...]" << std::endl;
std::cerr << "\nOptions:" << std::endl;
std::cerr << "-a -- Save calculated ADC. The output path will have _ADC appended (folder --> folder_ADC or file.ext --> file_ADC.ext)." << std::endl;
std::cerr << "-b -- Target b-value to calculate." << std::endl;
std::cerr << "-c -- Compress output." << std::endl;
std::cerr << "-h -- This help message." << std::endl;
std::cerr << "-k -- Save calculated kurtosis image. The output path will have _Kurtosis appended." << std::endl;
std::cerr << "-n -- Series number for calculated b-value image (default 13701)." << std::endl;
std::cerr << "-o -- Output path which may be a folder for DICOM output or a medical image format file." << std::endl;
std::cerr << "-p -- Save calculated perfusion fraction image. The output path will have _Perfusion appended." << std::endl;
std::cerr << "-s -- Scale factor of target b-value image intensities (default 1.0)." << std::endl;
std::cerr << "-A -- Load an existing ADC image to use for computing a b-value image." << std::endl;
std::cerr << "-I -- Initial expected b-value in a diffusion series of unknown b-values (default 0)." << std::endl;
exit(1);
}
// Process path/to/file:bvalue hint
std::pair<std::string, double> GetBValueHint(const std::string &strPath);
// Change name from ComputeDiffusionBValue* to GetDiffusionBValue* (since this program actually calculates B value images!)
double GetDiffusionBValue(const itk::MetaDataDictionary &clDicomTags);
double GetDiffusionBValueSiemens(const itk::MetaDataDictionary &clDicomTags);
double GetDiffusionBValueGE(const itk::MetaDataDictionary &clDicomTags);
double GetDiffusionBValueProstateX(const itk::MetaDataDictionary &clDicomTags); // Same as Skyra and Verio (and many others I can't remember)
double GetDiffusionBValuePhilips(const itk::MetaDataDictionary &clDicomTags);
std::map<double, std::vector<std::string>> ComputeBValueFileNames(const std::string &strPath, const std::string &strSeriesUID = std::string());
// BValue files but with unknown bvalues!
std::vector<std::vector<std::string>> ComputeUnknownBValueFileNames(const std::string &strPath, const std::string &strSeriesUID = std::string());
template<typename PixelType>
std::vector<typename itk::Image<PixelType, 3>::Pointer> LoadBValueImages(const std::string &strPath, const std::string &strSeriesUID = std::string());
template<typename PixelType>
std::map<double, typename itk::Image<PixelType, 3>::Pointer> ResolveBValueImages(std::vector<typename itk::Image<PixelType, 3>::Pointer> &vImages, itk::Image<short, 3>::Pointer p_clADCImage, double dInitialBValue = 0.0);
template<typename PixelType>
void Uninvert(itk::Image<PixelType, 3> *p_clBValueImage);
class BValueModel : public vnl_cost_function {
public:
typedef BValueModel SelfType;
typedef itk::Image<short, 3> ImageType;
typedef std::map<double, ImageType::Pointer> ImageMapType;
typedef vnl_lbfgsb SolverType;
virtual ~BValueModel() = default;
virtual std::string Name() const = 0;
virtual bool Good() const {
if (GetTargetBValue() < 0.0 || m_mImagesByBValue.empty())
return false;
auto itr = GetImages().begin();
auto prevItr = itr++;
if (prevItr->first < 0.0 || !prevItr->second)
return false;
while (itr != GetImages().end()) {
if (!itr->second || itr->second->GetBufferedRegion() != prevItr->second->GetBufferedRegion())
return false;
prevItr = itr++;
}
return true;
}
// Returns true if the model supports calculating this image
virtual bool SaveADC() { return false; }
virtual bool SavePerfusion() { return false; }
virtual bool SaveKurtosis() { return false; }
void SetCompress(bool bCompress) { m_bCompress = bCompress; }
bool GetCompress() const { return m_bCompress; }
void SetOutputPath(const std::string &strOutputPath) {
m_strOutputPath = strOutputPath;
}
const std::string & GetOutputPath() const { return m_strOutputPath; }
std::string GetOutputPathWithPrefix(const std::string &strPrefix) const {
const std::string strExtension = GetExtension(GetOutputPath());
if (strExtension.empty())
return StripTrailingDelimiters(GetOutputPath()) + strPrefix;
return StripExtension(GetOutputPath()) + strPrefix + strExtension;
}
std::string GetADCOutputPath() const { return GetOutputPathWithPrefix("_ADC"); }
std::string GetPerfusionOutputPath() const { return GetOutputPathWithPrefix("_Perfusion"); }
std::string GetKurtosisOutputPath() const { return GetOutputPathWithPrefix("_Kurtosis"); }
virtual bool SetImages(const ImageMapType &mImagesByBValue) {
m_mImagesByBValue = mImagesByBValue;
return m_mImagesByBValue.size() > 0;
}
const ImageMapType & GetImages() const { return m_mImagesByBValue; }
// These are for a given input ADC image (not computed one).
virtual bool SetADCImage(ImageType *p_clRawADCImage) { return false; } // Option not supported by default
virtual ImageType::Pointer GetADCImage() const { return ImageType::Pointer(); } // Option not supported by default
void SetTargetBValue(double dTargetBValue) { m_dTargetBValue = dTargetBValue; }
double GetTargetBValue() const { return m_dTargetBValue; }
void SetBValueScale(double dScale) { m_dScale = dScale; }
double GetBValueScale() const { return m_dScale; }
void SetSeriesNumber(int iSeriesNumber) { m_iSeriesNumber = iSeriesNumber; }
int GetSeriesNumber() const { return m_iSeriesNumber; }
int GetADCSeriesNumber() const { return GetSeriesNumber()+1; }
int GetPerfusionSeriesNumber() const { return GetSeriesNumber()+2; }
int GetKurtosisSeriesNumber() const { return GetSeriesNumber()+3; }
virtual bool Run();
virtual bool SaveImages() const;
ImageType::Pointer GetOutputBValueImage() const { return m_p_clBValueImage; }
protected:
BValueModel(int iNumberOfUnknowns)
: vnl_cost_function(iNumberOfUnknowns), m_clSolver(*this) { }
template<typename PixelType>
typename itk::Image<PixelType, 3>::Pointer NewImage() const;
// If needed, use the MonoExponentialModel to compute B0 and append it to the image map
virtual bool ComputeB0Image();
template<typename PixelType>
bool SaveImage(typename itk::Image<PixelType, 3>::Pointer p_clImage, const std::string &strPath, int iSeriesNumber, const std::string &strSeriesDescription) const;
// ADC is normally stored in DICOM and other medical image formats as short... but we store it in float inernally. This just cuts down on some code...
bool SaveADCImage(itk::Image<float, 3>::Pointer p_clADCImage, const std::string &strPath, int iSeriesNumber, const std::string &strSeriesDescription) const;
virtual double Solve(const itk::Index<3> &clIndex) = 0; // Return b-value or negative value for failure
virtual bool SetLogIntensities(const itk::Index<3> &clIndex);
double MinBValue() const {
if (GetImages().empty())
return -1.0;
return GetImages().begin()->first;
}
double MaxBValue() const {
if (GetImages().empty())
return -1.0;
return GetImages().rbegin()->first;
}
// Stupid Microsoft has a GetBValue macro
ImageType::Pointer GetBValueImage(double dBValue) const {
auto itr = GetImages().find(dBValue);
return itr != GetImages().end() ? itr->second : ImageType::Pointer();
}
const std::vector<std::pair<double, double>> & GetLogIntensities() const { return m_vBValueAndLogIntensity; }
SolverType & GetSolver() { return m_clSolver; }
private:
SolverType m_clSolver;
ImageMapType m_mImagesByBValue;
ImageType::Pointer m_p_clBValueImage;
std::string m_strOutputPath;
double m_dTargetBValue = -1.0;
std::vector<std::pair<double, double>> m_vBValueAndLogIntensity;
int m_iSeriesNumber = 13701;
bool m_bCompress = false;
double m_dScale = 1.0;
};
class MonoExponentialModel : public BValueModel {
public:
typedef BValueModel SuperType;
typedef itk::Image<float, 3> FloatImageType;
typedef ADVar<double, 2> ADVarType;
MonoExponentialModel()
: SuperType(ADVarType::GetNumIndependents()) { }
virtual ~MonoExponentialModel() = default;
virtual std::string Name() const override { return "Mono Exponential"; }
virtual bool Good() const override {
if (!SuperType::Good())
return false;
if (!m_p_clInputADCImage)
return GetImages().size() > 1;
return m_p_clInputADCImage->GetBufferedRegion() == GetImages().begin()->second->GetBufferedRegion();
}
virtual bool SetADCImage(ImageType *p_clInputADCImage) override {
m_p_clInputADCImage = p_clInputADCImage;
return true;
}
virtual ImageType::Pointer GetADCImage() const override { return m_p_clInputADCImage; }
virtual bool SaveADC() override { return m_bSaveADC = true; }
virtual bool Run() override;
virtual bool SaveImages() const override;
// Since we use automatic differentiation, let's do both operations simultaneously...
virtual void compute(const vnl_vector<double> &clX, double *p_dF, vnl_vector<double> *p_clG) override;
FloatImageType::Pointer GetOutputADCImage() const { return m_p_clADCImage; }
protected:
virtual double Solve(const itk::Index<3> &clIndex) override;
private:
bool m_bSaveADC = false;
ImageType::Pointer m_p_clTargetBValueImage; // In case we already have it
FloatImageType::Pointer m_p_clADCImage;
ImageType::Pointer m_p_clInputADCImage;
};
class IVIMModel : public BValueModel {
public:
typedef BValueModel SuperType;
typedef ADVar<double, 3> ADVarType;
typedef itk::Image<float, 3> FloatImageType;
IVIMModel()
: SuperType(ADVarType::GetNumIndependents()) { }
virtual ~IVIMModel() = default;
virtual std::string Name() const override { return "IVIM"; }
virtual bool Good() const override {
if (!SuperType::Good())
return false;
if (!m_p_clInputADCImage)
return GetImages().size() > 1;
return m_p_clInputADCImage->GetBufferedRegion() == GetImages().begin()->second->GetBufferedRegion();
}
virtual bool SetADCImage(ImageType *p_clRawADCImage) override {
m_p_clInputADCImage = p_clRawADCImage;
return true;
}
virtual ImageType::Pointer GetADCImage() const override { return m_p_clInputADCImage; }
virtual bool SaveADC() override { return m_bSaveADC = true; }
virtual bool SavePerfusion() override { return m_bSavePerfusion = true; }
virtual bool Run() override;
virtual bool SaveImages() const override;
// Since we use automatic differentiation, let's do both operations simultaneously...
virtual void compute(const vnl_vector<double> &clX, double *p_dF, vnl_vector<double> *p_clG) override;
FloatImageType::Pointer GetOutputADCImage() const { return m_p_clADCImage; }
FloatImageType::Pointer GetOutputPerfusionImage() const { return m_p_clPerfusionImage; }
protected:
virtual double Solve(const itk::Index<3> &clIndex) override;
private:
bool m_bSaveADC = false;
bool m_bSavePerfusion = false;
ImageType::Pointer m_p_clTargetBValueImage; // In case we already have it
FloatImageType::Pointer m_p_clADCImage;
FloatImageType::Pointer m_p_clPerfusionImage;
ImageType::Pointer m_p_clInputADCImage;
};
class DKModel : public BValueModel {
public:
typedef BValueModel SuperType;
typedef ADVar<double, 3> ADVarType;
typedef itk::Image<float, 3> FloatImageType;
DKModel()
: SuperType(ADVarType::GetNumIndependents()) { }
virtual ~DKModel() = default;
virtual std::string Name() const override { return "DK"; }
virtual bool Good() const override {
if (!SuperType::Good())
return false;
if (!m_p_clInputADCImage)
return GetImages().size() > 1;
return m_p_clInputADCImage->GetBufferedRegion() == GetImages().begin()->second->GetBufferedRegion();
}
virtual bool SetADCImage(ImageType *p_clRawADCImage) override {
m_p_clInputADCImage = p_clRawADCImage;
return true;
}
virtual ImageType::Pointer GetADCImage() const override { return m_p_clInputADCImage; }
virtual bool SaveADC() override { return m_bSaveADC = true; }
virtual bool SaveKurtosis() override { return m_bSaveKurtosis = true; }
virtual bool Run() override;
virtual bool SaveImages() const override;
// Since we use automatic differentiation, let's do both operations simultaneously...
virtual void compute(const vnl_vector<double> &clX, double *p_dF, vnl_vector<double> *p_clG) override;
FloatImageType::Pointer GetOutputADCImage() const { return m_p_clADCImage; }
FloatImageType::Pointer GetOutputKurtosisImage() const { return m_p_clKurtosisImage; }
protected:
virtual double Solve(const itk::Index<3> &clIndex) override;
private:
bool m_bSaveADC = false;
bool m_bSaveKurtosis = false;
ImageType::Pointer m_p_clTargetBValueImage; // In case we already have it
FloatImageType::Pointer m_p_clADCImage;
FloatImageType::Pointer m_p_clKurtosisImage;
ImageType::Pointer m_p_clInputADCImage;
};
class DKIVIMModel : public BValueModel {
public:
typedef BValueModel SuperType;
typedef ADVar<double, 4> ADVarType;
typedef itk::Image<float, 3> FloatImageType;
DKIVIMModel()
: SuperType(ADVarType::GetNumIndependents()) { }
virtual ~DKIVIMModel() = default;
virtual std::string Name() const override { return "DK+IVIM"; }
virtual bool Good() const override {
if (!SuperType::Good())
return false;
if (!m_p_clInputADCImage)
return GetImages().size() > 1;
return m_p_clInputADCImage->GetBufferedRegion() == GetImages().begin()->second->GetBufferedRegion();
}
virtual bool SetADCImage(ImageType *p_clRawADCImage) override {
m_p_clInputADCImage = p_clRawADCImage;
return true;
}
virtual ImageType::Pointer GetADCImage() const override { return m_p_clInputADCImage; }
virtual bool SaveADC() override { return m_bSaveADC = true; }
virtual bool SavePerfusion() override { return m_bSavePerfusion = true; }
virtual bool SaveKurtosis() override { return m_bSaveKurtosis = true; }
virtual bool Run() override;
virtual bool SaveImages() const override;
// Since we use automatic differentiation, let's do both operations simultaneously...
virtual void compute(const vnl_vector<double> &clX, double *p_dF, vnl_vector<double> *p_clG) override;
FloatImageType::Pointer GetOutputADCImage() const { return m_p_clADCImage; }
FloatImageType::Pointer GetOutputKurtosisImage() const { return m_p_clKurtosisImage; }
FloatImageType::Pointer GetOutputPerfusionImage() const { return m_p_clPerfusionImage; }
protected:
virtual double Solve(const itk::Index<3> &clIndex) override;
private:
bool m_bSaveADC = false;
bool m_bSavePerfusion = false;
bool m_bSaveKurtosis = false;
ImageType::Pointer m_p_clTargetBValueImage; // In case we already have it
FloatImageType::Pointer m_p_clADCImage;
FloatImageType::Pointer m_p_clPerfusionImage;
FloatImageType::Pointer m_p_clKurtosisImage;
ImageType::Pointer m_p_clInputADCImage;
};
int main(int argc, char **argv) {
const char * const p_cArg0 = argv[0];
bool bSaveADC = false;
bool bSavePerfusion = false;
bool bSaveKurtosis = false;
int iSeriesNumber = 13701;
bool bCompress = false;
double dLambda = 0.0;
double dBValue = -1.0;
double dBValueScale = 1.0;
double dInitialBValue = 0.0;
std::string strADCImagePath;
std::string strOutputPath = "output.mha";
int c = 0;
while ((c = getopt(argc, argv, "ab:chkn:o:ps:A:I:")) != -1) {
switch (c) {
case 'a':
bSaveADC = true;
break;
case 'b':
dBValue = FromString<double>(optarg, -1.0);
if (dBValue < 0.0)
Usage(p_cArg0);
break;
case 'c':
bCompress = true;
break;
case 'h':
Usage(p_cArg0);
break;
case 'k':
bSaveKurtosis = true;
break;
case 'o':
strOutputPath = optarg;
break;
case 'n':
iSeriesNumber = FromString<int>(optarg, -1); // Nobody will pick a negative series number...
if (iSeriesNumber < 0)
Usage(p_cArg0);
break;
case 'p':
bSavePerfusion = true;
break;
case 's':
dBValueScale = FromString<double>(optarg, -1.0);
if (dBValueScale <= 0.0)
Usage(p_cArg0);
break;
case 'A':
strADCImagePath = optarg;
break;
case 'I':
dInitialBValue = FromString<double>(optarg, -1.0);
if (dInitialBValue < 0.0)
Usage(p_cArg0);
break;
case '?':
default:
Usage(p_cArg0);
}
}
argc -= optind;
argv += optind;
if (argc < 2 || dBValue < 0.0)
Usage(p_cArg0);
std::string strModel = argv[0];
std::unique_ptr<BValueModel> p_clModel;
if (strModel == "mono") {
p_clModel = std::make_unique<MonoExponentialModel>();
}
else if (strModel == "ivim") {
p_clModel = std::make_unique<IVIMModel>();
}
else if (strModel == "dk") {
p_clModel = std::make_unique<DKModel>();
}
else if (strModel == "dkivim") {
p_clModel = std::make_unique<DKIVIMModel>();
}
else {
std::cerr << "Error: Unknown model type '" << strModel << "'.\n" << std::endl;
Usage(p_cArg0);
}
typedef itk::Image<short, 3> ImageType;
ImageType::Pointer p_clADCImage;
if (strADCImagePath.size() > 0) {
if (IsFolder(strADCImagePath))
p_clADCImage = LoadDicomImage<ImageType::PixelType, 3>(strADCImagePath);
else
p_clADCImage = LoadImg<ImageType::PixelType, 3>(strADCImagePath);
if (!p_clADCImage) {
std::cerr << "Error: Could not load ADC image '" << strADCImagePath << "'." << std::endl;
return -1;
}
std::cout << "Info: Loaded ADC image." << std::endl;
if (!p_clModel->SetADCImage(p_clADCImage))
std::cerr << "Warning: '" << strModel << "' model does not support using existing ADC image." << std::endl;
}
std::vector<ImageType::Pointer> vImages;
for (int i = 1; i < argc; ++i) {
std::vector<ImageType::Pointer> vTmp = LoadBValueImages<ImageType::PixelType>(argv[i]);
vImages.insert(vImages.end(), vTmp.begin(), vTmp.end());
}
std::map<double, ImageType::Pointer> mImagesByBValue = ResolveBValueImages<ImageType::PixelType>(vImages, p_clADCImage, dInitialBValue);
for (const auto &stPair : mImagesByBValue)
std::cout << "Info: Loaded b = " << stPair.first << std::endl;
p_clModel->SetTargetBValue(dBValue);
p_clModel->SetImages(mImagesByBValue);
p_clModel->SetOutputPath(strOutputPath);
p_clModel->SetSeriesNumber(iSeriesNumber);
p_clModel->SetCompress(bCompress);
p_clModel->SetBValueScale(dBValueScale);
if (bSaveADC && !p_clModel->SaveADC())
std::cerr << "Warning: '" << strModel << "' model does not support saving ADC images." << std::endl;
if (bSavePerfusion && !p_clModel->SavePerfusion())
std::cerr << "Warning: '" << strModel << "' model does not support saving perfusion fraction images." << std::endl;
if (bSaveKurtosis && !p_clModel->SaveKurtosis())
std::cerr << "Warning: '" << strModel << "' model does not support saving kurtosis images." << std::endl;
std::cout << "Info: Calculating b-" << dBValue << std::endl;
if (!p_clModel->Run()) {
std::cerr << "Error: Failed to compute b-value image." << std::endl;
return -1;
}
if (!p_clModel->SaveImages()) {
std::cerr << "Error: Failed to save output images." << std::endl;
return -1;
}
return 0;
}
std::pair<std::string, double> GetBValueHint(const std::string &strPath) {
size_t p = strPath.find_last_of(':');
if (p == std::string::npos || p+1 >= strPath.size())
return std::make_pair(strPath, -1.0); // Negative value indicates no bvalue hint
char *q = nullptr;
const std::string strTmp = strPath.substr(p+1);
const double dBValue = std::strtod(strTmp.c_str(), &q);
if (*q != '\0' || dBValue < 0.0)
return std::make_pair(strPath, -1.0); // Negative value indicates no bvalue hint
return std::make_pair(strPath.substr(0,p), dBValue);
}
double GetDiffusionBValue(const itk::MetaDataDictionary &clDicomTags) {
double dBValue = -1.0;
if (ExposeStringMetaData(clDicomTags, "0018|9087", dBValue))
return dBValue;
std::string strPatientName;
std::string strPatientId;
std::string strManufacturer;
ExposeStringMetaData(clDicomTags, "0010|0010", strPatientName);
ExposeStringMetaData(clDicomTags, "0010|0020", strPatientId);
if (strcasestr(strPatientName.c_str(), "prostatex") != nullptr || strcasestr(strPatientId.c_str(), "prostatex") != nullptr)
return GetDiffusionBValueProstateX(clDicomTags);
if (!ExposeStringMetaData(clDicomTags, "0008|0070", strManufacturer)) {
std::cerr << "Error: Could not determine manufacturer." << std::endl;
return -1.0;
}
if (strcasestr(strManufacturer.c_str(), "siemens") != nullptr)
return GetDiffusionBValueSiemens(clDicomTags);
else if (strcasestr(strManufacturer.c_str(), "ge") != nullptr)
return GetDiffusionBValueGE(clDicomTags);
else if (strcasestr(strManufacturer.c_str(), "philips") != nullptr)
return GetDiffusionBValuePhilips(clDicomTags);
return -1.0;
}
double GetDiffusionBValueSiemens(const itk::MetaDataDictionary &clDicomTags) {
std::string strModel;
if (itk::ExposeMetaData(clDicomTags, "0008|1090", strModel)) {
if ((strcasestr(strModel.c_str(), "skyra") != nullptr || strcasestr(strModel.c_str(), "verio") != nullptr)) {
double dBValue = GetDiffusionBValueProstateX(clDicomTags);
if (dBValue >= 0.0)
return dBValue;
}
}
gdcm::CSAHeader clCSAHeader;
if (!ExposeStringMetaData(clDicomTags, "0029|1010", clCSAHeader)) // Nothing to do
return -1.0;
std::string strTmp;
if (ExposeCSAMetaData(clCSAHeader, "B_value", strTmp))
return FromString(strTmp, -1.0);
return -1.0;
}
double GetDiffusionBValueGE(const itk::MetaDataDictionary &clDicomTags) {
std::string strValue;
if (!ExposeStringMetaData(clDicomTags, "0043|1039", strValue))
return -1.0; // Nothing to do
size_t p = strValue.find('\\');
if (p == std::string::npos)
return -1.0; // Not sure what to do
strValue.erase(p);
std::stringstream valueStream;
valueStream.str(strValue);
double dValue = 0.0;
if (!(valueStream >> dValue) || dValue < 0.0) // Bogus value
return -1.0;
// Something is screwed up here ... let's try to remove the largest significant digit
if (dValue > 4000.0) {
p = strValue.find_first_not_of(" \t0");
strValue.erase(strValue.begin(), strValue.begin()+p+1);
valueStream.clear();
valueStream.str(strValue);
if (!(valueStream >> dValue) || dValue < 0.0 || dValue > 4000.0)
return -1.0;
}
return std::floor(dValue);
}
double GetDiffusionBValueProstateX(const itk::MetaDataDictionary &clDicomTags) {
std::string strSequenceName;
if (!ExposeStringMetaData(clDicomTags, "0018|0024", strSequenceName)) {
std::cerr << "Error: Could not extract sequence name (0018,0024)." << std::endl;
return -1.0;
}
Trim(strSequenceName);
if (strSequenceName.empty()) {
std::cerr << "Error: Empty sequence name (0018,0024)." << std::endl;
return -1.0;
}
std::stringstream valueStream;
unsigned int uiBValue = 0;
size_t i = 0, j = 0;
while (i < strSequenceName.size()) {
i = strSequenceName.find('b', i);
if (i == std::string::npos || ++i >= strSequenceName.size())
break;
j = strSequenceName.find_first_not_of("0123456789", i);
// Should end with a 't' or a '\0'
if (j == std::string::npos)
j = strSequenceName.size();
else if (strSequenceName[j] != 't')
break;
if (j > i) {
std::string strBValue = strSequenceName.substr(i, j-i);
valueStream.clear();
valueStream.str(strBValue);
uiBValue = 0;
if (valueStream >> uiBValue) {
if (uiBValue < 4000)
return (double)uiBValue;
else
std::cerr << "Error: B-value of " << uiBValue << " seems bogus. Continuing to parse." << std::endl;
}
}
i = j;
}
std::cerr << "Error: Could not parse sequence name '" << strSequenceName << "'." << std::endl;
return -1.0;
}
double GetDiffusionBValuePhilips(const itk::MetaDataDictionary &clDicomTags) {
double dBValue = -1.0;
if (!ExposeStringMetaData(clDicomTags, "2001|1003", dBValue))
return -1.0;
return dBValue;
}
std::map<double, std::vector<std::string>> ComputeBValueFileNames(const std::string &strPath, const std::string &strSeriesUID) {
typedef std::map<double, std::vector<std::string>> MapType;
typedef itk::GDCMImageIO ImageIOType;
typedef itk::GDCMSeriesFileNames FileNameGeneratorType;
ImageIOType::Pointer p_clImageIO = ImageIOType::New();
p_clImageIO->LoadPrivateTagsOn();
p_clImageIO->KeepOriginalUIDOn();
if (!IsFolder(strPath.c_str())) {
// Get the series UID of the file
p_clImageIO->SetFileName(strPath);
try {
p_clImageIO->ReadImageInformation();
}
catch (itk::ExceptionObject &e) {
std::cerr << "Error: " << e << std::endl;
return MapType();
}
std::string strTmpSeriesUID;
if (!itk::ExposeMetaData(p_clImageIO->GetMetaDataDictionary(), "0020|000e", strTmpSeriesUID)) {
std::cerr << "Error: Could not load series UID from DICOM." << std::endl;
return MapType();
}
Trim(strTmpSeriesUID);
if (GetDiffusionBValue(p_clImageIO->GetMetaDataDictionary()) < 0.0) {
std::cerr << "Error: Image does not appear to be a diffusion image." << std::endl;
return MapType();
}
return ComputeBValueFileNames(DirName(strPath), strTmpSeriesUID);
}
FileNameGeneratorType::Pointer p_clFileNameGenerator = FileNameGeneratorType::New();
// Use the ACTUAL series UID ... not some custom ITK concatenations of lots of junk.
p_clFileNameGenerator->SetUseSeriesDetails(false);
p_clFileNameGenerator->SetDirectory(strPath);
if (strSeriesUID.empty()) {
// Passed a folder but no series UID ... pick the first series UID
const FileNameGeneratorType::SeriesUIDContainerType &vSeriesUIDs = p_clFileNameGenerator->GetSeriesUIDs();
if (vSeriesUIDs.empty())
return MapType();
return ComputeBValueFileNames(strPath, vSeriesUIDs[0]);
}
// These should be ordered by Z coordinate (they're not)
const FileNameGeneratorType::FileNamesContainerType &vDicomFiles = p_clFileNameGenerator->GetFileNames(strSeriesUID);
if (vDicomFiles.empty())
return MapType();
MapType mFilesByBValue;
typedef std::pair<std::string, itk::MetaDataDictionary> FileAndDictionaryPair;
std::unordered_map<double, std::vector<FileAndDictionaryPair>> mFilesAndDictionariesByBValue;
for (const std::string &strFileName : vDicomFiles) {
p_clImageIO->SetFileName(strFileName);
try {
p_clImageIO->ReadImageInformation();
}
catch (itk::ExceptionObject &e) {
std::cerr << "Error: " << e << std::endl;
return MapType();
}
const double dBValue = GetDiffusionBValue(p_clImageIO->GetMetaDataDictionary());
if (dBValue < 0.0) {
std::cerr << "Error: Could not extract diffusion b-value for '" << strFileName << "'." << std::endl;
return MapType();
}
mFilesAndDictionariesByBValue[dBValue].emplace_back(strFileName, p_clImageIO->GetMetaDataDictionary());
}
vnl_matrix_fixed<double, 3, 3> clR; // Assume this is the same for all slices
if (!GetOrientationMatrix(p_clImageIO->GetMetaDataDictionary(), clR)) {
std::cerr << "Error: Could not get orientation matrix." << std::endl;
return MapType();
}
auto fnCompareByPosition = [&clR](const FileAndDictionaryPair &a, const FileAndDictionaryPair &b) -> bool {
vnl_vector_fixed<double, 3> clTa, clTb;
// XXX: Could fail, but shouldn't!!!!
GetOrigin(a.second, clTa);
GetOrigin(b.second, clTb);
return (clR.transpose()*(clTa - clTb))[2] < 0.0;
};
// Sort by position
for (auto &stBValueAndFilesPair : mFilesAndDictionariesByBValue) {
const double &dBValue = stBValueAndFilesPair.first;
std::vector<FileAndDictionaryPair> &vFilesAndDictionaries = stBValueAndFilesPair.second;
std::sort(vFilesAndDictionaries.begin(), vFilesAndDictionaries.end(), fnCompareByPosition);
std::vector<std::string> &vFileNames = mFilesByBValue[dBValue];
vFileNames.resize(vFilesAndDictionaries.size());
std::transform(vFilesAndDictionaries.begin(), vFilesAndDictionaries.end(), vFileNames.begin(),
[](const FileAndDictionaryPair &stPair) -> const std::string & {
return stPair.first;
});
}
return mFilesByBValue;
}
std::vector<std::vector<std::string>> ComputeUnknownBValueFileNames(const std::string &strPath, const std::string &strSeriesUID) {
typedef itk::GDCMImageIO ImageIOType;
typedef itk::GDCMSeriesFileNames FileNameGeneratorType;
typedef itk::Image<short, 2> ImageType;
typedef itk::ImageFileReader<ImageType> ReaderType;
ImageIOType::Pointer p_clImageIO = ImageIOType::New();
p_clImageIO->LoadPrivateTagsOn();
p_clImageIO->KeepOriginalUIDOn();
if (!IsFolder(strPath.c_str())) {
// Get the series UID of the file
p_clImageIO->SetFileName(strPath);
try {
p_clImageIO->ReadImageInformation();
}
catch (itk::ExceptionObject &e) {
std::cerr << "Error: " << e << std::endl;
return std::vector<std::vector<std::string>>();
}
std::string strTmpSeriesUID;
if (!itk::ExposeMetaData(p_clImageIO->GetMetaDataDictionary(), "0020|000e", strTmpSeriesUID)) {
std::cerr << "Error: Could not load series UID from DICOM." << std::endl;
return std::vector<std::vector<std::string>>();
}
Trim(strTmpSeriesUID);
return ComputeUnknownBValueFileNames(DirName(strPath), strTmpSeriesUID);
}
FileNameGeneratorType::Pointer p_clFileNameGenerator = FileNameGeneratorType::New();
// Use the ACTUAL series UID ... not some custom ITK concatenations of lots of junk.
p_clFileNameGenerator->SetUseSeriesDetails(false);
p_clFileNameGenerator->SetDirectory(strPath);
if (strSeriesUID.empty()) {
// Passed a folder but no series UID ... pick the first series UID
const FileNameGeneratorType::SeriesUIDContainerType &vSeriesUIDs = p_clFileNameGenerator->GetSeriesUIDs();
if (vSeriesUIDs.empty())
return std::vector<std::vector<std::string>>();
return ComputeUnknownBValueFileNames(strPath, vSeriesUIDs[0]);
}
// These should be ordered by Z coordinate (they're not)
const FileNameGeneratorType::FileNamesContainerType &vDicomFiles = p_clFileNameGenerator->GetFileNames(strSeriesUID);
if (vDicomFiles.empty())
return std::vector<std::vector<std::string>>();
typedef std::pair<std::string, ImageType::Pointer> FileAndImagePair;
std::vector<FileAndImagePair> vFilesAndImages;
for (const std::string &strFileName : vDicomFiles) {
ReaderType::Pointer p_clReader = ReaderType::New();
p_clReader->SetFileName(strFileName);
p_clReader->SetImageIO(p_clImageIO);
try {
p_clReader->Update();
}
catch (itk::ExceptionObject &e) {
std::cerr << "Error: " << e << std::endl;
return std::vector<std::vector<std::string>>();
}