-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAutoscoperM.py
1372 lines (1127 loc) · 58 KB
/
AutoscoperM.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
import contextlib
import glob
import logging
import os
import shutil
import time
import zipfile
from typing import Optional, Union
import qt
import slicer
import vtk
import vtkAddon
from slicer.ScriptedLoadableModule import (
ScriptedLoadableModule,
ScriptedLoadableModuleLogic,
ScriptedLoadableModuleWidget,
)
from slicer.util import VTKObservationMixin
from AutoscoperMLib import IO, SubVolumeExtraction, Validation
#
# AutoscoperM
#
class AutoscoperM(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 = "AutoscoperM"
self.parent.categories = [
"Tracking",
]
self.parent.contributors = [
"Anthony Lombardi (Kitware)",
"Amy M Morton (Brown University)",
"Bardiya Akhbari (Brown University)",
"Beatriz Paniagua (Kitware)",
"Jean-Christophe Fillion-Robin (Kitware)",
]
# TODO: update with short description of the module and a link to online module documentation
self.parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
See more information in <a href="https://github.com/organization/projectname#AutoscoperM">module documentation</a>.
"""
# TODO: replace with organization, grant and thanks
self.parent.acknowledgementText = """
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc., Andras Lasso, PerkLab,
and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
"""
# Additional initialization step after application startup is complete
slicer.app.connect("startupCompleted()", registerSampleData)
#
# Register sample data sets in Sample Data module
#
def downloadAndExtract(source):
try:
logic = slicer.modules.SampleDataWidget.logic
except AttributeError:
import SampleData
logic = SampleData.SampleDataLogic()
logic.downloadFromSource(source)
cache_dir = slicer.mrmlScene.GetCacheManager().GetRemoteCacheDirectory()
logic.logMessage(f"<b>Extracting archive</b> <i>{source.fileNames[0]}<i/> into {cache_dir} ...</b>")
# Unzip the downloaded file
with zipfile.ZipFile(os.path.join(cache_dir, source.fileNames[0]), "r") as zip_ref:
zip_ref.extractall(cache_dir)
logic.logMessage("<b>Done</b>")
def registerAutoscoperSampleData(dataType, version, checksum):
import SampleData
iconsPath = os.path.join(os.path.dirname(__file__), "Resources/Icons")
SampleData.SampleDataLogic.registerCustomSampleDataSource(
# Category and sample name displayed in Sample Data module
category="Tracking",
sampleName=f"AutoscoperM - {dataType} BVR",
# 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, f"{dataType}.png"),
# Download URL and target file name
uris=f"https://github.com/BrownBiomechanics/Autoscoper/releases/download/sample-data/{version}-{dataType}.zip",
fileNames=f"{version}-{dataType}.zip",
# Checksum to ensure file integrity. Can be computed by this command:
# import hashlib; print(hashlib.sha256(open(filename, "rb").read()).hexdigest())
checksums=checksum,
# This node name will be used when the data set is loaded
# nodeNames=f"AutoscoperM - {dataType} BVR" # comment this line so the data is not loaded into the scene
customDownloader=downloadAndExtract,
)
def sampleDataConfigFile(dataType):
"""Return the trial config filename."""
return {
"2023-08-01-Wrist": "2023-07-20-Wrist.cfg",
"2023-08-01-Knee": "2023-07-26-Knee.cfg",
"2023-08-01-Ankle": "2023-07-20-Ankle.cfg",
}.get(dataType)
def registerSampleData():
"""
Add data sets to Sample Data module.
"""
registerAutoscoperSampleData(
"Wrist", "2025-01-12", checksum="SHA256:13eca7b7ddbf3111c433d10871aa5ee7328d056427cdaaf9407038a021ab8326"
)
registerAutoscoperSampleData(
"Knee", "2025-01-12", checksum="SHA256:b0cac0bd9d4320e3abaeff6f4236a7c40f947c7f8b4b2faf25fe94a8af2c161d"
)
registerAutoscoperSampleData(
"Ankle", "2025-01-12", checksum="SHA256:db39b4ebbdc8e2e5a939b3ddc6dc275316cf3043dc39f51893ac6b364d7a04ba"
)
#
# AutoscoperMWidget
#
class AutoscoperMWidget(ScriptedLoadableModuleWidget, VTKObservationMixin):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent=None):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
ScriptedLoadableModuleWidget.__init__(self, parent)
VTKObservationMixin.__init__(self) # needed for parameter node observation
self.logic = None
self._parameterNode = None
self._updatingGUIFromParameterNode = False
self.autoscoperExecutables = {}
def setup(self):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
ScriptedLoadableModuleWidget.setup(self)
# Load widget from .ui file (created by Qt Designer).
# Additional widgets can be instantiated manually and added to self.layout.
uiWidget = slicer.util.loadUI(self.resourcePath("UI/AutoscoperM.ui"))
self.layout.addWidget(uiWidget)
self.ui = slicer.util.childWidgetVariables(uiWidget)
# Set scene in MRML widgets. Make sure that in Qt designer the top-level qMRMLWidget's
# "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's.
# "setMRMLScene(vtkMRMLScene*)" slot.
uiWidget.setMRMLScene(slicer.mrmlScene)
# Create logic class. Logic implements all computations that should be possible to run
# in batch mode, without a graphical user interface.
self.logic = AutoscoperMLogic()
# Connections
# These connections ensure that we update parameter node when scene is closed
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.StartCloseEvent, self.onSceneStartClose)
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.EndCloseEvent, self.onSceneEndClose)
# These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene
# (in the selected parameter node).
# NA
# Buttons
self.ui.startAutoscoper.connect("clicked(bool)", self.startAutoscoper)
self.ui.closeAutoscoper.connect("clicked(bool)", self.logic.stopAutoscoper)
self.ui.loadConfig.connect("clicked(bool)", self.onLoadConfig)
# Lookup Autoscoper executables
for backend in ["CUDA", "OpenCL"]:
executableName = AutoscoperMWidget.autoscoperExecutableName(backend)
logging.info(f"Looking up '{executableName}' executable")
path = shutil.which(executableName)
if path:
self.autoscoperExecutables[backend] = path
logging.info(f"Found '{path}'")
else:
logging.info("No executable found")
if not self.autoscoperExecutables:
logging.error("Failed to lookup autoscoper executables")
# Available Autoscoper backends
self.ui.autoscoperRenderingBackendComboBox.addItems(list(self.autoscoperExecutables.keys()))
# Sample Data Buttons
self.ui.wristSampleButton.connect("clicked(bool)", lambda: self.onSampleDataButtonClicked("2023-08-01-Wrist"))
self.ui.kneeSampleButton.connect("clicked(bool)", lambda: self.onSampleDataButtonClicked("2023-08-01-Knee"))
self.ui.ankleSampleButton.connect("clicked(bool)", lambda: self.onSampleDataButtonClicked("2023-08-01-Ankle"))
# Pre-processing Library Buttons
self.ui.volumeSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onCurrentNodeChanged)
# segmentation and PV generation
self.ui.tiffGenButton.connect("clicked(bool)", self.onGeneratePartialVolumes)
self.ui.segGen_segmentationButton.connect("clicked(bool)", self.onSegmentation)
self.ui.segSTL_importModelsButton.connect("clicked(bool)", self.onImportModels)
self.ui.loadPVButton.connect("clicked(bool)", self.onLoadPV)
# config generation
self.ui.populateCameraCalListButton.connect("clicked(bool)", self.onPopulateCameraCalList)
self.ui.stageCameraCalFileButton.setIcon(qt.QApplication.style().standardIcon(qt.QStyle.SP_ArrowRight))
self.ui.stageCameraCalFileButton.connect("clicked(bool)", self.onStageCameraCalFile)
self.ui.populateTrialNameListButton.connect("clicked(bool)", self.onPopulateTrialNameList)
self.ui.stageTrialDirButton.setIcon(qt.QApplication.style().standardIcon(qt.QStyle.SP_ArrowRight))
self.ui.stageTrialDirButton.connect("clicked(bool)", self.onStageTrialDir)
self.ui.populatePartialVolumeListButton.connect("clicked(bool)", self.onPopulatePartialVolumeList)
self.ui.configGenButton.connect("clicked(bool)", self.onGenerateConfig)
# Default output directory
self.ui.mainOutputSelector.setCurrentPath(
os.path.join(slicer.mrmlScene.GetCacheManager().GetRemoteCacheDirectory(), "AutoscoperM-Pre-Processing")
)
# Make sure parameter node is initialized (needed for module reload)
self.initializeParameterNode()
# Trigger any required UI updates based on the volume node selected by default
self.onCurrentNodeChanged()
def cleanup(self):
"""
Called when the application closes and the module widget is destroyed.
"""
self.removeObservers()
def enter(self):
"""
Called each time the user opens this module.
"""
# Make sure parameter node exists and observed
self.initializeParameterNode()
def exit(self):
"""
Called each time the user opens a different module.
"""
# Do not react to parameter node changes (GUI wlil be updated when the user enters into the module)
self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
def onSceneStartClose(self, _caller, _event):
"""
Called just before the scene is closed.
"""
# Parameter node will be reset, do not use it anymore
self.setParameterNode(None)
def onSceneEndClose(self, _caller, _event):
"""
Called just after the scene is closed.
"""
# If this module is shown while the scene is closed then recreate a new parameter node immediately
if self.parent.isEntered:
self.initializeParameterNode()
def initializeParameterNode(self):
"""
Ensure parameter node exists and observed.
"""
# Parameter node stores all user choices in parameter values, node selections, etc.
# so that when the scene is saved and reloaded, these settings are restored.
self.setParameterNode(self.logic.getParameterNode())
# Select default input nodes if nothing is selected yet to save a few clicks for the user
# NA
def setParameterNode(self, inputParameterNode):
"""
Set and observe parameter node.
Observation is needed because when the parameter node is changed then the GUI must be updated immediately.
"""
if inputParameterNode:
self.logic.setDefaultParameters(inputParameterNode)
# Unobserve previously selected parameter node and add an observer to the newly selected.
# Changes of parameter node are observed so that whenever parameters are changed by a script or any other module
# those are reflected immediately in the GUI.
if self._parameterNode is not None and self.hasObserver(
self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode
):
self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
self._parameterNode = inputParameterNode
if self._parameterNode is not None:
self.addObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
# Initial GUI update
self.updateGUIFromParameterNode()
def updateGUIFromParameterNode(self, _caller=None, _event=None):
"""
This method is called whenever parameter node is changed.
The module GUI is updated to show the current state of the parameter node.
"""
if self._parameterNode is None or self._updatingGUIFromParameterNode:
return
# Make sure GUI changes do not call updateParameterNodeFromGUI (it could cause infinite loop)
self._updatingGUIFromParameterNode = True
# Update node selectors and sliders
# NA
# Update buttons states and tooltips
# NA
# All the GUI updates are done
self._updatingGUIFromParameterNode = False
def updateParameterNodeFromGUI(self, _caller=None, _event=None):
"""
This method is called when the user makes any change in the GUI.
The changes are saved into the parameter node (so that they are restored when the scene is saved and loaded).
"""
if self._parameterNode is None or self._updatingGUIFromParameterNode:
return
wasModified = self._parameterNode.StartModify() # Modify all properties in a single batch
# NA
self._parameterNode.EndModify(wasModified)
@property
def autoscoperExecutableToLaunchBackend(self):
return self.ui.autoscoperRenderingBackendComboBox.currentText
@autoscoperExecutableToLaunchBackend.setter
def autoscoperExecutableToLaunchBackend(self, value):
self.ui.autoscoperRenderingBackendComboBox.currentText = value
@staticmethod
def autoscoperExecutableName(backend=None):
"""Returns the Autoscoper executable name to lookup given a backend name."""
suffix = f"-{backend}" if backend else ""
return f"autoscoper{suffix}"
def startAutoscoper(self):
"""Start a new process using the Autoscoper executable corresponding to the selected backend.
This call waits that the process has been started and returns.
"""
try:
executablePath = self.autoscoperExecutables[self.autoscoperExecutableToLaunchBackend]
except KeyError:
logging.error("Autoscoper executable not found")
return
self.logic.startAutoscoper(executablePath)
def onLoadConfig(self):
self.loadConfig(self.ui.configSelector.currentPath)
def loadConfig(self, configPath):
if not configPath.endswith(".cfg"):
logging.error(f"Failed to load config file: {configPath} is expected to have the .cfg extension")
return False
if not os.path.exists(configPath):
logging.error(f"Failed to load config file: {configPath} not found")
return False
# Ensure that autoscoper is running
if self.logic.AutoscoperProcess.state() != qt.QProcess.Running and slicer.util.confirmYesNoDisplay(
"Autoscoper is not running. Do you want to start Autoscoper?"
):
self.startAutoscoper()
if self.logic.AutoscoperProcess.state() != qt.QProcess.Running:
logging.error("failed to load the Sample Data: Autoscoper is not running. ")
return False
self.logic.AutoscoperSocket.loadTrial(configPath)
return True
def onSampleDataButtonClicked(self, dataType):
# Ensure that the sample data is installed
slicerCacheDir = slicer.mrmlScene.GetCacheManager().GetRemoteCacheDirectory()
sampleDataDir = os.path.join(slicerCacheDir, dataType)
if not os.path.exists(sampleDataDir):
logging.error(
f"Sample data not found. Please install the {dataType} sample data set using the Sample Data module."
)
return
# Load the sample data
configFile = os.path.join(sampleDataDir, sampleDataConfigFile(dataType))
if not os.path.exists(configFile):
logging.error(f"Failed to load config file: {configFile} not found")
return
if not self.loadConfig(configFile):
return
# Load filter settings
numCams = len(glob.glob(os.path.join(sampleDataDir, "Calibration", "*.txt")))
filterSettings = os.path.join(sampleDataDir, "xParameters", "control_settings.vie")
for cam in range(numCams):
self.logic.AutoscoperSocket.loadFilters(cam, filterSettings)
def onCurrentNodeChanged(self):
"""
Updates and UI components that correspond to the selected input volume node
"""
volumeNode = self.ui.volumeSelector.currentNode()
if volumeNode:
with slicer.util.tryWithErrorDisplay("Failed to grab volume node information", waitCursor=True):
vSizeX, vSizeY, vSizeZ = self.logic.GetVolumeSpacing(volumeNode)
self.ui.voxelSizeX.value = vSizeX
self.ui.voxelSizeY.value = vSizeY
self.ui.voxelSizeZ.value = vSizeZ
def onGeneratePartialVolumes(self):
"""
This function creates partial volumes for each segment in the segmentation node for the selected volume node.
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results", waitCursor=True):
volumeNode = self.ui.volumeSelector.currentNode()
mainOutputDir = self.ui.mainOutputSelector.currentPath
tiffSubDir = self.ui.tiffSubDir.text
tfmSubDir = self.ui.tfmSubDir.text
trackingSubDir = self.ui.trackingSubDir.text
modelSubDir = self.ui.modelSubDir.text
segmentationNode = self.ui.pv_SegNodeComboBox.currentNode()
Validation.validateInputs(
volumeNode=volumeNode,
segmentationNode=segmentationNode,
mainOutputDir=mainOutputDir,
volumeSubDir=tiffSubDir,
transformSubDir=tfmSubDir,
trackingSubDir=trackingSubDir,
modelSubDir=modelSubDir,
)
self.logic.createPathsIfNotExists(
mainOutputDir,
os.path.join(mainOutputDir, tiffSubDir),
os.path.join(mainOutputDir, tfmSubDir),
os.path.join(mainOutputDir, trackingSubDir),
os.path.join(mainOutputDir, modelSubDir),
)
self.ui.progressBar.setValue(0)
self.ui.progressBar.setMaximum(100)
self.logic.saveSubVolumesFromSegmentation(
volumeNode,
segmentationNode,
mainOutputDir,
volumeSubDir=tiffSubDir,
transformSubDir=tfmSubDir,
trackingSubDir=trackingSubDir,
modelSubDir=modelSubDir,
progressCallback=self.updateProgressBar,
)
# Load TIFFs and Transforms back for visualization
self.onLoadPV()
# onLoadPV has a call to the "success" display, remove the one here so the user doesn't get two.
def onGenerateConfig(self):
"""
Generates a complete config file (including all partial volumes, radiographs,
and camera calibration files) for Autoscoper.
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results", waitCursor=True):
volumeNode = self.ui.volumeSelector.currentNode()
mainOutputDir = self.ui.mainOutputSelector.currentPath
configFileName = self.ui.configFileName.text
configPath = os.path.join(mainOutputDir, f"{configFileName}.cfg")
tiffSubDir = self.ui.tiffSubDir.text
radiographSubDir = self.ui.radiographSubDir.text
calibrationSubDir = self.ui.cameraSubDir.text
trialList = self.ui.trialList
partialVolumeList = self.ui.partialVolumeList
camCalList = self.ui.camCalList
# Validate the inputs
Validation.validateInputs(
volumeNode=volumeNode,
mainOutputDir=mainOutputDir,
configFileName=configFileName,
tiffSubDir=tiffSubDir,
radiographSubDir=radiographSubDir,
calibrationSubDir=calibrationSubDir,
trialList=trialList,
partialVolumeList=partialVolumeList,
camCalList=camCalList,
)
Validation.validatePaths(
mainOutputDir=mainOutputDir,
tiffDir=os.path.join(mainOutputDir, tiffSubDir),
radiographSubDir=os.path.join(mainOutputDir, radiographSubDir),
calibDir=os.path.join(mainOutputDir, calibrationSubDir),
)
def get_staged_items(listWidget):
staged_items = []
for row in range(listWidget.count):
item = listWidget.item(row)
widget = listWidget.itemWidget(item)
# try to find the label of this item
label = widget.findChild(qt.QLabel) if widget else None
if not label:
raise ValueError(f"Could not extract item label from list at index {row}")
staged_items.append(label.text)
return staged_items
# extract filenames from UI lists, and use them to construct the paths relative to mainOutputDir.
# NOTE: We rely here on the order of the files as constructed by the user in the UI. The order of items
# in the staged camera files list and the radiograph root dirs list are expected to match.
camCalFiles = [os.path.join(calibrationSubDir, item) for item in get_staged_items(camCalList)]
trialDirs = [os.path.join(radiographSubDir, item) for item in get_staged_items(trialList)]
if len(camCalFiles) == 0:
raise ValueError(
"Invalid inputs: must select at least one camera calibration file, but zero were provided."
)
if len(trialDirs) == 0:
raise ValueError(
"Invalid inputs: must select at least one radiograph subdirectory, but zero were provided."
)
if len(camCalFiles) != len(trialDirs):
raise ValueError(
"Invalid inputs: number of selected trial directories must match the number "
f"of camera calibration files: {len(camCalFiles)} != {len(trialDirs)}"
)
def get_checked_items(listWidget):
checked_items = []
for idx in range(listWidget.count):
item = listWidget.item(idx)
if item.checkState() == qt.Qt.Checked:
checked_items.append(item.text())
return checked_items
partialVolumeFiles = [os.path.join(tiffSubDir, item) for item in get_checked_items(partialVolumeList)]
if len(partialVolumeFiles) == 0:
raise ValueError("Invalid inputs: at least one volume file must be selected!")
optimizationOffsets = [
self.ui.optOffX.value,
self.ui.optOffY.value,
self.ui.optOffZ.value,
self.ui.optOffYaw.value,
self.ui.optOffPitch.value,
self.ui.optOffRoll.value,
]
volumeFlip = [
int(self.ui.flipX.isChecked()),
int(self.ui.flipY.isChecked()),
int(self.ui.flipZ.isChecked()),
]
renderResolution = [
self.ui.configRes_width.value,
self.ui.configRes_height.value,
]
voxel_spacing = [
self.ui.voxelSizeX.value,
self.ui.voxelSizeY.value,
self.ui.voxelSizeZ.value,
]
# Validate the extracted parameters
Validation.validateInputs(
*trialDirs,
*partialVolumeFiles,
*camCalFiles,
*optimizationOffsets,
*volumeFlip,
*renderResolution,
*voxel_spacing,
)
# generate the config file
IO.generateConfigFile(
outputConfigPath=configPath,
trialName=configFileName,
camCalFiles=camCalFiles,
camRootDirs=trialDirs,
volumeFiles=partialVolumeFiles,
volumeFlip=volumeFlip,
voxelSize=voxel_spacing,
renderResolution=renderResolution,
optimizationOffsets=optimizationOffsets,
)
# Set the path to this newly created config file in the "Config File" field in the Autoscoper Control UI
self.ui.configSelector.setCurrentPath(configPath)
slicer.util.messageBox("Success!")
def onImportModels(self):
"""
Imports Models from a directory- converts to Segmentation Nodes
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results", waitCursor=True):
self.ui.progressBar.setValue(0)
self.ui.progressBar.setMaximum(100)
volumeNode = self.ui.volumeSelector.currentNode()
Validation.validateInputs(volumeNode=volumeNode)
if self.ui.segSTL_loadRadioButton.isChecked():
segmentationFileDir = self.ui.segSTL_modelsDir.currentPath
Validation.validatePaths(segmentationFileDir=segmentationFileDir)
segmentationFiles = glob.glob(os.path.join(segmentationFileDir, "*.*"))
segmentationNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLSegmentationNode")
segmentationNode.CreateDefaultDisplayNodes()
for idx, file in enumerate(segmentationFiles):
returnedNode = IO.loadSegmentation(segmentationNode, file)
if returnedNode:
# get the segment from the returned node and add it to the segmentation node
segment = returnedNode.GetSegmentation().GetNthSegment(0)
segmentationNode.GetSegmentation().AddSegment(segment)
slicer.mrmlScene.RemoveNode(returnedNode)
self.ui.progressBar.setValue((idx + 1) / len(segmentationFiles) * 100)
else: # Should never happen but just in case
raise ValueError("Please select the 'Segmentation From Model' option in order to import models")
return
slicer.util.messageBox("Success!")
def onSegmentation(self):
"""
Launches the automatic segmentation process
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results", waitCursor=True):
self.ui.progressBar.setValue(0)
self.ui.progressBar.setMaximum(100)
volumeNode = self.ui.volumeSelector.currentNode()
Validation.validateInputs(volumeNode=volumeNode)
if self.ui.segGen_autoRadioButton.isChecked():
currentVolumeNode = volumeNode
numFrames = 1
if self.logic.IsSequenceVolume(volumeNode):
numFrames = volumeNode.GetNumberOfDataNodes()
currentVolumeNode = self.logic.getItemInSequence(volumeNode, 0)
segmentationSequenceNode = self.logic.createSequenceNodeInBrowser(
nodename=f"{volumeNode.GetName()}_Segmentation", sequenceNode=volumeNode
)
for i in range(numFrames):
self.logic.cleanFilename(currentVolumeNode.GetName(), i)
segmentationNode = SubVolumeExtraction.automaticSegmentation(
currentVolumeNode,
self.ui.segGen_thresholdSpinBox.value,
self.ui.segGen_marginSizeSpin.value,
progressCallback=self.updateProgressBar,
)
progress = (i + 1) / numFrames * 100
self.ui.progressBar.setValue(progress)
if self.logic.IsSequenceVolume(volumeNode):
segmentationSequenceNode.SetDataNodeAtValue(segmentationNode, str(i))
slicer.mrmlScene.RemoveNode(segmentationNode)
currentVolumeNode = self.logic.getNextItemInSequence(volumeNode)
else: # Should never happen but just in case
raise ValueError("Please select the 'Automatic Segmentation' option in order to generate segmentations")
return
slicer.util.messageBox("Success!")
def updateProgressBar(self, value):
"""
Progress bar callback function for use with AutoscoperMLib functions
"""
self.ui.progressBar.setValue(value)
slicer.app.processEvents()
def onLoadPV(self):
with slicer.util.tryWithErrorDisplay("Failed to compute results.", waitCursor=True):
mainOutputDir = self.ui.mainOutputSelector.currentPath
volumeSubDir = self.ui.tiffSubDir.text
transformSubDir = self.ui.tfmSubDir.text
# Check number of generated scale and translation transform files matches the number of volumes
vols = glob.glob(os.path.join(mainOutputDir, volumeSubDir, "*.tif"))
tfms_t = glob.glob(os.path.join(mainOutputDir, transformSubDir, "*_t.tfm"))
tfms_scale = glob.glob(os.path.join(mainOutputDir, transformSubDir, "*_scale.tfm"))
if len(vols) == 0:
raise ValueError("No data found")
return
if len(vols) != len(tfms_t) != len(tfms_scale):
raise ValueError(
"Volume TFM mismatch, missing scale or translation tfm files! "
f"vols: ({len(vols)}) != tfms_t: ({len(tfms_t)}) != tfms_scale: ({len(tfms_scale)})"
)
return
# get the IJK to RAS direction matrix from original input volume
parentVolume = self.ui.volumeSelector.currentNode()
parentIJKToRAS = vtk.vtkMatrix4x4()
parentVolume.GetIJKToRASDirectionMatrix(parentIJKToRAS)
# check 3 transform files have been generated (translation, scale and combined)
# and load only the combined scale and translation transform for each generated partial volume
for i in range(len(vols)):
nodeName = os.path.splitext(os.path.basename(vols[i]))[0]
volumeNode = slicer.util.loadVolume(vols[i])
# ensure we maintain the original RAS/LPS directions from the parent volume
volumeNode.SetIJKToRASDirectionMatrix(parentIJKToRAS)
translationTransformFileName = os.path.join(mainOutputDir, transformSubDir, f"{nodeName}_t.tfm")
scaleTranformFileName = os.path.join(mainOutputDir, transformSubDir, f"{nodeName}_scale.tfm")
transformFileName = os.path.join(mainOutputDir, transformSubDir, f"{nodeName}.tfm")
if not os.path.exists(translationTransformFileName):
raise ValueError(
f"Failed to load partial volume {nodeName}: "
"Corresponding translation transform file {translationTransformFileName} not found"
)
if not os.path.exists(scaleTranformFileName):
raise ValueError(
f"Failed to load partial volume {nodeName}: "
"Corresponding scaling transform file {scaleTranformFileName} not found"
)
if not os.path.exists(transformFileName):
raise ValueError(
f"Failed to load partial volume {nodeName}: "
"Corresponding combined transform file {transformFileName} not found"
)
transformNode = slicer.util.loadTransform(transformFileName)
volumeNode.SetAndObserveTransformNodeID(transformNode.GetID())
self.logic.showVolumeIn3D(volumeNode)
slicer.util.messageBox("Success!")
def onPopulateTrialNameList(self):
"""
Populates trial name UI list using files from the selected radiograph directory
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results.", waitCursor=True):
self.populateListFromOutputSubDir(self.ui.trialCandidateList, self.ui.radiographSubDir.text, itemType="dir")
def onPopulatePartialVolumeList(self):
"""
Populates partial volumes UI list using files from the selected PV directory
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results.", waitCursor=True):
self.populateListFromOutputSubDir(self.ui.partialVolumeList, self.ui.tiffSubDir.text)
def onPopulateCameraCalList(self):
"""
Populates camera calibration UI list using files from the selected camera directory
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results.", waitCursor=True):
self.populateListFromOutputSubDir(self.ui.camCalCandidateList, self.ui.cameraSubDir.text)
def populateListFromOutputSubDir(self, listWidget, fileSubDir, itemType="file"):
"""
Populates input UI list with files/directories that exist in the given input directory
"""
listWidget.clear()
mainOutputDir = self.ui.mainOutputSelector.currentPath
Validation.validateInputs(
listWidget=listWidget,
mainOutputDir=mainOutputDir,
fileSubDir=fileSubDir,
)
fileDir = os.path.join(mainOutputDir, fileSubDir)
Validation.validatePaths(fileDir=fileDir)
if itemType == "file":
listFiles = [f.name for f in os.scandir(fileDir) if os.path.isfile(f)]
elif itemType == "dir":
listFiles = [f.name for f in os.scandir(fileDir) if os.path.isdir(f)]
else:
raise ValueError(
"Invalid input: can either search for type 'file' or 'dir' "
f"in specified path, but given itemType='{itemType}'"
)
return
for file in sorted(listFiles):
fileItem = qt.QListWidgetItem(file)
fileItem.setFlags(fileItem.flags() & ~qt.Qt.ItemIsSelectable) # Remove the selectable flag
fileItem.setCheckState(qt.Qt.Unchecked)
listWidget.addItem(fileItem)
def onStageCameraCalFile(self):
"""
Adds selected items from the camera calibration list to the staged files list
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results.", waitCursor=True):
self.stageSelectedFiles(self.ui.camCalCandidateList, self.ui.camCalList)
def onStageTrialDir(self):
"""
Adds selected items from the radiograph subdirectories list to the staged subdirs list
"""
with slicer.util.tryWithErrorDisplay("Failed to compute results.", waitCursor=True):
self.stageSelectedFiles(self.ui.trialCandidateList, self.ui.trialList)
def stageSelectedFiles(self, candidateListWidget, listWidget):
"""
Stages chosen files into listWidget based on the selected items
in candidateListWidget which contains all candidate file names
"""
# gether checked items from the input candidate list
checked_items = []
for idx in range(candidateListWidget.count):
item = candidateListWidget.item(idx)
if item.checkState() == qt.Qt.Checked:
checked_items.append(item.text())
item.setCheckState(qt.Qt.Unchecked)
if len(checked_items) == 0:
raise ValueError("No items were selected.")
def stagedItemExists(itemText):
# iterate over the list items and see if item with the given label already exists
for row in range(listWidget.count):
item = listWidget.item(row)
widget = listWidget.itemWidget(item)
if widget:
# extract label to compare the text in the item
label = widget.findChild(qt.QLabel)
if label and label.text == itemText:
return True
return False
# stage all selected items if they're not already in the target list
for file in checked_items:
if not stagedItemExists(file):
# create item widget with text and a delete button
itemBaseWidget = qt.QWidget()
itemLayout = qt.QHBoxLayout()
itemLabel = qt.QLabel(file)
itemDeleteButton = qt.QPushButton("Delete")
# set styling attributes to make it look nice in the UI
itemLayout.setContentsMargins(3, 1, 3, 1)
itemLayout.setSpacing(3)
itemDeleteButton.setSizePolicy(qt.QSizePolicy(qt.QSizePolicy.Minimum, qt.QSizePolicy.Fixed))
itemLayout.addWidget(itemLabel)
# add spacing so that the delete button is always aligned to the right
itemLayout.addItem(qt.QSpacerItem(0, 0, qt.QSizePolicy.Expanding, qt.QSizePolicy.Minimum))
itemLayout.addWidget(itemDeleteButton)
itemBaseWidget.setLayout(itemLayout)
itemWidget = qt.QListWidgetItem(listWidget)
itemWidget.setFlags(itemWidget.flags() & ~qt.Qt.ItemIsSelectable)
# finally, add the composite widget as an item to the list
listWidget.setItemWidget(itemWidget, itemBaseWidget)
# add delete functionality to the button
itemDeleteButton.clicked.connect(lambda _, item=itemWidget: listWidget.takeItem(listWidget.row(item)))
else:
logging.info(f"Skipped adding the item '{file}' as it already exists in the target list.")
#
# AutoscoperMLogic
#
class AutoscoperMLogic(ScriptedLoadableModuleLogic):
"""This class should implement all the actual
computation done by your module. The interface
should be such that other python code can import
this class and make use of the functionality without
requiring an instance of the Widget.
Uses ScriptedLoadableModuleLogic base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self):
"""
Called when the logic class is instantiated. Can be used for initializing member variables.
"""
ScriptedLoadableModuleLogic.__init__(self)
self.AutoscoperProcess = qt.QProcess()
self.AutoscoperProcess.setProcessChannelMode(qt.QProcess.ForwardedChannels)
self.AutoscoperSocket = None
@staticmethod
def IsSequenceVolume(node: Union[slicer.vtkMRMLNode, None]) -> bool:
return isinstance(node, slicer.vtkMRMLSequenceNode)
def setDefaultParameters(self, parameterNode):
"""
Initialize parameter node with default settings.
"""
pass
def connectToAutoscoper(self):
"""Connect to a running instance of Autoscoper."""
if self.AutoscoperProcess.state() != qt.QProcess.Running:
logging.error("failed to connect to Autoscoper: The process is not running")
return
try:
from PyAutoscoper.connect import AutoscoperConnection
except ImportError:
slicer.util.pip_install("PyAutoscoper~=2.0.0")
from PyAutoscoper.connect import AutoscoperConnection
self.AutoscoperSocket = AutoscoperConnection()
logging.info("connection to Autoscoper is established")
def disconnectFromAutoscoper(self):
"""Disconnect from a running instance of Autoscoper."""
if self.AutoscoperSocket is None:
logging.warning("connection to Autoscoper is not established")
return
self.AutoscoperSocket.closeConnection()
time.sleep(0.5)
self.AutoscoperSocket = None
logging.info("Autoscoper is disconnected from 3DSlicer")
def startAutoscoper(self, executablePath):
"""Start Autoscoper executable in a new process
This call waits the process has been started and returns.
"""
if not os.path.exists(executablePath):
logging.error(f"Specified executable {executablePath} does not exist")
return
if self.AutoscoperProcess.state() in [qt.QProcess.Starting, qt.QProcess.Running]:
logging.error("Autoscoper executable already started")
return
@contextlib.contextmanager
def changeCurrentDir(directory):
currentDirectory = os.getcwd()
try:
os.chdir(directory)
yield
finally:
os.chdir(currentDirectory)
executableDirectory = os.path.dirname(executablePath)
with changeCurrentDir(executableDirectory):
logging.info(f"Starting Autoscoper {executablePath}")
self.AutoscoperProcess.setProgram(executablePath)
self.AutoscoperProcess.start()
self.AutoscoperProcess.waitForStarted()
slicer.app.processEvents()
time.sleep(4) # wait for autoscoper to boot up before connecting
# Since calling "time.sleep()" prevents Slicer application from being
# notified when the QProcess state changes (e.g Autoscoper is closed while
# Slicer as asleep waiting), we are calling waitForFinished() explicitly
# to ensure that the QProcess state is up-to-date.
self.AutoscoperProcess.waitForFinished(1)
self.connectToAutoscoper()
def stopAutoscoper(self):
"""Stop Autoscoper process"""
if self.AutoscoperProcess.state() == qt.QProcess.NotRunning:
logging.error("Autoscoper executable is not running")
return