forked from IntrAnatSEEGSoftware/IntrAnat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageImport.py
3105 lines (2844 loc) · 170 KB
/
ImageImport.py
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
# -*- coding: utf-8 -*-
#
# Importation of data in the database + image registration and normalization
# (c) Inserm U836 2012-2021 - Manik Bhattacharjee, Pierre Deman, Francois Tadel
#
# License GNU GPL v3
import os
import pickle
import tempfile
import json
import numpy
import csv
import sys
import time
myEnv = os.environ.copy()
from scipy import ndimage
from shutil import copyfile, rmtree
from soma import aims
from brainvisa import axon
from brainvisa.configuration import neuroConfig
neuroConfig.gui = True
from brainvisa.configuration.qtgui import neuroConfigGUI
from brainvisa.data import neuroHierarchy
import brainvisa.registration as registration
from brainvisa.processes import *
from soma.qt_gui.qt_backend import uic, QtGui, QtCore, QtWidgets
from brainvisa.data.readdiskitem import ReadDiskItem
from brainvisa.data.writediskitem import WriteDiskItem
import brainvisa.data.neuroDiskItems
from soma.wip.application.api import Application
from brainvisa import anatomist
from freesurfer.brainvisaFreesurfer import *
from externalprocesses import *
setEnv(myEnv)
from TimerMessageBox import TimerMessageBox
from progressbar import ProgressDialog
import DialogCheckbox
# =============================================================================
# ===== SPM CALLS =============================================================
# =============================================================================
# SPM12 Coregister
spm12_coregister = """try
addpath(genpath(%s));
VF=spm_vol(%s);
VG=spm_vol(%s);
centermatF = eye(4);
center_F = %s;
F_orient = %s;
F_orient = reshape(F_orient,4,4)';
centermatF(:,4) = F_orient*[center_F 1]';
centermatG = eye(4);
center_G = %s;
G_orient = %s;
G_orient = reshape(G_orient,4,4)';
centermatG(:,4) = G_orient*[center_G 1]';
centeredmatF = inv(centermatF)*VF.private.mat;
centeredmatG = inv(centermatG)*VG.private.mat;
VF.mat = centeredmatF;
VF.private.mat = centeredmatF;
VF.private.mat0 = centeredmatF;
VG.mat = centeredmatG;
VG.private.mat = centeredmatG;
VG.private.mat0 = centeredmatG;
x = spm_coreg(VF,VG);
matCoreg = spm_matrix(x(:)');
trm = centermatG*matCoreg*inv(centermatF);
trm = [trm(1:3,4)';trm(1:3,1:3)];
dlmwrite(%s,trm, 'delimiter',' ','precision',16); \n
catch
disp 'AN ERROR OCCURED';
end
quit;"""
# SPM12 Coregistration + reslice
spm12_coregisterReslice = """try
addpath(genpath(%s));
spm('defaults', 'FMRI');spm_jobman('initcfg');
matlabbatch{1}.spm.spatial.coreg.estwrite.ref == %s;
matlabbatch{1}.spm.spatial.coreg.estwrite.source = %s;
matlabbatch{1}.spm.spatial.coreg.estwrite.other = {''};
matlabbatch{1}.spm.spatial.coreg.estwrite.eoptions.cost_fun = 'nmi';
matlabbatch{1}.spm.spatial.coreg.estwrite.eoptions.sep = [4 2];
matlabbatch{1}.spm.spatial.coreg.estwrite.eoptions.tol = [0.02 0.02 0.02 0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001];
matlabbatch{1}.spm.spatial.coreg.estwrite.eoptions.fwhm = [7 7];
matlabbatch{1}.spm.spatial.coreg.estwrite.roptions.interp = 1;
matlabbatch{1}.spm.spatial.coreg.estwrite.roptions.wrap = [0 0 0];
matlabbatch{1}.spm.spatial.coreg.estwrite.roptions.mask = 0;
matlabbatch{1}.spm.spatial.coreg.estwrite.roptions.prefix = 'r';
spm_jobman('run',matlabbatch);
catch
disp 'AN ERROR OCCURED';
end
quit;"""
# SPM12 MNI normalization
spm12_normalise = """try
addpath(genpath(%s));
spm('defaults', 'FMRI');
spm_jobman('initcfg');
matlabbatch{1}.spm.spatial.normalise.estwrite.subj.vol = %s;
matlabbatch{1}.spm.spatial.normalise.estwrite.subj.resample = %s;
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.biasreg = 0.0001;
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.biasfwhm = 60;
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.tpm = {%s};
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.affreg = 'mni';
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.reg = [0 0.001 0.5 0.05 0.2];
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.fwhm = 0;
matlabbatch{1}.spm.spatial.normalise.estwrite.eoptions.samp = 3;
matlabbatch{1}.spm.spatial.normalise.estwrite.woptions.bb = [-78 -112 -70
78 76 85];
matlabbatch{1}.spm.spatial.normalise.estwrite.woptions.vox = [1 1 1];
matlabbatch{1}.spm.spatial.normalise.estwrite.woptions.interp = 4;
spm_jobman('run',matlabbatch);
catch
disp 'AN ERROR OCCURED';
end
quit;"""
# SPM12 remove gado
spm12_removeGado = """try
addpath(genpath(%s));
spm('defaults', 'FMRI');
spm_jobman('initcfg');
matlabbatch{1}.spm.spatial.preproc.channel.vols = {%s};
matlabbatch{1}.spm.spatial.preproc.channel.biasreg = 0.001;
matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 60;
matlabbatch{1}.spm.spatial.preproc.channel.write = [0 0];
matlabbatch{1}.spm.spatial.preproc.tissue(1).tpm = {%s};
matlabbatch{1}.spm.spatial.preproc.tissue(1).ngaus = 1;
matlabbatch{1}.spm.spatial.preproc.tissue(1).native = [1 0];
matlabbatch{1}.spm.spatial.preproc.tissue(1).warped = [0 0];
matlabbatch{1}.spm.spatial.preproc.tissue(2).tpm = {%s};
matlabbatch{1}.spm.spatial.preproc.tissue(2).ngaus = 1;
matlabbatch{1}.spm.spatial.preproc.tissue(2).native = [1 0];
matlabbatch{1}.spm.spatial.preproc.tissue(2).warped = [0 0];
matlabbatch{1}.spm.spatial.preproc.tissue(3).tpm = {%s};
matlabbatch{1}.spm.spatial.preproc.tissue(3).ngaus = 2;
matlabbatch{1}.spm.spatial.preproc.tissue(3).native = [1 0];
matlabbatch{1}.spm.spatial.preproc.tissue(3).warped = [0 0];
matlabbatch{1}.spm.spatial.preproc.tissue(4).tpm = {%s};
matlabbatch{1}.spm.spatial.preproc.tissue(4).ngaus = 3;
matlabbatch{1}.spm.spatial.preproc.tissue(4).native = [1 0];
matlabbatch{1}.spm.spatial.preproc.tissue(4).warped = [0 0];
matlabbatch{1}.spm.spatial.preproc.tissue(5).tpm = {%s};
matlabbatch{1}.spm.spatial.preproc.tissue(5).ngaus = 4;
matlabbatch{1}.spm.spatial.preproc.tissue(5).native = [1 0];
matlabbatch{1}.spm.spatial.preproc.tissue(5).warped = [0 0];
matlabbatch{1}.spm.spatial.preproc.tissue(6).tpm = {%s};
matlabbatch{1}.spm.spatial.preproc.tissue(6).ngaus = 2;
matlabbatch{1}.spm.spatial.preproc.tissue(6).native = [0 0];
matlabbatch{1}.spm.spatial.preproc.tissue(6).warped = [0 0];
matlabbatch{1}.spm.spatial.preproc.warp.mrf = 1;
matlabbatch{1}.spm.spatial.preproc.warp.cleanup = 1;
matlabbatch{1}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2];
matlabbatch{1}.spm.spatial.preproc.warp.affreg = 'mni';
matlabbatch{1}.spm.spatial.preproc.warp.fwhm = 0;
matlabbatch{1}.spm.spatial.preproc.warp.samp = 2;
matlabbatch{1}.spm.spatial.preproc.warp.write = [0 0];
spm_jobman('run',matlabbatch);
c1 = spm_vol(%s);
c2 = spm_vol(%s);
c3 = spm_vol(%s);
c4 = spm_vol(%s);
Yc1 = spm_read_vols(c1);
Yc2 = spm_read_vols(c2);
Yc3 = spm_read_vols(c3);
Yc4 = spm_read_vols(c4);
keepC1 = find(Yc1 ~= 0);
keepC2 = find(Yc2 ~= 0);
keepC3 = find(Yc3 ~= 0);
keepC4 = find(Yc4 ~= 0);
all_keep = unique([keepC1; keepC2]);
fullImage = spm_vol(%s);
YfullImage = spm_read_vols(fullImage);
all_remove = [1:1:size(YfullImage(:))];
all_remove(all_keep)=[];
YfullImage(all_remove)=0;
fullImage.fname=%s;
spm_write_vol(fullImage,YfullImage);
catch
disp 'AN ERROR OCCURED';
end
quit;"""
# spm_inverse_y_field12 = """try
# addpath(genpath(%s));
# spm('defaults', 'FMRI');
# spm_jobman('initcfg');
# clear matlabbatch;
# matlabbatch{1}.spm.util.defs.comp{1}.inv.comp{1}.def = {%s};
# matlabbatch{1}.spm.util.defs.comp{1}.inv.space = {%s};
# matlabbatch{1}.spm.util.defs.out{1}.savedef.ofname = %s;
# matlabbatch{1}.spm.util.defs.out{1}.savedef.savedir.saveusr = {%s};
# spm_jobman('run',matlabbatch);
# catch
# disp 'AN ERROR OCCURED';
# end
# quit;"""
# spm_MNItoScannerBased = """try
# addpath(genpath(%s));
# spm('defaults', 'FMRI');
# spm_jobman('initcfg');
# clear matlabbatch;
# matlabbatch{1}.spm.spatial.normalise.write.subj.def = {%s};
# matlabbatch{1}.spm.spatial.normalise.write.subj.resample = {%s};
# matlabbatch{1}.spm.spatial.normalise.write.woptions.bb = [-150 -150 -150
# 150 150 150];
# matlabbatch{1}.spm.spatial.normalise.write.woptions.vox = [1 1 1];
# matlabbatch{1}.spm.spatial.normalise.write.woptions.interp = 4;
# matlabbatch{1}.spm.spatial.normalise.write.woptions.prefix = 'tmpMNItoScannerBased';
# matlabbatch{2}.spm.spatial.realign.write.data = {
# %s
# %s
# };
# matlabbatch{2}.spm.spatial.realign.write.roptions.which = [2 1];
# matlabbatch{2}.spm.spatial.realign.write.roptions.interp = 4;
# matlabbatch{2}.spm.spatial.realign.write.roptions.wrap = [0 0 0];
# matlabbatch{2}.spm.spatial.realign.write.roptions.mask = 1;
# matlabbatch{2}.spm.spatial.realign.write.roptions.prefix = '';
# spm_jobman('run',matlabbatch);
# catch
# disp 'AN ERROR OCCURED';
# end
# quit;"""
class ImageImport(QtWidgets.QDialog):
"""ImageImport is the main dialog class of the Image Importer software"""
def __init__(self, app=None, isGui=True):
QtWidgets.QDialog.__init__(self)
self.ui = uic.loadUi("ImageImport.ui", self)
self.setWindowTitle('Image Import - NOT FOR MEDICAL USE')
self.app = app
self.seriesUIDbyName = {}
self.studiesUIDbyName = {}
self.currentProtocol = None
self.currentSubject = None
self.AcPc = {}
self.brainCenter = None
self.defaultAcqDate = QtCore.QDate(1900, 1, 1)
self.ui.acqDate.setDate(self.defaultAcqDate)
self.modas = {'t1mri': 'Raw T1 MRI', 't2mri': 'T2 MRI', 'ct': 'CT', 'pet': 'PET', 'fmri_epile': 'fMRI-epile',
'statistic_data': 'Statistic-Data', 'flair': 'FLAIR', 'freesurfer_atlas': 'FreesurferAtlas',
'fgatir': 'FGATIR'}
self.dispObj = []
self.threads = []
self.waitingForThreads = {}
# Allow calling brainvisa
self.brainvisaContext = defaultContext()
# Get Transformation Manager
self.transfoManager = registration.getTransformationManager()
# Load anatomist
self.a = anatomist.Anatomist('-b')
# Force all the scanner-based referentials to be linked
self.a.config()['setAutomaticReferential'] = 1
self.a.config()['commonScannerBasedReferential'] = 1
# Initialize GUI
self.initialize()
# Prepare interactivity
if isGui:
layout = QtGui.QVBoxLayout(self.ui.windowContainer1)
layout2 = QtGui.QHBoxLayout()
layout3 = QtGui.QHBoxLayout()
self.axWindow = self.a.createWindow('Axial', options={'hidden': 1})
self.axWindow.setControl('Selection 3D')
self.axWindow2 = self.a.createWindow('Sagittal', options={'hidden': 1})
self.axWindow2.setControl('Selection 3D')
self.axWindow3 = self.a.createWindow('Axial', options={'hidden': 1})
self.axWindow3.setControl('Selection 3D')
self.axWindow4 = self.a.createWindow('Sagittal', options={'hidden': 1}) # , no_decoration=True )
self.axWindow4.setControl('Selection 3D')
self.wins = [self.axWindow, self.axWindow2, self.axWindow3, self.axWindow4]
layout2.addWidget(self.axWindow.getInternalRep())
layout2.addWidget(self.axWindow2.getInternalRep())
layout3.addWidget(self.axWindow3.getInternalRep())
layout3.addWidget(self.axWindow4.getInternalRep())
layout.addLayout(layout2)
layout.addLayout(layout3)
# Hide control window
self.a.getControlWindow().setVisible(False)
# TABS: Reload at each tab change
self.ui.tabWidget.currentChanged[int].connect(self.analyseBrainvisaDB)
# TAB1: Database
self.ui.bvProtocolCombo.currentIndexChanged[str].connect(
lambda s: self.selectProtocol(s, self.ui.bvSubjectCombo))
self.ui.bvSubjectCombo.currentIndexChanged[str].connect(self.selectBvSubject)
self.ui.bvSubjectCombo.activated[str].connect(self.setCurrentSubject)
self.ui.bvImageList.itemDoubleClicked.connect(self.selectBvImage)
self.ui.bvNewSubjectButton.clicked.connect(lambda x: self.addBvSubject())
self.ui.bvDeleteImageButton.clicked.connect(lambda x: self.deleteBvImage())
self.ui.bvDeleteSubjectButton.clicked.connect(lambda x: self.deleteBvSubject())
self.ui.bvEditPref.clicked.connect(lambda x: self.editBvPref())
self.ui.bvUpdateDb.clicked.connect(lambda x: self.updateBvDb())
self.ui.bvImportBids.clicked.connect(lambda x: self.importBids())
# TAB2: Add subject
self.ui.subjectSiteCombo.activated[str].connect(self.updatePatientCode)
self.ui.subjectSiteCombo.editTextChanged[str].connect(self.updatePatientCode)
self.ui.subjectYearSpinbox.valueChanged.connect(self.updatePatientCode)
self.ui.subjectPatientName.textChanged[str].connect(self.updatePatientCode)
self.ui.subjectPatientFirstName.textChanged[str].connect(self.updatePatientCode)
self.ui.subjectAddSubjectButton.clicked.connect(lambda x: self.storePatientInDB())
# TAB3: Import to BrainVisa
self.ui.chooseNiftiButton.clicked.connect(lambda x: self.chooseNifti())
self.ui.niftiImportButton.clicked.connect(lambda x: self.importNifti())
self.ui.niftiSetBraincenterButton.clicked.connect(lambda x: self.setBrainCenter())
self.ui.ImportFSoutputspushButton.clicked.connect(lambda x: self.importFSoutput())
self.ui.buttonImportLausanne.clicked.connect(lambda x: self.importLausanne2008())
self.ui.buttonImportVEP.clicked.connect(lambda x: self.importVEP())
self.ui.niftiSubjectCombo.activated[str].connect(self.setCurrentSubject)
self.ui.niftiSeqType.currentIndexChanged[str].connect(self.enable_disable_gadooption)
# TAB4: Coregistration
self.ui.regSubjectCombo.currentIndexChanged[str].connect(self.selectRegSubject)
self.ui.regSubjectCombo.activated[str].connect(self.setCurrentSubject)
self.ui.regImageList.itemDoubleClicked.connect(self.selectRegImage)
self.ui.regImageList2.itemDoubleClicked.connect(self.selectRegImage2)
self.ui.registerNormalizeSubjectButton.clicked.connect(lambda x: self.registerNormalizeSubject())
self.ui.segmentationHIPHOPbutton.clicked.connect(lambda x: self.runPipelineBV())
self.ui.runMarsAtlasFreesurferButton.clicked.connect(lambda x: self.runPipelineFS())
self.ui.runHiphopOnly.clicked.connect(lambda x: self.runProcessHiphop())
# TAB5: Preferences
self.ui.prefSpmTemplateButton.clicked.connect(lambda x: self.setSpmTemplatePath())
self.ui.prefANTsButton.clicked.connect(lambda x: self.setANTsPath())
self.ui.prefFreesurferButton.clicked.connect(lambda x: self.setFreesurferPath())
self.ui.prefBidsButton.clicked.connect(lambda x: self.setBidsPath())
self.ui.prefANTScheckbox.clicked.connect(lambda x: self.setPrefCoregister('ANTS'))
self.ui.prefSPMcheckbox.clicked.connect(lambda x: self.setPrefCoregister('SPM'))
self.ui.prefProjectCombo.currentIndexChanged[str].connect(self.setPrefProject)
self.ui.prefSaveButton.clicked.connect(lambda x: self.savePreferences())
self.warningMEDIC()
# Rest of the interface
def setDictValue(d, k, v, button):
d[k] = v
button.setStyleSheet("background-color: rgb(90, 255, 95);")
self.ui.regAcButton.clicked.connect(lambda: setDictValue(self.AcPc, 'AC',
list(self.a.linkCursorLastClickedPosition()),
self.ui.regAcButton))
self.ui.regPcButton.clicked.connect(lambda: setDictValue(self.AcPc, 'PC',
list(self.a.linkCursorLastClickedPosition()),
self.ui.regPcButton))
self.ui.regIhButton.clicked.connect(lambda: setDictValue(self.AcPc, 'IH',
list(self.a.linkCursorLastClickedPosition()),
self.ui.regIhButton))
self.ui.regLhButton.clicked.connect(lambda: setDictValue(self.AcPc, 'LH',
list(self.a.linkCursorLastClickedPosition()),
self.ui.regLhButton))
self.ui.regAcPcValidateButton.clicked.connect(lambda x: self.validateAcPc())
# Finds the available protocols in brainvisa database and fills the comboboxes
self.analyseBrainvisaDB()
self.enableACPCButtons(False)
# Show anatomist
self.showAnatomist.setIcon(QtGui.QIcon('logoAnatomist.png'))
self.showAnatomist.setIconSize(QtGui.QSize(24, 24))
self.showAnatomist.clicked.connect(lambda x: self.toggleAnatomistWindow())
def __del__(self):
self.ui = None
def closeEvent(self, event):
QtGui.QFrame.closeEvent(self, event)
self.savePreferences()
# Kill all hat may still be running (stuck) or better, wait for them to complete
maxTimeToCompletion = 1000*60*20 # 20min in ms -> max duration for any thread (it will be killed after that)
qthr = [t for t in self.threads if isinstance(t, QtCore.QThread)]
thr = [t for t in self.threads if not isinstance(t, QtCore.QThread)]
print("Closing all qthreads")
unfinished = [t for t in qthr if not t.wait(maxTimeToCompletion)]
print("Killing %i QThreads still running" % len(unfinished))
[t.terminate() for t in unfinished]
def checkKill(p, timeout):
""" This function checks if the thread is still running.
If so, it waits until timeout (in ms), then kills it if it is still running"""
try:
print("Trying to kill "+repr(p))
t = 0
while p.poll() is None and t < timeout:
time.sleep(5)
t = t + 5000
if p.poll() is None:
p.kill()
except:
pass
print("Closing all threads")
[checkKill(t, maxTimeToCompletion) for t in thr]
print("Quitting BrainVisa")
axon.cleanup()
print("Quit !")
self.app.quit()
def setStatus(self, text):
""" Sets the status text displayed at the bottom of the dialog"""
self.ui.statusCombo.insertItem(0, QtCore.QTime.currentTime().toString("H:m:s") + ': ' + text)
self.ui.statusCombo.setCurrentIndex(0)
def initialize(self):
"""Reads the preference file, checks the available patients and sequences"""
# Localisation du fichier de preference
prefpath = os.path.join(os.path.expanduser('~'), '.imageimport')
# Chargement du fichier et stockage dans self.prefs
self.prefs = {'sites': ['Gre', ],
'coregisterMethod': 'spm'}
try:
if os.path.exists(prefpath):
filein = open(prefpath, 'rU')
try:
self.prefs = json.loads(filein.read())
except: # If json loading failed, try older-style pickle file
filein.close()
filein = open(prefpath, 'rU')
self.prefs = pickle.load(filein)
filein.close()
except:
print("There is a problem with %s opening apparently" % prefpath)
if 'currentProtocol' in self.prefs:
self.currentProtocol = self.prefs['currentProtocol']
if 'currentSubject' in self.prefs:
self.currentSubject = self.prefs['currentSubject']
# Grenoble/Lyon/Other sites...
if 'sites' in self.prefs:
self.ui.subjectSiteCombo.clear()
self.ui.subjectSiteCombo.addItems(self.prefs['sites'])
if 'projectSelected' not in self.prefs:
self.prefs['projectSelected'] = 'Other' # 'CHUGA':
# Check what spm path has been defined in BrainVisa
configuration = Application().configuration
brainvisa_spm12_path = configuration.SPM.spm12_path
try:
brainvisa_freesurfer_home_path = configuration.freesurfer._freesurfer_home_path
except:
print("configuration.freesurfer -> not found !")
brainvisa_freesurfer_home_path = ""
if 'spm' in self.prefs:
if brainvisa_spm12_path != self.prefs['spm']:
QtGui.QMessageBox.warning(self, "SPM", "SPM path different between IntrAnat and BrainVisa, strange, you should check that, by default keep the one precised in IntrAnat")
print("SPM path different between IntrAnat and BrainVisa, strange, you should check that, by default keep the one precised in IntrAnat")
if os.path.isfile(self.prefs['spm']+os.sep+'Contents.m'):
op_cont = open(self.prefs['spm']+os.sep+'Contents.m')
line = op_cont.readline()
line = op_cont.readline()
spm_version = line.split(' ')[3]
if spm_version == '(SPM12)':
self.setSpmTemplatePath(self.prefs['spm']) # + os.sep + 'toolbox/OldNorm/T1.nii')
elif spm_version == '(SPM8)':
QtGui.QMessageBox.warning(self, "SPM", "SPM version not supported anymore")
print("SPM version not supported anymore")
# self.setSpmTemplatePath(self.prefs['spm']) # + os.sep + 'templates/T1.nii')
else:
# QtGui.QMessageBox.warning(self, u"SPM", u"SPM version unknown")
print("SPM version unknown")
else:
QtGui.QMessageBox.warning(self, "SPM", "SPM path is not defined in tab 'Pref'\n Normalization and SPM coregistration won't work !")
print("SPM path is not defined in tab 'Préférences'\n Normalization and SPM coregistration won't work !")
else:
if len(configuration.SPM.spm12_path) > 0:
print("used brainvisa spm path")
self.setSpmTemplatePath(brainvisa_spm12_path)
self.prefs['spm'] = brainvisa_spm12_path
else:
QtGui.QMessageBox.warning(self, "SPM", "SPM path is not defined (or wrong) in tab 'Préférences'\n Normalization and SPM coregistration won't work !")
print("SPM path is not defined (or wrong) in tab 'Préférences'\n Normalization and SPM coregistration won't work !")
if 'freesurfer' in self.prefs:
if brainvisa_freesurfer_home_path != self.prefs['freesurfer']:
QtGui.QMessageBox.warning(self, "Freesurfer", "Freesurfer path different between IntrAnat and BrainVisa, strange, you should check that, by default keep the one precised in IntrAnat")
print("Freesurfer path different between IntrAnat and BrainVisa, strange, you should check that, by default keep the one precised in IntrAnat")
# self.setFreesurferPath(self.prefs['freesurfer'])
else:
self.setFreesurferPath(brainvisa_freesurfer_home_path)
if 'ants' in self.prefs:
self.setANTsPath(self.prefs['ants'])
if 'bids' in self.prefs:
self.setBidsPath(self.prefs['bids'])
if 'coregisterMethod' in self.prefs:
if self.prefs['coregisterMethod'] == 'ANTs':
self.ui.prefSPMcheckbox.setCheckState(False)
self.ui.prefANTScheckbox.setCheckState(True)
if self.prefs['coregisterMethod'] == 'spm':
self.ui.prefSPMcheckbox.setCheckState(True)
self.ui.prefANTScheckbox.setCheckState(False)
if ('projectSelected' in self.prefs) and (self.prefs['projectSelected']) and isinstance(self.prefs['projectSelected'], str):
iProject = self.ui.prefProjectCombo.findText(self.prefs['projectSelected'])
if iProject != -1:
self.ui.prefProjectCombo.setCurrentIndex(iProject)
def warningMEDIC(self):
shortwarning = TimerMessageBox(5, self)
shortwarning.exec_()
def toggleAnatomistWindow(self):
self.a.getControlWindow().setVisible(self.showAnatomist.isChecked())
def savePreferences(self):
prefpath = os.path.join(os.path.expanduser('~'), '.imageimport')
self.prefs['currentProtocol'] = self.currentProtocol
self.prefs['currentSubject'] = self.currentSubject
self.prefs['sites'] = [str(self.ui.subjectSiteCombo.itemText(item)) for item in range(self.ui.subjectSiteCombo.count())]
# SPM path
if len(str(self.ui.prefSpmTemplateEdit.text())) > 0:
self.prefs['spm'] = str(self.ui.prefSpmTemplateEdit.text())
else:
self.prefs.pop('spm', None)
# ANTs path
if len(str(self.ui.prefANTsEdit.text())) > 0:
self.prefs['ants']=str(self.ui.prefANTsEdit.text())
else:
self.prefs.pop('ants', None)
# FreeSurfer path
if len(str(self.ui.prefFreesurferEdit.text())) > 0:
self.prefs['freesurfer'] = str(self.ui.prefFreesurferEdit.text())
else:
self.prefs.pop('freesurfer', None)
# BIDS database
if len(str(self.ui.prefBidsEdit.text())) > 0:
self.prefs['bids'] = str(self.ui.prefBidsEdit.text())
else:
self.prefs.pop('bids', None)
# Coregistration
if self.ui.prefANTScheckbox.isChecked():
self.prefs['coregisterMethod'] = 'ANTs'
elif self.ui.prefSPMcheckbox.isChecked():
self.prefs['coregisterMethod'] = 'spm'
else:
self.prefs['coregisterMethod'] = 'spm'
# Project
self.prefs['projectSelected'] = str(self.ui.prefProjectCombo.currentText())
# Save file
fileout = open(prefpath, 'wb')
pickle.dump(self.prefs, fileout)
fileout.close()
def storeImageReferentialsAndTransforms(self, image):
"""Stores referential and transformation files for an image from its headers -> native, scanner-based, coregistered to"""
# Notes : on prend le header de l'image, on crée un objet referentiel pour le référentiel natif,
# puis un pour chaque transformation définie dans le header
# On stocke les transfos entre le natif et chacun de ces référentiels à partir des infos du header.
# Comment alors faire pour lier le 'coregistered to blabla' au 'scanner based' d'une autre image ? Stocker une transfo identité ou utiliser copyReferential ?
# Et est-ce que copyReferential met à jour toutes les transfos stockées qui utilisaient le référentiel écrasé ?
# D'autre part, comment repérer le référentiel Scanner-based d'une image en particulier ? Pour créer la transfo t1post vers t1pre à partir du recalage SPM...
att = image.attributes()
refName = att['modality'] + '_' + att['acquisition']
print("Storing refs/transfos for " + str(refName))
# Create a Referential object in the database to represent the native referential of the image
moda = self.modas[att['modality']]
nativeRef = self.transfoManager.referential(image)
if nativeRef is None:
print('...Creating native ref')
nativeRef = self.transfoManager.createNewReferentialFor(image, name=refName+'native',
description='Native Anatomist Referential for ' + refName + ' image',
referentialType='Referential of '+moda)
try:
neuroHierarchy.databases.createDiskItemFromFileName(os.path.dirname(nativeRef.fullPath()))
except:
pass
# Create the scanner-based referential
refScan = self.transfoManager.findOrCreateReferential('Scanner Based Referential', image,
name=refName+'_Scanner-Based',
description='Scanner-Based referential for ' + refName + ' image')
try:
neuroHierarchy.databases.createDiskItemFromFileName(os.path.dirname(refScan.fullPath()))
except:
pass
if refScan is None:
print('...Creating scanner-based ref')
refScan = self.transfoManager.createNewReferentialFor(wdiScan, name=refName+'_Scanner-Based',
description='Scanner-Based referential for ' + refName + ' image',
referentialType='Scanner Based Referential')
try:
neuroHierarchy.databases.createDiskItemFromFileName(os.path.dirname(refScan.fullPath()))
except:
pass
# Find where to store the scanner-base transformation
wdiTransformScan = WriteDiskItem('Transformation to Scanner Based Referential',
'Transformation matrix', exactType=True)
transformScan = wdiTransformScan.findValue(image)
# Read the header of the image and read all transformations available
f = aims.Finder()
f.check(image.fileName())
trs = list(f.header()['transformations'])
refs = list(f.header()['referentials'])
trm_to_scannerBased = None
if "Scanner-based anatomical coordinates" in refs:
trm_to_scannerBased = trs[refs.index("Scanner-based anatomical coordinates")]
if trm_to_scannerBased is None:
print("No Scanner-based transfo in image header, using first available transfo instead.")
try:
trm_to_scannerBased = trs[0]
except:
pass
if transformScan is None:
print("Cannot find path for Scanner-based transform in database -> transformation not stored !")
elif trm_to_scannerBased is None:
print("Cannot find Scanner-based transformation in header !")
else:
print('...storing scanner-based transfo')
# Store information into the trm file
mot = aims.Motion(trm_to_scannerBased)
image.setMinf('SB_Transform', str(trm_to_scannerBased))
aims.write(mot, transformScan.fullPath())
try:
neuroHierarchy.databases.createDiskItemFromFileName(os.path.dirname(transformScan.fullPath()))
except:
pass
#set and update database
print(".... setting transfo info : from %s to %s for %s" % (repr(nativeRef),
repr(refScan), repr(transformScan)))
self.transfoManager.setNewTransformationInfo(transformScan, source_referential=nativeRef,
destination_referential=refScan)
def analyseBrainvisaDB(self, tab=None):
"""
Analyze the BrainVisa Database to fill the data for the brainvisa and registration tab (provide the tab number to update only the chosen one, 0 or 4)
"""
try:
rdi = ReadDiskItem('Center', 'Directory') # , requiredAttributes={'center':'Epilepsy'} )
except Exception as e:
QtGui.QMessageBox.warning(self, "Database error", "DATABASE error: " + str(e))
print("DATABASE error: ", str(e))
return
protocols = list(rdi._findValues({}, None, False))
protocols = sorted([str(p.attributes()['center']) for p in protocols])
if len(protocols) == 0:
rep = QtGui.QMessageBox.warning(self, "Center (former protocol)", "No center/protocole defined in BrainVisa Database !")
text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter the name of the center/protocole:')
if ok & bool(text):
wdi = WriteDiskItem('Center', 'Directory') # 'gz compressed NIFTI-1 image')
di = wdi.findValue({'center': str(text)})
if di is None:
QtGui.QMessageBox.warning(self, "Center (former protocol)", "Could not create the center/protocole directory in the database. \nHint: BrainVisa must have a database directory set in its preferences!")
return
os.mkdir(di.fullPath())
neuroHierarchy.databases.insertDiskItem(di, update=True)
if self.currentProtocol in protocols:
currentIndex = protocols.index(self.currentProtocol)
else:
currentIndex = 0
# Update subjects lists
if tab == 0 or tab is None: # BrainVisa database tab
self.ui.bvProtocolCombo.clear()
self.ui.bvProtocolCombo.addItems(protocols)
self.ui.bvProtocolCombo.setCurrentIndex(currentIndex)
if tab == 1 or tab is None: # Create Subject tab
pass
if tab == 2 or tab is None: # Import Nifti tab
self.updateSubjectList(self.ui.niftiSubjectCombo)
if tab == 3 or tab is None: # Registration tab
self.updateSubjectList(self.ui.regSubjectCombo)
def selectProtocol(self, proto, subjCombo):
"""
A BrainVisa protocol was selected : query the database to get the list
of subjects and put them in the provided QComboBox
"""
self.currentProtocol = str(proto)
self.updateSubjectList(subjCombo)
def updateSubjectList(self, subjCombo):
# Update subject list
rdi = ReadDiskItem('Subject', 'Directory', requiredAttributes={'center': self.currentProtocol})
subjects = list(rdi._findValues({}, None, False))
subjCombo.clear()
subjCombo.addItems(sorted([s.attributes()['subject'] for s in subjects]))
# Update selected subject
if self.currentSubject:
idx = subjCombo.findText(self.currentSubject)
if idx != -1:
subjCombo.setCurrentIndex(idx)
def setCurrentSubject(self, subj):
if not subj: # ignore empty values
return
print("current subj : "+str(subj))
self.currentSubject = str(subj)
self.clearAnatomist()
def findAllImagesForSubject(self, protocol, subj):
""" Returns all images for a subject from the brainvisa database.
@return an array of ReadDiskItem
"""
rdi = ReadDiskItem('Raw T1 MRI', 'BrainVISA volume formats',
requiredAttributes={'center': str(protocol), 'subject': str(subj), 'normalized': 'no'})
images = list(rdi._findValues({}, None, False))
images = [x for x in images if "skull_stripped" not in x.fullName()]
rdi = ReadDiskItem('T2 MRI', 'BrainVISA volume formats',
requiredAttributes={'center': str(protocol), 'subject': str(subj)})
images += list(rdi._findValues({}, None, False))
rdi = ReadDiskItem('CT', 'BrainVISA volume formats',
requiredAttributes={'center': str(protocol), 'subject': str(subj)})
images += list(rdi._findValues({}, None, False))
rdi = ReadDiskItem('PET', 'BrainVISA volume formats',
requiredAttributes={'center': str(protocol), 'subject': str(subj)})
images += list(rdi._findValues({}, None, False))
try:
rdi = ReadDiskItem('fMRI-epile', 'BrainVISA volume formats',
requiredAttributes={'center': str(protocol), 'subject': str(subj)})
except:
print("Error loading fMRI-epile file type: epilepsy toolbox probably not installed in Brainvisa !")
QtGui.QMessageBox.warning(self, "Error", "Cannot find fMRI-epile filetype: Intranat's epilepsy-toolbox not installed in Brainvisa !")
return images
images += list(rdi._findValues({}, None, False))
rdi = ReadDiskItem('Statistic-Data', 'BrainVISA volume formats',
requiredAttributes={'center': str(protocol), 'subject': str(subj)})
images += list(rdi._findValues({}, None, False))
rdi = ReadDiskItem('FLAIR', 'BrainVISA volume formats',
requiredAttributes={'center': str(protocol), 'subject': str(subj)})
images += list(rdi._findValues({}, None, False))
rdi = ReadDiskItem('FreesurferAtlas', 'BrainVISA volume formats',
requiredAttributes={'center': str(protocol), 'subject': str(subj)})
images += list(rdi._findValues({}, None, False))
rdi = ReadDiskItem('FGATIR', 'BrainVISA volume formats',
requiredAttributes={'center': str(protocol), 'subject': str(subj)})
images += list(rdi._findValues({}, None, False))
return images
def selectBvSubject(self, subj):
""" A BrainVisa subject was selected : query the database to get the list of images"""
# Change subject
self.clearAnatomist()
# Display "Date : XXXX-XX-XX - Seq: T1 - Acq : T1Pre
self.ui.bvImageList.clear()
images = self.findAllImagesForSubject(self.ui.bvProtocolCombo.currentText(), subj)
self.ui.bvImageList.addItems(sorted(
[i.attributes()['modality'] + ' - ' + i.attributes()['acquisition'] + ' - ' + i.attributes()['subacquisition']
if 'subacquisition' in list(i.attributes().keys())
else i.attributes()['modality'] + ' - ' + i.attributes()['acquisition'] for i in images]))
self.bvImages = {}
for i in images:
if 'subacquisition' in list(i.attributes().keys()):
self.bvImages.update({i.attributes()['modality'] + ' - '
+ i.attributes()['acquisition'] + ' - ' + i.attributes()['subacquisition']: i})
else:
self.bvImages.update({i.attributes()['modality'] + ' - ' + i.attributes()['acquisition']: i})
def selectBvImage(self, item):
""" A BrainVisa image was double-clicked : display it !"""
# Get image to display
image = self.bvImages[str(item.text())]
# Display images
self.displayImage(image, self.wins)
def addBvSubject(self):
self.ui.tabWidget.setCurrentIndex(1)
def deleteBvSubject(self):
protocol = str(self.ui.bvProtocolCombo.currentText())
subj = str(self.ui.bvSubjectCombo.currentText())
rep = QtGui.QMessageBox.warning(self, 'Confirmation',
"<font color='red'><b>WARNING</b><br/>You are about to erase ALL the patient data.<br/><br/><b>DELETE PATIENT \"%s\" ?</b></font>" % subj,
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if rep == QtGui.QMessageBox.Yes:
print("Deleting subject %s" % subj)
rdi = ReadDiskItem('Subject', 'Directory',
requiredAttributes={'center': str(protocol), 'subject': str(subj)})
di = list(rdi._findValues({}, None, False))
if len(di) != 1:
print("%s subject(s) found ! Cannot delete if there is more than 1 !" % repr(len(di)))
return
removeFromDB(di[0].fullPath(), neuroHierarchy.databases.database(di[0].get("_database")))
self.setStatus("Subject %s deleted from the database" % subj)
# Reset the list of subjects :
self.selectProtocol(str(self.ui.bvProtocolCombo.currentText()), self.ui.bvSubjectCombo)
def deleteBvImage(self):
# Delete the current acquisition (including transforms and segmentations : the full acquisition directory
imageName = None
try:
imageName = str(self.ui.bvImageList.currentItem().text())
except: # Probably no image available or no image selected
return
rep = QtGui.QMessageBox.warning(self, 'Confirmation',
"<font color='red'><b>WARNING</b><br/>You are about to delete the selected image and all linked data.<br/><br/><b>DELETE IMAGE \"%s\" ?</b></font>" % imageName,
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if rep == QtGui.QMessageBox.Yes:
image = self.bvImages[imageName] # Gives the path of the image
di = neuroHierarchy.databases.getDiskItemFromFileName(image.fileName())
acqPath = os.path.dirname(image.fileName())
if str(os.path.basename(acqPath)) != str(di.attributes()['acquisition']):
print("CANNOT REMOVE IMAGE : acquisition path does not match acquisition name !")
return
if "subacquisition" in list(di.attributes().keys()):
self.removeDiskItems(di, eraseFiles=True)
else:
removeFromDB(acqPath)
self.setStatus("Image %s deleted from the database" % imageName)
self.selectBvSubject(str(self.ui.bvSubjectCombo.currentText()))
# ===== EDIT BRAINVISA PREFERENCES =====
def editBvPref(self):
""" Open a dialog window to edit the BrainVISA preferences """
# Edit preferences
neuroConfigGUI.editConfiguration()
# Reset the list of subjects
self.analyseBrainvisaDB()
# ===== UPDATE BRAINVISA DATABASES =====
def updateBvDb(self):
""" Open a dialog window to update BrainVISA databases """
from brainvisa.processing.qt4gui import neuroProcessesGUI
# Create dialog to update the databases
d = QtGui.QDialog()
mainLayout = QtGui.QVBoxLayout()
# Display update database process
updateDialog = neuroProcessesGUI.ProcessView(brainvisa.processes.getProcessInstance('updateDatabases'), d)
mainLayout.addWidget(updateDialog)
d.setLayout(mainLayout)
d.move(100, 100)
d.resize(600, 801)
d.exec_()
# Reset the list of subjects
self.analyseBrainvisaDB()
# ===== IMPORT FROM BIDS =====
def importBids(self):
""" Open a dialog window to import subjects from a BIDS database """
if ('bids' not in self.prefs) or (not self.prefs['bids']):
QtGui.QMessageBox.warning(self, "BIDS", "Set the path to the BIDS database in the Prefs tab.")
return
# === GET BIDS SUBJECTS ===
# Parse folders to list subjects
dirListSub = os.listdir(self.prefs['bids'])
bidsSub = []
bidsImg = []
imgDates = dict()
for dirSub in dirListSub:
# Skip all the files that are not subject folder
pathSub = os.path.join(self.prefs['bids'], dirSub)
if not ((len(dirSub) >= 8) and (dirSub[:4] == 'sub-') and os.path.isdir(pathSub)):
continue
# List sessions
dirListSes = sorted(os.listdir(pathSub))
for dirSes in dirListSes:
# Reset list of images to add for this subject
addImg = []
# Skip all the files that are not session folders
pathSes = os.path.join(pathSub, dirSes)
if not ((len(dirSes) > 4) and (dirSes[:4] == 'ses-') and os.path.isdir(pathSes)):
continue
# List modalities
dirListMod = os.listdir(pathSes)
for dirMod in dirListMod:
# Full path
pathMod = os.path.join(pathSes, dirMod)
# ANAT/PET modality folders
if (dirMod == "anat") or (dirMod == "pet"):
# List images to import
dirListImg = os.listdir(pathMod)
for dirImg in dirListImg:
# Look for T1, T2, FLAIR, CT and PET files
pathImg = os.path.join(pathMod, dirImg)
if '_T1w.nii' in dirImg:
imgMod = 'T1'
elif '_T2w.nii' in dirImg:
imgMod = 'T2'
elif '_FLAIR.nii' in dirImg:
imgMod = 'FLAIR'
elif '_pet.nii' in dirImg:
imgMod = 'PET'
elif '_CT.nii' in dirImg:
imgMod = 'CT'
else:
continue
# Look for acquisition: pre, post, postop
if '_acq-pre_' in dirImg:
imgAcq = 'pre'
elif '_acq-post_' in dirImg:
imgAcq = 'post'
elif '_acq-postop_' in dirImg:
imgAcq = 'postOp'
else:
continue
# Look for Gado tag
if '_ce-GADOLINIUM_' in dirImg:
isGado = True
else:
isGado = False
# Add images for this subject
addImg.append({'sub': dirSub[4:], 'ses': dirSes[4:], 'file': dirImg, 'path': pathImg,
'mod': imgMod, 'acq': imgAcq, 'isGado': isGado})
# BIDS Metadata: scans.tsv
elif '_scans.tsv' in dirMod:
# Open file
tsv_file = open(pathMod)
# Not sure this will always work
try:
tsv_reader = csv.reader(tsv_file, delimiter="\t")
# Read header
tsv_header = next(tsv_reader)
iColFile = tsv_header.index('filename')
iColTime = tsv_header.index('acq_time')
# Read all scans
imgDates = dict()
for line in tsv_reader:
imgDates[os.path.split(line[iColFile].replace('\\', '/'))[1]] = line[iColTime]
except:
print(("Could not parse scans info: " + pathMod))
# Close file
tsv_file.close()
# If there are no images to import in this session: skip
if not addImg:
continue
# Add acquisition dates
for i in range(len(addImg)):
try:
addImg[i]['date'] = imgDates[addImg[i]['file']]
except:
print("No acquisition date for image ", repr(addImg[i]))
# Add FreeSurfer for this session
pathFs = os.path.join(self.prefs['bids'], 'derivatives', 'freesurfer', dirSub + '_' + dirSes)
if os.path.exists(os.path.join(pathFs, 'mri', 'aparc.a2009s+aseg.mgz')):
addImg.append({'sub': dirSub[4:], 'ses': dirSes[4:], 'file': 'freesurfer', 'path': pathFs})
# Add subject to list of subjects to import
subName = self.ui.subjectSiteCombo.currentText() + '_' + dirSes[4:] \
+ '_' + dirSub[4:7].upper() + dirSub[7].lower()
bidsSub.append(subName)
bidsImg.append(addImg)
if not bidsSub:
QtGui.QMessageBox.warning(self, "BIDS Import",
"No subjects with anat or pet modalities found in:\n%s" % self.prefs['bids'])
return
# Sort alphabetically
bidsSub, bidsImg = (list(t) for t in zip(*sorted(zip(bidsSub, bidsImg))))
# === GET BRAINVISA SUBJECTS ===
# Get list of subjects in BrainVISA database
rdi = ReadDiskItem('Subject', 'Directory',
requiredAttributes={'center': str(self.ui.bvProtocolCombo.currentText())})
bvFiles = list(rdi._findValues({}, None, False))
if bvFiles:
bvSub = [os.path.split(s.attributes()['subject'])[1] for s in bvFiles]
# Difference between two lists
subNew = list(set(bidsSub) - set(bvSub))
else:
subNew = bidsSub
# No subjects to import
if not subNew:
QtGui.QMessageBox.warning(self, "BIDS Import",
"All BIDS subjects are already imported in the IntrAnat database.")
return
# Ask user to select which ones to import
dialog = DialogCheckbox.DialogCheckbox(subNew, "Import BIDS", "Select the patients to import:")
selSub = dialog.exec_()
if not selSub:
return
# Get selected BIDS subjects
iSubImport = [bidsSub.index(subNew[i]) for i in range(len(subNew)) if selSub[i]]
# === ASK IMPORT OPTIONS ===
# Ask user to select which ones to import
dialog = DialogCheckbox.DialogCheckbox(('Normalize T1pre + Coregister images', 'Reslice images based on T1pre'),
"Import BIDS", "Run automatically after importing:", (True, False))
selOpt = dialog.exec_()
if not selOpt:
return