/
ALPACA.py
3732 lines (3354 loc) · 150 KB
/
ALPACA.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
##BASE PYTHON
import os
import unittest
import logging
import copy
import json
import subprocess
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import glob
import vtk.util.numpy_support as vtk_np
import numpy as np
from datetime import datetime
import time
import sys
import os
import platform
import math
#
# ALPACA
#
class ALPACA(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)
self.parent.title = "ALPACA"
self.parent.categories = ["SlicerMorph.Geometric Morphometrics"]
self.parent.dependencies = []
self.parent.contributors = [
"Arthur Porto (LSU), Sara Rolfe (UW), Chi Zhang (SCRI), Murat Maga (UW)"
]
self.parent.helpText = """
This module automatically transfers landmarks on a reference 3D model (mesh) to a target 3D model using dense correspondence and deformable registration. First optimize the parameters in single alignment analysis, then use them in batch mode to apply to all 3D models.
<p>For more information see the <a href="https://github.com/SlicerMorph/SlicerMorph/tree/master/Docs/ALPACA">online documentation.</a>.</p>
"""
self.parent.acknowledgementText = """
This module was developed by Arthur Porto, Sara Rolfe, and Murat Maga for SlicerMorph. SlicerMorph was originally supported by an NSF/DBI grant, "An Integrated Platform for Retrieval, Visualization and Analysis of 3D Morphology From Digital Biological Collections"
awarded to Murat Maga (1759883), Adam Summers (1759637), and Douglas Boyer (1759839).
https://nsf.gov/awardsearch/showAward?AWD_ID=1759883&HistoricalAwards=false
"""
# Additional initialization step after application startup is complete
slicer.app.connect("startupCompleted()", registerSampleData)
# Define custom layouts for multi-templates selection tab in slicer global namespace
slicer.customLayoutSM = """
<layout type=\"horizontal\" split=\"true\" >
<item splitSize=\"500\">
<item>
<view class=\"vtkMRMLPlotViewNode\" singletontag=\"PlotViewerWindow_1\">
<property name=\"viewlabel\" action=\"default\">1</property>
</view>
</item>
<item>
<view class=\"vtkMRMLTableViewNode\" singletontag=\"TableViewerWindow_1\">"
<property name=\"viewlabel\" action=\"default\">T</property>"
</view>"
</item>"
</item>
</layout>
"""
slicer.customLayoutTableOnly = """
<layout type=\"horizontal\" >
<item>
<view class=\"vtkMRMLTableViewNode\" singletontag=\"TableViewerWindow_1\">"
<property name=\"viewlabel\" action=\"default\">T</property>"
</view>"
</item>"
</layout>
"""
slicer.customLayoutPlotOnly = """
<layout type=\"horizontal\" >
<item>
<view class=\"vtkMRMLPlotViewNode\" singletontag=\"PlotViewerWindow_1\">
<property name=\"viewlabel\" action=\"default\">1</property>
</view>"
</item>"
</layout>
"""
#
# Register sample data sets in Sample Data module
#
def registerSampleData():
"""
Add data sets to Sample Data module.
"""
# It is always recommended to provide sample data for users to make it easy to try the module,
# but if no sample data is available then this method (and associated startupCompeted signal connection) can be removed.
import SampleData
iconsPath = os.path.join(os.path.dirname(__file__), "Resources/Icons")
# To ensure that the source code repository remains small (can be downloaded and installed quickly)
# it is recommended to store data sets that are larger than a few MB in a Github release.
# TemplateKey1
SampleData.SampleDataLogic.registerCustomSampleDataSource(
# Category and sample name displayed in Sample Data module
category="TemplateKey",
sampleName="TemplateKey1",
# Thumbnail should have size of approximately 260x280 pixels and stored in Resources/Icons folder.
# It can be created by Screen Capture module, "Capture all views" option enabled, "Number of images" set to "Single".
thumbnailFileName=os.path.join(iconsPath, "TemplateKey1.png"),
# Download URL and target file name
uris="https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/998cb522173839c78657f4bc0ea907cea09fd04e44601f17c82ea27927937b95",
fileNames="TemplateKey1.nrrd",
# Checksum to ensure file integrity. Can be computed by this command:
# import hashlib; print(hashlib.sha256(open(filename, "rb").read()).hexdigest())
checksums="SHA256:998cb522173839c78657f4bc0ea907cea09fd04e44601f17c82ea27927937b95",
# This node name will be used when the data set is loaded
nodeNames="TemplateKey1",
)
# TemplateKey2
SampleData.SampleDataLogic.registerCustomSampleDataSource(
# Category and sample name displayed in Sample Data module
category="TemplateKey",
sampleName="TemplateKey2",
thumbnailFileName=os.path.join(iconsPath, "TemplateKey2.png"),
# Download URL and target file name
uris="https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/1a64f3f422eb3d1c9b093d1a18da354b13bcf307907c66317e2463ee530b7a97",
fileNames="TemplateKey2.nrrd",
checksums="SHA256:1a64f3f422eb3d1c9b093d1a18da354b13bcf307907c66317e2463ee530b7a97",
# This node name will be used when the data set is loaded
nodeNames="TemplateKey2",
)
#
# ALPACAWidget
#
class ALPACAWidget(ScriptedLoadableModuleWidget):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent=None):
ScriptedLoadableModuleWidget.__init__(self, parent)
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
needInstall = False
try:
from itk import Fpfh
import cpdalp
except ModuleNotFoundError:
needInstall = True
if needInstall:
progressDialog = slicer.util.createProgressDialog(
windowTitle="Installing...",
labelText="Installing ALPACA Python packages. This may take a minute...",
maximum=0,
)
slicer.app.processEvents()
try:
slicer.util.pip_install(["itk==5.3.0"])
slicer.util.pip_install(["scikit-learn"])
slicer.util.pip_install(["itk_fpfh==0.1.1"])
slicer.util.pip_install(["itk_ransac==0.1.4"])
slicer.util.pip_install(f"cpdalp")
except:
slicer.util.infoDisplay("Issue while installing the ITK Python packages")
progressDialog.close()
import itk
fpfh = itk.Fpfh.PointFeature.MF3MF3.New()
progressDialog.close()
try:
import cpdalp
import itk
from itk import Fpfh
from itk import Ransac
except ModuleNotFoundError as e:
print("Module Not found. Please restart Slicer to load packages.")
progressDialog = slicer.util.createProgressDialog(
windowTitle="Importing...",
labelText="Importing ALPACA Python packages. This may take few seconds...",
maximum=0,
)
slicer.app.processEvents()
with slicer.util.WaitCursor():
fpfh = itk.Fpfh.PointFeature.MF3MF3.New()
progressDialog.close()
# Load widget from .ui file (created by Qt Designer).
uiWidget = slicer.util.loadUI(self.resourcePath("UI/ALPACA.ui"))
self.layout.addWidget(uiWidget)
self.ui = slicer.util.childWidgetVariables(uiWidget)
# Setup checkbox stylesheets
moduleDir = os.path.dirname(slicer.util.modulePath(self.__module__))
self.onIconPath = moduleDir + "/Resources/Icons/switch_on.png"
self.offIconPath = moduleDir + "/Resources/Icons/switch_off.png"
# Single Alignment connections
self.ui.sourceModelSelector.connect(
"currentNodeChanged(vtkMRMLNode*)", self.onSelect
)
self.ui.sourceModelSelector.setMRMLScene(slicer.mrmlScene)
self.ui.sourceLandmarkSetSelector.connect(
"currentNodeChanged(vtkMRMLNode*)", self.onSelect
)
self.ui.sourceLandmarkSetSelector.setMRMLScene(slicer.mrmlScene)
self.ui.targetModelSelector.connect(
"currentNodeChanged(vtkMRMLNode*)", self.onSelect
)
self.ui.targetModelSelector.setMRMLScene(slicer.mrmlScene)
self.ui.targetLandmarkSetSelector.connect(
"currentNodeChanged(vtkMRMLNode*)", self.onSelect
)
self.ui.targetLandmarkSetSelector.setMRMLScene(slicer.mrmlScene)
self.ui.pointDensitySlider.connect(
"valueChanged(double)", self.onChangeDensitySingle
)
self.ui.subsampleButton.connect("clicked(bool)", self.onSubsampleButton)
self.ui.runALPACAButton.connect(
"clicked(bool)", self.onRunALPACAButton
) # Connection for run all ALPACA steps button
self.ui.switchSettingsButton.connect(
"clicked(bool)", self.onSwitchSettingsButton
)
self.ui.showTargetPCDCheckBox.connect(
"toggled(bool)", self.onShowTargetPCDCheckBox
)
self.setCheckboxStyle(self.ui.showTargetPCDCheckBox)
self.ui.showSourcePCDCheckBox.connect(
"toggled(bool)", self.onShowSourcePCDCheckBox
)
self.setCheckboxStyle(self.ui.showSourcePCDCheckBox)
self.ui.showTargetModelCheckBox.connect(
"toggled(bool)", self.onshowTargetModelCheckBox
)
self.setCheckboxStyle(self.ui.showTargetModelCheckBox)
self.ui.showSourceModelCheckBox.connect(
"toggled(bool)", self.onshowSourceModelCheckBox
)
self.setCheckboxStyle(self.ui.showSourceModelCheckBox)
self.ui.showUnprojectLMCheckBox.connect(
"toggled(bool)", self.onShowUnprojectLMCheckBox
)
self.setCheckboxStyle(self.ui.showUnprojectLMCheckBox)
self.ui.showTPSModelCheckBox.connect(
"toggled(bool)", self.onshowTPSModelCheckBox
)
self.setCheckboxStyle(self.ui.showTPSModelCheckBox)
self.ui.showFinalLMCheckbox.connect("toggled(bool)", self.onShowFinalLMCheckbox)
self.setCheckboxStyle(self.ui.showFinalLMCheckbox)
self.ui.showManualLMCheckBox.connect(
"toggled(bool)", self.onShowManualLMCheckBox
)
self.setCheckboxStyle(self.ui.showManualLMCheckBox)
# Advanced Settings connections
self.ui.projectionFactorSlider.connect(
"valueChanged(double)", self.onChangeAdvanced
)
self.ui.pointDensityAdvancedSlider.connect(
"valueChanged(double)", self.onChangeAdvanced
)
self.ui.normalSearchRadiusSlider.connect(
"valueChanged(double)", self.onChangeAdvanced
)
self.ui.FPFHNeighborsSlider.connect(
"valueChanged(double)", self.onChangeAdvanced
)
self.ui.FPFHSearchRadiusSlider.connect(
"valueChanged(double)", self.onChangeAdvanced
)
self.ui.maximumCPDThreshold.connect(
"valueChanged(double)", self.onChangeAdvanced
)
self.ui.maxRANSAC.connect("valueChanged(double)", self.onChangeAdvanced)
self.ui.poissonSubsampleCheckBox.connect("toggled(bool)", self.onChangeAdvanced)
self.ui.ICPDistanceThresholdSlider.connect(
"valueChanged(double)", self.onChangeAdvanced
)
self.ui.alpha.connect("valueChanged(double)", self.onChangeAdvanced)
self.ui.beta.connect("valueChanged(double)", self.onChangeAdvanced)
self.ui.CPDIterationsSlider.connect(
"valueChanged(double)", self.onChangeAdvanced
)
self.ui.CPDToleranceSlider.connect(
"valueChanged(double)", self.onChangeAdvanced
)
self.ui.accelerationCheckBox.connect("toggled(bool)", self.onChangeCPD)
self.ui.accelerationCheckBox.connect("toggled(bool)", self.onChangeAdvanced)
self.ui.BCPDFolder.connect("validInputChanged(bool)", self.onChangeAdvanced)
self.ui.BCPDFolder.connect("validInputChanged(bool)", self.onChangeCPD)
self.ui.BCPDFolder.currentPath = ALPACALogic().getBCPDPath()
# Batch Processing connections
self.ui.methodBatchWidget.connect(
"currentIndexChanged(int)", self.onChangeMultiTemplate
)
self.ui.sourceModelMultiSelector.connect(
"validInputChanged(bool)", self.onSelectMultiProcess
)
self.ui.sourceFiducialMultiSelector.connect(
"validInputChanged(bool)", self.onSelectMultiProcess
)
self.ui.targetModelMultiSelector.connect(
"validInputChanged(bool)", self.onSelectMultiProcess
)
self.ui.landmarkOutputSelector.connect(
"validInputChanged(bool)", self.onSelectMultiProcess
)
self.ui.skipScalingMultiCheckBox.connect(
"toggled(bool)", self.onSelectMultiProcess
)
self.ui.replicateAnalysisCheckBox.connect(
"toggled(bool)", self.onSelectReplicateAnalysis
)
self.ui.applyLandmarkMultiButton.connect(
"clicked(bool)", self.onApplyLandmarkMulti
)
# Template Selection connections
self.ui.modelsMultiSelector.connect(
"validInputChanged(bool)", self.onSelectKmeans
)
self.ui.kmeansOutputSelector.connect(
"validInputChanged(bool)", self.onSelectKmeans
)
self.ui.selectRefCheckBox.connect("toggled(bool)", self.onSelectKmeans)
self.ui.downReferenceButton.connect("clicked(bool)", self.onDownReferenceButton)
self.ui.matchingPointsButton.connect(
"clicked(bool)", self.onMatchingPointsButton
)
self.ui.multiGroupInput.connect("toggled(bool)", self.onToggleGroupInput)
self.ui.resetTableButton.connect("clicked(bool)", self.onRestTableButton)
self.ui.kmeansTemplatesButton.connect(
"clicked(bool)", self.onkmeansTemplatesButton
)
# RMSE Table initialization
self.col1List = []
# Test Target cloud initialization
self.targetCloudNodeTest = None
# Add menu buttons
self.addLayoutButton(
503,
"MALPACA multi-templates View",
"Custom layout for MALPACA multi-templates tab",
"LayoutSlicerMorphView.png",
slicer.customLayoutSM,
)
self.addLayoutButton(
504,
"Table Only View",
"Custom layout for GPA module",
"LayoutTableOnlyView.png",
slicer.customLayoutTableOnly,
)
self.addLayoutButton(
505,
"Plot Only View",
"Custom layout for GPA module",
"LayoutPlotOnlyView.png",
slicer.customLayoutPlotOnly,
)
# initialize the parameter dictionary from single run parameters
self.parameterDictionary = {
"projectionFactor": self.ui.projectionFactorSlider.value,
"pointDensity": self.ui.pointDensityAdvancedSlider.value,
"normalSearchRadius": self.ui.normalSearchRadiusSlider.value,
"FPFHNeighbors": int(self.ui.FPFHNeighborsSlider.value),
"FPFHSearchRadius": self.ui.FPFHSearchRadiusSlider.value,
"distanceThreshold": self.ui.maximumCPDThreshold.value,
"maxRANSAC": int(self.ui.maxRANSAC.value),
"ICPDistanceThreshold": float(self.ui.ICPDistanceThresholdSlider.value),
"alpha": self.ui.alpha.value,
"beta": self.ui.beta.value,
"CPDIterations": int(self.ui.CPDIterationsSlider.value),
"CPDTolerance": self.ui.CPDToleranceSlider.value,
"Acceleration": self.ui.accelerationCheckBox.checked,
"BCPDFolder": self.ui.BCPDFolder.currentPath,
}
def cleanup(self):
pass
def setCheckboxStyle(self, checkbox):
checkbox.setStyleSheet(
"QCheckBox::indicator:unchecked{image: url("
+ self.offIconPath
+ "); } \n"
+ "QCheckBox::indicator:checked{image: url("
+ self.onIconPath
+ "); } \n"
+ "QCheckBox::indicator{width: 50px;height: 25px;}\n"
)
def addLayoutButton(
self, layoutID, buttonAction, toolTip, imageFileName, layoutDiscription
):
layoutManager = slicer.app.layoutManager()
layoutManager.layoutLogic().GetLayoutNode().AddLayoutDescription(
layoutID, layoutDiscription
)
viewToolBar = slicer.util.mainWindow().findChild("QToolBar", "ViewToolBar")
layoutMenu = viewToolBar.widgetForAction(viewToolBar.actions()[0]).menu()
layoutSwitchActionParent = layoutMenu
# use `layoutMenu` to add inside layout list, use `viewToolBar` to add next the standard layout list
layoutSwitchAction = layoutSwitchActionParent.addAction(
buttonAction
) # add inside layout list
moduleDir = os.path.dirname(slicer.util.modulePath(self.__module__))
iconPath = os.path.join(moduleDir, "Resources/Icons", imageFileName)
layoutSwitchAction.setIcon(qt.QIcon(iconPath))
layoutSwitchAction.setToolTip(toolTip)
layoutSwitchAction.connect(
"triggered()",
lambda layoutId=layoutID: slicer.app.layoutManager().setLayout(layoutId),
)
layoutSwitchAction.setData(layoutID)
def onSelect(self):
# Enable run ALPACA button
self.ui.skipScalingMultiCheckBox.checked = self.ui.skipScalingCheckBox.checked
self.ui.skipProjectionCheckBoxMulti.checked = (
self.ui.skipProjectionCheckBox.checked
)
self.ui.subsampleButton.enabled = bool(
self.ui.sourceModelSelector.currentNode()
and self.ui.targetModelSelector.currentNode()
and self.ui.sourceLandmarkSetSelector.currentNode()
)
self.ui.runALPACAButton.enabled = bool(
self.ui.sourceModelSelector.currentNode()
and self.ui.targetModelSelector.currentNode()
and self.ui.sourceLandmarkSetSelector.currentNode()
)
self.ui.switchSettingsButton.enabled = bool(
self.ui.sourceModelSelector.currentNode()
and self.ui.targetModelSelector.currentNode()
and self.ui.sourceLandmarkSetSelector.currentNode()
)
def onSelectMultiProcess(self):
self.ui.applyLandmarkMultiButton.enabled = bool(
self.ui.sourceModelMultiSelector.currentPath
and self.ui.sourceFiducialMultiSelector.currentPath
and self.ui.targetModelMultiSelector.currentPath
and self.ui.landmarkOutputSelector.currentPath
)
def onSelectReplicateAnalysis(self):
self.ui.replicationNumberLabel.enabled = bool(
self.ui.replicateAnalysisCheckBox.isChecked()
)
self.ui.replicationNumberSpinBox.enabled = bool(
self.ui.replicateAnalysisCheckBox.isChecked()
)
def transform_numpy_points(self, points_np, transform):
import itk
mesh = itk.Mesh[itk.F, 3].New()
mesh.SetPoints(
itk.vector_container_from_array(points_np.flatten().astype("float32"))
)
transformed_mesh = itk.transform_mesh_filter(mesh, transform=transform)
points_tranformed = itk.array_from_vector_container(
transformed_mesh.GetPoints()
)
points_tranformed = np.reshape(points_tranformed, [-1, 3])
return points_tranformed
def onSubsampleButton(self):
try:
if self.targetCloudNodeTest is not None:
slicer.mrmlScene.RemoveNode(self.targetCloudNodeTest)
self.targetCloudNodeTest = None
except:
pass
logic = ALPACALogic()
self.sourceModelNode_orig = self.ui.sourceModelSelector.currentNode()
self.sourceModelNode_orig.GetDisplayNode().SetVisibility(False)
# Create a copy of sourceModelNode then clone it for ALPACA steps
shNode = slicer.vtkMRMLSubjectHierarchyNode.GetSubjectHierarchyNode(
slicer.mrmlScene
)
itemIDToClone = shNode.GetItemByDataNode(self.sourceModelNode_orig)
clonedItemID = slicer.modules.subjecthierarchy.logic().CloneSubjectHierarchyItem(
shNode, itemIDToClone
)
self.sourceModelNode_clone = shNode.GetItemDataNode(clonedItemID)
self.sourceModelNode_clone.SetName("SourceModelNode_clone")
self.sourceModelNode_clone.GetDisplayNode().SetVisibility(False)
# slicer.mrmlScene.RemoveNode(self.sourceModelNode_copy)
# Create target Model Node
self.targetModelNode = self.ui.targetModelSelector.currentNode()
self.targetModelNode.GetDisplayNode().SetVisibility(False)
self.ui.sourceLandmarkSetSelector.currentNode().GetDisplayNode().SetVisibility(
False
)
(
self.sourcePoints,
self.targetPoints,
self.sourceFeatures,
self.targetFeatures,
self.voxelSize,
self.scaling,
) = logic.runSubsample(
self.sourceModelNode_clone,
self.targetModelNode,
self.ui.skipScalingCheckBox.checked,
self.parameterDictionary,
self.ui.poissonSubsampleCheckBox.checked,
)
# Convert to VTK points for visualization
self.targetVTK = logic.convertPointsToVTK(self.targetPoints)
slicer.mrmlScene.RemoveNode(self.sourceModelNode_clone)
# Display target points
blue = [0, 0, 1]
self.targetCloudNodeTest = logic.displayPointCloud(
self.targetVTK, self.voxelSize / 10, "Target Pointcloud_test", blue
)
self.targetCloudNodeTest.GetDisplayNode().SetVisibility(True)
self.updateLayout()
# Output information on subsampling
self.ui.subsampleInfo.clear()
self.ui.subsampleInfo.insertPlainText(
f":: Your subsampled source pointcloud has a total of {len(self.sourcePoints)} points. \n"
)
self.ui.subsampleInfo.insertPlainText(
f":: Your subsampled target pointcloud has a total of {len(self.targetPoints)} points. "
)
self.ui.runALPACAButton.enabled = True
if bool(self.ui.targetLandmarkSetSelector.currentNode()) == True:
self.ui.targetLandmarkSetSelector.currentNode().GetDisplayNode().SetVisibility(
False
)
try:
self.manualLMNode.GetDisplayNode().SetVisibility(False)
except:
pass
self.ui.showTargetPCDCheckBox.checked = 0
self.ui.showSourcePCDCheckBox.checked = 0
self.ui.showTargetModelCheckBox.checked = 0
self.ui.showSourceModelCheckBox.checked = 0
self.ui.showUnprojectLMCheckBox.checked = 0
self.ui.showTPSModelCheckBox.checked = 0
self.ui.showFinalLMCheckbox.checked = 0
self.ui.showManualLMCheckBox.checked = 0
# Run all button for Single Alignment ALPACA
def onRunALPACAButton(self):
run_counter = (
self.runALPACACounter()
) # the counter for executing this function in str format
logic = ALPACALogic()
try:
self.manualLMNode.GetDisplayNode().SetVisibility(False)
except:
pass
try:
if self.targetCloudNodeTest is not None:
slicer.mrmlScene.RemoveNode(
self.targetCloudNodeTest
) # Remove targe cloud node created in the subsampling to avoid confusion
self.targetCloudNodeTest = None
# slicer.mrmlScene.RemoveNode(self.sourceModelNode)
self.ui.showTargetPCDCheckBox.checked = 0
self.ui.showSourcePCDCheckBox.checked = 0
self.ui.showTargetModelCheckBox.checked = 0
self.ui.showSourceModelCheckBox.checked = 0
self.ui.showUnprojectLMCheckBox.checked = 0
self.ui.showTPSModelCheckBox.checked = 0
self.ui.showFinalLMCheckbox.checked = 0
self.ui.showManualLMCheckBox.checked = 0
except:
pass
#
self.sourceModelNode_orig = self.ui.sourceModelSelector.currentNode()
self.sourceModelNode_orig.GetDisplayNode().SetVisibility(False)
# Clone the original source mesh stored in the node sourceModelNode_orig
shNode = slicer.vtkMRMLSubjectHierarchyNode.GetSubjectHierarchyNode(
slicer.mrmlScene
)
itemIDToClone = shNode.GetItemByDataNode(self.sourceModelNode_orig)
clonedItemID = slicer.modules.subjecthierarchy.logic().CloneSubjectHierarchyItem(
shNode, itemIDToClone
)
self.sourceModelNode = shNode.GetItemDataNode(clonedItemID)
self.sourceModelNode.GetDisplayNode().SetVisibility(False)
self.sourceModelNode.SetName(
"Source model(rigidly registered)_" + run_counter
) # Create a cloned source model node
# slicer.mrmlScene.RemoveNode(self.sourceModelNode_copy)
#
self.targetModelNode = self.ui.targetModelSelector.currentNode()
self.targetModelNode.GetDisplayNode().SetVisibility(False)
self.ui.sourceLandmarkSetSelector.currentNode().GetDisplayNode().SetVisibility(
False
)
#
(
self.sourcePoints,
self.targetPoints,
self.sourceFeatures,
self.targetFeatures,
self.voxelSize,
self.scaling,
) = logic.runSubsample(
self.sourceModelNode,
self.targetModelNode,
self.ui.skipScalingCheckBox.checked,
self.parameterDictionary,
self.ui.poissonSubsampleCheckBox.checked,
)
# Convert to VTK points for visualization
self.targetVTK = logic.convertPointsToVTK(self.targetPoints)
blue = [0, 0, 1]
self.targetCloudNode_2 = logic.displayPointCloud(
self.targetVTK,
self.voxelSize / 10,
"Target Pointcloud_" + run_counter,
blue,
)
self.targetCloudNode_2.GetDisplayNode().SetVisibility(False)
# Output information on subsampling
self.ui.subsampleInfo.clear()
self.ui.subsampleInfo.insertPlainText(
f":: Your subsampled source pointcloud has a total of {len(self.sourcePoints)} points. \n"
)
self.ui.subsampleInfo.insertPlainText(
f":: Your subsampled target pointcloud has a total of {len(self.targetPoints)} points. "
)
#
# RANSAC & ICP transformation of source pointcloud
self.transformMatrix, similarityFlag = logic.estimateTransform(
self.sourcePoints,
self.targetPoints,
self.sourceFeatures,
self.targetFeatures,
self.voxelSize,
self.ui.skipScalingCheckBox.checked,
self.parameterDictionary,
)
vtkTransformMatrix = logic.itkToVTKTransform(
self.transformMatrix, similarityFlag
)
self.ICPTransformNode = logic.convertMatrixToTransformNode(
vtkTransformMatrix, "Rigid Transformation Matrix_" + run_counter
)
self.sourcePoints = logic.transform_numpy_points(
self.sourcePoints, self.transformMatrix
)
# Setup source pointcloud VTK object
self.sourceVTK = logic.convertPointsToVTK(self.sourcePoints)
#
red = [1, 0, 0]
self.sourceCloudNode = logic.displayPointCloud(
self.sourceVTK,
self.voxelSize / 10,
("Source Pointcloud (rigidly registered)_" + run_counter),
red,
)
self.sourceCloudNode.GetDisplayNode().SetVisibility(False)
#
# Transform the source model
self.sourceModelNode.SetAndObserveTransformNodeID(self.ICPTransformNode.GetID())
slicer.vtkSlicerTransformLogic().hardenTransform(self.sourceModelNode)
#
self.sourceModelNode.GetDisplayNode().SetColor(red)
self.sourceModelNode.GetDisplayNode().SetVisibility(False)
#
# CPD registration
print("-----------------------------------------------------------")
print("Performing Deformable Registration ")
self.sourceLandmarks, self.sourceLMNode = logic.loadAndScaleFiducials(
self.ui.sourceLandmarkSetSelector.currentNode(), self.scaling, scene=True
)
self.sourceLandmarks = logic.transform_numpy_points(
self.sourceLandmarks, self.transformMatrix
)
self.sourceLMNode.SetName("Source_Landmarks_clone_" + run_counter)
self.sourceLMNode.SetAndObserveTransformNodeID(self.ICPTransformNode.GetID())
slicer.vtkSlicerTransformLogic().hardenTransform(self.sourceLMNode)
# Registration
self.registeredSourceArray = logic.runCPDRegistration(
self.sourceLandmarks,
self.sourcePoints,
self.targetPoints,
self.parameterDictionary,
)
self.outputPoints = logic.exportPointCloud(
self.registeredSourceArray,
"Initial ALPACA landmark estimate(unprojected)_" + run_counter,
) # outputPoints = ininital predicted LMs, non projected
self.inputPoints = logic.exportPointCloud(
self.sourceLandmarks, "Original Landmarks"
) # input points = source landmarks
# set up output initial predicted landmarkslandmark as vtk class
#
outputPoints_vtk = logic.getFiducialPoints(self.outputPoints)
inputPoints_vtk = logic.getFiducialPoints(self.inputPoints)
#
# Get warped source model and final predicted landmarks
self.warpedSourceNode = logic.applyTPSTransform(
inputPoints_vtk,
outputPoints_vtk,
self.sourceModelNode,
"TPS Warped source model_" + run_counter,
)
self.warpedSourceNode.GetDisplayNode().SetVisibility(False)
green = [0, 1, 0]
self.warpedSourceNode.GetDisplayNode().SetColor(green)
self.outputPoints.GetDisplayNode().SetPointLabelsVisibility(False)
slicer.mrmlScene.RemoveNode(self.inputPoints)
#
if self.ui.skipProjectionCheckBox.checked:
logic.propagateLandmarkTypes(self.sourceLMNode, self.outputPoints)
else:
print(":: Projecting landmarks to external surface")
projectionFactor = self.ui.projectionFactorSlider.value / 100
# self.projected Landmarks = "refined predicted landmarks"
self.projectedLandmarks = logic.runPointProjection(
self.warpedSourceNode,
self.targetModelNode,
self.outputPoints,
projectionFactor,
)
logic.propagateLandmarkTypes(self.sourceLMNode, self.projectedLandmarks)
self.projectedLandmarks.SetName(
"Final ALPACA landmark estimate_" + run_counter
)
self.projectedLandmarks.GetDisplayNode().SetVisibility(False)
self.outputPoints.GetDisplayNode().SetVisibility(False)
# Other visualization
self.sourceLMNode.GetDisplayNode().SetVisibility(False)
self.sourceModelNode.GetDisplayNode().SetVisibility(False)
# Enable reset
# self.resetSceneButton.enabled = True
# Create a folder and add all objects into the folder
folderNode = slicer.mrmlScene.GetSubjectHierarchyNode()
sceneItemID = folderNode.GetSceneItemID()
newFolder = folderNode.CreateFolderItem(
sceneItemID, "ALPACA_output_" + run_counter
)
sourceModelItem = folderNode.GetItemByDataNode(self.sourceModelNode)
sourceCloudItem = folderNode.GetItemByDataNode(self.sourceCloudNode)
targetCloudItem = folderNode.GetItemByDataNode(self.targetCloudNode_2)
ICPTransformItem = folderNode.GetItemByDataNode(self.ICPTransformNode)
sourceLMItem = folderNode.GetItemByDataNode(self.sourceLMNode)
nonProjectLMItem = folderNode.GetItemByDataNode(self.warpedSourceNode)
warpedSourceItem = folderNode.GetItemByDataNode(self.outputPoints)
#
folderNode.SetItemParent(sourceModelItem, newFolder)
folderNode.SetItemParent(sourceCloudItem, newFolder)
folderNode.SetItemParent(targetCloudItem, newFolder)
folderNode.SetItemParent(ICPTransformItem, newFolder)
folderNode.SetItemParent(sourceLMItem, newFolder)
folderNode.SetItemParent(nonProjectLMItem, newFolder)
folderNode.SetItemParent(warpedSourceItem, newFolder)
# Add projected points if they have been created
if not self.ui.skipProjectionCheckBox.isChecked():
finalLMItem = folderNode.GetItemByDataNode(self.projectedLandmarks)
folderNode.SetItemParent(finalLMItem, newFolder)
#
# self.ui.subsampleButton.enabled = False
self.ui.runALPACAButton.enabled = False
#
# Enable visualization
self.ui.showTargetPCDCheckBox.enabled = True
self.ui.showTargetPCDCheckBox.checked = 0
#
self.ui.showSourcePCDCheckBox.enabled = True
self.ui.showSourcePCDCheckBox.checked = 0
#
self.ui.showTargetModelCheckBox.enabled = True
self.ui.showTargetModelCheckBox.checked = 1
#
self.ui.showSourceModelCheckBox.enabled = True
self.ui.showSourceModelCheckBox.checked = 0
#
self.ui.showUnprojectLMCheckBox.enabled = True
self.ui.showUnprojectLMCheckBox.checked = 0
#
self.ui.showTPSModelCheckBox.enabled = True
self.ui.showTPSModelCheckBox.checked = 0
#
self.ui.showFinalLMCheckbox.enabled = True
self.ui.showFinalLMCheckbox.checked = 1
#
# Calculate rmse
# Manual LM numpy array
if bool(self.ui.targetLandmarkSetSelector.currentNode()) == True:
point = [0, 0, 0]
self.manualLMNode = self.ui.targetLandmarkSetSelector.currentNode()
self.manualLMNode.GetDisplayNode().SetSelectedColor(green)
self.ui.showManualLMCheckBox.enabled = True
self.ui.showManualLMCheckBox.checked = 0
self.manualLMNode.GetDisplayNode().SetVisibility(False)
manualLMs = np.zeros(
shape=(self.manualLMNode.GetNumberOfControlPoints(), 3)
)
for i in range(self.manualLMNode.GetNumberOfControlPoints()):
self.manualLMNode.GetNthControlPointPosition(i, point)
manualLMs[i, :] = point
# Source LM numpy array
point2 = [0, 0, 0]
if not self.ui.skipProjectionCheckBox.isChecked():
finalLMs = np.zeros(
shape=(self.projectedLandmarks.GetNumberOfControlPoints(), 3)
)
for i in range(self.projectedLandmarks.GetNumberOfControlPoints()):
self.projectedLandmarks.GetNthControlPointPosition(i, point2)
finalLMs[i, :] = point2
else:
finalLMs = np.zeros(
shape=(self.outputPoints.GetNumberOfControlPoints(), 3)
)
for i in range(self.outputPoints.GetNumberOfControlPoints()):
self.outputPoints.GetNthControlPointPosition(i, point2)
finalLMs[i, :] = point2
#
rmse = logic.rmse(manualLMs, finalLMs)
print(rmse)
self.singleRMSETable(rmse, run_counter)
# progressDialog.close()
def singleRMSETable(self, rmse, counter_str):
self.rmseTableNode = slicer.mrmlScene.GetNodesByName(
"Single Alignment RMSE table Preview"
).GetItemAsObject(0)
if self.rmseTableNode is None:
# Create rmseTableNode and add the first row of rmse
self.rmseTableNode = slicer.mrmlScene.AddNewNodeByClass(
"vtkMRMLTableNode", "Single Alignment RMSE table Preview"
)
col1 = self.rmseTableNode.AddColumn()
col1.SetName("ALPACA test")
col1Item = "ALPACA_" + counter_str
self.col1List = [col1Item]
self.rmseTableNode.AddEmptyRow()
self.rmseTableNode.SetCellText(0, 0, col1Item)
#
col2 = self.rmseTableNode.AddColumn()
col2.SetName("RMSE")
self.rmseTableNode.SetCellText(0, 1, format(rmse, ".6f"))
else:
# print(hasattr(self, 'rmseTableNode'))
# if rmseTableNode exists
# Add a new row of rmse
col1Item = "ALPACA_" + counter_str
self.col1List.append(col1Item)
# Add col1
self.rmseTableNode.AddEmptyRow()
self.rmseTableNode.SetCellText(len(self.col1List) - 1, 0, col1Item)
# Add col2
self.rmseTableNode.SetCellText(
len(self.col1List) - 1, 1, format(rmse, ".6f")
)
slicer.app.layoutManager().setLayout(35)
slicer.app.applicationLogic().GetSelectionNode().SetReferenceActiveTableID(
self.rmseTableNode.GetID()
)
slicer.app.applicationLogic().PropagateTableSelection()
self.rmseTableNode.GetTable().Modified()
# Count the times run ALPAACA function is executed
def runALPACACounter(self, run_counter=[0]):
run_counter[0] += 1
return str(run_counter[0])
def onSwitchSettingsButton(self):
self.ui.tabsWidget.setCurrentWidget(self.ui.advancedSettingsTab)
self.ui.runALPACAButton.enabled = True
def onShowTargetPCDCheckBox(self):
try:
if self.ui.showTargetPCDCheckBox.isChecked():
self.targetCloudNode_2.GetDisplayNode().SetVisibility(True)
else:
self.targetCloudNode_2.GetDisplayNode().SetVisibility(False)
except:
self.ui.showTargetPCDCheckBox.enabled = False
def onShowSourcePCDCheckBox(self):
try:
if self.ui.showSourcePCDCheckBox.isChecked():
self.sourceCloudNode.GetDisplayNode().SetVisibility(True)
else:
self.sourceCloudNode.GetDisplayNode().SetVisibility(False)
except:
self.ui.showSourcePCDCheckBox.enabled = False
def onshowTargetModelCheckBox(self):
try:
if self.ui.showTargetModelCheckBox.isChecked():
self.targetModelNode.GetDisplayNode().SetVisibility(True)
else:
self.targetModelNode.GetDisplayNode().SetVisibility(False)
except:
self.ui.showTargetModelCheckBox.enabled = False
def onshowSourceModelCheckBox(self):
try:
if self.ui.showSourceModelCheckBox.isChecked():
self.sourceModelNode.GetDisplayNode().SetVisibility(True)
else:
self.sourceModelNode.GetDisplayNode().SetVisibility(False)
except:
self.ui.showSourceModelCheckBox.enabled = False
def onShowUnprojectLMCheckBox(self):
try:
if self.ui.showUnprojectLMCheckBox.isChecked():
self.outputPoints.GetDisplayNode().SetVisibility(True)
else:
self.outputPoints.GetDisplayNode().SetVisibility(False)
except:
self.ui.showUnprojectLMCheckBox.enabled = False
def onshowTPSModelCheckBox(self):
try:
if self.ui.showTPSModelCheckBox.isChecked():
self.warpedSourceNode.GetDisplayNode().SetVisibility(True)
else:
self.warpedSourceNode.GetDisplayNode().SetVisibility(False)
except:
self.ui.showTPSModelCheckBox.enabled = False
def onShowFinalLMCheckbox(self):
try:
if self.ui.showFinalLMCheckbox.isChecked():
self.projectedLandmarks.GetDisplayNode().SetVisibility(True)
else:
self.projectedLandmarks.GetDisplayNode().SetVisibility(False)
except:
self.ui.showFinalLMCheckbox.enabled = False
def onShowManualLMCheckBox(self):
try:
if self.ui.showManualLMCheckBox.isChecked():
self.manualLMNode.GetDisplayNode().SetVisibility(True)
else:
self.manualLMNode.GetDisplayNode().SetVisibility(False)
except:
self.ui.showManualLMCheckBox.enabled = False
def onApplyLandmarkMulti(self):
logic = ALPACALogic()
if self.ui.skipProjectionCheckBoxMulti.checked != 0:
projectionFactor = 0
else:
projectionFactor = self.ui.projectionFactorSlider.value / 100
if not self.ui.replicateAnalysisCheckBox.checked:
logic.runLandmarkMultiprocess(
self.ui.sourceModelMultiSelector.currentPath,
self.ui.sourceFiducialMultiSelector.currentPath,
self.ui.targetModelMultiSelector.currentPath,
self.ui.landmarkOutputSelector.currentPath,
self.ui.skipScalingMultiCheckBox.checked,
projectionFactor,
self.ui.JSONFileFormatSelector.checked,
self.parameterDictionary,
)
else:
for i in range(0, self.ui.replicationNumberSpinBox.value):