/
PlmMismatchError.py
350 lines (293 loc) · 11.6 KB
/
PlmMismatchError.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
import os
import unittest
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
#
# PlmMismatchError
#
class PlmMismatchError(ScriptedLoadableModule):
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "Landmark Mismatch Error"
self.parent.categories = ["Plastimatch.DIR Validation"]
self.parent.dependencies = []
self.parent.contributors = ["Gregory Sharp (MGH)"]
self.parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
"""
self.parent.acknowledgementText = """
This file was originally developed by Greg Sharp, Massachusetts General Hospital, and was partially funded by NIH grant 2-U54-EB005149.
""" # replace with organization, grant and thanks.
class PlmMismatchErrorWidgetLogicIO:
def __init__(self):
self.FixedFiducialsNode = False
self.MovingFiducialsNode = False
self.average = 0
self.variance = 0
self.stdev = 0
self.separation = {}
self.landm_distance = []
def SetAverage(self, x=0):
self.average = x
def SetVariance(self, x=0):
self.variance = x
def SetStdev(self, x=0):
self.stdev = x
def SetSeparation(self):
self.separation = {}
# qPlmMismatchErrorWidget
class PlmMismatchErrorWidget(ScriptedLoadableModuleWidget):
def __init__(self, parent = None):
ScriptedLoadableModuleWidget.__init__(self, parent)
self.logic = PlmMismatchErrorLogic()
self.WLIO = PlmMismatchErrorWidgetLogicIO()
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# Instantiate and connect widgets ...
### Parameters Area
inputCollapsibleButton = ctk.ctkCollapsibleButton()
inputCollapsibleButton.text = "Input"
self.layout.addWidget(inputCollapsibleButton)
# Layout within the dummy collapsible button
inputFormLayout = qt.QFormLayout(inputCollapsibleButton)
# fixed landmarks (mrml input)
self.fixedLandmarks = slicer.qMRMLNodeComboBox()
self.fixedLandmarks.nodeTypes = ["vtkMRMLMarkupsFiducialNode"]
self.fixedLandmarks.selectNodeUponCreation = True
self.fixedLandmarks.addEnabled = False
self.fixedLandmarks.removeEnabled = False
self.fixedLandmarks.noneEnabled = True
self.fixedLandmarks.showHidden = False
self.fixedLandmarks.renameEnabled = True
self.fixedLandmarks.setMRMLScene( slicer.mrmlScene )
self.fixedLandmarks.setToolTip( "Landmarks on fixed image." )
inputFormLayout.addRow("Fixed landmarks: ", self.fixedLandmarks)
# fixed landmarks (directory input)
self.fixedLandmarksDirectory = ctk.ctkDirectoryButton()
self.fixedLandmarksDirectory.directory = qt.QDir.homePath()
inputFormLayout.addRow("", self.fixedLandmarksDirectory)
# moving landmarks (mrml input)
self.movingLandmarks = slicer.qMRMLNodeComboBox()
self.movingLandmarks.nodeTypes = ["vtkMRMLMarkupsFiducialNode"]
self.movingLandmarks.selectNodeUponCreation = True
self.movingLandmarks.addEnabled = False
self.movingLandmarks.removeEnabled = False
self.movingLandmarks.noneEnabled = True
self.movingLandmarks.showHidden = False
self.movingLandmarks.showChildNodeTypes = False
self.movingLandmarks.setMRMLScene( slicer.mrmlScene )
self.movingLandmarks.setToolTip( "Landmarks on moving image." )
inputFormLayout.addRow("Moving landmarks: ", self.movingLandmarks)
self.view = qt.QTableView()
self.view.sortingEnabled = True
self.parent.layout().addWidget(self.view)
# moving landmarks (directory input)
self.movingLandmarksDirectory = ctk.ctkDirectoryButton()
self.movingLandmarksDirectory.directory = qt.QDir.homePath()
inputFormLayout.addRow("", self.movingLandmarksDirectory)
# Apply Button
self.applyButton = qt.QPushButton("Apply")
self.applyButton.toolTip = "Run the algorithm."
self.applyButton.enabled = True
self.layout.addWidget(self.applyButton)
### Output Area
outputCollapsibleButton = ctk.ctkCollapsibleButton()
outputCollapsibleButton.text = "Output statistics"
self.layout.addWidget(outputCollapsibleButton)
# Layout within the dummy collapsible button
outputFormLayout = qt.QFormLayout(outputCollapsibleButton)
# output statistics
buttonLayout = qt.QHBoxLayout()
self.averageError = qt.QLineEdit()
self.averageErrorValue = 1
self.averageError.setToolTip( "Average landmark separation" )
buttonLayout.addWidget(self.averageError)
outputFormLayout.addRow("Average error:", buttonLayout)
buttonLayout = qt.QHBoxLayout()
self.Variance = qt.QLineEdit()
self.VarianceValue = 1
self.Variance.setToolTip( "Variance" )
buttonLayout.addWidget(self.Variance)
outputFormLayout.addRow("Variance:", buttonLayout)
buttonLayout = qt.QHBoxLayout()
self.stDev = qt.QLineEdit()
self.stDevValue = 1
self.stDev.setToolTip( "Standard deviation" )
buttonLayout.addWidget(self.stDev)
outputFormLayout.addRow("Standard deviation:", buttonLayout)
# model and view for stats table
self.view = qt.QTableView()
self.view.sortingEnabled = True
self.parent.layout().addWidget(self.view)
# connections
self.fixedLandmarks.connect("currentNodeChanged(vtkMRMLNode*)", self.onFixedLandmarksSelect)
self.movingLandmarks.connect("currentNodeChanged(vtkMRMLNode*)", self.onMovingLandmarksSelect)
self.applyButton.connect('clicked(bool)', self.onMismatchErrorApply)
# Add vertical spacer
#self.layout.addStretch(1)
def cleanup(self):
pass
def onFixedLandmarksSelect(self):
print "fixed landmarks selected"
self.WLIO.FixedFiducialsNode = self.fixedLandmarks.currentNode()
def onMovingLandmarksSelect(self):
print "moving landmarks selected"
self.WLIO.MovingFiducialsNode = self.movingLandmarks.currentNode()
def onMismatchErrorApply(self):
print "apply button\n"
myWLIO = self.logic.RunMismatchError( self.WLIO )
self.averageError.setText(myWLIO.average)
self.Variance.setText(myWLIO.variance)
self.stDev.setText(myWLIO.stdev)
print "ready to draw table:"
for dist in myWLIO.landm_distance:
print dist
# the table.. - separate into a function?
self.items = []
self.model = qt.QStandardItemModel()
self.view.setModel(self.model)
self.view.verticalHeader().visible = False
row = 0
landmarkcounter = 0
for dist in myWLIO.landm_distance:
# 1st column (row,0)
item = qt.QStandardItem()
landmarkcounter += 1
item.setText(landmarkcounter)
self.model.setItem(row,0,item)
self.items.append(item)
# 2nd column (row,1)
item = qt.QStandardItem()
item.setText(dist)
self.model.setItem(row,1,item)
self.items.append(item)
row += 1
#done!
#self.view.setColumnWidth(0,30)
self.model.setHeaderData(0,1,"Landmark")
self.model.setHeaderData(1,1,"dist, mm")
def populateDistances(self):
if not self.logic:
return
self.items = []
self.model = qt.QStandardItemModel()
self.view.setModel(self.model)
self.view.verticalHeader().visible = False
row = 0
for i in self.logic.landmarkPairs["Landmarks"]:
item = qt.QStandardItem()
item.setData(points[fixed])
#item.setToolTip(colorNode.GetColorName(i))
self.model.setItem(row,0,item)
self.items.append(item)
col = 1
for k in self.logic.keys:
item = qt.QStandardItem()
item.setText(str(self.logic.landmarkPairs[i,k]))
#item.setToolTip(colorNode.GetColorName(i))
self.model.setItem(row,col,item)
self.items.append(item)
col += 1
row += 1
self.view.setColumnWidth(0,30)
self.model.setHeaderData(0,1," ")
col = 1
for k in self.logic.keys:
self.view.setColumnWidth(col,15*len(k))
self.model.setHeaderData(col,1,k)
col += 1
# PlmMismatchErrorLogic
class PlmMismatchErrorLogic(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
"""
def hasImageData(self,volumeNode):
"""This is a dummy logic method that
returns true if the passed in volume
node has valid image data
"""
if not volumeNode:
print('no volume node')
return False
if volumeNode.GetImageData() == None:
print('no image data')
return False
return True
self.keys = ("Separation")
self.landmarkPairs = {}
self.landmarkPairs['Landmarks'] = []
self.landmarkPairs["Landmarks"].append(i)
self.landmarkPairs[i,"Separation"] = reg.GetSeparationString()
def RunMismatchError(self, WLIO):
import os, sys, vtk, math
loadablePath = os.path.join(slicer.modules.plastimatch_slicer_bspline.path,'..'+os.sep+'..'+os.sep+'qt-loadable-modules')
if loadablePath not in sys.path:
sys.path.append(loadablePath)
import vtkSlicerPlastimatchPyModuleLogicPython
reg = vtkSlicerPlastimatchPyModuleLogicPython.vtkSlicerPlastimatchPyModuleLogic()
reg.SetMRMLScene(slicer.mrmlScene)
print "running RunMismatchError"
# Set landmarks from Slicer
print "trying to SetFixed/MovingLandmarks"
fixpoints = vtk.vtkPoints()
movpoints = vtk.vtkPoints()
point = [0,]*3
fixFidNode = WLIO.FixedFiducialsNode # it is a vtkMRMLMarkupsFiducialNode
nfix = fixFidNode.GetNumberOfFiducials()
print( "found %s fiducials in fixed" % str(nfix) )
for n in range(nfix):
fixFidNode.GetNthFiducialPosition(n, point)
fixpoints.InsertNextPoint(point)
#print("fix %s:" % str(point))
movFidNode = WLIO.MovingFiducialsNode # it is a vtkMRMLMarkupsFiducialNode
nmov = movFidNode.GetNumberOfFiducials()
print( "found %s fiducials in moving" % str(nmov) )
for n in range(nmov):
movFidNode.GetNthFiducialPosition(n, point)
movpoints.InsertNextPoint(point)
#print("mov %s:" % str(point))
WidgetLogicIO = PlmMismatchErrorWidgetLogicIO() # this is for output to GUI widget
p1 = [0,]*3
p2 = [0,]*3
counter = 0
d1sum = 0
d2sum = 0
d3sum = 0
for n in range(nfix):
fixpoints.GetPoint(n, p1)
movpoints.GetPoint(n, p2)
d2 = (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + (p1[2]-p2[2])*(p1[2]-p2[2])
d1 = math.sqrt(d2)
d1sum += d1
d2sum += d2
counter += 1
WidgetLogicIO.landm_distance.append(d1)
#print (n, d1, d2, d1sum, d2sum)
average = d1sum/counter
for n in range(nfix):
fixpoints.GetPoint(n, p1)
movpoints.GetPoint(n, p2)
d2 = (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + (p1[2]-p2[2])*(p1[2]-p2[2])
d1 = math.sqrt(d2)
d3 = (d1 - average)*(d1 - average)
d3sum += d3
counter += 1
variance = d3sum/counter
stdev = math.sqrt(variance)
#reg.SetFixedLandmarks( fixpoints)
#reg.SetMovingLandmarks(movpoints)
#print "Done SetFixed/MovingLandmarks"
# Run Mismatch Error
#print "starting RunMismatchError"
#reg.RunMismatchError()
#print "control went past RunMismatchError"
# Done
# return error values to caller
WidgetLogicIO.SetAverage(average)
WidgetLogicIO.SetVariance(variance)
WidgetLogicIO.SetStdev(stdev)
#WidgetLogicIO.SetSeparation(reg.GetSeparationString())
return WidgetLogicIO