-
Notifications
You must be signed in to change notification settings - Fork 22
/
ShapeVariationAnalyzer.py
2426 lines (1978 loc) · 104 KB
/
ShapeVariationAnalyzer.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
from __future__ import print_function
from __future__ import division
import os, sys
import csv
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
from types import *
import math
import shutil
import pickle
import numpy as np
import zipfile
import json
import subprocess
from copy import deepcopy
from scipy import stats
import time
import shapepcalib as shapca
class ShapeVariationAnalyzer(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
parent.title = "Population Analysis"
parent.categories = ["Shape Analysis"]
parent.dependencies = []
parent.contributors = ["Lopez Mateo (University of North Carolina), Priscille de Dumast (University of Michigan), Laura Pascal (University of Michigan)"]
parent.helpText = """
Shape Variation Analyzer allows the PCA decomposition and exploration of 3D models.
The generated models can be evaluated by computing their specificity, compactness and generalization.
"""
parent.acknowledgementText = """
This work was supported by the National
Institutes of Dental and Craniofacial Research
and Biomedical Imaging and Bioengineering of
the National Institutes of Health under Award
Number R01DE024450.
"""
class ShapeVariationAnalyzerWidget(ScriptedLoadableModuleWidget):
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# ---- Widget Setup ----
# Global Variables
self.logic = ShapeVariationAnalyzerLogic()
#print(dir(self.logic))
self.dictVTKFiles = dict()
self.dictGroups = dict()
self.dictCSVFile = dict()
self.directoryList = list()
self.groupSelected = set()
self.dictShapeModels = dict()
self.patientList = list()
self.dictResults = dict()
self.dictFeatData = dict()
#self.dictPCA = dict()
self.PCA_sliders=list()
self.PCA_sliders_label=list()
self.PCA_sliders_value_label=list()
self.PCANode = None
# Interface
self.moduleName = 'ShapeVariationAnalyzer'
scriptedModulesPath = eval('slicer.modules.%s.path' % self.moduleName.lower())
scriptedModulesPath = os.path.dirname(scriptedModulesPath)
path = os.path.join(scriptedModulesPath, 'Resources', 'UI', '%s.ui' % self.moduleName)
self.widget = slicer.util.loadUI(path)
self.layout.addWidget(self.widget)
# global variables of the Interface:
# Tab: Creation of CSV File for Classification Groups
self.collapsibleButton_creationCSVFile = self.getUI('CollapsibleButton_creationCSVFile')
self.spinBox_group = self.getUI('spinBox_group')
self.directoryButton_creationCSVFile = self.getUI('DirectoryButton_creationCSVFile')
self.stackedWidget_manageGroup = self.getUI('stackedWidget_manageGroup')
self.pushButton_addGroup = self.getUI('pushButton_addGroup')
self.pushButton_removeGroup = self.getUI('pushButton_removeGroup')
self.pushButton_modifyGroup = self.getUI('pushButton_modifyGroup')
self.pushButton_exportCSVfile = self.getUI('pushButton_exportCSVfile')
# Tab: Creation of New Classification Groups
self.collapsibleButton_previewClassificationGroups = self.getUI('CollapsibleButton_previewClassificationGroups')
self.pathLineEdit_previewGroups = self.getUI('pathLineEdit_previewGroups')
self.collapsibleGroupBox_previewVTKFiles = self.getUI('CollapsibleGroupBox_previewVTKFiles')
self.checkableComboBox_ChoiceOfGroup = self.getUI('CheckableComboBox_ChoiceOfGroup')
self.tableWidget_VTKFiles = self.getUI('tableWidget_VTKFiles')
self.pushButton_previewVTKFiles = self.getUI('pushButton_previewVTKFiles')
self.pushButton_exportUpdatedClassification = self.getUI('pushButton_exportUpdatedClassification')
# Tab: PCA Analysis
self.label_valueExploration=self.getUI('label_valueExploration')
self.label_varianceExploration=self.getUI('label_varianceExploration')
self.label_groupExploration=self.getUI('label_groupExploration')
self.label_minVariance=self.getUI('label_minVariance')
self.label_maxSlider=self.getUI('label_maxSlider')
self.label_colorMode=self.getUI('label_colorMode')
self.label_colorModeParam1=self.getUI('label_colorModeParam1')
self.label_colorModeParam2=self.getUI('label_colorModeParam2')
self.label_numberShape=self.getUI('label_numberShape')
self.label_normalLabel_1=self.getUI('label_normalLabel_1')
self.label_normalLabel_2=self.getUI('label_normalLabel_2')
self.label_normalLabel_3=self.getUI('label_normalLabel_3')
self.label_normalLabel_4=self.getUI('label_normalLabel_4')
self.label_normalLabel_5=self.getUI('label_normalLabel_5')
self.label_normalLabel_6=self.getUI('label_normalLabel_6')
self.label_normalLabel_7=self.getUI('label_normalLabel_7')
self.collapsibleButton_PCA = self.getUI('collapsibleButton_PCA')
self.pathLineEdit_CSVFilePCA = self.getUI('pathLineEdit_CSVFilePCA')
self.pathLineEdit_exploration = self.getUI('pathLineEdit_exploration')
self.comboBox_groupPCA = self.getUI('comboBox_groupPCA')
self.comboBox_colorMode = self.getUI('comboBox_colorMode')
self.pushButton_PCA = self.getUI('pushButton_PCA')
self.pushButton_resetSliders = self.getUI('pushButton_resetSliders')
self.pushButton_saveExploration=self.getUI('pushButton_saveExploration')
self.pushButton_toggleMean=self.getUI('pushButton_toggleMean')
self.pushButton_evaluateModels=self.getUI('pushButton_evaluateModels')
self.label_statePCA = self.getUI('label_statePCA')
self.gridLayout_PCAsliders=self.getUI('gridLayout_PCAsliders')
self.spinBox_minVariance=self.getUI('spinBox_minVariance')
self.spinBox_maxSlider=self.getUI('spinBox_maxSlider')
self.spinBox_colorModeParam1=self.getUI('spinBox_colorModeParam_1')
self.spinBox_colorModeParam2=self.getUI('spinBox_colorModeParam_2')
self.spinBox_numberShape=self.getUI('spinBox_numberShape')
self.ctkColorPickerButton_groupColor=self.getUI('ctkColorPickerButton_groupColor')
self.checkBox_useHiddenEigenmodes=self.getUI('checkBox_useHiddenEigenmodes')
# Tab: PCA Export
self.collapsibleButton_PCAExport = self.getUI('CollapsibleButton_PCAExport')
self.comboBox_SingleExportGroup = self.getUI('comboBox_SingleExportGroup')
self.comboBox_SingleExportPC = self.getUI('comboBox_SingleExportPC')
self.label_PC = self.getUI('label_PC')
self.label_Group = self.getUI('label_Group')
self.DirectoryButton_PCASingleExport = self.getUI('DirectoryButton_PCASingleExport')
self.pushButton_PCAExport = self.getUI('pushButton_PCAExport')
self.pushButton_PCACurrentExport = self.getUI('pushButton_PCACurrentExport')
self.checkBox_stdMaxMin = self.getUI('checkBox_stdMaxMin')
self.checkBox_stdRegular = self.getUI('checkBox_stdRegular')
self.doubleSpinBox_stdRegular = self.getUI('doubleSpinBox_stdRegular')
self.doubleSpinBox_stdmin = self.getUI('doubleSpinBox_stdmin')
self.doubleSpinBox_stdmax = self.getUI('doubleSpinBox_stdmax')
self.label_stdRegular = self.getUI('label_stdRegular')
self.label_stdmin = self.getUI('label_stdmin')
self.label_stdmax = self.getUI('label_stdmax')
self.doubleSpinBox_step = self.getUI('doubleSpinBox_step')
#self.doubleSpinBox_insideLimit=self.getUI('doubleSpinBox_insideLimit')
#self.doubleSpinBox_insideLimit=self.getUI('doubleSpinBox_outsidesideLimit')
# --------------------------------------------------------- #
# Widget Configuration #
# --------------------------------------------------------- #
##PCA exploration Widgets Configuration
#self.pushButton_PCA.setDisabled(True)
#self.comboBox_groupPCA.setDisabled(True)
self.comboBox_colorMode.addItem('Group color')
self.comboBox_colorMode.addItem('Unsigned distance to mean shape')
self.comboBox_colorMode.addItem('Signed distance to mean shape')
self.spinBox_minVariance.setValue(2)
self.spinBox_maxSlider.setMinimum(1)
self.spinBox_maxSlider.setMaximum(8)
self.spinBox_maxSlider.setValue(8)
self.spinBox_colorModeParam1.setMinimum(1)
self.spinBox_colorModeParam2.setMinimum(1)
self.spinBox_colorModeParam1.setMaximum(10000)
self.spinBox_colorModeParam2.setMaximum(10000)
self.spinBox_colorModeParam1.setValue(1)
self.spinBox_colorModeParam2.setValue(1)
self.spinBox_numberShape.setMinimum(100)
self.spinBox_numberShape.setMaximum(1000000)
self.spinBox_numberShape.setValue(10000)
self.checkBox_useHiddenEigenmodes.setChecked(True)
self.label_statePCA.hide()
self.ctkColorPickerButton_groupColor.color=qt.QColor(255,255,255)
self.ctkColorPickerButton_groupColor.setDisplayColorName(False)
self.label_normalLabel_1.hide()
self.label_normalLabel_2.hide()
self.label_normalLabel_3.hide()
self.label_normalLabel_4.hide()
self.label_normalLabel_5.hide()
self.label_normalLabel_6.hide()
self.label_normalLabel_7.hide()
self.comboBox_groupPCA.hide()
self.comboBox_colorMode.hide()
self.ctkColorPickerButton_groupColor.hide()
self.pushButton_resetSliders.hide()
self.label_valueExploration.hide()
self.label_groupExploration.hide()
self.label_varianceExploration.hide()
self.pushButton_saveExploration.hide()
self.pushButton_toggleMean.hide()
self.pushButton_evaluateModels.hide()
self.spinBox_minVariance.hide()
self.spinBox_maxSlider.hide()
self.label_minVariance.hide()
self.label_maxSlider.hide()
self.spinBox_colorModeParam1.hide()
self.spinBox_colorModeParam2.hide()
self.label_colorMode.hide()
self.label_colorModeParam1.hide()
self.label_colorModeParam2.hide()
self.label_numberShape.hide()
self.spinBox_numberShape.hide()
self.checkBox_useHiddenEigenmodes.hide()
# disable/enable and hide/show widget
#self.comboBox_healthyGroup.setDisabled(True)
self.pushButton_exportUpdatedClassification.setDisabled(True)
self.checkableComboBox_ChoiceOfGroup.setDisabled(True)
self.tableWidget_VTKFiles.setDisabled(True)
self.pushButton_previewVTKFiles.setDisabled(True)
self.label_statePCA.hide()
self.collapsibleButton_creationCSVFile.setChecked(False)
self.collapsibleButton_previewClassificationGroups.setChecked(False)
# initialisation of the stackedWidget to display the button "add group"
self.stackedWidget_manageGroup.setCurrentIndex(0)
# spinbox configuration in the tab "Creation of CSV File for Classification Groups"
self.spinBox_group.setMinimum(0)
self.spinBox_group.setMaximum(0)
self.spinBox_group.setValue(0)
# configuration of the table for preview VTK file
self.tableWidget_VTKFiles.setColumnCount(4)
self.tableWidget_VTKFiles.setHorizontalHeaderLabels([' VTK files ', ' Group ', ' Visualization ', 'Color'])
self.tableWidget_VTKFiles.setColumnWidth(0, 200)
horizontalHeader = self.tableWidget_VTKFiles.horizontalHeader()
horizontalHeader.setStretchLastSection(False)
'''horizontalHeader.setResizeMode(0,qt.QHeaderView.Stretch)
horizontalHeader.setResizeMode(1,qt.QHeaderView.ResizeToContents)
horizontalHeader.setResizeMode(2,qt.QHeaderView.ResizeToContents)
horizontalHeader.setResizeMode(3,qt.QHeaderView.ResizeToContents)'''
self.tableWidget_VTKFiles.verticalHeader().setVisible(True)
# TAB: PCA Export
self.pushButton_PCAExport.setEnabled(False)
self.comboBox_SingleExportPC.setEnabled(False)
self.comboBox_SingleExportGroup.setEnabled(False)
self.pushButton_PCACurrentExport.setEnabled(False)
self.checkBox_stdRegular.setChecked(True)
self.checkBox_stdMaxMin.setChecked(False)
self.doubleSpinBox_stdmin.setDisabled(True)
self.doubleSpinBox_stdmax.setDisabled(True)
# --------------------------------------------------------- #
# Connection #
# --------------------------------------------------------- #
# Tab: Creation of CSV File for Classification Groups
self.collapsibleButton_creationCSVFile.connect('clicked()',
lambda: self.onSelectedCollapsibleButtonOpen(self.collapsibleButton_creationCSVFile))
self.spinBox_group.connect('valueChanged(int)', self.onManageGroup)
self.pushButton_addGroup.connect('clicked()', self.onAddGroupForCreationCSVFile)
self.pushButton_removeGroup.connect('clicked()', self.onRemoveGroupForCreationCSVFile)
self.pushButton_modifyGroup.connect('clicked()', self.onModifyGroupForCreationCSVFile)
self.pushButton_exportCSVfile.connect('clicked()', self.onExportForCreationCSVFile)
# Tab: Preview / Update Classification Groups
self.collapsibleButton_previewClassificationGroups.connect('clicked()',
lambda: self.onSelectedCollapsibleButtonOpen(self.collapsibleButton_previewClassificationGroups))
self.pathLineEdit_previewGroups.connect('currentPathChanged(const QString)', self.onSelectPreviewGroups)
self.checkableComboBox_ChoiceOfGroup.connect('checkedIndexesChanged()', self.onCheckableComboBoxValueChanged)
self.pushButton_previewVTKFiles.connect('clicked()', self.onPreviewVTKFiles)
self.pushButton_exportUpdatedClassification.connect('clicked()', self.onExportUpdatedClassificationGroups)
# Tab: Select Input Data
self.collapsibleButton_PCA.connect('clicked()',
lambda: self.onSelectedCollapsibleButtonOpen(self.collapsibleButton_PCA))
slicer.mrmlScene.AddObserver(slicer.mrmlScene.EndCloseEvent, self.onCloseScene)
self.stateCSVMeansShape = False
self.stateCSVDataset = False
# Tab : PCA
self.pathLineEdit_CSVFilePCA.connect('currentPathChanged(const QString)', self.onCSV_PCA)
self.pathLineEdit_exploration.connect('currentPathChanged(const QString)', self.onLoadExploration)
self.pushButton_PCA.connect('clicked()', self.onExportForExploration)
self.pushButton_resetSliders.connect('clicked()', self.onResetSliders)
self.pushButton_saveExploration.connect('clicked()',self.onSaveExploration)
self.pushButton_toggleMean.connect('clicked()',self.onToggleMeanShape)
self.pushButton_evaluateModels.connect('clicked()',self.onEvaluateModels)
self.comboBox_groupPCA.connect('activated(QString)',self.explorePCA)
self.comboBox_colorMode.connect('activated(QString)',self.onColorModeChange)
self.spinBox_maxSlider.connect('valueChanged(int)',self.onUpdateSliderList)
self.spinBox_minVariance.connect('valueChanged(int)',self.onUpdateSliderList)
self.spinBox_colorModeParam1.connect('valueChanged(int)',self.onUpdateColorModeParam)
self.spinBox_colorModeParam2.connect('valueChanged(int)',self.onUpdateColorModeParam)
self.ctkColorPickerButton_groupColor.connect('colorChanged(QColor)',self.onGroupColorChanged)
self.checkBox_useHiddenEigenmodes.connect('stateChanged(int)',self.onEigenCheckBoxChanged)
self.evaluationFlag="DONE"
# Tab : PCA Export
self.pushButton_PCAExport.connect('clicked()', self.onExportForPCAExport)
self.pushButton_PCACurrentExport.connect('clicked()', self.onExportForPCACurrentExport)
self.checkBox_stdMaxMin.connect('clicked()', self.onMinMaxstdCheckBoxChanged)
self.checkBox_stdRegular.connect('clicked()', self.onRegularstdCheckBoxChanged)
def getUI(self, objectName):
""" Functions to recovery the widget in the .ui file
"""
return slicer.util.findChild(self.widget, objectName)
# function called each time that the user "enter" in Diagnostic Index interface
def enter(self):
#TODO
pass
# function called each time that the user "exit" in Diagnostic Index interface
def exit(self):
#TODO
pass
# function called each time that the scene is closed (if Diagnostic Index has been initialized)
def onCloseScene(self, obj, event):
print("onCloseScene")
#self.logic = ShapeVariationAnalyzerLogic(self)
sys.stdout.flush()
self.dictVTKFiles = dict()
self.dictGroups = dict()
self.dictCSVFile = dict()
self.directoryList = list()
self.groupSelected = set()
self.dictShapeModels = dict()
self.patientList = list()
self.dictResults = dict()
self.dictFeatData = dict()
# Tab: New Classification Groups
self.pathLineEdit_previewGroups.setCurrentPath(" ")
self.checkableComboBox_ChoiceOfGroup.setDisabled(True)
self.tableWidget_VTKFiles.clear()
self.tableWidget_VTKFiles.setColumnCount(4)
self.tableWidget_VTKFiles.setHorizontalHeaderLabels([' VTK files ', ' Group ', ' Visualization ', 'Color'])
self.tableWidget_VTKFiles.setColumnWidth(0, 200)
horizontalHeader = self.tableWidget_VTKFiles.horizontalHeader()
horizontalHeader.setStretchLastSection(False)
'''horizontalHeader.setResizeMode(0,qt.QHeaderView.Stretch)
horizontalHeader.setResizeMode(1,qt.QHeaderView.ResizeToContents)
horizontalHeader.setResizeMode(2,qt.QHeaderView.ResizeToContents)
horizontalHeader.setResizeMode(3,qt.QHeaderView.ResizeToContents)'''
self.tableWidget_VTKFiles.verticalHeader().setVisible(False)
self.tableWidget_VTKFiles.setDisabled(True)
self.pushButton_previewVTKFiles.setDisabled(True)
self.pushButton_exportUpdatedClassification.setDisabled(True)
#PCA
self.label_normalLabel_1.hide()
self.label_normalLabel_2.hide()
self.label_normalLabel_3.hide()
self.label_normalLabel_4.hide()
self.label_normalLabel_5.hide()
self.label_normalLabel_6.hide()
self.label_normalLabel_7.hide()
self.deletePCASliders()
self.comboBox_groupPCA.hide()
self.comboBox_colorMode.hide()
self.ctkColorPickerButton_groupColor.hide()
self.pushButton_resetSliders.hide()
self.label_valueExploration.hide()
self.label_groupExploration.hide()
self.label_varianceExploration.hide()
self.pushButton_saveExploration.hide()
self.pushButton_toggleMean.hide()
self.pushButton_evaluateModels.hide()
self.spinBox_minVariance.hide()
self.spinBox_maxSlider.hide()
self.label_minVariance.hide()
self.label_maxSlider.hide()
self.spinBox_colorModeParam1.hide()
self.spinBox_colorModeParam2.hide()
self.label_colorMode.hide()
self.label_colorModeParam1.hide()
self.label_colorModeParam2.hide()
self.label_numberShape.hide()
self.spinBox_numberShape.hide()
self.checkBox_useHiddenEigenmodes.hide()
self.checkBox_useHiddenEigenmodes.setChecked(True)
self.pushButton_PCA.setEnabled(False)
self.pathLineEdit_CSVFilePCA.disconnect('currentPathChanged(const QString)', self.onCSV_PCA)
self.pathLineEdit_CSVFilePCA.setCurrentPath(" ")
self.pathLineEdit_CSVFilePCA.connect('currentPathChanged(const QString)', self.onCSV_PCA)
self.pathLineEdit_exploration.setCurrentPath(" ")
if self.evaluationFlag!="DONE":
self.onKillEvaluation()
try:
self.pushButton_evaluateModels.clicked.disconnect()
except:
pass
self.pushButton_evaluateModels.setText("Evaluate models (It may take a long time)")
self.pushButton_evaluateModels.connect('clicked()',self.onEvaluateModels)
self.spinBox_minVariance.setValue(2)
# Enable/disable
self.pushButton_exportUpdatedClassification.setDisabled(True)
self.checkableComboBox_ChoiceOfGroup.setDisabled(True)
self.tableWidget_VTKFiles.setDisabled(True)
self.pushButton_previewVTKFiles.setDisabled(True)
self.label_statePCA.hide()
self.stateCSVMeansShape = False
self.stateCSVDataset = False
self.collapsibleButton_PCA.setChecked(True)
self.collapsibleButton_creationCSVFile.setChecked(False)
self.collapsibleButton_previewClassificationGroups.setChecked(False)
# initialisation of the stackedWidget to display the button "add group"
self.stackedWidget_manageGroup.setCurrentIndex(0)
# spinbox configuration in the tab "Creation of CSV File for Classification Groups"
self.spinBox_group.setMinimum(0)
self.spinBox_group.setMaximum(0)
self.spinBox_group.setValue(0)
def onSelectedCollapsibleButtonOpen(self, selectedCollapsibleButton):
""" Only one tab can be display at the same time:
When one tab is opened all the other tabs are closed
"""
if selectedCollapsibleButton.isChecked():
collapsibleButtonList = [self.collapsibleButton_creationCSVFile,
self.collapsibleButton_previewClassificationGroups,
self.collapsibleButton_PCA]
for collapsibleButton in collapsibleButtonList:
collapsibleButton.setChecked(False)
selectedCollapsibleButton.setChecked(True)
# ---------------------------------------------------- #
# Tab: Creation of CSV File for Classification Groups #
# ---------------------------------------------------- #
def onManageGroup(self):
""" Function to display the 3 button:
- "Add Group" for a group which hasn't been added yet
- "Remove Group" for the last group added
- "Modify Group" for all the groups added
"""
if self.spinBox_group.maximum == self.spinBox_group.value:
self.stackedWidget_manageGroup.setCurrentIndex(0)
else:
self.stackedWidget_manageGroup.setCurrentIndex(1)
if (self.spinBox_group.maximum - 1) == self.spinBox_group.value:
self.pushButton_removeGroup.show()
else:
self.pushButton_removeGroup.hide()
# Update the path of the directory button
if len(self.directoryList) > 0:
self.directoryButton_creationCSVFile.directory = self.directoryList[self.spinBox_group.value - 1]
def onAddGroupForCreationCSVFile(self):
"""Function to add a group of the dictionary
- Add the paths of all the vtk files found in the directory given
of a dictionary which will be used to create the CSV file
"""
# Error message
directory = self.directoryButton_creationCSVFile.directory
if directory in self.directoryList:
index = self.directoryList.index(directory) + 1
slicer.util.errorDisplay('Path of directory already used for the group ' + str(index))
return
# Add the paths of vtk files of the dictionary
self.logic.addGroupToDictionary(self.dictCSVFile, directory, self.directoryList, self.spinBox_group.value)
condition = self.logic.checkSeveralMeshInDict(self.dictCSVFile)
if not condition:
# Remove the paths of vtk files of the dictionary
self.logic.removeGroupToDictionary(self.dictCSVFile, self.directoryList, self.spinBox_group.value)
return
# Increment of the number of the group in the spinbox
self.spinBox_group.blockSignals(True)
self.spinBox_group.setMaximum(self.spinBox_group.value + 1)
self.spinBox_group.setValue(self.spinBox_group.value + 1)
self.spinBox_group.blockSignals(False)
# Message for the user
slicer.util.delayDisplay("Group Added")
def onRemoveGroupForCreationCSVFile(self):
""" Function to remove a group of the dictionary
- Remove the paths of all the vtk files corresponding to the selected group
of the dictionary which will be used to create the CSV file
"""
# Remove the paths of the vtk files of the dictionary
self.logic.removeGroupToDictionary(self.dictCSVFile, self.directoryList, self.spinBox_group.value)
# Decrement of the number of the group in the spinbox
self.spinBox_group.blockSignals(True)
self.spinBox_group.setMaximum(self.spinBox_group.maximum - 1)
self.spinBox_group.blockSignals(False)
# Change the buttons "remove group" and "modify group" in "add group"
self.stackedWidget_manageGroup.setCurrentIndex(0)
# Message for the user
slicer.util.delayDisplay("Group removed")
def onModifyGroupForCreationCSVFile(self):
""" Function to modify a group of the dictionary:
- Remove of the dictionary the paths of all vtk files corresponding to the selected group
- Add of the dictionary the new paths of all the vtk files
"""
# Error message
directory = self.directoryButton_creationCSVFile.directory
if directory in self.directoryList:
index = self.directoryList.index(directory) + 1
slicer.util.errorDisplay('Path of directory already used for the group ' + str(index))
return
# Remove the paths of vtk files of the dictionary
self.logic.removeGroupToDictionary(self.dictCSVFile, self.directoryList, self.spinBox_group.value)
# Add the paths of vtk files of the dictionary
self.logic.addGroupToDictionary(self.dictCSVFile, directory, self.directoryList, self.spinBox_group.value)
# Message for the user
slicer.util.delayDisplay("Group modified")
def onExportForCreationCSVFile(self):
""" Function to export the CSV file in the directory chosen by the user
- Save the CSV file from the dictionary previously filled
- Load automatically this CSV file in the next tab: "Creation of New Classification Groups"
"""
# Path of the csv file
dlg = ctk.ctkFileDialog()
filepath = dlg.getSaveFileName(None, "Export CSV file for Classification groups", os.path.join(qt.QDir.homePath(), "Desktop"), "CSV File (*.csv)")
directory = os.path.dirname(filepath)
basename = os.path.basename(filepath)
# Save the CSV File
self.logic.creationCSVFile(directory, basename, self.dictCSVFile, "Groups")
# Re-Initialization of the first tab
self.spinBox_group.setMaximum(1)
self.spinBox_group.setValue(1)
self.stackedWidget_manageGroup.setCurrentIndex(0)
self.directoryButton_creationCSVFile.directory = qt.QDir.homePath() + '/Desktop'
# Re-Initialization of:
# - the dictionary containing all the paths of the vtk groups
# - the list containing all the paths of the different directories
self.directoryList = list()
self.dictCSVFile = dict()
# Message in the python console
print("Export CSV File: " + filepath)
sys.stdout.flush()
# Load automatically the CSV file in the pathline in the next tab "Creation of New Classification Groups"
self.pathLineEdit_previewGroups.setCurrentPath(filepath)
self.pathLineEdit_CSVFilePCA.setCurrentPath(filepath)
#self.pathLineEdit_CSVFileDataset.setCurrentPath(filepath)
# ---------------------------------------------------- #
# Tab: Creation of New Classification Groups #
#
# Preview/Update classification Groups
#
# ---------------------------------------------------- #
def onSelectPreviewGroups(self):
""" Function to read the CSV file containing all the vtk
filepaths needed to create the new Classification Groups
"""
# Re-initialization of the dictionary containing all the vtk files
# which will be used to create a new Classification Groups
self.dictVTKFiles = dict()
# Check if the path exists:
if not os.path.exists(self.pathLineEdit_previewGroups.currentPath):
return
# Check if it's a CSV file
condition1 = self.logic.checkExtension(self.pathLineEdit_previewGroups.currentPath, ".csv")
if not condition1:
self.pathLineEdit_previewGroups.setCurrentPath(" ")
return
# Download the CSV file
self.logic.table = self.logic.readCSVFile(self.pathLineEdit_previewGroups.currentPath)
condition2 = self.logic.creationDictVTKFiles(self.dictVTKFiles)
condition3 = self.logic.checkSeveralMeshInDict(self.dictVTKFiles)
# If the file is not conformed:
# Re-initialization of the dictionary containing all the data
# which will be used to create a new Classification Groups
if not (condition2 and condition3):
self.dictVTKFiles = dict()
self.pathLineEdit_previewGroups.setCurrentPath(" ")
return
# Fill the table for the preview of the vtk files in Shape Population Viewer
self.fillTableForPreviewVTKFilesInSPV(self.dictVTKFiles,
self.checkableComboBox_ChoiceOfGroup,
self.tableWidget_VTKFiles)
# Enable/disable buttons
self.checkableComboBox_ChoiceOfGroup.setEnabled(True)
self.tableWidget_VTKFiles.setEnabled(True)
self.pushButton_previewVTKFiles.setEnabled(True)
# self.pushButton_compute.setEnabled(True)
def fillTableForPreviewVTKFilesInSPV(self, dictVTKFiles, checkableComboBox, table):
"""Function to fill the table of the preview of all VTK files
- Checkable combobox: allow the user to select one or several groups that he wants to display in SPV
- Column 0: filename of the vtk file
- Column 1: combobox with the group corresponding to the vtk file
- Column 2: checkbox to allow the user to choose which models will be displayed in SPV
- Column 3: color that the mesh will have in SPV
"""
row = 0
for key, value in dictVTKFiles.items():
# Fill the Checkable Combobox
checkableComboBox.addItem("Group " + str(key))
# Table:
for vtkFile in value:
table.setRowCount(row + 1)
# Column 0:
filename = os.path.basename(vtkFile)
labelVTKFile = qt.QLabel(filename)
labelVTKFile.setAlignment(0x84)
table.setCellWidget(row, 0, labelVTKFile)
# Column 1:
widget = qt.QWidget()
layout = qt.QHBoxLayout(widget)
comboBox = qt.QComboBox()
comboBox.addItems(list(dictVTKFiles.keys()))
comboBox.setCurrentIndex(key)
layout.addWidget(comboBox)
layout.setAlignment(0x84)
layout.setContentsMargins(0, 0, 0, 0)
widget.setLayout(layout)
table.setCellWidget(row, 1, widget)
comboBox.connect('currentIndexChanged(int)', self.onGroupValueChanged)
# Column 2:
widget = qt.QWidget()
layout = qt.QHBoxLayout(widget)
checkBox = qt.QCheckBox()
layout.addWidget(checkBox)
layout.setAlignment(0x84)
layout.setContentsMargins(0, 0, 0, 0)
widget.setLayout(layout)
table.setCellWidget(row, 2, widget)
checkBox.connect('stateChanged(int)', self.onCheckBoxTableValueChanged)
# Column 3:
table.setItem(row, 3, qt.QTableWidgetItem())
table.item(row,3).setBackground(qt.QColor(255,255,255))
row = row + 1
def onCheckableComboBoxValueChanged(self):
""" Function to manage the checkable combobox to allow
the user to choose the group that he wants to preview in SPV
"""
# Update the checkboxes in the qtableWidget of each vtk file
index = self.checkableComboBox_ChoiceOfGroup.currentIndex
for row in range(0,self.tableWidget_VTKFiles.rowCount):
# Recovery of the group of the vtk file contained in the combobox (column 2)
widget = self.tableWidget_VTKFiles.cellWidget(row, 1)
tuple = widget.children()
comboBox = qt.QComboBox()
comboBox = tuple[1]
group = comboBox.currentIndex + 1
if group == (index + 1):
# check the checkBox
widget = self.tableWidget_VTKFiles.cellWidget(row, 2)
tuple = widget.children()
checkBox = tuple[1]
checkBox.blockSignals(True)
item = self.checkableComboBox_ChoiceOfGroup.model().item(index, 0)
if item.checkState():
checkBox.setChecked(True)
self.groupSelected.add(index + 1)
else:
checkBox.setChecked(False)
self.groupSelected.discard(index + 1)
checkBox.blockSignals(False)
# Update the color in the qtableWidget of each vtk file
colorTransferFunction = self.logic.creationColorTransfer(self.groupSelected)
self.updateColorInTableForPreviewInSPV(colorTransferFunction)
def onGroupValueChanged(self):
""" Function to manage the combobox which
allow the user to change the group of a vtk file
"""
# Updade the dictionary which containing the VTK files sorted by groups
self.logic.onComboBoxTableValueChanged(self.dictVTKFiles, self.tableWidget_VTKFiles)
# Update the checkable combobox which display the groups selected to preview them in SPV
self.onCheckBoxTableValueChanged()
# Enable exportation of the last updated csv file
self.pushButton_exportUpdatedClassification.setEnabled(True)
# Default path to override the previous one
# self.directoryButton_exportUpdatedClassification.directory = os.path.dirname(self.pathLineEdit_previewGroups.currentPath)
def onCheckBoxTableValueChanged(self):
""" Function to manage the checkbox in
the table used to make a preview in SPV
"""
self.groupSelected = set()
# Update the checkable comboBox which allow to select what groups the user wants to display in SPV
self.checkableComboBox_ChoiceOfGroup.blockSignals(True)
allcheck = True
for key, value in self.dictVTKFiles.items():
item = self.checkableComboBox_ChoiceOfGroup.model().item(key, 0)
if not value == []:
for vtkFile in value:
filename = os.path.basename(vtkFile)
for row in range(0,self.tableWidget_VTKFiles.rowCount):
qlabel = self.tableWidget_VTKFiles.cellWidget(row, 0)
if qlabel.text == filename:
widget = self.tableWidget_VTKFiles.cellWidget(row, 2)
tuple = widget.children()
checkBox = tuple[1]
if not checkBox.checkState():
allcheck = False
item.setCheckState(0)
else:
self.groupSelected.add(key)
if allcheck:
item.setCheckState(2)
else:
item.setCheckState(0)
allcheck = True
self.checkableComboBox_ChoiceOfGroup.blockSignals(False)
# Update the color in the qtableWidget which will display in SPV
colorTransferFunction = self.logic.creationColorTransfer(self.groupSelected)
self.updateColorInTableForPreviewInSPV(colorTransferFunction)
def updateColorInTableForPreviewInSPV(self, colorTransferFunction):
""" Function to update the colors that the selected
vtk files will have in Shape Population Viewer
"""
for row in range(0,self.tableWidget_VTKFiles.rowCount):
# Recovery of the group display in the table for each vtk file
widget = self.tableWidget_VTKFiles.cellWidget(row, 1)
tuple = widget.children()
comboBox = qt.QComboBox()
comboBox = tuple[1]
group = comboBox.currentIndex + 1
# Recovery of the checkbox for each vtk file
widget = self.tableWidget_VTKFiles.cellWidget(row, 2)
tuple = widget.children()
checkBox = qt.QCheckBox()
checkBox = tuple[1]
# If the checkbox is check, the color is found thanks to the color transfer function
# Else the color is put at white
if checkBox.isChecked():
rgb = colorTransferFunction.GetColor(group)
widget = self.tableWidget_VTKFiles.cellWidget(row, 3)
self.tableWidget_VTKFiles.item(row,3).setBackground(qt.QColor(rgb[0]*255,rgb[1]*255,rgb[2]*255))
else:
self.tableWidget_VTKFiles.item(row,3).setBackground(qt.QColor(255,255,255))
def onPreviewVTKFiles(self):
""" Function to display the selected vtk files in Shape Population Viewer
- Add a color map "DisplayClassificationGroup"
- Launch the CLI ShapePopulationViewer
"""
if os.path.exists(self.pathLineEdit_previewGroups.currentPath):
# Creation of a color map to visualize each group with a different color in ShapePopulationViewer
self.logic.addColorMap(self.tableWidget_VTKFiles, self.dictVTKFiles)
# Creation of a CSV file to load the vtk files in ShapePopulationViewer
filePathCSV = slicer.app.temporaryPath + '/' + 'VTKFilesPreview_OAIndex.csv'
self.logic.creationCSVFileForSPV(filePathCSV, self.tableWidget_VTKFiles, self.dictVTKFiles)
slicer.modules.shapepopulationviewer.widgetRepresentation().loadCSVFile(filePathCSV)
slicer.util.selectModule(slicer.modules.shapepopulationviewer)
# Remove the vtk files previously created in the temporary directory of Slicer
for value in self.dictVTKFiles.values():
self.logic.removeDataVTKFiles(value)
def onExportUpdatedClassificationGroups(self):
""" Function to export the new Classification Groups
- Data saved:
- Save the mean vtk files in the selected directory
- Save the CSV file in the selected directory
- Load automatically the CSV file in the next tab: "Selection of Classification Groups"
"""
dlg = ctk.ctkFileDialog()
filepath = dlg.getSaveFileName(None, "Export Updated CSV file", "", "CSV File (*.csv)")
directory = os.path.dirname(filepath)
basename = os.path.basename(filepath)
# Save the CSV File and the shape model of each group
self.logic.creationCSVFile(directory, basename, self.dictVTKFiles, "Groups")
# Re-Initialization of the dictionary containing the path of the shape model of each group
# self.dictVTKFiles = dict()
# Message for the user
slicer.util.delayDisplay("Files Saved")
# Disable the option to export the new data
self.pushButton_exportUpdatedClassification.setDisabled(True)
# Load automatically the CSV file in the pathline in the next tab "Selection of Classification Groups"
if self.pathLineEdit_selectionClassificationGroups.currentPath == filepath:
self.pathLineEdit_selectionClassificationGroups.setCurrentPath(" ")
self.pathLineEdit_selectionClassificationGroups.setCurrentPath(filepath)
#self.pathLineEdit_CSVFileDataset.setCurrentPath(filepath)
# ---------------------------------------------------- #
# Tab: PCA Analysis #
# ---------------------------------------------------- #
def onCSV_PCA(self):
try:
self.logic.pca_exploration.loadCSVFile(self.pathLineEdit_CSVFilePCA.currentPath)
self.pathLineEdit_exploration.setCurrentPath(" ")
except shapca.CSVFileError as e:
print('CSVFileError:'+e.value)
slicer.util.errorDisplay('Invalid CSV file')
return
self.pushButton_PCA.setEnabled(True)
def onExportForExploration(self):
self.logic.pca_exploration.process()
self.comboBox_groupPCA.setEnabled(True)
self.comboBox_groupPCA.clear()
# Activate the PCA Single Export Widgets
self.comboBox_SingleExportGroup.setEnabled(True)
self.comboBox_SingleExportGroup.clear()
self.comboBox_SingleExportPC.setEnabled(True)
self.comboBox_SingleExportPC.clear()
# Add personalized groups to comboboxes with the CSV
dictPCA=self.logic.pca_exploration.getDictPCA()
for key, value in dictPCA.items():
group_name = value["group_name"]
if key != "All":
self.comboBox_groupPCA.addItem(str(key)+': '+group_name)
self.comboBox_SingleExportGroup.addItem(str(key)+': '+group_name)
else:
self.comboBox_groupPCA.addItem(key)
self.comboBox_SingleExportGroup.addItem(key)
self.setColorModeSpinBox()
self.showmean=False
self.generate3DVisualisationNodes()
self.generate2DVisualisationNodes()
index = self.comboBox_colorMode.findText('Group color', qt.Qt.MatchFixedString)
if index >= 0:
self.comboBox_colorMode.setCurrentIndex(index)
self.pathLineEdit_exploration.disconnect('currentPathChanged(const QString)', self.onLoadExploration)
self.pathLineEdit_exploration.setCurrentPath(' ')
self.pathLineEdit_exploration.connect('currentPathChanged(const QString)', self.onLoadExploration)
if self.evaluationFlag=="DONE":
try:
self.pushButton_evaluateModels.clicked.disconnect()
except:
pass
self.pushButton_evaluateModels.setText("Evaluate models (It may take a long time)")
self.pushButton_evaluateModels.connect('clicked()',self.onEvaluateModels)
self.explorePCA()
def onResetSliders(self):
self.logic.pca_exploration.resetPCAPolyData()
#self.polyDataPCA.Modified()
for slider in self.PCA_sliders:
slider.setSliderPosition(0)
def onChangePCAPolyData(self, num_slider):
ratio = self.PCA_sliders[num_slider].value
X=1-(((ratio/1000.0)+1)/2.0)
self.PCA_sliders_value_label[num_slider].setText(str(round(stats.norm.isf(X),3)))
self.logic.pca_exploration.updatePolyDataExploration(num_slider,ratio/1000.0)
#self.polyDataPCA.Modified()
def onLoadExploration(self):
JSONfile=self.pathLineEdit_exploration.currentPath
# Check if the path exists:
if not os.path.exists(JSONfile):
return
try:
self.logic.pca_exploration.load(JSONfile)
self.pathLineEdit_CSVFilePCA.disconnect('currentPathChanged(const QString)', self.onCSV_PCA)
self.pathLineEdit_CSVFilePCA.setCurrentPath(" ")
self.pathLineEdit_CSVFilePCA.connect('currentPathChanged(const QString)', self.onCSV_PCA)
except shapca.JSONFileError as e:
print('JSONFileError:'+e.value)
slicer.util.errorDisplay('Invalid JSON file')
return
self.comboBox_groupPCA.setEnabled(True)
self.comboBox_groupPCA.clear()
dictPCA=self.logic.pca_exploration.getDictPCA()
for key, value in dictPCA.items():
group_name = value["group_name"]
if key != "All":
self.comboBox_groupPCA.addItem(str(key)+': '+group_name)
else:
self.comboBox_groupPCA.addItem(key)
self.setColorModeSpinBox()
self.showmean=False
self.generate3DVisualisationNodes()
self.generate2DVisualisationNodes()
index = self.comboBox_colorMode.findText('Group color', qt.Qt.MatchFixedString)
if index >= 0:
self.comboBox_colorMode.setCurrentIndex(index)
#slicer.mrmlScene.RemoveAllDefaultNodes()
if self.evaluationFlag=="DONE":
try:
self.pushButton_evaluateModels.clicked.disconnect()
except:
pass
self.pushButton_evaluateModels.setText("Evaluate models (It may take a long time)")
self.pushButton_evaluateModels.connect('clicked()',self.onEvaluateModels)
self.explorePCA()
def onGroupColorChanged(self,newcolor):
#change the plot color
plotSeriesNode = slicer.mrmlScene.GetFirstNodeByName("PCA projection")
plotSeriesNode.SetColor(newcolor.red()/255.0,newcolor.green()/255.0,newcolor.blue()/255.0)
newcolor=(newcolor.red()/255.0,newcolor.green()/255.0,newcolor.blue()/255.0)
self.logic.pca_exploration.changeCurrentGroupColor(newcolor)
r,g,b=self.logic.pca_exploration.getColor()
displayNode = slicer.mrmlScene.GetFirstNodeByName("PCA Display")
displayNode.SetColor(r,g,b)