Guest User

Untitled

a guest
Sep 16th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.35 KB | None | 0 0
  1. Why does my GUI go unresponsive even though I'm outsourcing to a worker thread?
  2. for i in range(0, np.shape(dataStack)[2]):
  3.  
  4. print('Saving slice ' + str(i + 1))
  5.  
  6. #Save tumor stack
  7. im1 = Image.fromarray(tumorStack[:,:,i]*255)
  8. im1.save(saveLocationStr + 'Slice' + str(i+1) + '.tif')
  9.  
  10. #Set up correct number of subplots for review plot.
  11. if T0 is not None:
  12. plt.subplot(141)
  13. else:
  14. plt.subplot(131)
  15.  
  16. #Plot current brain slice in 1st position
  17. plt.imshow(dataStack[:,:,i], cmap=mpl.cm.bone)
  18. plt.axis('off')
  19.  
  20. plt.title(patient + 'n' + date + 'n' + 'Slice ' + str(i+1) + ' of ' + str(int(np.shape(dataStack)[2])))
  21.  
  22. #Select correct next subplot
  23. if T0 is not None:
  24. plt.subplot(142)
  25. else:
  26. plt.subplot(132)
  27.  
  28. #Get a masked copy of the tumorStack
  29. tempTumorStack = copy.deepcopy(tumorStack[:,:,i])
  30. tempTumorStack = np.ma.masked_where(tempTumorStack == 0, tempTumorStack)
  31.  
  32. #Plot masked tumor stack over brain data
  33. plt.imshow(dataStack[:,:,i], cmap=mpl.cm.bone)
  34. plt.imshow(tempTumorStack, cmap=mpl.cm.jet_r, interpolation='nearest')
  35. plt.axis('off')
  36.  
  37. plt.title(modality + ' Region')
  38.  
  39. #Get the auto-zoomed region and plot it
  40. (x, y) = tumorStack[:,:,i].nonzero()
  41. if( int(np.shape(x)[0]) == 0 or int(np.shape(y)[0]) == 0):
  42. if T0 is not None:
  43. plt.subplot(143)
  44. plt.imshow(T0[:,:,i], cmap=mpl.cm.bone)
  45. plt.axis('off')
  46.  
  47. plt.title('T0')
  48.  
  49. #Plot autozoomed with perimiter over brain data
  50. plt.subplot(144)
  51. plt.imshow(np.zeros(np.shape(dataStack[:,:,i])), cmap=mpl.cm.bone)
  52.  
  53. plt.title('Perimiter of n' + modality + ' + T0 for SA')
  54.  
  55. plt.axis('off')
  56.  
  57. else:
  58. plt.subplot(133)
  59. plt.imshow(np.zeros(np.shape(dataStack[:,:,i])), cmap=mpl.cm.bone)
  60.  
  61. plt.title('Perimiter of n' + modality + ' for SA')
  62.  
  63. plt.axis('off')
  64.  
  65. else:
  66. minX = np.min(x)
  67. minY = np.min(y)
  68. maxX = np.max(x)
  69. maxY = np.max(y)
  70.  
  71. zoomedXmin = minX - (minX * .10)
  72. zoomedXmax = (maxX * .10) + maxX
  73. zoomedYmin = minY - (minY * .10)
  74. zoomedYmax = (maxY * .10) + maxY
  75.  
  76. widthOf = zoomedXmax - zoomedXmin
  77. heigthOf = zoomedYmax - zoomedYmin
  78.  
  79. #Get perimiter of tumor for autozoomed region
  80. #Can do n=8 if we want
  81. #tempTumorStack = bwperim(tempTumorStack,n=8)
  82. tempTumorStack = mahotas.labeled.borders(tempTumorStack)
  83. tempTumorStack = np.where(tempTumorStack == np.max(tempTumorStack), 1, np.nan)
  84.  
  85. #Plot T0 then auto-zoomed if user wanted T0
  86. if T0 is not None:
  87. plt.subplot(143)
  88. plt.imshow(T0[:,:,i], cmap=mpl.cm.bone)
  89. plt.axis('off')
  90.  
  91. plt.title('T0')
  92.  
  93. #Plot autozoomed with perimiter over brain data
  94. plt.subplot(144)
  95. plt.imshow(dataStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax), i ], cmap=mpl.cm.bone)
  96. plt.imshow(tempTumorStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax) ], cmap=mpl.cm.jet_r)
  97. #plt.xlim(minX, maxX-minX)
  98. #plt.ylim(minY, maxY-minY)
  99.  
  100. plt.title('Perimiter of n' + modality + ' + T0 for SA')
  101.  
  102. plt.axis('off')
  103.  
  104. #Just plot autozoomed
  105. else:
  106. plt.subplot(133)
  107. plt.imshow(dataStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax), i ], cmap=mpl.cm.bone)
  108. plt.imshow(tempTumorStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax) ], cmap=mpl.cm.jet_r)
  109.  
  110. plt.title('Perimiter of n' + modality + ' for SA')
  111.  
  112. plt.axis('off')
  113.  
  114. #Finish setting up plot to specs, render, and save it
  115. plt.subplots_adjust(wspace=.5)
  116. plt.axis('off')
  117. plt.tick_params(bottom='off', top='off', left='off', right='off')
  118. plt.draw()
  119. plt.savefig(saveLocationStr + 'MRI_Comparison\Slice' + str(i+1) + '.png', dpi=200)
  120.  
  121. # create instance of saveImageStackWorker(QThread) thread class
  122. self.saveThread = brain_io.saveImageStackWorker()
  123. self.saveThread.populate(self.tumorBrain.pixData, self.tumorBrain.tumor, saveLocationStr, self.measurer, self.tumorBrain.patient, dateForPlots, imageModality, T0pass)
  124.  
  125. class saveImageStackWorker(QThread):
  126. """
  127.  
  128. """
  129.  
  130. def __init__(self, parent=None):
  131.  
  132. QThread.__init__(self, parent)
  133.  
  134. def __del__(self):
  135.  
  136. self.wait()
  137.  
  138. def populate(self, dataStack, tumorStack, saveLocationStr, measurer, patient, date, modality, T0):
  139. self.dataStack = dataStack
  140. self.tumorStack = tumorStack
  141. self.saveLocationStr = saveLocationStr
  142. self.measurer = measurer
  143. self.patient = patient
  144. self.date = date
  145. self.modality = modality
  146. self.T0 = T0
  147.  
  148. self.start()
  149.  
  150. def run(self):
  151. self.saveImageStack(self.dataStack, self.tumorStack, self.saveLocationStr, self.measurer, self.patient, self.date, self.modality, self.T0)
  152.  
  153. def saveImageStack(self, dataStack, tumorStack, saveLocationStr, measurer, patient, date, modality, T0): #, dateStr, measurer,, saveLocationStr):
  154. """
  155. Input:
  156. dataStack:
  157. numpy array of the brain image data.
  158. tumorStack:
  159. numpy binary array of tumor data.
  160. modality:
  161. the modality of the image.
  162. T0:
  163. numpy binary array of T0, if you do not
  164. wish to show T0 (i.e. for flair or something)
  165. leave as default None.
  166. Output:
  167. None
  168. Description:
  169. Saves the image stack of tumor and the review plots
  170. to the output directory.
  171. """
  172.  
  173. print('Saving image stack from within worker thread...')
  174.  
  175. font = {'size' : 10}
  176.  
  177. matplotlib.rc('font', **font)
  178.  
  179. np.seterr(all='ignore')
  180. warnings.simplefilter('ignore')
  181.  
  182. for i in range(0, np.shape(dataStack)[2]):
  183.  
  184. print('Saving slice ' + str(i + 1))
  185.  
  186. #Save tumor stack
  187. im1 = Image.fromarray(tumorStack[:,:,i]*255)
  188. im1.save(saveLocationStr + 'Slice' + str(i+1) + '.tif')
  189.  
  190. #Set up correct number of subplots for review plot.
  191. if T0 is not None:
  192. plt.subplot(141)
  193. else:
  194. plt.subplot(131)
  195.  
  196. #Plot current brain slice in 1st position
  197. plt.imshow(dataStack[:,:,i], cmap=mpl.cm.bone)
  198. plt.axis('off')
  199.  
  200. plt.title(patient + 'n' + date + 'n' + 'Slice ' + str(i+1) + ' of ' + str(int(np.shape(dataStack)[2])))
  201.  
  202. #Select correct next subplot
  203. if T0 is not None:
  204. plt.subplot(142)
  205. else:
  206. plt.subplot(132)
  207.  
  208. #Get a masked copy of the tumorStack
  209. tempTumorStack = copy.deepcopy(tumorStack[:,:,i])
  210. tempTumorStack = np.ma.masked_where(tempTumorStack == 0, tempTumorStack)
  211.  
  212. #Plot masked tumor stack over brain data
  213. plt.imshow(dataStack[:,:,i], cmap=mpl.cm.bone)
  214. plt.imshow(tempTumorStack, cmap=mpl.cm.jet_r, interpolation='nearest')
  215. plt.axis('off')
  216.  
  217. plt.title(modality + ' Region')
  218.  
  219. #Get the auto-zoomed region and plot it
  220. (x, y) = tumorStack[:,:,i].nonzero()
  221. if( int(np.shape(x)[0]) == 0 or int(np.shape(y)[0]) == 0):
  222. if T0 is not None:
  223. plt.subplot(143)
  224. plt.imshow(T0[:,:,i], cmap=mpl.cm.bone)
  225. plt.axis('off')
  226.  
  227. plt.title('T0')
  228.  
  229. #Plot autozoomed with perimiter over brain data
  230. plt.subplot(144)
  231. plt.imshow(np.zeros(np.shape(dataStack[:,:,i])), cmap=mpl.cm.bone)
  232.  
  233. plt.title('Perimiter of n' + modality + ' + T0 for SA')
  234.  
  235. plt.axis('off')
  236.  
  237. else:
  238. plt.subplot(133)
  239. plt.imshow(np.zeros(np.shape(dataStack[:,:,i])), cmap=mpl.cm.bone)
  240.  
  241. plt.title('Perimiter of n' + modality + ' for SA')
  242.  
  243. plt.axis('off')
  244.  
  245. else:
  246. minX = np.min(x)
  247. minY = np.min(y)
  248. maxX = np.max(x)
  249. maxY = np.max(y)
  250.  
  251. zoomedXmin = minX - (minX * .10)
  252. zoomedXmax = (maxX * .10) + maxX
  253. zoomedYmin = minY - (minY * .10)
  254. zoomedYmax = (maxY * .10) + maxY
  255.  
  256. widthOf = zoomedXmax - zoomedXmin
  257. heigthOf = zoomedYmax - zoomedYmin
  258.  
  259. #Get perimiter of tumor for autozoomed region
  260. #Can do n=8 if we want
  261. #tempTumorStack = bwperim(tempTumorStack,n=8)
  262. tempTumorStack = mahotas.labeled.borders(tempTumorStack)
  263. tempTumorStack = np.where(tempTumorStack == np.max(tempTumorStack), 1, np.nan)
  264.  
  265. #Plot T0 then auto-zoomed if user wanted T0
  266. if T0 is not None:
  267. plt.subplot(143)
  268. plt.imshow(T0[:,:,i], cmap=mpl.cm.bone)
  269. plt.axis('off')
  270.  
  271. plt.title('T0')
  272.  
  273. #Plot autozoomed with perimiter over brain data
  274. plt.subplot(144)
  275. plt.imshow(dataStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax), i ], cmap=mpl.cm.bone)
  276. plt.imshow(tempTumorStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax) ], cmap=mpl.cm.jet_r)
  277. #plt.xlim(minX, maxX-minX)
  278. #plt.ylim(minY, maxY-minY)
  279.  
  280. plt.title('Perimiter of n' + modality + ' + T0 for SA')
  281.  
  282. plt.axis('off')
  283.  
  284. #Just plot autozoomed
  285. else:
  286. plt.subplot(133)
  287. plt.imshow(dataStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax), i ], cmap=mpl.cm.bone)
  288. plt.imshow(tempTumorStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax) ], cmap=mpl.cm.jet_r)
  289.  
  290. plt.title('Perimiter of n' + modality + ' for SA')
  291.  
  292. plt.axis('off')
  293.  
  294. #Finish setting up plot to specs, render, and save it
  295. plt.subplots_adjust(wspace=.5)
  296. plt.axis('off')
  297. plt.tick_params(bottom='off', top='off', left='off', right='off')
  298. plt.draw()
  299. plt.savefig(saveLocationStr + 'MRI_Comparison\Slice' + str(i+1) + '.png', dpi=200)
  300.  
  301. def uploadAndSave(self):
  302. [db, unused] = initGUI.getDbDataBetter()
  303. self.db = db
  304.  
  305. subtypeID = str(self.dbImage.image_subtype_id.toString())
  306. query = QtSql.QSqlQuery("SELECT subtype_name FROM image_subtypes where "
  307. + "id = " + subtypeID, self.db)
  308. query.next()
  309. imageModality = str(query.value(0).toString())
  310.  
  311. dateForPlots = str(self.dbImage.date_of_image.toString()).replace('T',' ')
  312. date = dateForPlots.replace('-','').replace(':','.')
  313.  
  314. basePath = 'S:Lab_KSwansonMRI ProjectTest measurements\' + self.tumorBrain.patient + '\' + self.measurer + '\' + date + '\'
  315. print('Saving images...')
  316. seriesDescription = str(self.dbImage.series_description.toString())
  317. saveLocationStr = brain_io.createOutputFilepath(basePath, seriesDescription, imageModality)
  318. if imageModality.upper().find('T1') < 0:
  319. T0pass = None
  320. else:
  321. T0pass = self.tumorBrain.T0
  322.  
  323.  
  324. operation_time = datetime.datetime.now().isoformat().replace('T',' ')[0:19]
  325.  
  326. # create instance of saveImageStackWorker(QThread) thread class
  327. self.saveThread = brain_io.saveImageStackWorker()
  328. self.saveThread.populate(self.tumorBrain.pixData, self.tumorBrain.tumor, saveLocationStr, self.measurer, self.tumorBrain.patient, dateForPlots, imageModality, T0pass)
  329.  
  330. # brain_io.saveImageStack(self.tumorBrain.pixData, self.tumorBrain.tumor, saveLocationStr, self.measurer, self.tumorBrain.patient, dateForPlots, imageModality, T0pass)
  331. self.tumorBrain.save(saveLocationStr + date + '.dat')
  332.  
  333. [db, unused] = initGUI.getDbDataBetter()
  334. query = QtSql.QSqlQuery('SELECT file_path FROM measurements m WHERE m.user_id = ' + self.userIDStr + ' AND m.image_id = '
  335. + str(self.dbImage.id.toString()) + ' AND m.status = "R"', db)
  336.  
  337. #If there was a rejected measurement, this will return True
  338. remeasure = query.next()
  339.  
  340. print('Computing volume, surface area, etc...')
  341. T1 = algorithms.vtk_stats(self.tumorBrain.tumor,
  342. spacing=(self.tumorBrain.xSpacing,
  343. self.tumorBrain.ySpacing,
  344. np.mean(self.tumorBrain.SliceThickness)))
  345.  
  346. T0 = algorithms.vtk_stats(self.tumorBrain.T0,
  347. spacing=(self.tumorBrain.xSpacing,
  348. self.tumorBrain.ySpacing,
  349. np.mean(self.tumorBrain.SliceThickness)))
  350.  
  351.  
  352. mass = tvtk.MassProperties(input=T1.output)
  353. T0mass = tvtk.MassProperties(input=T0.output)
  354. #mySA = algorithms.calculateSurfaceArea(self.tumorBrain.tumor,
  355. # self.tumorBrain.xSpacing,
  356. # self.tumorBrain.ySpacing,
  357. # self.tumorBrain.SliceThickness)
  358.  
  359. #mySAT0 = algorithms.calculateSurfaceArea(self.tumorBrain.T0,
  360. # self.tumorBrain.xSpacing,
  361. # self.tumorBrain.ySpacing,
  362. # self.tumorBrain.SliceThickness)
  363. #print('mysa = ' + str(mySA))
  364.  
  365. #area = 0
  366. #for i in range(0, int(self.tumorBrain.tumor.shape[2])):
  367. # tumor_filt = self.tumorBrain.tumor[:,:,i]
  368. # currThreshold = self.thresholdList[i]
  369. # tumor_filt = np.where(tumor_filt > currThreshold, 1, 0)
  370. # area = area + np.sum(np.sum(tumor_filt))
  371.  
  372. #myVolumeT1 = np.sum(self.tumorBrain.xSpacing**2 * area * self.tumorBrain.SliceThickness)
  373. myVolumeT1 = mass.volume
  374.  
  375. #T0sum = np.sum(np.sum(np.sum(self.tumorBrain.T0)))
  376. #myVolumeT0 = np.sum(self.tumorBrain.xSpacing**2 * T0sum * self.tumorBrain.SliceThickness)
  377. myVolumeT0 = T0mass.volume
  378.  
  379. myVolume_T0_T1 = myVolumeT1 + myVolumeT0
  380.  
  381. T0_radius = ((3.0*(myVolumeT0))/(4.0*math.pi))**(1.0/3.0)
  382. T0_T1_radius = ((3.0*(myVolume_T0_T1))/(4.0*math.pi))**(1.0/3.0)
  383.  
  384. #print('volume vtk = ' + str(mass.volume))
  385. #print('my volume = ' + str(myVolume_T0_T1))
  386. #print('my radius = ' + str(T0_T1_radius))
  387.  
  388. if mass.volume + T0mass.volume == 0 or mass.surface_area == 0:
  389. circularity = 0
  390. else:
  391. circularity = ((math.pi)**(1.0/3.0))*((6.0*(myVolume_T0_T1))**(2.0/3.0) / mass.surface_area)
  392.  
  393. print('SA = ' + str(mass.surface_area))
  394. print('T0 SA = ' + str(T0mass.surface_area))
  395. print('Volume = ' + str(myVolume_T0_T1))
  396. print('T0 Volume = ' + str(myVolumeT0))
  397. print('Radius = ' + str(T0_T1_radius))
  398. print('T0 Radius = ' + str(T0_radius))
  399. print('Circularity = ' + str(circularity))
  400.  
  401. # Ask to see rendering
  402. msgBox = QtGui.QMessageBox(QtGui.QMessageBox.Question, QtCore.QString('Render'), QtCore.QString('Show Tumor Rendering?'), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
  403. ret = msgBox.exec_()
  404. if ret == QtGui.QMessageBox.Yes:
  405. algorithms.render_surface(T1, T0)
  406.  
  407. query = QtSql.QSqlQuery('select max(group_id) from ' +
  408. 'measurement_audit_log where measurement_type_id = '
  409. + "'1'", db)
  410.  
  411. query.next()
  412. group_id = str(query.value(0).toInt()[0] + 1)
  413.  
  414. # Check for a measurement assignment.
  415. osUserName = os.environ.get("USERNAME").lower()
  416. query = QtSql.QSqlQuery('SELECT id from users where pathology_user_name = "' + osUserName + '"')
  417. query.next()
  418. user_id = str(query.value(0).toInt()[0])
  419.  
  420. query = QtSql.QSqlQuery('select id from ' +
  421. 'measurement_assignments_audit ' +
  422. 'where image_id = ' + str(self.dbImage.id.toString()) + ' ' +
  423. 'and measurer_id = ' + user_id + ' ' +
  424. 'and status = "P"')
  425. assignment = query.next()
  426. date_of_completion = operation_time[0:10]
  427. if not assignment:
  428. # Create a new assignment
  429. newAssignmentQuery = ('insert into measurement_assignments_audit ' +
  430. '(measurement_assignment_id, assigner_id, measurer_id, image_id, patient_id, date_of_assignment, ' +
  431. 'comments, date_of_completion, priority, measurement_group_id, operation_user_id, operation_code, ' +
  432. 'operation_time, status) values (0, ' + user_id + ', ' + user_id + ', ' + str(self.dbImage.id.toString()) + ', ' +
  433. str(self.dbImage.patient_id.toString()) + ', "' + date_of_completion + '", ' + '"Self-assigned through brainsegment", "' +
  434. date_of_completion + '", 2, ' + group_id + ', ' + user_id + ', "I", "' + operation_time + '", "P")')
  435. query = QtSql.QSqlQuery(newAssignmentQuery)
  436. else:
  437. # Update the assignment
  438. updateAssignmentQuery = ('update measurement_assignments_audit set date_of_completion = "' + date_of_completion + '", ' +
  439. 'measurement_group_id = ' + group_id + ' where id = ' + str(query.value(0).toInt()[0]))
  440. query = QtSql.QSqlQuery(updateAssignmentQuery)
  441.  
  442. brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 1, 1, T0_T1_radius, saveLocationStr + 'MRI_Comparison', operation_time, str(self.dbImage.id.toString()), group_id)
  443. brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 2, 2, myVolume_T0_T1, saveLocationStr + 'MRI_Comparison', operation_time, str(self.dbImage.id.toString()), group_id)
  444. brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 7, 3, mass.surface_area, saveLocationStr + 'MRI_Comparison', operation_time, str(self.dbImage.id.toString()),group_id)
  445. brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 11, 11, circularity, saveLocationStr + 'MRI_Comparison', operation_time, str(self.dbImage.id.toString()),group_id)
  446.  
  447. if T0pass is not None:
  448. query = QtSql.QSqlQuery('SELECT image_file_path from images i where i.id = ' + str(self.dbImage.id.toString()), db)
  449. query.next()
  450. #print('SELECT i.image_file_path from images i where i.id = ' + str(self.dbImage.id.toString()))
  451. image_file_path = str(query.value(0).toString()).replace('\','\\')
  452.  
  453. query = QtSql.QSqlQuery('SELECT id from images i where i.image_file_path = "' + image_file_path + '" and i.image_subtype_id in (14, 15, 20, 21) ', db)
  454. #print('SELECT id from images i where i.image_file_path = "' + image_file_path + '" and i.image_subtype_id in (14, 15, 20, 21) ')
  455. query.next()
  456. T0idStr = str(query.value(0).toString())
  457.  
  458. T0radius = ((3.0*T0mass.volume)/(4.0*math.pi))**(1.0/3.0)
  459.  
  460. brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 1, 1, T0_radius, saveLocationStr + 'MRI_Comparison', operation_time, T0idStr, group_id)
  461. brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 2, 2, myVolumeT0, saveLocationStr + 'MRI_Comparison', operation_time, T0idStr, group_id)
  462. brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 7, 3, T0mass.surface_area, saveLocationStr + 'MRI_Comparison', operation_time, T0idStr, group_id)
Add Comment
Please, Sign In to add comment