forked from IntrAnatSEEGSoftware/IntrAnat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
locateElectrodes.py
4460 lines (3723 loc) · 224 KB
/
locateElectrodes.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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Localisation graphique des electrodes
#
# (c) Inserm U836 2012-2014 - Manik Bhattacharjee
#
# License GNU GPL v3
#
# Pour un seul patient
#
# 1) Charger les modeles d'electrode
# 2) Recherche de sujet/classement par date des sujets
# 3) Obtenir la liste des données nécessaires
# 4) Rechercher les référentiels disponibles (MNI/Talairach/IRM/CA-CP/CA-CPnormalise)
# et tous les referentiels "image" (pre/post/IRMf/PET ?)
# 5) Interface : Ajout/Sélection/Suppression d'électrodes, labels (attention au numéro des plots)
# Plot 1 = extremite
# 6) Afficher les coordonnées de chacun des plots dans le referentiel choisi
# 7) Exporter (et reimporter) les coordonnées des electrodes
#
# TODO
# Liens BrainVisa (chargement des images, sauvegarde des implantations)
# Affichage des labels --> problème de référentiel ?
# En normalisant et exportant : si un fichier va être écrasé, demander confirmation !
# RemoveElectrode : remove also the label objects
# Exportation : classer les plots pour que l'exportation comporte A0 A1 A2 B1 B3 et pas B3 A1 B1 A0...
# AimsMIRegister -> utilisation des fichiers TRM ou utilisation du recalage SPM ?
# Valider les templates d'electrodes avant de les utiliser : un plot doit TOUJOURS se nommer "Plot152" et pas "Element 21" ou "Plot 152" -> modifier l'éditeur de template
# for DTI : ./AimsMeshDistance --help
import sys, os, pickle, glob, numpy, re, string, time, subprocess, json, copy, csv, gc #gc.get_referrers pour trouver où est encore déclarer une variable (pour problem quand variable déclarer en python et en c++)
import openpyxl
from PyQt4 import QtGui, QtCore, uic, Qt
from PyQt4.QtGui import QVBoxLayout
from numpy import *
from math import sqrt, cos, sin
from collections import OrderedDict
from soma import aims
from brainvisa import axon
#from soma.aims.spmnormalizationreader import readSpmNormalization
from brainvisa import anatomist
from brainvisa.data import neuroHierarchy
import registration
from externalprocesses import *
from MicromedListener import MicromedListener as ML
from referentialconverter import ReferentialConverter
from checkSpmVersion import *
from readSulcusLabelTranslationFile import *
from readFreesurferLabelFile import *
from neuroProcesses import defaultContext
from TimerMessageBox import *
from generate_contact_colors import *
from bipoleSEEGColors import bipoleSEEGColors
from DeetoMaison import DeetoMaison
#from neuroProcesses import *
import ImportTheoreticalImplentation
from scipy import ndimage
from brainvisa.processes import *
from PIL import Image
import pdb
#import objgraph #if not install in a terminal : pip install objgraph --prefix /brainvisa_4.50/
#name = 'Anatomist Show MarsAtlas Parcels Texture'
#roles = ('viewer',)
#userLevel = 0
#def validation():
# anatomist.validation()
#signature = Signature(
# 'texture_marsAtlas_parcels', ReadDiskItem('hemisphere marsAtlas parcellation texture', 'aims Texture formats', requiredAttributes={ 'regularized': 'false' }),
# 'white_mesh',ReadDiskItem( 'Hemisphere White Mesh', 'aims mesh formats' ),
#)
########## SPM calls
# Convert SPM normalization _sn.mat to vector field
spm_SnToField8 = """try, addpath(genpath(%s));spm('defaults', 'FMRI');spm_jobman('initcfg');
clear matlabbatch;
FileNameSN = '%s';
matlabbatch{1}.spm.util.defs.comp{1}.inv.comp{1}.sn2def.matname{1}=FileNameSN;
matlabbatch{1}.spm.util.defs.comp{1}.inv.comp{1}.sn2def.vox=[NaN NaN NaN];
matlabbatch{1}.spm.util.defs.comp{1}.inv.comp{1}.sn2def.bb=NaN*ones(2,3);
matlabbatch{1}.spm.util.defs.comp{1}.inv.space{1}=['%s' ',1'];
matlabbatch{1}.spm.util.defs.ofname='%s';
matlabbatch{1}.spm.util.defs.fnames='';
matlabbatch{1}.spm.util.defs.savedir.saveusr{1}=spm_str_manip(FileNameSN,'h');
matlabbatch{1}.spm.util.defs.interp=1;
spm_jobman('run',matlabbatch);catch, disp 'AN ERROR OCCURED'; end;quit;""" # %(FileNameSN, FileSource, ofname) -> '_sn.mat' file and source image FileSource (normalized with the _sn). For the Database, we want y_<subject>_inverse.nii, so we need ofname = '<subject>_inverse' --> Maybe should provide also the output dir ? Right now, same as _sn.mat
# API changed in SPM12...
spm_SnToField12 = """try, addpath(genpath(%s));spm('defaults', 'FMRI');spm_jobman('initcfg');
clear matlabbatch;
FileNameSN = '%s';
matlabbatch{1}.spm.util.defs.comp{1}.inv.comp{1}.sn2def.matname{1}=FileNameSN;
matlabbatch{1}.spm.util.defs.comp{1}.inv.comp{1}.sn2def.vox=[NaN NaN NaN];
matlabbatch{1}.spm.util.defs.comp{1}.inv.comp{1}.sn2def.bb=NaN*ones(2,3);
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{1}=spm_str_manip(FileNameSN,'h');
spm_jobman('run',matlabbatch);catch, disp 'AN ERROR OCCURED'; end;quit;"""
#spm_SnToField = spm_SnToField12
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_inverse_y_field8 ="""try,addpath(genpath(%s));spm('defaults', 'FMRI');spm_jobman('initcfg');
spm_jobman('run',matlabbatch);catch, disp 'AN ERROR OCCURED'; end;quit;"""
# Read deformation field y_<subject>_inverse.nii, apply the vector field to scanner-based coordinates of electrodes
spm_normalizePoints = """
try, addpath(genpath(%s));P='%s';
P1=spm_vol([P ',1,1']);
P2=spm_vol([P ',1,2']);
P3=spm_vol([P ',1,3']);
[V1,XYZ]=spm_read_vols(P1);
V2=spm_read_vols(P2);
V3=spm_read_vols(P3);
%% Apply tranformation to electrodes
PosElectrode = dlmread('%s');
wPosElectrode=PosElectrode;
for i1=1:size(PosElectrode,1)
D=(XYZ(1,:)-PosElectrode(i1,1)).^2+(XYZ(2,:)-PosElectrode(i1,2)).^2+(XYZ(3,:)-PosElectrode(i1,3)).^2;
[tmp,order]=sort(D);
tmp=tmp(1:18); %% cubic neighborhood
order=order(1:18);
W=1./tmp; %% weight inverse to distance
if sum(isinf(W))>0
W=[1 zeros(1,length(W)-1)];
end
wPosElectrode(i1,:)=[sum(V1(order).*W)./sum(W) sum(V2(order).*W)./sum(W) sum(V3(order).*W)./sum(W)];
end
dlmwrite('%s',wPosElectrode,'precision',18);
catch, disp 'AN ERROR OCCURED'; end;quit;
"""
#coregister and reslice and segmentation (for resection estimation)
spm_resection_estimation = """try, addpath(genpath(%s)); spm('defaults', 'FMRI'); spm_jobman('initcfg');
clear matlabbatch;
final_directory = %s;
if isdir(final_directory) == 0
mkdir(final_directory)
end
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 = 4;
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';
matlabbatch{2}.spm.spatial.preproc.channel.vols = %s;
matlabbatch{2}.spm.spatial.preproc.channel.biasreg = 0.001;
matlabbatch{2}.spm.spatial.preproc.channel.biasfwhm = 60;
matlabbatch{2}.spm.spatial.preproc.channel.write = [0 0];
matlabbatch{2}.spm.spatial.preproc.tissue(1).tpm = %s;
matlabbatch{2}.spm.spatial.preproc.tissue(1).ngaus = 2;
matlabbatch{2}.spm.spatial.preproc.tissue(1).native = [1 0];
matlabbatch{2}.spm.spatial.preproc.tissue(1).warped = [0 0];
matlabbatch{2}.spm.spatial.preproc.warp.mrf = 1;
matlabbatch{2}.spm.spatial.preproc.warp.cleanup = 1;
matlabbatch{2}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2];
matlabbatch{2}.spm.spatial.preproc.warp.affreg = 'mni';
matlabbatch{2}.spm.spatial.preproc.warp.fwhm = 0;
matlabbatch{2}.spm.spatial.preproc.warp.samp = 3;
matlabbatch{2}.spm.spatial.preproc.warp.write = [0 0];
matlabbatch{3}.spm.spatial.preproc.channel.vols = %s;
matlabbatch{3}.spm.spatial.preproc.channel.biasreg = 0.001;
matlabbatch{3}.spm.spatial.preproc.channel.biasfwhm = 60;
matlabbatch{3}.spm.spatial.preproc.channel.write = [0 0];
matlabbatch{3}.spm.spatial.preproc.tissue(1).tpm = %s;
matlabbatch{3}.spm.spatial.preproc.tissue(1).ngaus = 2;
matlabbatch{3}.spm.spatial.preproc.tissue(1).native = [1 0];
matlabbatch{3}.spm.spatial.preproc.tissue(1).warped = [0 0];
matlabbatch{3}.spm.spatial.preproc.warp.mrf = 1;
matlabbatch{3}.spm.spatial.preproc.warp.cleanup = 1;
matlabbatch{3}.spm.spatial.preproc.warp.reg = [0 0.001 0.5 0.05 0.2];
matlabbatch{3}.spm.spatial.preproc.warp.affreg = 'mni';
matlabbatch{3}.spm.spatial.preproc.warp.fwhm = 0;
matlabbatch{3}.spm.spatial.preproc.warp.samp = 3;
matlabbatch{3}.spm.spatial.preproc.warp.write = [0 0];
matlabbatch{4}.spm.util.imcalc.input = {
%s
%s
};
matlabbatch{4}.spm.util.imcalc.output = %s;
matlabbatch{4}.spm.util.imcalc.outdir = %s;
matlabbatch{4}.spm.util.imcalc.expression = 'i1-i2';
matlabbatch{4}.spm.util.imcalc.var = struct('name', {}, 'value', {});
matlabbatch{4}.spm.util.imcalc.options.dmtx = 0;
matlabbatch{4}.spm.util.imcalc.options.mask = 0;
matlabbatch{4}.spm.util.imcalc.options.interp = 1;
matlabbatch{4}.spm.util.imcalc.options.dtype = 4;
spm_jobman('run',matlabbatch);catch, disp 'AN ERROR OCCURED'; end;quit;"""
region_grow="""try,addpath(genpath(%s));
imgresec = %s;
iSeed = %s;
reseccenter = %s;
f_orient = %s;
f_orient = reshape(f_orient,4,4)';
centermatF = eye(4);
centermatF(:,4) = f_orient*[reseccenter 1]';
VF = spm_vol(imgresec);
reseccenter_pix = inv(VF.mat)*centermatF(:,4);
mat_to_grow=spm_read_vols(VF);
new_image = regiongrowing(mat_to_grow,iSeed,reseccenter_pix(1:3));
VF.fname = %s;
VF.private.mat0 = VF.mat;
spm_write_vol(VF,new_image);
catch, disp 'AN ERROR OCCURED'; end;quit;"""
def viewFile(filepath):
""" Launches an external app to display the provided file (windows/linux/mac-specific methods) """
if sys.platform.startswith('darwin'):
subprocess.call(('open', filepath))
elif os.name == 'nt':
os.startfile(filepath)
elif os.name == 'posix':
subprocess.call(('xdg-open', filepath))
# Functions to sort the contacts A1,A2...,A10 and not A1, A10, A2..
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
"""alist.sort(key=natural_keys) sorts in human order"""
return [ atoi(c) for c in re.split('(\d+)', text) ]
##################### Electrode functions (to be exported in another file FIXME needs natural_keys function ##################################
from electrode import ElectrodeModel
def moveElectrode(target, entry, referential, newRef, a, meshes):
# a is anatomist object
if entry is None or target is None:
print("entry or target is None")
return
#print "entry : "+repr(entry)+"target : "+repr(target)
if newRef is None:
newRef = a.createReferential()
transl = target#[-target[0], -target[1], -target[2]]
i = array([[1,0,0]])
z = array([target,]) - array([entry,])
if z[0][1] < 0.001 and z[0][2] < 0.001:# si i est colinéaire avec z, changer i car on n'obtiendra pas un vecteur perpendiculaire aux deux
i = array([[0,1,0]])
if linalg.norm(z) == 0:
return
z = -z / linalg.norm(z)
#print "z = "+repr(z)
y = cross (i,z)
y = -y/linalg.norm(y)
#print "y = "+repr(y)
x = cross(y,z)
#print "x = "+repr(x)
#m = [x[0][0], x[0][1], x[0][2], y[0][0],y[0][1], y[0][2], z[0][0], z[0][1], z[0][2]]
m = [x[0][0], y[0][0], z[0][0], x[0][1],y[0][1], z[0][1], x[0][2], y[0][2], z[0][2]]
try:
transf = a.createTransformation(transl+m, origin = newRef, destination = referential)
except:
print("problem transformation")
return
pdb.set_trace()
a.assignReferential(newRef, meshes)
#print " Electrode moved : target = "+repr(target) + ", entry = "+repr(entry) + " and Matrix "+repr(transl+m)
#pdb.set_trace()
return (newRef, transf)
def createElectrode(target, entry, referential, ana=None, windows=None, model = None, dispMode=None, dispParams=None):
elecModel = ElectrodeModel(ana)
elecModel.open(model,dispMode, dispParams)
#elecModel.setDisplayReferential(newRef)
meshes = elecModel.getAnatomistObjects()
(newRef, transf) = moveElectrode(target, entry, referential, None, ana, meshes)
#pdb.set_trace()
if windows is not None:
ana.addObjects(meshes, windows)
return (newRef, transf, elecModel)
def createBipole(target, entry, referential, ana=None, windows=None, model = None, dispMode=None, dispParams=None):
elecModel = ElectrodeModel(ana)
elecModel.open(str(model),dispMode, dispParams)
#elecModel.setDisplayReferential(newRef)
meshes = elecModel.getAnatomistObjects()
#mesh = self.a.toAObject(aims.SurfaceGenerator.cylinder(aims.Point3df(p[0], p[1], p[2]), aims.Point3df(pEnd), r, r, 24, True, True))
(newRef, transf) = moveElectrode(target, entry, referential, None, ana, meshes)
if windows is not None:
ana.addObjects(meshes, windows)
return (newRef, transf, elecModel)
# Récupération des plots dans l'ordre plot1 -> plot n
def getPlots(elecModel):
cyls = elecModel.getCylinders()
return dict((name,cyls[name]) for name in cyls if cyls[name]['type'] == 'Plot')
def getPlotsNames(elecModel):
cyls = elecModel.getCylinders()
plots = [n for n in cyls if cyls[n]['type'] == 'Plot']
return sorted(plots, key=natural_keys)
# Récupération des coordonnées des centres des plots dans le référentiel électrode
def getPlotsCenters(elecModel):
plots = getPlots(elecModel)
return dict((p, plots[p]['center']) for p in plots)
############### 3D text annotations from anagraphannotate.py #############"
byvertex = False
# This intermediate class is only here because I cannot (yet) make SIP
# generate a non-abstract class for TextObject binding. One day, I'll find out!
class TObj ( anatomist.anatomist.cpp.TextObject ):
def __init__( self, message='', pos=[0,0,0] ):
anatomist.anatomist.cpp.TextObject.__init__( self, message, pos )
class Props( object ):
def __init__( self ):
self.lvert = []
self.lpoly = []
self.usespheres = True
self.colorlabels = True
self.center = aims.Point3df()
def makelabel( a, label, gc, pos, ref, color, props ):
""" Create a text label designating gc at position pos, using anatomist instance a, a color and stores the generated elements in props"""
objects = []
# create a text object
to = TObj( label )
to.setScale( 0.1 )
to.setName( 'label: ' + label )
a.releaseObject(to)
# If we want to show a sphere at the target point
if props.usespheres:
sph = aims.SurfaceGenerator.icosphere( gc, 2, 50 )
asph = a.toAObject( sph )
asph.setMaterial( diffuse=color )
asph.setName( 'gc: ' + label )
a.registerObject( asph, False )
a.releaseObject(asph) #registerObject le "dérelease"
objects.append( asph )
# Choose the color of the label text
if props.colorlabels:
to.GetMaterial().set( { 'diffuse': color } )
# texto is the label (2D texture on a rectangle), but defined to always face the camera
texto = anatomist.anatomist.cpp.TransformedObject( [ to ], False, True, pos )
texto.setDynamicOffsetFromPoint( props.center )
texto.setName( 'annot: ' + label )
objects.append( texto )
# Add to the polygons a line (to link the label and the target position)
props.lpoly.append( aims.AimsVector_U32_2( ( len( props.lvert ),
len( props.lvert ) + 1 ) ) )
props.lvert += [ gc, pos ]
a.registerObject( texto, False )
a.assignReferential(ref, objects)
a.releaseObject(texto)
return objects
############################### Useful functions
def createItemDirs(item):
""" Create the directories containing the provided WriteDiskItem and insert them in the BrainVisa database """
# Copied from brainvisa.processes, in ExecutionContext._processExecution()
dirname = os.path.dirname( item.fullPath() )
dir=dirname
dirs = []
while not os.path.exists( dir ):
dirs.append(dir)
dir=os.path.dirname(dir)
if dirs:
try:
os.makedirs( dirname )
except OSError, e:
if not e.errno == errno.EEXIST:
# filter out 'File exists' exception, if the same dir has
# been created concurrently by another instance of BrainVisa
# or another thread
raise
for d in dirs:
dirItem=neuroHierarchy.databases.createDiskItemFromFileName(d, None)
######################### FENETRE PRINCIPALE ############################
class LocateElectrodes(QtGui.QDialog):
def __init__(self, app=None, loadAll = True):
# UI init
if loadAll == True:
QtGui.QWidget.__init__(self)
self.ui = uic.loadUi("epilepsie-electrodes.ui", self)
self.setWindowTitle('Epilepsie - localisation des electrodes - NOT FOR MEDICAL USAGE')
# Widget 0 (buttons panel) will be at minimum size (stretch factor 0), the windows will fill up the rest
self.splitter_2.setStretchFactor(0,0)
self.splitter_2.setStretchFactor(1,1)
# Equal size for both views
self.splitter.setStretchFactor(0,1)
self.splitter.setStretchFactor(1,1)
self.nameEdit.setText('A')
# Load the list of protocols, patients and electrode models from BrainVisa
if loadAll == True:
self.modalities = ['Raw T1 MRI', 'T2 MRI', 'CT', 'PET', 'Electrode Implantation Coronal Image', 'Electrode Implantation Sagittal Image','fMRI-epile', 'Statistic-Data','FLAIR', 'resection', 'FreesurferAtlas', 'FGATIR','HippoFreesurferAtlas']
# Electrode models
self.elecModelList = []
self.elecModelListByName = []
self.loadFromBrainVisa()
# Init of variables
self.app = app
self.dispObj = {} # All displayable objects "t1mri-pre", "t2"...
self.objtokeep = {} #all object we must keep alive for anatomist but not in other variables
self.diskItems = {} # For each dispObj, a list of dictionnaries {'refName', 'refObj', 'refId', 'transf'}
# Coordinates displayed using referential : 'Natif' par defaut
self.coordsDisplayRef = 'Natif'
self.referentialCombo.clear()
self.referentialCombo.addItems(['Natif',])
self.dispMode = 'real'
self.dispParams = None
self.t1preMniFieldPath = None
self.t1pre2ScannerBasedId = None
self.electrodes = []# {Les objets electrodes avec les coordonnées, les meshes
self.bipoles = [] #{Les objects bipoles}
self.electrodeTemplateStubs = [] # Un objet electrode par template disponible dans la base de données (chargé à la demande par getElectrodeTemplates)
self.contacts = [] # {name:n, number:2, electrode: e, mesh:m}
self.transfs = [] # identity transforms (must be stored)
self.currentWindowRef = None # Referential used by windows (because pyanatomist AWindow.getReferential is not implemented yet)
self.linkedRefs = [] # Referentials linked by a identity transform
self.transf2Mni = {} # Transformation from T1 pre referential to MNI referential
self.threads = [] # List of running threads
self.t1pre2ScannerBasedTransform = None #Transfo from T1pre native to scanner-based referential (Anatomist Transformation object)
self.brainvisaPatientAttributes = None # Attributes of a BrainVisa ReadDiskItem MRI of the loaded patient
self.spmpath = None
#self.MicromedListener = ML()
# list of objects to display in window for each scenario (MNI, pre, post, etc)
self.windowContent = { 'IRM pre':['T1pre','electrodes',],\
'IRM pre T2':['T2pre','electrodes',],\
'IRM pre + hemisphere droit':['T1pre','T1pre-rightHemi','electrodes',],\
'IRM pre + MARS ATLAS droit':['T1pre','right MARS ATLAS BIDULE','electrodes',],\
'IRM pre + hemisphere gauche':['T1pre','T1pre-leftHemi','electrodes',],\
'IRM pre + MARS ATLAS gauche':['T1pre','left MARS ATLAS BIDULE','electrodes',],\
'IRM pre + hemispheres':['T1pre','T1pre-rightHemi','T1pre-leftHemi','electrodes',],\
'IRM pre + hemispheres + tete':['T1pre','T1pre-rightHemi','T1pre-leftHemi', 'T1pre-head','electrodes',],\
'IRM post':['T1post','electrodes',],\
'IRM post T2':['T2post','electrodes',],\
'CT post':['CTpost','electrodes',],\
'PET pre':['PETpre','electrodes',],\
'FLAIR pre':['FLAIRpre','electrodes',],\
'FGATIR pre':['FGATIRpre','electrodes',],\
'fMRI pre':['fMRIpre','electrodes'],\
'Statistic Data':['Statisticspre','electrodes'],\
'IRM post-op':['T1postOp','electrodes',],\
'Resection':['Resection','electrodes',],\
'FreeSurferAtlas':['FreesurferAtlaspre','electrodes',],\
'HippoFreeSurferAtlas':['HippoFreesurferAtlaspre','electrodes',],\
}
self.windowCombo1.clear()
self.windowCombo1.addItems(sorted(self.windowContent.keys()))
self.windowCombo2.clear()
self.windowCombo2.addItems(sorted(self.windowContent.keys()))
# Anatomist windows
if loadAll == True:
self.wins=[]
self.a = anatomist.Anatomist('-b') #Batch mode (hide Anatomist window)
self.a.onCursorNotifier.add(self.clickHandler)
layoutAx = QtGui.QHBoxLayout( self.windowContainer1 )
self.axWindow = self.a.createWindow( 'Axial' )#, no_decoration=True )
self.axWindow.setParent(self.windowContainer1)
layoutAx.addWidget( self.axWindow.getInternalRep() )
layoutSag = QtGui.QHBoxLayout( self.windowContainer2 )
self.sagWindow = self.a.createWindow( 'Axial' )#, no_decoration=True )
self.sagWindow.setParent(self.windowContainer2)
layoutSag.addWidget( self.sagWindow.getInternalRep() )
self.wins = [self.axWindow, self.sagWindow]
# Get Transformation Manager
self.transfoManager = registration.getTransformationManager()
# Get ReferentialConverter (for Talairach, AC-PC...)
self.refConv = ReferentialConverter()
if loadAll == True:
# Linking UI elements to functions
self.connect(self.loadPatientButton, QtCore.SIGNAL('clicked()'), self.loadPatient)
self.connect(self.changePatientButton, QtCore.SIGNAL('clicked()'), self.changePatient)
self.connect(self.patientList, QtCore.SIGNAL('itemDoubleClicked(QListWidgetItem*)'), lambda x:self.loadPatient())
self.connect(self.protocolCombo, QtCore.SIGNAL('currentIndexChanged(int)'), self.updateBrainvisaProtocol)
self.connect(self.filterSiteCombo, QtCore.SIGNAL('currentIndexChanged(int)'), self.filterSubjects)
self.connect(self.filterYearCombo, QtCore.SIGNAL('currentIndexChanged(int)'), self.filterSubjects)
self.connect(self.addElectrodeButton, QtCore.SIGNAL('clicked()'), self.addElectrode)
self.connect(self.removeElectrodeButton, QtCore.SIGNAL('clicked()'), self.removeElectrode)
self.connect(self.nameEdit, QtCore.SIGNAL('editingFinished()'), self.editElectrodeName)
self.connect(self.targetButton, QtCore.SIGNAL('clicked()'), self.updateTarget)
self.connect(self.entryButton, QtCore.SIGNAL('clicked()'), self.updateEntry)
self.connect(self.electrodeList, QtCore.SIGNAL("currentRowChanged(int)"), self.electrodeSelect)
self.connect(self.electrodeList, QtCore.SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.electrodeGo)
self.connect(self.contactList, QtCore.SIGNAL("itemClicked(QListWidgetItem*)"), self.contactSelect)
self.connect(self.contactList, QtCore.SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.contactGo)
self.connect(self.typeComboBox, QtCore.SIGNAL('currentIndexChanged(QString)'), self.updateElectrodeModel)
# itemClicked(QListWidgetItem*) , currentItemChanged ( QListWidgetItem * current, QListWidgetItem * previous ), currentRowChanged ( int currentRow )
self.connect(self.electrodeLoadButton, QtCore.SIGNAL('clicked()'), self.loadElectrodes)
self.connect(self.electrodeSaveButton, QtCore.SIGNAL('clicked()'), self.saveElectrodes)
self.connect(self.normalizeExportButton, QtCore.SIGNAL('clicked()'), self.normalizeExportElectrodes)
#self.connect(self.marsatlasExportButton, QtCore.SIGNAL('clicked()'),self.parcelsExportElectrodes)
self.connect(self.colorConfigButton, QtCore.SIGNAL('clicked()'), self.configureColors)
self.connect(self.dispModeCombo, QtCore.SIGNAL('currentIndexChanged(int)'), self.updateDispMode)
self.connect(self.windowCombo1, QtCore.SIGNAL('currentIndexChanged(QString)'), lambda s: self.windowUpdate(0,s))
self.connect(self.windowCombo2, QtCore.SIGNAL('currentIndexChanged(QString)'), lambda s: self.windowUpdate(1,s))
self.connect(self.referentialCombo, QtCore.SIGNAL('currentIndexChanged(QString)'), self.updateCoordsDisplay)
self.connect(self.electrodeRefCheck, QtCore.SIGNAL('stateChanged(int)'), self.updateElectrodeView)
self.connect(self.electrodeRefRotationSlider, QtCore.SIGNAL('valueChanged(int)'), self.updateElectrodeViewRotation)
self.connect(self.Clipping_checkbox,QtCore.SIGNAL('clicked()'),self.clippingUpdate)
self.connect(self.makefusionButton,QtCore.SIGNAL('clicked()'),self.makeFusion)
self.connect(self.generateResectionArray,QtCore.SIGNAL('clicked()'),self.generateResection)
self.connect(self.validateROIresection,QtCore.SIGNAL('clicked()'),self.ROIResectiontoNiftiResection)
self.connect(self.deleteMarsAtlasfiles,QtCore.SIGNAL('clicked()'),self.DeleteMarsAtlasFiles)
self.connect(self.generateDictionariesComboBox,QtCore.SIGNAL('activated(QString)'),self.generateDictionaries)
self.connect(self.ImportTheoriticalImplantation,QtCore.SIGNAL('clicked()'),self.importRosaImplantation)
self.connect(self.approximateButton,QtCore.SIGNAL('clicked()'),self.approximateElectrode)
prefpath_imageimport = os.path.join(os.path.expanduser('~'), '.imageimport')
try:
if (os.path.exists(prefpath_imageimport)):
filein = open(prefpath_imageimport, 'rb')
prefs_imageimport = pickle.load(filein)
self.spmpath = prefs_imageimport['spm']
self.fileNoDBpath = prefs_imageimport['FileNoDBPath']
filein.close()
except:
print 'NO SPM path found, will be unable to export MNI position'
pass
self.warningMEDIC()
# Reload options, check brainvisa and matlab/SPM
def closeEvent(self, event):
self.quit(event)
def quit(self, event=None):
reply = QtGui.QMessageBox.question(self, 'Message',
"Quit the software without saving ?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.No)
#if self.brainvisaPatientAttributes is not None:
#self.saveElectrodes()
# Remove the vector field to MNI if it was computed
#self.clearT1preMniTransform()
if reply == QtGui.QMessageBox.Yes:
axon.processes.cleanup()
if event is None:
self.app.quit()
else:
event.accept()
else:
event.ignore()
def warningMEDIC(self):
shortwarning = TimerMessageBox(5,self)
shortwarning.exec_()
#messagebox = QtGui.QMessageBox(self)
#messagebox.setWindowTitle("NOT FOR MEDICAL USAGE")
#messagebox.setText("NOT FOR MEDICAL USAGE\n (closing automatically in {0} secondes.)".format(3))
#messagebox.setStandardButtons(messagebox.NoButton)
#self.timer2 = QtCore.QTimer()
#self.time_to_wait = 3
#def close_messagebox(e):
#e.accept()
#self.timer2.stop()
#self.time_to_wait = 10
#def decompte():
#messagebox.setText("NOT FOR MEDICAL USAGE\n (closing automatically in {0} secondes.)".format(self.time_to_wait))
#if self.time_to_wait <= 0:
#messagebox.closeEvent = close_messagebox
#messagebox.close()
#self.time_to_wait -= 1
#self.connect(self.timer2,QtCore.SIGNAL("timeout()"),decompte)
#self.timer2.start(1000)
#messagebox.exec_()
def loadFromBrainVisa(self):
# Find available patients in BV database
print "LOADING DATA FROM BRAINVISA"
rdi = ReadDiskItem( 'Subject', 'Directory',requiredAttributes={'_ontology':'brainvisa-3.2.0'} ) #, requiredAttributes={'center':'Epilepsy'} )
subjects = list( rdi._findValues( {}, None, False ) )
protocols = list(set([s.attributes()['center'] for s in subjects if 'center' in s.attributes()]))
# Fill the combo
self.protocolCombo.clear()
self.protocolCombo.addItems(sorted(protocols))
self.allSubjects = subjects
self.updateBrainvisaProtocol()
def updateBrainvisaProtocol(self, idx=None):
"""Updates the UI when the selected protocol changes"""
self.currentProtocol = str(self.protocolCombo.currentText())
self.subjects = [s.attributes()['subject'] for s in self.allSubjects if 'center' in s.attributes() and s.attributes()['center'] == self.currentProtocol]
print 'all subjects:' + repr(self.subjects)
self.patientList.clear()
self.patientList.addItems(sorted(self.subjects))
# Update the filters
sites = ['*',] + sorted(set([s.split('_')[0] for s in self.subjects]))
years = ['*',] + sorted(set([s.split('_')[1] for s in self.subjects if len(s.split('_')) > 1]))
self.filterSiteCombo.clear()
self.filterSiteCombo.addItems(sites)
self.filterYearCombo.clear()
self.filterYearCombo.addItems(years)
# Loading electrode models
rdiEM = ReadDiskItem('Electrode Model', 'Electrode Model format', requiredAttributes={'center':self.currentProtocol})
self.elecModelList = list (rdiEM._findValues( {}, None, False ) )
elecNames = [e.attributes()['model_name'] for e in self.elecModelList]
self.elecModelListByName = dict((e.attributes()['model_name'], e) for e in self.elecModelList)
self.typeComboBox.clear()
self.typeComboBox.addItems(elecNames)
def filterSubjects(self, value=None):
"""Filtering subject list"""
subs = self.subjects
if str(self.filterSiteCombo.currentText()) != '*':
subs = [s for s in subs if s.split('_')[0] == str(self.filterSiteCombo.currentText())]
if str(self.filterYearCombo.currentText()) != '*':
subs = [s for s in subs if len(s.split('_')) > 1 and s.split('_')[1] == str(self.filterYearCombo.currentText())]
self.patientList.clear()
self.patientList.addItems(sorted(subs))
def getT1preMniTransform(self):
"""Returns the path of the transformation to MNI (vector field) and compute it if necessary (from _sn.mat)"""
#pdb.set_trace()
if self.t1preMniFieldPath is not None:
return self.t1preMniFieldPath
# Find _sn.mat
if 'T1pre' not in self.dispObj:
print "No T1pre loaded : cannot get MNI transform from it"
return None
#look for a y_file_inverse first
rdi_inv_read = ReadDiskItem('SPM normalization inverse deformation field','NIFTI-1 image')
di_inv_read = rdi_inv_read.findValue(self.diskItems['T1pre'])
if di_inv_read is None:
print "No inverse deformation field found in database"
else:
print "inverse deformation field found and used"
#pdb.set_trace()
self.t1preMniFieldPath = di_inv_read.fileName()
return self.t1preMniFieldPath
spm_version = checkSpmVersion(self.spmpath)
#look for a y_file second
rdi_y = ReadDiskItem('SPM normalization deformation field','NIFTI-1 image')
di_y = rdi_y.findValue(self.diskItems['T1pre'])
#pdb.set_trace()
if di_y is None:
print "No deformation field found in database"
else:
print "deformation field found and used"
wdi_inverse = WriteDiskItem('SPM normalization inverse deformation field','NIFTI-1 image')
dir_yinv_split = str(di_y.fileName()).split('/')
name_yinverse = dir_yinv_split.pop()[2:]
#name_yinverse.replace('.nii','_inverse.nii')
dir_yinverse = "/".join(dir_yinv_split)
di_inverse = wdi_inverse.findValue(di_y)
#on fait l'inversion de la deformation
#pdb.set_trace()
#pour le moment ce bout de code ne marche qu'avec spm12
if spm_version == '(SPM12)':
print 'SPM12 used'
matlabRun(spm_inverse_y_field12%("'"+self.spmpath+"'","'"+str(di_y.fileName())+"'","'"+self.dispObj['T1pre'].fileName()+"'","'"+name_yinverse.replace('.nii','_inverse.nii')+"'","'"+dir_yinverse+"'"))
if spm_version == '(SPM8)':
print 'SPM8 used'
matlabRun(spm_inverse_y_field8%("'"+self.spmpath+"'","'"+str(di_y.fileName())+"'","'"+self.dispObj['T1pre'].fileName()+"'","'"+name_yinverse.replace('.nii','_inverse.nii')+"'","'"+dir_yinverse+"'"))
self.t1preMniFieldPath = di_inverse.fileName()
neuroHierarchy.databases.insertDiskItem( di_inverse, update=True )
return self.t1preMniFieldPath
#look for a _sn.mat if no y_file
rdi = ReadDiskItem( 'SPM2 normalization matrix', 'Matlab file' )
di = rdi.findValue(self.diskItems['T1pre'])
#pdb.set_trace()
if di is None:
print "SPM deformation _sn.mat not found in database"
return None
# Convert to field
#pdb.set_trace()
wdi = WriteDiskItem( 'SPM normalization inverse deformation field', 'NIFTI-1 image' )
diField = wdi.findValue(di)
if diField is None:
print "Cannot find path to save MNI vector field in the DB"
return None
#For a file /database/y_SubjectName_inverse.nii, get SubjectName_inverse
ofname = os.path.basename(diField.fullPath()).lstrip('y_').rsplit('.',1)[0]
#pdb.set_trace()
if spm_version == '(SPM12)':
print 'SPM12 used'
matlabRun(spm_SnToField12%("'"+self.spmpath+"'",str(di.fullPath()), str(self.diskItems['T1pre'].fullPath()), ofname) )
if spm_version == '(SPM8)':
print 'SPM8 used'
matlabRun(spm_SnToField8%("'"+self.spmpath+"'",str(di.fullPath()), str(self.diskItems['T1pre'].fullPath()), ofname) )
if os.path.exists(diField.fullPath()):
self.t1preMniFieldPath = diField.fullPath()
return self.t1preMniFieldPath
else:
print "Matlab did not convert the MNI transform to vector field !"
return None
def clearT1preMniTransform(self):
"""Reset MNI transform field if it was generated"""
if self.t1preMniFieldPath is not None:
try:
os.remove(self.t1preMniFieldPath) #to change with: self.removeDiskItems(di,eraseFiles=True)
except:
pass
self.t1preMniFieldPath = None
def changePatient(self):
self.loadPatientButton.setEnabled(True)
self.patientList.setEnabled(True)
self.a.removeObjects(self.a.getObjects(),self.wins[0])
self.a.removeObjects(self.a.getObjects(),self.wins[1])
self.a.config()[ 'linkedCursor' ] = 0
referentials=self.a.getReferentials()
for element in referentials:
if element.getInfos().get('name') not in ('Talairach-MNI template-SPM', 'Talairach-AC/PC-Anatomist'):
self.a.deleteElements(element)
#for element in self.electrodes:
#for elecKeys in element.keys():
#del element[elecKeys]
#variablesG=globals()
#variablesL=locals()
self.electrodeList.clear()
self.contactList.clear()
self.currentWindowRef = None
listEl=[]
#for el , value in self.dispObj.items():
# listEl.append(value)
#self.__init__(self,loadAll=False)
#for el in listEl:
# if type(el)==list:
# listElec=el
# else:
# self.a.deleteObjects(el)
#del self.electrodes
self.electrodes = []
#del self.dispObj
#parcourir les objets, détruire les fusions avant
#for obj in self.dispObj:
self.currentElectrodes = []
self.currentContacts = []
#todelete = []
#for name,obj in self.dispObj.items():
# if isinstance(obj.internalRep,anatomist.anatomist.cpp.MObject):
# todelete.append(name)
#for name in todelete:
# del self.dispObj[name]
self.dispObj={}
#if hasattr(self,"objtokeep"):
self.objtokeep = {}
self.__init__(loadAll = False)
def loadPatient(self, patient=None):
if patient is None:
patient = str(self.patientList.selectedItems()[0].text())
volumes = []
self.t1pre2ScannerBasedTransform = None
self.clearT1preMniTransform()
pre_select_1 = self.windowCombo1.currentText()
pre_select_2 = self.windowCombo2.currentText()
for moda in self.modalities:
rdi2 = ReadDiskItem( moda, 'aims readable volume formats', requiredAttributes={'subject':patient, 'center':self.currentProtocol} )
volumes.extend(list( rdi2._findValues( {}, None, False ) ))
dictionnaire_list_images = {'IRM pre':['T1pre','electrodes',],\
'IRM pre + hemisphere droit':['T1pre','T1pre-rightHemi','electrodes',],\
'IRM pre + hemisphere gauche':['T1pre','T1pre-leftHemi','electrodes',],\
'IRM pre + hemispheres':['T1pre','T1pre-rightHemi','T1pre-leftHemi','electrodes',],\
'IRM pre + hemispheres + tete':['T1pre','T1pre-rightHemi','T1pre-leftHemi', 'T1pre-head','electrodes']}
#pdb.set_trace()
for t in volumes:
if "skull_stripped" in t.fullName():
continue
self.brainvisaPatientAttributes = t.attributes()
if (t.attributes()['modality'] == 't2mri') and ('pre' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'IRM pre T2':['T2pre','electrodes']})
elif (t.attributes()['modality'] == 't2mri') and ('post' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'IRM post T2':['T2post','electrodes']})
elif (t.attributes()['modality'] == 't1mri') and ('post' in t.attributes()['acquisition']) and not ('postOp' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'IRM post':['T1post','electrodes']})
elif (t.attributes()['modality'] == 'ct') and ('post' in t.attributes()['acquisition']) and not ('postOp' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'CT post':['CTpost','electrodes']})
elif (t.attributes()['modality'] == 'ct') and ('postOp' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'CT post-op':['CTpostOp','electrodes']})
elif (t.attributes()['modality'] == 'pet') and ('pre' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'PET pre':['PETpre','electrodes']})
elif (t.attributes()['modality'] == 'flair') and ('pre' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'FLAIR pre':['FLAIRpre','electrodes']})
elif (t.attributes()['modality'] == 'fgatir') and ('pre' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'FGATIR pre':['FGATIRpre','electrodes']})
elif (t.attributes()['modality'] == 'fmri_epile') and ('pre' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'fMRI pre'+ ' - ' + t.attributes()['subacquisition']:['fMRIpre','electrodes']}) #mettre le nom de la subacquisition
elif t.attributes()['modality'] == 'statistic_data' and ('pre' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'Statistic Data' + ' - ' + t.attributes()['subacquisition']:['Statisticspre'+t.attributes()['subacquisition'],'electrodes']}) #mettre le nom de la subacquisition
elif t.attributes()['modality'] == 'statistic_data' and ('post' in t.attributes()['acquisition']) and not ('postOp' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'Statistic Data' + ' - ' + t.attributes()['subacquisition']:['Statisticspost'+t.attributes()['subacquisition'],'electrodes']}) #mettre le nom de la subacquisition
elif (t.attributes()['modality'] == 't1mri') and ('postOp' in t.attributes()['acquisition']):
dictionnaire_list_images.update({'IRM post-op':['T1postOp','electrodes']})
elif (t.attributes()['modality'] == 'resection'):
dictionnaire_list_images.update({'Resection':['Resection','electrodes']})
elif (t.attributes()['modality'] == 'freesurfer_atlas'):
dictionnaire_list_images.update({'FreeSurferAtlas pre':['FreesurferAtlaspre','electrodes']})
elif (t.attributes()['modality'] == 'hippofreesurfer_atlas'):
dictionnaire_list_images.update({'HippoFreeSurferAtlas pre':['HippoFreesurferAtlaspre','electrodes']})
try:
nameAcq = t.attributes()['acquisition']
#print "Loading %s as %s"%(t.fileName(), nameAcq)
#print repr(t.attributes())
# We try to get the acquisition name without the date (if there is one) : T1pre_2000-01-01 -> T1pre
if 'Statistics' in nameAcq:
na = nameAcq.split('_')[0] + t.attributes()['subacquisition']
else:
na = nameAcq.split('_')[0]
except:
if moda == 'Electrode Implantation Coronal Image':
na = 'ImplantationCoro'
elif moda == 'Electrode Implantation Sagittal Image':
na = 'ImplantationSag'
else:
print "CANNOT find a nameAcq for ",repr(t)
na = 'unknown'
self.loadAndDisplayObject(t, na)
if na == 'T1pre':
# Load standard transformations (AC-PC, T1pre Scanner-based, BrainVisa Talairach)
try:
self.refConv.loadACPC(t)
except Exception, e:
print "Cannot load AC-PC referential from T1 pre MRI : "+repr(e)
try:
self.refConv.loadTalairach(t)
except Exception, e:
print "Cannot load Talairach referential from T1 pre MRI : "+repr(e)
try:
tr2sb = self.t1pre2ScannerBased()
if tr2sb is not None:
self.refConv.setAnatomistTransform("Scanner-based", tr2sb, toRef=True)
# Add the AC-centered Scanner-Based (for PTS importation using AC-centered Olivier David method
if self.refConv.isRefAvailable('AC-PC'):
acInScannerBased = self.refConv.anyRef2AnyRef([0.0,0.0,0.0],'AC-PC', 'Scanner-based')
inf = tr2sb.getInfos()
rot = inf['rotation_matrix']
trans = [inf['translation'][0] - acInScannerBased[0], inf['translation'][1] - acInScannerBased[1], inf['translation'][2] - acInScannerBased[2]]
m = aims.Motion(rot[:3]+[trans[0]]+rot[3:6]+[trans[1]]+rot[6:]+[trans[2]]+[0,0,0,1])
self.refConv.setTransformMatrix('AC-centered Scanner-Based', m.inverse(), m)
except Exception, e:
print "Cannot load Scanner-based referential from T1 pre MRI : "+repr(e)
# Get the hemisphere meshes for the acquisition : name = na + filename base : for example, if the acquisition is T1pre_2000-01-01 and the file head.gii, we want T1pre-head
rdi3 = ReadDiskItem( 'Hemisphere Mesh', 'Anatomist mesh formats', requiredAttributes={'subject':patient, 'acquisition':nameAcq, 'center':self.currentProtocol} )
hemis = list(rdi3._findValues( {}, None, False ) )
for hh in hemis:
#pdb.set_trace()
self.loadAndDisplayObject(hh, na + '-' + hh.attributes()['side'] + 'Hemi', color=[0.8,0.7,0.4,0.7])
print "Found hemisphere "+ str(na + '-' + hh.attributes()['side'] + 'Hemi')
atlas_di = ReadDiskItem('hemisphere marsAtlas parcellation texture', 'aims Texture formats', requiredAttributes={ 'regularized': 'false','subject':patient, 'center':self.currentProtocol, 'acquisition':nameAcq })
atlas_di_list = list(atlas_di._findValues({}, None, False ))
#probleme
wm_di = ReadDiskItem( 'Hemisphere White Mesh', 'aims mesh formats',requiredAttributes={'subject':patient, 'center':self.currentProtocol })
if len(atlas_di_list) > 0:
for atl in atlas_di_list:
wm_side = wm_di.findValue(atl)
self.loadAndDisplayObject(wm_side, na + '-' + atl.attributes()['side'] + 'MARSATLAS', texture_item = atl, palette = 'MarsAtlas', color=[0.8,0.7,0.4,0.7])
print "Found hemisphere "+ str(na + '-' + atl.attributes()['side'] + 'MARSATLAS')
dictionnaire_list_images.update({'IRM pre + MARS ATLAS ' + atl.attributes()['side']:['T1pre','T1pre-'+ atl.attributes()['side'] + 'MARSATLAS','electrodes']})
#pdb.set_trace()
# Get head mesh for the acquisition
#probleme
rdi3 = ReadDiskItem( 'Head Mesh', 'Anatomist mesh formats', requiredAttributes={'subject':patient, 'acquisition':nameAcq, 'center':self.currentProtocol} )
head = list(rdi3._findValues( {}, None, False ) )
if len(head) > 0: # Only if there is one !
self.loadAndDisplayObject(head[0], na + '-' + 'head', color=[0.0,0.0,0.8,0.3])
self.windowContent = dictionnaire_list_images;
self.windowCombo1.clear()
self.windowCombo1.addItems(sorted(dictionnaire_list_images.keys()))
self.windowCombo2.clear()
self.windowCombo2.addItems(sorted(dictionnaire_list_images.keys()))
self.windowCombo1.setCurrentIndex(max(self.windowCombo1.findText(pre_select_1),0))
self.windowCombo2.setCurrentIndex(max(self.windowCombo2.findText(pre_select_2),0))
# Display referential informations
self.setWindowsReferential()
self.loadElectrodes(self.brainvisaPatientAttributes)
self.refreshAvailableDisplayReferentials()
# Display all
self.allWindowsUpdate()
# Disable the button because no cleanup is attempted when loading a patient when one is already loaded -> there may be a mixup
self.loadPatientButton.setEnabled(False)
self.patientList.setEnabled(False)
# Chargement d'un objet (IRM, mesh...) dans Anatomist et mise à jour de l'affichage
def loadAndDisplayObject(self, diskitem, name = None, color=None, palette=None, texture_item = None):
if name is None:
return
#Already exists ! Remove it.
if name in self.dispObj:
self.a.removeObjects([self.dispObj[name],], self.wins) # Remove from windows
self.a.deleteObjects(self.dispObj[name]) # CURRENT
del self.dispObj[name]
del self.diskItems[name]