forked from adrienkaiser/DTIAtlasBuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScriptWriter.cxx
executable file
·1661 lines (1428 loc) · 87.8 KB
/
ScriptWriter.cxx
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
/*std classes*/
#include <iostream>
#include <string>
#include <vector>
#include <sstream> // to convert int to std::string
#include <math.h> // for the absolute value
/*itk classes*/
#include "itkImage.h"
#include "itkImageFileReader.h"
#include <itksys/SystemTools.hxx> // for GetFilenamePath()
#include "ScriptWriter.h"
std::string IntToStr(int IntVar)
{
std::ostringstream oss;
oss << IntVar;
return oss.str();
}
/////////////////////////////////////////
// SUB WRITING FUNCTIONS //
/////////////////////////////////////////
// to avoid having to write twice the same and reduce writing functions size
std::string pyTestGridProcess ( bool NoCase1 )
{
std::string Script = "\n# Function that tests if all batches have been processed on the grid\n";
if( NoCase1 )
{
Script = Script + "def TestGridProcess ( FilesFolder, NbCases , NoCase1): # if NbCases == 0, then just search the file \'file\' (unique command)\n";
Script = Script + " if NbCases>0 : print(\"\\n| Waiting for all batches (\" + str(NbCases-NoCase1) + \") to be processed on grid...\") # NoCase1 is 0 or 1\n";
}
else
{
Script = Script + "def TestGridProcess ( FilesFolder, NbCases ): # if NbCases == 0, then just search the file \'file\' (unique command)\n";
Script = Script + " if NbCases>0 : print(\"\\n| Waiting for all batches (\" + str(NbCases) + \") to be processed on grid...\")\n";
}
Script = Script + " else : print(\"\\n| Waiting for 1 batch to be processed on grid...\")\n";
Script = Script + " filesOK = 0\n";
Script = Script + " OldNbFilesOK = 0\n";
Script = Script + " while not filesOK :\n";
Script = Script + " filesOK = 1\n";
Script = Script + " if NbCases>0 :\n";
Script = Script + " NbfilesOK = 0\n";
if( NoCase1 )
{
Script = Script + " case = int(NoCase1) # NoCase1 is 0 or 1 (bool)\n";
}
else
{
Script = Script + " case = 0\n";
}
Script = Script + " while case < NbCases:\n";
Script = Script + " if not os.path.isfile( FilesFolder + \"/Case\" + str(case+1) ) : filesOK = 0\n";
Script = Script + " else : NbfilesOK = NbfilesOK + 1\n";
Script = Script + " case += 1\n";
if( NoCase1 )
{
Script = Script + " if NbfilesOK != OldNbFilesOK : print(\"| [\" + str(NbfilesOK) + \"\\t / \" + str(NbCases-NoCase1) + \" ] cases processed\")\n";
}
else
{
Script = Script + " if NbfilesOK != OldNbFilesOK : print(\"| [\" + str(NbfilesOK) + \"\\t / \" + str(NbCases) + \" ] cases processed\")\n";
}
Script = Script + " OldNbFilesOK=NbfilesOK\n";
Script = Script + " elif not os.path.isfile( FilesFolder + \"/file\" ) : filesOK = 0\n";
Script = Script + " time.sleep(60) # Test only every minute\n";
Script = Script + " print(\"\\n=> All files processed\\n\")\n";
Script = Script + " shutil.rmtree(FilesFolder) # clear directory and recreate it\n";
Script = Script + " os.mkdir(FilesFolder)\n";
return Script;
}
std::string pyCheckFileExists ()
{
std::string Script = "# Function that checks if file exist and replace old names by new names if needed\n";
Script = Script + "def CheckFileExists ( File, case, caseID ) : # returns 1 if file exists or has been renamed and 0 if not\n";
Script = Script + " if os.path.isfile( File ) : # file exists\n";
Script = Script + " return 1\n";
Script = Script + " else : # file does not exist: check if older version of file can exist (if file name has been changed)\n";
Script = Script + " NamesThatHaveChanged = [\"MeanImage\", \"DiffeomorphicDTI\", \"DiffeomorphicAtlasDTI\", \"HField\", \"GlobalDisplacementField\"] # latest versions of the names\n";
Script = Script + " if any( changedname in File for changedname in NamesThatHaveChanged ) : # if name has been changed, check if older version files exist\n";
Script = Script + " if \"MeanImage\" in File :\n";
Script = Script + " OldFile = File.replace(\"Mean\", \"Average\")\n";
Script = Script + " if os.path.isfile( OldFile ) : # old file exists: rename and return 1\n";
Script = Script + " os.rename(OldFile, File)\n";
Script = Script + " return 1\n";
Script = Script + " else:\n";
Script = Script + " return 0\n";
Script = Script + " if \"DiffeomorphicDTI\" in File :\n";
Script = Script + " OldFile = File.replace( caseID, \"Case\" + str(case+1) ).replace(\"DiffeomorphicDTI\", \"AWDTI\")\n";
Script = Script + " if os.path.isfile( OldFile ) : # old file exists: rename and return 1\n";
Script = Script + " os.rename(OldFile, File)\n";
Script = Script + " os.rename(OldFile.replace(\"AWDTI\",\"AWFA\"), File.replace(\"DiffeomorphicDTI\",\"DiffeomorphicFA\"))\n";
Script = Script + " os.rename(OldFile.replace(\"AWDTI\",\"AWDTI_float\"), File.replace(\"DiffeomorphicDTI\",\"DiffeomorphicDTI_float\"))\n";
Script = Script + " return 1\n";
Script = Script + " else : # test other old name\n";
Script = Script + " OldFile = File.replace( caseID, \"Case\" + str(case+1) )\n";
Script = Script + " if os.path.isfile( OldFile ) : # old file exists: rename and return 1\n";
Script = Script + " os.rename(OldFile, File)\n";
Script = Script + " os.rename(OldFile.replace(\"DiffeomorphicDTI\",\"DiffeomorphicFA\"), File.replace(\"DiffeomorphicDTI\",\"DiffeomorphicFA\"))\n";
Script = Script + " os.rename(OldFile.replace(\"DiffeomorphicDTI\",\"DiffeomorphicDTI_float\"), File.replace(\"DiffeomorphicDTI\",\"DiffeomorphicDTI_float\"))\n";
Script = Script + " return 1\n";
Script = Script + " else:\n";
Script = Script + " return 0\n";
Script = Script + " if \"DiffeomorphicAtlasDTI\" in File :\n";
Script = Script + " OldFile = File.replace(\"DiffeomorphicAtlasDTI\", \"AWAtlasDTI\")\n";
Script = Script + " if os.path.isfile( OldFile ) : # old file exists: rename and return 1\n";
Script = Script + " os.rename(OldFile, File)\n";
Script = Script + " os.rename(OldFile.replace(\"AWAtlasDTI\",\"AWAtlasFA\"), File.replace(\"DiffeomorphicAtlasDTI\",\"DiffeomorphicAtlasFA\"))\n";
Script = Script + " os.rename(OldFile.replace(\"AWAtlasDTI\",\"AWAtlasDTI_float\"), File.replace(\"DiffeomorphicAtlasDTI\",\"DiffeomorphicAtlasDTI_float\"))\n";
Script = Script + " return 1\n";
Script = Script + " else:\n";
Script = Script + " return 0\n";
Script = Script + " if \"HField\" in File :\n";
Script = Script + " OldFile = File.replace( caseID, \"Case\" + str(case+1) ).replace(\"H\", \"Deformation\")\n";
Script = Script + " if os.path.isfile( OldFile ) : # old file exists: rename and return 1\n";
Script = Script + " os.rename(OldFile, File)\n";
Script = Script + " return 1\n";
Script = Script + " else : # test other old name\n";
Script = Script + " OldFile = File.replace( caseID, \"Case\" + str(case+1) )\n";
Script = Script + " if os.path.isfile( OldFile ) : # old file exists: rename and return 1\n";
Script = Script + " os.rename(OldFile, File)\n";
Script = Script + " return 1\n";
Script = Script + " else:\n";
Script = Script + " return 0\n";
Script = Script + " if \"GlobalDisplacementField\" in File :\n";
Script = Script + " OldFile = File.replace( caseID, \"Case\" + str(case+1) ).replace(\"Displacement\", \"Deformation\")\n";
Script = Script + " if os.path.isfile( OldFile ) : # old file exists: rename and return 1\n";
Script = Script + " os.rename(OldFile, File)\n";
Script = Script + " return 1\n";
Script = Script + " else : # test other old name\n";
Script = Script + " OldFile = File.replace( caseID, \"Case\" + str(case+1) )\n";
Script = Script + " if os.path.isfile( OldFile ) : # old file exists: rename and return 1\n";
Script = Script + " os.rename(OldFile, File)\n";
Script = Script + " return 1\n";
Script = Script + " else:\n";
Script = Script + " return 0\n";
Script = Script + " else: # file does not exist and name has not been changed: check if the caseX version exists\n";
Script = Script + " if caseID : # CaseID is empty for averages\n";
Script = Script + " OldFile = File.replace( caseID, \"Case\" + str(case+1) )\n";
Script = Script + " if os.path.isfile( OldFile ) : # old file exists: rename and return 1\n";
Script = Script + " os.rename(OldFile, File)\n";
Script = Script + " return 1\n";
Script = Script + " else:\n";
Script = Script + " return 0\n";
Script = Script + " else: # for averages\n";
Script = Script + " return 0\n\n";
return Script;
}
std::string ScriptWriter::pyExecuteCommandPreprocessCase ( std::string NameOfFileVarToTest, std::string NameOfCmdVarToExec, std::string ErrorTxtToDisplay, std::string SpacesBeforeFirstIf )
{
std::string Script="";
if(m_Overwrite==1)
{
Script = Script + SpacesBeforeFirstIf + "if 1 :\n";
}
else
{
Script = Script + SpacesBeforeFirstIf + "if not CheckFileExists( " + NameOfFileVarToTest + ", case, allcasesIDs[case] ) :\n";
}
if( ! m_useGridProcess )
{
Script = Script + SpacesBeforeFirstIf + " if os.system(" + NameOfCmdVarToExec + ")!=0 : DisplayErrorAndQuit(\'[\' + allcasesIDs[case] + \'] " + ErrorTxtToDisplay + "\')\n";
}
else
{
Script = Script + SpacesBeforeFirstIf + " GridProcessCaseCommandsArray.append(" + NameOfCmdVarToExec + ") # Executed eventually\n";
}
Script = Script + SpacesBeforeFirstIf + "else : print(\"=> The file \\'\" + " + NameOfFileVarToTest + " + \"\\' already exists so the command will not be executed\")\n"; // not used if overwrite because "if 1 :"
return Script;
}
/////////////////////////////////////////
// WRITING FUNCTIONS //
/////////////////////////////////////////
void ScriptWriter::WriteScript()
{
std::cout<<"|"<<std::endl; // command line display
std::cout<<"| Number of Cases: "<<m_CasesPath.size()<<std::endl; // command line display
std::cout<<"| Output Directory : "<<m_OutputPath<<"/DTIAtlas"<<std::endl; // command line display
if( m_useGridProcess )
{
std::cout<<"| Using grid processing"<<std::endl; // command line display
}
if(m_RegType==1)
{
std::cout<<"| Using Case 1 (" << m_CasesIDs[0] << ") as reference in the first Registration Loop"<<std::endl; // command line display
}
else
{
std::cout<<"| Using Template as reference for the Registration: "<<m_TemplatePath<<std::endl; // command line display
}
std::cout<<"| Number of loops in the Registration Loop : "<<m_nbLoops<<std::endl; // command line display
std::cout<<"| Writing begin: "; // command line display (no endl)
Preprocess();
AtlasBuilding();
MainScript();
}
void ScriptWriter::Preprocess ()
{
std::string Script;
std::cout<<"[Pre Processing]"; // command line display (no endl)
Script = Script + "#!/usr/bin/python\n\n";
Script = Script + "import os # To run a shell command : os.system(\"[shell command]\")\n";
Script = Script + "import sys # to return an exit code\n";
Script = Script + "import shutil # to remove a non empty directory\n\n";
Script = Script + "PIDlogFile = \"" + m_OutputPath + "/DTIAtlas/Script/PID.log\"\n";
Script = Script + "PIDfile = open( PIDlogFile, 'a') # open in Append mode\n";
Script = Script + "PIDfile.write( str(os.getpid()) + \"\\n\" )\n";
Script = Script + "PIDfile.close()\n\n";
Script = Script + "print(\"\\n============ Pre processing =============\")\n\n";
Script = Script + "# Files Paths\n";
// allcases
Script = Script + "allcases = [\"" + m_CasesPath[0];
for (unsigned int i=1;i<m_CasesPath.size();i++)
{
Script = Script + "\", \"" + m_CasesPath[i];
}
Script = Script+ "\"]\n\n";
// allcasesIDs
Script = Script + "allcasesIDs = [\"" + m_CasesIDs[0];
for (unsigned int i=1;i<m_CasesIDs.size();i++)
{
Script = Script + "\", \"" + m_CasesIDs[i];
}
Script = Script+ "\"]\n\n";
Script = Script + "OutputPath= \"" + m_OutputPath + "/DTIAtlas/1_Affine_Registration\"\n";
if(m_RegType==1)
{
Script = Script + "AtlasFAref= OutputPath + \"/" + m_CasesIDs[0] + "_FA.nrrd\" #the reference will be the first case for the first loop\n\n";
}
else
{
Script = Script + "AtlasFAref= \"" + m_TemplatePath + "\" #the reference will be the given template for the first loop\n\n";
}
/* Function to display error and quit */
Script = Script + "def DisplayErrorAndQuit ( Error ):\n";
Script = Script + " print \'\\n\\nERROR DETECTED IN WORKFLOW:\',Error\n";
Script = Script + " print \'ABORT\'\n";
Script = Script + " sys.exit(1)\n\n";
/* Function that checks if file exist and replace old names by new names if needed */
Script = Script + pyCheckFileExists();
/* Call script to run command on grid */
std::string NoCase1 = IntToStr(m_RegType); // m_RegType = 0 if template (-> NoCase1=0) | = 1 if case1=ref (-> NoCase1=1) => NoCase1 = (string) m_RegType
if( m_useGridProcess )
{
Script = Script + "\n# Call script to run command on server\n";
Script = Script + "import time # To test existence of files only every minute\n";
Script = Script + "FilesFolder = \"" + m_OutputPath + "/DTIAtlas/GridProcessingFiles\"\n";
Script = Script + "if os.path.isdir(FilesFolder): shutil.rmtree(FilesFolder) # remove directory to get rid of any previous file\n";
Script = Script + "os.mkdir(FilesFolder)\n";
Script = Script + "print(\"\\n=> Creation of the directory for the grid processing = \" + FilesFolder)\n";
//Test Function
Script = Script + pyTestGridProcess( true ); // bool NoCase1
}
/* Create directory for temporary files */
Script = Script + "\n# Create directory for temporary files\n";
Script = Script + "if not os.path.isdir(OutputPath):\n";
Script = Script + " os.mkdir(OutputPath)\n";
Script = Script + " print(\"\\n=> Creation of the affine directory = \" + OutputPath)\n\n";
/* Rescaling template */
if(m_RegType==0) // with template
{
Script = Script + "\n# Rescaling template\n";
Script = Script + "RescaleTemp= OutputPath + \"/FATemplate_Rescaled.nrrd\"\n";
Script = Script + "RescaleTempCommand= \"" + m_SoftPath[0] + " \" + AtlasFAref + \" -outfile \" + RescaleTemp + \" -rescale 0,10000\"\n";
if( m_useGridProcess )
{
Script = Script + "RescaleTempCommand= \"" + m_GridCommand + " " + m_PythonPath + " " + m_OutputPath + "/DTIAtlas/Script/RunCommandOnServer.py \" + FilesFolder + \"/file \\'\" + RescaleTempCommand + \"\\'\"\n";
}
Script = Script + "print(\"\\n[Rescaling FA template] => $ \" + RescaleTempCommand)\n";
if(m_Overwrite==1)
{
Script = Script + "if 1 :\n";
}
else
{
Script = Script + "if not CheckFileExists(RescaleTemp, 0, \"\" ) :\n";
}
Script = Script + " if os.system(RescaleTempCommand)!=0 : DisplayErrorAndQuit(\'ImageMath: Rescaling FA template\')\n";
if( m_useGridProcess )
{
Script = Script + " TestGridProcess( FilesFolder, 0, 0) # stays in the function until all process is done : 0 makes the function look only for \'file\'\n";
}
Script = Script + "else : print(\"=> The file \\'\" + RescaleTemp + \"\\' already exists so the command will not be executed\")\n";
Script = Script + "AtlasFAref= RescaleTemp\n\n";
} // if(m_RegType==0)
else // if no given template, create the template by computing FA of case 1 (+ cropping if needed)
{
Script = Script + "print(\"\")\n";
Script = Script + "# Creating template by processing Case 1 DTI\n";
// Filter DTI
Script = Script + "\n# Filter case 1 DTI\n";
Script = Script + "FilteredDTI= OutputPath + \"/" + m_CasesIDs[0] + "_filteredDTI.nrrd\"\n";
Script = Script + "FilterDTICommand= \"" + m_SoftPath[1] + " \" + allcases[0] + \" \" + FilteredDTI + \" --correction zero\"\n";
Script = Script + "print(\"[" + m_CasesIDs[0] + "] [Filter DTI] => $ \" + FilterDTICommand)\n";
if(m_Overwrite==1)
{
Script = Script + "if 1 :\n";
}
else
{
Script = Script + "if not CheckFileExists(FilteredDTI, 0, \"" + m_CasesIDs[0] + "\" ) :\n";
}
if( ! m_useGridProcess )
{
Script = Script + " if os.system(FilterDTICommand)!=0 : DisplayErrorAndQuit(\'[" + m_CasesIDs[0] + "] ResampleDTIlogEuclidean: Filter DTI to remove negative values\')\n";
}
Script = Script + "else : print(\"=> The file \\'\" + FilteredDTI + \"\\' already exists so the command will not be executed\")\n"; // not used if overwrite because "if 1 :"
// Cropping case 1 DTI image
if(m_NeedToBeCropped==1)
{
Script = Script + "\n# Cropping case 1 DTI\n";
Script = Script + "croppedDTI= OutputPath + \"/" + m_CasesIDs[0] + "_croppedDTI.nrrd\"\n";
Script = Script + "CropCommand= \"" + m_SoftPath[2] + " \" + FilteredDTI + \" -o \" + croppedDTI + \" -size " + m_CropSize[0] + "," + m_CropSize[1] + "," + m_CropSize[2] + " -v\"\n";
Script = Script + "print(\"[" + m_CasesIDs[0] + "] [Cropping DTI Image] => $ \" + CropCommand)\n";
if(m_Overwrite==1)
{
Script = Script + "if 1 :\n";
}
else
{
Script = Script + "if not CheckFileExists(croppedDTI, 0, \"" + m_CasesIDs[0] + "\" ) :\n";
}
if( ! m_useGridProcess )
{
Script = Script + " if os.system(CropCommand)!=0 : DisplayErrorAndQuit(\'[" + m_CasesIDs[0] + "] CropDTI: Cropping DTI image\')\n";
}
Script = Script + "else : print(\"=> The file \\'\" + croppedDTI + \"\\' already exists so the command will not be executed\")\n"; // not used if overwrite because "if 1 :"
} //if(m_NeedToBeCropped==1)
// Generating case 1 FA
Script = Script + "\n# Generating case 1 FA\n";
if(m_NeedToBeCropped==1)
{
Script = Script + "DTI= OutputPath + \"/" + m_CasesIDs[0] + "_croppedDTI.nrrd\"\n";
}
else
{
Script = Script + "DTI= allcases[0]\n";
}
Script = Script + "FA= OutputPath + \"/" + m_CasesIDs[0] + "_FA.nrrd\"\n";
Script = Script + "GeneFACommand= \"" + m_SoftPath[3] + " --dti_image \" + DTI + \" -f \" + FA\n";
Script = Script + "print(\"[" + m_CasesIDs[0] + "] [Generating FA] => $ \" + GeneFACommand)\n";
if(m_Overwrite==1)
{
Script = Script + "if 1 :\n";
}
else
{
Script = Script + "if not CheckFileExists(FA, 0, \"" + m_CasesIDs[0] + "\" ) :\n";
}
if( ! m_useGridProcess )
{
Script = Script + " if os.system(GeneFACommand)!=0 : DisplayErrorAndQuit(\'[" + m_CasesIDs[0] + "] dtiprocess: Generating FA of DTI image\')\n";
}
Script = Script + "else : print(\"=> The file \\'\" + FA + \"\\' already exists so the command will not be executed\")\n\n"; // not used if overwrite because "if 1 :"
// Execute commands here if grid processing (to process them together)
if( m_useGridProcess )
{
Script = Script + "# Run Case1 template commands on grid\n";
Script = Script + "if CropDTICase1Template or GeneFACase1Template :\n";
Script = Script + " GridCase1TemplateCommand= \"" + m_GridCommand + " " + m_PythonPath + " " + m_OutputPath + "/DTIAtlas/Script/RunCommandOnServer.py \" + FilesFolder + \"/file\"\n";
Script = Script + " GridCase1TemplateCommand = GridCase1TemplateCommand + \" \'\" + FilterDTICommand + \"\'\"\n";
if(m_NeedToBeCropped==1)
{
Script = Script + " GridCase1TemplateCommand = GridCase1TemplateCommand + \" \'\" + CropCommand + \"\'\"\n";
}
Script = Script + " GridCase1TemplateCommand = GridCase1TemplateCommand + \" \'\" + GeneFACommand + \"\'\"\n";
Script = Script + " print(\"[" + m_CasesIDs[0] + "] => Submitting : \" + GridCase1TemplateCommand)\n";
Script = Script + " if os.system(GridCase1TemplateCommand)!=0 : DisplayErrorAndQuit(\'[" + m_CasesIDs[0] + "] Grid processing script\') # Run script and collect error if so\n";
Script = Script + " TestGridProcess( FilesFolder, 0, 0) # stays in the function until all process is done : 0 makes the function look only for \'file\'\n\n";
}
} // if case 1 as reference ( else of if(m_RegType==0) )
Script = Script + "print(\"\")\n";
/* Affine Registration and Normalization Loop */
Script = Script + "\n# Affine Registration and Normalization Loop\n";
Script = Script + "n = 0\n";
Script = Script + "while n <= " + IntToStr(m_nbLoops) + " :\n";
Script = Script + " if not os.path.isdir(OutputPath + \"/Loop\" + str(n)):\n";
Script = Script + " print(\"\\n=> Creation of the Output directory for Loop \" + str(n) + \" = \" + OutputPath + \"/Loop\" + str(n) + \"\\n\")\n";
Script = Script + " os.mkdir(OutputPath + \"/Loop\" + str(n))\n\n";
Script = Script + " # Cases Loop\n";
if(m_RegType==1)
{
Script = Script + " case = (n==0) # (n==0) -> bool: =1(true) =0(false) : the first case is the reference for the first loop so it will not be normalized or registered (it is cropped and FAed before the loop)\n";
}
else
{
Script = Script + " case = 0\n";
}
Script = Script + " while case < len(allcases):\n";
if( m_useGridProcess )
{
Script = Script + " GridProcessCaseCommandsArray=[] # Empty the cmds array\n";
}
Script = Script + "\n if n==0: # Filtering and Cropping DTI and Generating FA are only part of the first loop\n";
/* Filter DTI */
Script = Script + "# Filter DTI\n";
Script = Script + " # ResampleDTIlogEuclidean does by default a correction of tensor values by setting the negative values to zero\n";
Script = Script + " FilteredDTI= OutputPath + \"/\" + allcasesIDs[case] + \"_filteredDTI.nrrd\"\n";
Script = Script + " FilterDTICommand= \"" + m_SoftPath[1] + " \" + allcases[case] + \" \" + FilteredDTI + \" --correction zero\"\n";
Script = Script + " print(\"[\" + allcasesIDs[case] + \"] [Filter DTI] => $ \" + FilterDTICommand)\n";
Script = Script + pyExecuteCommandPreprocessCase("FilteredDTI", "FilterDTICommand", "ResampleDTIlogEuclidean: Filter DTI to remove negative values", " ");
/* Cropping DTI image */
if(m_NeedToBeCropped==1)
{
Script = Script + "\n# Cropping DTI image\n";
Script = Script + " croppedDTI= OutputPath + \"/\" + allcasesIDs[case] + \"_croppedDTI.nrrd\"\n";
Script = Script + " CropCommand= \"" + m_SoftPath[2] + " \" + FilteredDTI + \" -o \" + croppedDTI + \" -size " + m_CropSize[0] + "," + m_CropSize[1] + "," + m_CropSize[2] + " -v\"\n";
Script = Script + " print(\"[\" + allcasesIDs[case] + \"] [Cropping DTI Image] => $ \" + CropCommand)\n";
Script = Script + pyExecuteCommandPreprocessCase("croppedDTI", "CropCommand", "CropDTI: Cropping DTI image", " ");
} //if(m_NeedToBeCropped==1)
/* Generating FA */
Script = Script + "\n# Generating FA\n";
if(m_NeedToBeCropped==1)
{
Script = Script + " DTI= OutputPath + \"/\" + allcasesIDs[case] + \"_croppedDTI.nrrd\"\n";
}
else
{
Script = Script + " DTI= allcases[case]\n";
}
Script = Script + " FA= OutputPath + \"/\" + allcasesIDs[case] + \"_FA.nrrd\"\n";
Script = Script + " GeneFACommand= \"" + m_SoftPath[3] + " --dti_image \" + DTI + \" -f \" + FA\n";
Script = Script + " print(\"[\" + allcasesIDs[case] + \"] [Generating FA] => $ \" + GeneFACommand)\n";
Script = Script + pyExecuteCommandPreprocessCase("FA", "GeneFACommand", "dtiprocess: Generating FA of DTI image", " ");
/* Normalization */
Script = Script + "\n# Normalization\n";
Script = Script + " FA= OutputPath + \"/\" + allcasesIDs[case] + \"_FA.nrrd\"\n";
Script = Script + " NormFA= OutputPath + \"/Loop\" + str(n) + \"/\" + allcasesIDs[case] + \"_Loop\" + str(n) + \"_NormFA.nrrd\"\n";
Script = Script + " NormFACommand= \"" + m_SoftPath[0] + " \" + FA + \" -outfile \" + NormFA + \" -matchHistogram \" + AtlasFAref\n";
Script = Script + " print(\"[LOOP \" + str(n) + \"/" + IntToStr(m_nbLoops) + "] [\" + allcasesIDs[case] + \"] [Normalization] => $ \" + NormFACommand)\n";
Script = Script + pyExecuteCommandPreprocessCase("NormFA", "NormFACommand", "ImageMath: Normalizing FA image", " ");
/* Affine registration with BrainsFit */
Script = Script + "\n# Affine registration with BrainsFit\n";
Script = Script + " NormFA= OutputPath + \"/Loop\" + str(n) + \"/\" + allcasesIDs[case] + \"_Loop\" + str(n) + \"_NormFA.nrrd\"\n";
Script = Script + " LinearTranstfm= OutputPath + \"/Loop\" + str(n) + \"/\" + allcasesIDs[case] + \"_Loop\" + str(n) + \"_LinearTrans.txt\"\n";
Script = Script + " LinearTrans= OutputPath + \"/Loop\" + str(n) + \"/\" + allcasesIDs[case] + \"_Loop\" + str(n) + \"_LinearTrans_FA.nrrd\"\n";
Script = Script + " AffineCommand= \"" + m_SoftPath[4] + " --fixedVolume \" + AtlasFAref + \" --movingVolume \" + NormFA + \" --useAffine --outputVolume \" + LinearTrans + \" --outputTransform \" + LinearTranstfm\n";
Script = Script + " InitLinearTransTxt= OutputPath + \"/\" + allcasesIDs[case] + \"_InitLinearTrans.txt\"\n";
Script = Script + " InitLinearTransMat= OutputPath + \"/\" + allcasesIDs[case] + \"_InitLinearTrans.mat\"\n";
Script = Script + " if n==0 and CheckFileExists( InitLinearTransMat, case, allcasesIDs[case] ) and CheckFileExists( InitLinearTransTxt, case, allcasesIDs[case] ):\n";
Script = Script + " print(\"[WARNING] Both \\'\" + allcasesIDs[case] + \"_InitLinearTrans.mat\\' and \\'\" + allcasesIDs[case] + \"_InitLinearTrans.txt\\' have been found. The .mat file will be used.\")\n";
Script = Script + " AffineCommand= AffineCommand + \" --initialTransform \" + InitLinearTransMat\n";
Script = Script + " elif n==0 and CheckFileExists( InitLinearTransMat, case, allcasesIDs[case] ) : AffineCommand= AffineCommand + \" --initialTransform \" + InitLinearTransMat\n";
Script = Script + " elif n==0 and CheckFileExists( InitLinearTransTxt, case, allcasesIDs[case] ) : AffineCommand= AffineCommand + \" --initialTransform \" + InitLinearTransTxt\n";
Script = Script + " else : AffineCommand= AffineCommand + \" --initializeTransformMode " + m_BFAffineTfmMode + "\"\n";
Script = Script + " print(\"[LOOP \" + str(n) + \"/" + IntToStr(m_nbLoops) + "] [\" + allcasesIDs[case] + \"] [Affine registration with BrainsFit] => $ \" + AffineCommand)\n";
Script = Script + " CheckFileExists( LinearTrans, case, allcasesIDs[case] ) # Not for checking but to rename _LinearTrans_FA if old version\n";
Script = Script + pyExecuteCommandPreprocessCase("LinearTranstfm", "AffineCommand", "BRAINSFit: Affine Registration of FA image", " ");
/* Implementing the affine registration */
Script = Script + "\n# Implementing the affine registration\n";
Script = Script + " LinearTranstfm= OutputPath + \"/Loop\" + str(n) + \"/\" + allcasesIDs[case] + \"_Loop\" + str(n) + \"_LinearTrans.txt\"\n";
Script = Script + " LinearTransDTI= OutputPath + \"/Loop\" + str(n) + \"/\" + allcasesIDs[case] + \"_Loop\" + str(n) + \"_LinearTrans_DTI.nrrd\"\n";
if(m_NeedToBeCropped==1)
{
Script = Script + " originalDTI= OutputPath + \"/\" + allcasesIDs[case] + \"_croppedDTI.nrrd\"\n";
}
else
{
Script = Script + " originalDTI= allcases[case]\n";
}
Script = Script + " ImplementCommand= \"" + m_SoftPath[1] + " \" + originalDTI + \" \" + LinearTransDTI + \" -f \" + LinearTranstfm + \" -R \" + AtlasFAref\n";
Script = Script + " print(\"[LOOP \" + str(n) + \"/" + IntToStr(m_nbLoops) + "] [\" + allcasesIDs[case] + \"] [Implementing the Affine registration] => $ \" + ImplementCommand)\n";
Script = Script + pyExecuteCommandPreprocessCase("LinearTransDTI", "ImplementCommand", "ResampleDTIlogEuclidean: Implementing the Affine Registration on FA image", " ");
/* Generating FA of registered images */
Script = Script + "\n# Generating FA of registered images\n";
Script = Script + " LinearTransDTI= OutputPath + \"/Loop\" + str(n) + \"/\" + allcasesIDs[case] + \"_Loop\" + str(n) + \"_LinearTrans_DTI.nrrd\"\n";
Script = Script + " if n == " + IntToStr(m_nbLoops) + " : LoopFA= OutputPath + \"/Loop" + IntToStr(m_nbLoops) + "/\" + allcasesIDs[case] + \"_Loop" + IntToStr(m_nbLoops) + "_FinalFA.nrrd\" # the last FA will be the Final output\n";
Script = Script + " else : LoopFA= OutputPath + \"/Loop\" + str(n) + \"/\" + allcasesIDs[case] + \"_Loop\" + str(n) + \"_FA.nrrd\"\n";
Script = Script + " GeneLoopFACommand= \"" + m_SoftPath[3] + " --dti_image \" + LinearTransDTI + \" -f \" + LoopFA\n";
Script = Script + " print(\"[LOOP \" + str(n) + \"/" + IntToStr(m_nbLoops) + "] [\" + allcasesIDs[case] + \"] [Generating FA of registered images] => $ \" + GeneLoopFACommand)\n";
Script = Script + pyExecuteCommandPreprocessCase("LoopFA", "GeneLoopFACommand", "dtiprocess: Generating FA of affine registered images", " ");
/* Run grid process command for case X, containing all operations */
if( m_useGridProcess )
{
Script = Script + "\n# Run grid process command for case X, containing all operations\n";
Script = Script + " if len(GridProcessCaseCommandsArray)!=0 : # There are operations to run\n";
Script = Script + " GridAffineCommand= \"" + m_GridCommand + " " + m_PythonPath + " " + m_OutputPath + "/DTIAtlas/Script/RunCommandOnServer.py \" + FilesFolder + \"/Case\" + str(case+1)\n";
Script = Script + " GridCmd = 0\n";
Script = Script + " while GridCmd < len(GridProcessCaseCommandsArray):\n";
Script = Script + " GridAffineCommand = GridAffineCommand + \" \'\" + GridProcessCaseCommandsArray[GridCmd] + \"\'\"\n";
Script = Script + " GridCmd += 1\n";
Script = Script + " print(\"[LOOP \" + str(n) + \"/" + IntToStr(m_nbLoops) + "] [\" + allcasesIDs[case] + \"] => Submitting : \" + GridAffineCommand)\n";
Script = Script + " if os.system(GridAffineCommand)!=0 : # Run script and collect error if so\n";
Script = Script + " DisplayErrorAndQuit(\'[Loop \' + str(n) + \'][\' + allcasesIDs[case] + \'] Grid processing script\')\n";
Script = Script + " else : # No operations to run for this case\n";
Script = Script + " print(\"=> No operations to run for case \" + str(case+1))\n";
Script = Script + " f = open( FilesFolder + \"/Case\" + str(case+1), 'w')\n";
Script = Script + " f.close()\n";
} // if( m_useGridProcess )
Script = Script + "\n print(\"\")\n";
Script = Script + " case += 1 # indenting cases loop\n\n";
if( m_useGridProcess )
{
Script = Script + " TestGridProcess( FilesFolder, len(allcases), " + NoCase1 + "*(n==0)) # stays in the function until all process is done\n\n";
}
/* FA Average of registered images with ImageMath */
Script = Script + "\n# FA Average of registered images with ImageMath\n";
if ( m_nbLoops!=0 ) // if no looping, compute average for the only preprocessing for QC (if 1:)
{
Script = Script + " if n != " + IntToStr(m_nbLoops) + " : # this will not be done for the last lap\n";
}
else
{
Script = Script + " if 1 :\n";
}
Script = Script + " FAAverage = OutputPath + \"/Loop\" + str(n) + \"/Loop\" + str(n) + \"_FAAverage.nrrd\"\n";
if(m_RegType==1) //use case 1 as loop 1 ref
{
Script = Script + " if n == 0 : FAforAVG= OutputPath + \"/" + m_CasesIDs[0] + "_FA.nrrd\"\n";
Script = Script + " else : FAforAVG= OutputPath + \"/Loop\" + str(n) + \"/" + m_CasesIDs[0] + "_Loop\" + str(n) + \"_FA.nrrd\"\n";
}
else
{
Script = Script + " FAforAVG= OutputPath + \"/Loop\" + str(n) + \"/" + m_CasesIDs[0] + "_Loop\" + str(n) + \"_FA.nrrd\"\n";
}
Script = Script + " AverageCommand = \"" + m_SoftPath[0] + " \" + FAforAVG + \" -outfile \" + FAAverage + \" -avg \"\n";
Script = Script + " case = 1\n";
Script = Script + " while case < len(allcases):\n";
Script = Script + " FAforAVG= OutputPath + \"/Loop\" + str(n) + \"/\" + allcasesIDs[case] + \"_Loop\" + str(n) + \"_FA.nrrd \"\n";
Script = Script + " AverageCommand= AverageCommand + FAforAVG\n";
Script = Script + " case += 1\n";
if( m_useGridProcess )
{
Script = Script + " AverageCommand= \"" + m_GridCommand + " " + m_PythonPath + " " + m_OutputPath + "/DTIAtlas/Script/RunCommandOnServer.py \" + FilesFolder + \"/file \\'\" + AverageCommand + \"\\'\"\n";
}
Script = Script + " print(\"[LOOP \" + str(n) + \"/" + IntToStr(m_nbLoops) + "] [Computing FA Average of registered images] => $ \" + AverageCommand)\n";
if(m_Overwrite==1)
{
Script = Script + " if 1 :\n";
}
else
{
Script = Script + " if not CheckFileExists(FAAverage, 0, \"\") :\n";
}
Script = Script + " if os.system(AverageCommand)!=0 : DisplayErrorAndQuit(\'[Loop \' + str(n) + \'] dtiaverage: Computing FA Average of registered images\')\n";
if( m_useGridProcess )
{
Script = Script + " TestGridProcess( FilesFolder, 0, 0) # stays in the function until all process is done : 0 makes the function look for \'file\'\n";
}
Script = Script + " else :\n"; // not used if overwrite because "if 1 :"
Script = Script + " print(\"=> The file \\'\" + FAAverage + \"\\' already exists so the command will not be executed\")\n";
Script = Script + " AtlasFAref = FAAverage # the average becomes the reference\n\n";
Script = Script + " print(\"\")\n";
Script = Script + " n += 1 # indenting main loop\n\n";
Script = Script + "print(\"\\n============ End of Pre processing =============\")\n\n";
Script = Script + "sys.exit(0)\n";
m_Script_Preprocess=Script;
}
/////////////////////////////////////////
// ATLAS BUILDING //
/////////////////////////////////////////
void ScriptWriter::AtlasBuilding()
{
std::string Script;
std::cout<<"[AtlasBuilding]"; // command line display (no endl)
Script = Script + "#!/usr/bin/python\n\n";
Script = Script + "import os # To run a shell command : os.system(\"[shell command]\")\n";
Script = Script + "import sys # to return an exit code\n";
Script = Script + "import shutil # to remove a non empty directory and copy files\n\n";
Script = Script + "PIDlogFile = \"" + m_OutputPath + "/DTIAtlas/Script/PID.log\"\n";
Script = Script + "PIDfile = open( PIDlogFile, 'a') # open in Append mode\n";
Script = Script + "PIDfile.write( str(os.getpid()) + \"\\n\" )\n";
Script = Script + "PIDfile.close()\n\n";
Script = Script + "print(\"\\n============ Atlas Building =============\")\n\n";
Script = Script + "# Files Paths\n";
Script = Script + "DeformPath= \"" + m_OutputPath + "/DTIAtlas/2_NonLinear_Registration\"\n";
Script = Script + "AffinePath= \"" + m_OutputPath + "/DTIAtlas/1_Affine_Registration\"\n";
Script = Script + "FinalPath= \"" + m_OutputPath + "/DTIAtlas/3_Diffeomorphic_Atlas\"\n";
Script = Script + "FinalResampPath= \"" + m_OutputPath + "/DTIAtlas/4_Final_Resampling\"\n\n";
/* Function to display error and quit */
Script = Script + "def DisplayErrorAndQuit ( Error ):\n";
Script = Script + " print \'\\n\\nERROR DETECTED IN WORKFLOW:\',Error\n";
Script = Script + " print \'ABORT\'\n";
Script = Script + " sys.exit(1)\n\n";
/* Function that checks if file exist and replace old names by new names if needed */
Script = Script + pyCheckFileExists();
/* Call script to run command on grid */
std::string GridApostrophe = "";
std::string GridProcessCmd = "";
std::string GridProcessFileExistCmd1 = "";
std::string GridProcessCmdNoCase = "";
std::string GridProcessFileExistCmdNoCase = "";
std::string GridProcessFileExistIndent = "";
std::string GridProcessFileExistIndent1 = "";
if( m_useGridProcess )
{
Script = Script + "# Call script to run command on server\n";
Script = Script + "import time # To test existence of files only every minute\n";
Script = Script + "FilesFolder = \"" + m_OutputPath + "/DTIAtlas/GridProcessingFiles\"\n";
//Test Function
Script = Script + pyTestGridProcess( false ); // bool NoCase1
GridApostrophe = " + \"\\'\"";
std::string File = "FilesFolder + \"/Case\" + str(case+1)";
GridProcessCmd = "\"" + m_GridCommand + " " + m_PythonPath + " " + m_OutputPath + "/DTIAtlas/Script/RunCommandOnServer.py \" + " + File + " + \" \"" + GridApostrophe + " + ";
GridProcessFileExistCmd1 = " f = open( " + File + ", 'w')\n f.close()\n"; // if the image already exists, create the "semaphore" file
std::string FileNoCase = "FilesFolder + \"/file\""; // for the commands executed only once = not once per case
GridProcessCmdNoCase = "\"" + m_GridCommand + " " + m_PythonPath + " " + m_OutputPath + "/DTIAtlas/Script/RunCommandOnServer.py \" + " + FileNoCase + " + \" \"" + GridApostrophe + " + ";
GridProcessFileExistCmdNoCase = " f = open( " + FileNoCase + ", 'w')\n f.close()\n";
GridProcessFileExistIndent = "\n "; // if the file already exists, several commands in the else (create file), so change line and indent
GridProcessFileExistIndent1 = "\n "; // if the file already exists, several commands in the else (create file), so change line and indent (double)
}
/* Create directory for temporary files and final */
Script = Script + "# Create directory for temporary files and final\n";
Script = Script + "if not os.path.isdir(DeformPath):\n";
Script = Script + " OldDeformPath= \"" + m_OutputPath + "/DTIAtlas/2_NonLinear_Registration_AW\"\n";
Script = Script + " if os.path.isdir(OldDeformPath):\n";
Script = Script + " os.rename(OldDeformPath,DeformPath)\n";
Script = Script + " else:\n";
Script = Script + " print(\"\\n=> Creation of the Deformation transform directory = \" + DeformPath)\n";
Script = Script + " os.mkdir(DeformPath)\n\n";
Script = Script + "if not os.path.isdir(FinalPath):\n";
Script = Script + " OldFinalPath= \"" + m_OutputPath + "/DTIAtlas/3_AW_Atlas\"\n";
Script = Script + " if os.path.isdir(OldFinalPath):\n";
Script = Script + " os.rename(OldFinalPath,FinalPath)\n";
Script = Script + " else:\n";
Script = Script + " print(\"\\n=> Creation of the Final Atlas directory = \" + FinalPath)\n";
Script = Script + " os.mkdir(FinalPath)\n\n";
Script = Script + "if not os.path.isdir(FinalResampPath):\n";
Script = Script + " print(\"\\n=> Creation of the Final Resampling directory = \" + FinalResampPath)\n";
Script = Script + " os.mkdir(FinalResampPath)\n\n";
Script = Script + "if not os.path.isdir(FinalResampPath + \"/First_Resampling\"):\n";
Script = Script + " print(\"\\n=> Creation of the First Final Resampling directory = \" + FinalResampPath + \"/First_Resampling\")\n";
Script = Script + " os.mkdir(FinalResampPath + \"/First_Resampling\")\n\n";
Script = Script + "if not os.path.isdir(FinalResampPath + \"/Second_Resampling\"):\n";
Script = Script + " print(\"\\n=> Creation of the Second Final Resampling directory = \" + FinalResampPath + \"/Second_Resampling\")\n";
Script = Script + " os.mkdir(FinalResampPath + \"/Second_Resampling\")\n\n";
Script = Script + "if not os.path.isdir(FinalResampPath + \"/FinalTensors\"):\n";
Script = Script + " print(\"\\n=> Creation of the Final Tensors directory = \" + FinalResampPath + \"/FinalTensors\")\n";
Script = Script + " os.mkdir(FinalResampPath + \"/FinalTensors\")\n\n";
Script = Script + "if not os.path.isdir(FinalResampPath + \"/FinalDeformationFields\"):\n";
Script = Script + " print(\"\\n=> Creation of the Final Deformation Fields directory = \" + FinalResampPath + \"/FinalDeformationFields\\n\")\n";
Script = Script + " os.mkdir(FinalResampPath + \"/FinalDeformationFields\")\n\n";
/* Cases variables: */
Script = Script + "# Cases variables\n";
// alltfms
Script = Script + "alltfms = [AffinePath + \"/Loop" + IntToStr(m_nbLoops) + "/" + m_CasesIDs[0] + "_Loop" + IntToStr(m_nbLoops) + "_LinearTrans.txt\"";
for (unsigned int i=1;i<m_CasesPath.size();i++)
{
Script = Script + ", AffinePath + \"/Loop" + IntToStr(m_nbLoops) + "/" + m_CasesIDs[i] + "_Loop" + IntToStr(m_nbLoops) + "_LinearTrans.txt\"";
}
Script = Script+ "]\n\n";
// allcases
if(m_NeedToBeCropped==1)
{
Script = Script + "allcases = [AffinePath + \"/" + m_CasesIDs[0] + "_croppedDTI.nrrd\"";
}
else
{
Script = Script + "allcases = [\"" + m_CasesPath[0] + "\"";
}
for (unsigned int i=1;i<m_CasesPath.size();i++)
{
if(m_NeedToBeCropped==1)
{
Script = Script + ", AffinePath + \"/" + m_CasesIDs[i] + "_croppedDTI.nrrd\"";
}
else Script = Script + ", \"" + m_CasesPath[i] + "\"";
}
Script = Script + "]\n\n";
// allcasesIDs
Script = Script + "allcasesIDs = [\"" + m_CasesIDs[0];
for (unsigned int i=1;i<m_CasesIDs.size();i++)
{
Script = Script + "\", \"" + m_CasesIDs[i];
}
Script = Script+ "\"]\n\n";
/* GreedyAtlas Command: */
Script = Script + "# GreedyAtlas Command\n";
Script = Script + "XMLFile= DeformPath + \"/GreedyAtlasParameters.xml\"\n";
Script = Script + "ParsedFile= DeformPath + \"/ParsedXML.xml\"\n";
Script = Script + "AtlasBCommand= " + GridProcessCmdNoCase + "\"" + m_SoftPath[5] + " -f \" + XMLFile + \" -o \" + ParsedFile" + GridApostrophe + "\n";
Script = Script + "print(\"[Computing the Deformation Fields with GreedyAtlas] => $ \" + AtlasBCommand)\n";
if(m_Overwrite==1)
{
Script = Script + "if 1 :\n";
}
else
{
Script = Script + "if not CheckFileExists(DeformPath + \"/MeanImage.mhd\", 0, \"\") :\n";
}
Script = Script + " if os.system(AtlasBCommand)!=0 : DisplayErrorAndQuit(\'GreedyAtlas: Computing non-linear atlas from affine registered images\')\n";
if( m_useGridProcess )
{
Script = Script + " TestGridProcess( FilesFolder, 0) # stays in the function until all process is done : 0 makes the function look for \'file\'\n\n";
}
Script = Script + " case = 0\n";
Script = Script + " while case < len(allcases): # Renaming\n";
Script = Script + " originalImage=DeformPath + \"/\" + allcasesIDs[case] + \"_Loop" + IntToStr(m_nbLoops) + "_FinalFADefToMean.mhd\"\n";
Script = Script + " originalHField=DeformPath + \"/\" + allcasesIDs[case] + \"_Loop" + IntToStr(m_nbLoops) + "_FinalFADefFieldImToMean.mhd\"\n";
Script = Script + " originalInvHField=DeformPath + \"/\" + allcasesIDs[case] + \"_Loop" + IntToStr(m_nbLoops) + "_FinalFADefFieldMeanToIm.mhd\"\n";
Script = Script + " NewImage= DeformPath + \"/\" + allcasesIDs[case] + \"_NonLinearTrans_FA.mhd\"\n";
Script = Script + " NewHField=DeformPath + \"/\" + allcasesIDs[case] + \"_HField.mhd\"\n";
Script = Script + " NewInvHField=DeformPath + \"/\" + allcasesIDs[case] + \"_InverseHField.mhd\"\n";
Script = Script + " print(\"[\" + allcasesIDs[case] + \"] => Renaming \\'\" + originalImage + \"\\' to \\'\" + NewImage + \"\\'\")\n";
Script = Script + " os.rename(originalImage,NewImage)\n";
Script = Script + " print(\"[\" + allcasesIDs[case] + \"] => Renaming \\'\" + originalHField + \"\\' to \\'\" + NewHField + \"\\'\")\n";
Script = Script + " os.rename(originalHField,NewHField)\n";
Script = Script + " print(\"[\" + allcasesIDs[case] + \"] => Renaming \\'\" + originalInvHField + \"\\' to \\'\" + NewInvHField + \"\\'\")\n";
Script = Script + " os.rename(originalInvHField,NewInvHField)\n";
Script = Script + " case += 1\n";
if(m_Overwrite==0)
{
Script = Script + "else :\n";
Script = Script + " print(\"=> The file \\'\" + DeformPath + \"/MeanImage.mhd\\' already exists so the command will not be executed\")\n";
Script = Script + " # Renaming possible existing old named files from GreedyAtlas\n";
Script = Script + " case = 0\n";
Script = Script + " while case < len(allcases): # Updating old names if needed\n";
Script = Script + " NewImage= DeformPath + \"/\" + allcasesIDs[case] + \"_NonLinearTrans_FA.mhd\"\n";
Script = Script + " CheckFileExists(NewImage, case, allcasesIDs[case])\n";
Script = Script + " NewHField=DeformPath + \"/\" + allcasesIDs[case] + \"_HField.mhd\"\n";
Script = Script + " CheckFileExists(NewHField, case, allcasesIDs[case])\n";
Script = Script + " NewInvHField=DeformPath + \"/\" + allcasesIDs[case] + \"_InverseHField.mhd\"\n";
Script = Script + " CheckFileExists(NewInvHField, case, allcasesIDs[case])\n";
Script = Script + " case += 1\n";
}
/* Apply deformation fields */
Script = Script + "\n# Apply deformation fields\n";
if( m_useGridProcess )
{
Script = Script + "GridProcessCommandsArray=[] # Empty the cmds array\n";
Script = Script + "NbGridCommandsRan = 0\n";
}
Script = Script + "case = 0\n";
Script = Script + "while case < len(allcases):\n";
Script = Script + " FinalDTI= FinalPath + \"/\" + allcasesIDs[case] + \"_DiffeomorphicDTI.nrrd\"\n";
if(m_NeedToBeCropped==1)
{
Script = Script + " originalDTI= AffinePath + \"/\" + allcasesIDs[case] + \"_croppedDTI.nrrd\"\n";
}
else
{
Script = Script + " originalDTI= allcases[case]\n";
}
if(m_nbLoops==0)
{
Script = Script + " Ref = AffinePath + \"/Loop0/Loop0_FAAverage.nrrd\"\n"; // if no looping ((m_nbLoops==0), an average is computed anyway for QC
}
else
{
Script = Script + " Ref = AffinePath + \"/Loop" + IntToStr(m_nbLoops-1) + "/Loop" + IntToStr(m_nbLoops-1) + "_FAAverage.nrrd\"\n"; // an average image has been generated in the loops of affine reg for reference
}
Script = Script + " HField= DeformPath + \"/\" + allcasesIDs[case] + \"_HField.mhd\"\n";
Script = Script + " FinalReSampCommand=\"" + m_SoftPath[1] + " -R \" + Ref + \" -H \" + HField + \" -f \" + alltfms[case] + \" \" + originalDTI + \" \" + FinalDTI\n";
/* options */
if(m_InterpolType.compare("Linear")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -i linear\"\n";
if(m_InterpolType.compare("Nearest Neighborhoor")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -i nn\"\n";
if(m_InterpolType.compare("Windowed Sinc")==0)
{
if(m_InterpolOption.compare("Hamming")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -i ws -W h\"\n";
if(m_InterpolOption.compare("Cosine")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -i ws -W c\"\n";
if(m_InterpolOption.compare("Welch")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -i ws -W w\"\n";
if(m_InterpolOption.compare("Lanczos")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -i ws -W l\"\n";
if(m_InterpolOption.compare("Blackman")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -i ws -W b\"\n";
}
if(m_InterpolType.compare("BSpline")==0)
{
std::istringstream istr(m_InterpolOption);
int i;
istr >> i;
if(i>=0 && i<=5) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -i bs -o " + m_InterpolOption + "\"\n";
}
if(m_TensInterpol.compare("Non Log Euclidean")==0)
{
if(m_InterpolLogOption.compare("Zero")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" --nolog --correction zero\"\n";
if(m_InterpolLogOption.compare("None")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" --nolog --correction none\"\n";
if(m_InterpolLogOption.compare("Absolute Value")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" --nolog --correction abs\"\n";
if(m_InterpolLogOption.compare("Nearest")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" --nolog --correction nearest\"\n";
}
if(m_TensTfm.compare("Preservation of the Principal Direction (PPD)")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -T PPD\"\n";
if(m_TensTfm.compare("Finite Strain (FS)")==0) Script = Script + " FinalReSampCommand = FinalReSampCommand + \" -T FS\"\n";
Script = Script + " print(\"\\n[\" + allcasesIDs[case] + \"] [Applying deformation fields to original DTIs] => $ \" + FinalReSampCommand)\n";
if(m_Overwrite==1)
{
Script = Script + " if 1 :\n";
}
else
{
Script = Script + " if not CheckFileExists(FinalDTI, case, allcasesIDs[case]) :\n";
}
Script = Script + " DiffeomorphicCaseFA = FinalPath + \"/\" + allcasesIDs[case] + \"_DiffeomorphicFA.nrrd\"\n";
Script = Script + " GeneDiffeomorphicCaseFACommand=\"" + m_SoftPath[3] + " --scalar_float --dti_image \" + FinalDTI + \" -f \" + DiffeomorphicCaseFA\n";
Script = Script + " CaseDbleToFloatCommand=\"" + m_SoftPath[8] + " convert -t float -i \" + FinalDTI + \" | " + m_SoftPath[8] + " save -f nrrd -e gzip -o \" + FinalPath + \"/\" + allcasesIDs[case] + \"_DiffeomorphicDTI_float.nrrd\"\n\n";
if( ! m_useGridProcess )
{
Script = Script + " if os.system(FinalReSampCommand)!=0 : DisplayErrorAndQuit(\'[\' + allcasesIDs[case] + \'] ResampleDTIlogEuclidean: Applying deformation fields to original DTIs\')\n";
Script = Script + " print(\"[\" + allcasesIDs[case] + \"] => $ \" + GeneDiffeomorphicCaseFACommand)\n";
Script = Script + " if os.system(GeneDiffeomorphicCaseFACommand)!=0 : DisplayErrorAndQuit(\'[\' + allcasesIDs[case] + \'] dtiprocess: Computing Diffeomorphic FA\')\n";
Script = Script + " print(\"[\" + allcasesIDs[case] + \"] => $ \" + CaseDbleToFloatCommand + \"\\n\")\n";
Script = Script + " if os.system(CaseDbleToFloatCommand)!=0 : DisplayErrorAndQuit(\'[\' + allcasesIDs[case] + \'] unu: Converting the final DTI images from double to float DTI\')\n";
}
else // run up to 50 commands in the same script
{
Script = Script + " GridProcessCommandsArray.append(FinalReSampCommand)\n";
Script = Script + " GridProcessCommandsArray.append(GeneDiffeomorphicCaseFACommand)\n";
Script = Script + " GridProcessCommandsArray.append(CaseDbleToFloatCommand)\n";
Script = Script + " if len(GridProcessCommandsArray)>=50 or case==len(allcases)-1 : # launch a script if more than 50 operations or if last case\n";
Script = Script + " GridProcessCmd= \"" + m_GridCommand + " " + m_PythonPath + " " + m_OutputPath + "/DTIAtlas/Script/RunCommandOnServer.py \" + FilesFolder + \"/Case\" + str(NbGridCommandsRan+1)\n";
Script = Script + " GridCmd = 0\n";
Script = Script + " while GridCmd < len(GridProcessCommandsArray):\n";
Script = Script + " GridProcessCmd = GridProcessCmd + \" \'\" + GridProcessCommandsArray[GridCmd] + \"\'\"\n";
Script = Script + " GridCmd += 1\n";
Script = Script + " GridProcessCommandsArray=[] # Empty the cmds array\n";
Script = Script + " NbGridCommandsRan += 1\n";
Script = Script + " if os.system(GridProcessCmd)!=0 : # Run script and collect error if so\n";
Script = Script + " DisplayErrorAndQuit(\'[] Applying deformation fields to original DTIs\')\n";
}
Script = Script + " else : print(\"=> The file \\'\" + FinalDTI + \"\\' already exists so the command will not be executed\")\n"; // not used if overwrite because "if 1 :"
Script = Script + " case += 1\n\n";
if( m_useGridProcess )
{
Script = Script + "if NbGridCommandsRan!=0 : TestGridProcess( FilesFolder, NbGridCommandsRan ) # stays in the function until all process is done : 0 cmds makes the function look for \'file\'\n\n";
}
/* dtiaverage computing */
Script = Script + "# DTIaverage computing\n";
Script = Script + "DTIAverage = FinalPath + \"/DiffeomorphicAtlasDTI.nrrd\"\n";
Script = Script + "AverageCommand = \"" + m_SoftPath[6] + " \"\n";
Script = Script + "case = 0\n";
Script = Script + "while case < len(allcases):\n";
Script = Script + " DTIforAVG= \"--inputs \" + FinalPath + \"/\" + allcasesIDs[case] + \"_DiffeomorphicDTI.nrrd \"\n";
Script = Script + " AverageCommand = AverageCommand + DTIforAVG\n";
Script = Script + " case += 1\n";
Script = Script + "AverageCommand = AverageCommand + \"--tensor_output \" + DTIAverage\n";
Script = Script + "print(\"\\n[Computing the Diffeomorphic DTI average] => $ \" + AverageCommand)\n";
if(m_Overwrite==1)
{
Script = Script + "if 1 : \n";
}
else
{
Script = Script + "if not CheckFileExists(DTIAverage, 0, \"\") : \n";
}
/* Computing some images from the final DTI with dtiprocess */
Script = Script + "# Computing some images from the final DTI with dtiprocess\n";
Script = Script + " FA= FinalPath + \"/DiffeomorphicAtlasFA.nrrd\"\n";
Script = Script + " cFA= FinalPath + \"/DiffeomorphicAtlasColorFA.nrrd\"\n";
Script = Script + " RD= FinalPath + \"/DiffeomorphicAtlasRD.nrrd\"\n"; // Radial Diffusivity
Script = Script + " MD= FinalPath + \"/DiffeomorphicAtlasMD.nrrd\"\n"; // Mean Diffusivity
Script = Script + " AD= FinalPath + \"/DiffeomorphicAtlasAD.nrrd\"\n"; // Axial Diffusivity
Script = Script + " GeneFACommand=\"" + m_SoftPath[3] + " --scalar_float --dti_image \" + DTIAverage + \" -f \" + FA + \" -m \" + MD + \" --color_fa_output \" + cFA + \" --RD_output \" + RD + \" --lambda1_output \" + AD\n\n";
Script = Script + " DbleToFloatCommand=\"" + m_SoftPath[8] + " convert -t float -i \" + DTIAverage + \" | " + m_SoftPath[8] + " save -f nrrd -e gzip -o \" + FinalPath + \"/DiffeomorphicAtlasDTI_float.nrrd\"\n\n";
if( ! m_useGridProcess )
{
Script = Script + " if os.system(AverageCommand)!=0 : DisplayErrorAndQuit(\'dtiaverage: Computing the final DTI average\')\n";
Script = Script + " print(\"[Computing some images from the final DTI with dtiprocess] => $ \" + GeneFACommand)\n";
Script = Script + " if os.system(GeneFACommand)!=0 : DisplayErrorAndQuit(\'dtiprocess: Computing Diffeomorphic FA, color FA, MD, RD and AD\')\n";
Script = Script + " print(\"[Computing some images from the final DTI with dtiprocess] => $ \" + DbleToFloatCommand)\n";
Script = Script + " if os.system(DbleToFloatCommand)!=0 : DisplayErrorAndQuit(\'unu: Converting the final DTI atlas from double to float DTI\')\n";
}
else // run all commands in the same time in the script
{
Script = Script + " AverageGridCommand=" + GridProcessCmdNoCase + "AverageCommand + \"\\' \" + \"\\'\" + GeneFACommand + \"\\' \" + \"\\'\" + DbleToFloatCommand + \"\\'\"\n";
Script = Script + " if os.system(AverageGridCommand)!=0 : DisplayErrorAndQuit(\'Computing the final DTI average\')\n";
}
if(m_Overwrite==0)
{
Script = Script + "else : " + GridProcessFileExistIndent + "print(\"=> The file \\'\" + DTIAverage + \"\\' already exists so the command will not be executed\")\n" + GridProcessFileExistCmdNoCase;
}
if( m_useGridProcess )
{
Script = Script + "TestGridProcess( FilesFolder, 0 ) # stays in the function until all process is done : 0 makes the function look for \'file\'\n";
}
/* Computing global deformation fields */