-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
executable file
·1493 lines (1226 loc) · 66.5 KB
/
main.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
"""
Beta-2 release for Revision of SR length measurement
v2.1.1-beta-2
update date: 20230716
"""
import sys
import os
import shutil
import PySide6
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QMessageBox, QProgressDialog, QFileDialog, QVBoxLayout, QGridLayout, QRadioButton, QButtonGroup, QLabel, QLineEdit
from PySide6.QtCore import QFile, QIODevice, Slot, Qt, QThread, Signal, QRect
from PySide6.QtUiTools import QUiLoader
from PySide6.QtGui import QIcon
import pyqtgraph as pg
import toolbox
from logics import DiffractionLimitedAnalysis, LiposomeAssayAnalysis, SuperResAnalysis
import pandas as pd
import numpy as np
import imagej
import scyjava
import json
plugins_dir = os.path.join(os.path.dirname(__file__), 'Fiji.app/plugins')
scyjava.config.add_option(f'-Dplugins.dir={plugins_dir}')
pg.setConfigOption('background', 'w')
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.loadUI()
def loadUI(self):
path = os.path.join(os.path.dirname(__file__), "UI_form/MainWindow.ui")
ui_file = QFile(path)
if not ui_file.open(QIODevice.ReadOnly):
print(f"Cannot open {ui_file_name}: {ui_file.errorString()}")
sys.exit(-1)
class UiLoader(QUiLoader): # Enable promotion to custom widgets
def createWidget(self, className, parent=None, name=""):
#if className == "PlotWidget":
# return pg.PlotWidget(parent=parent) # promote to pyqtgraph.PlotWidget
if className == "LogTextEdit":
return toolbox.LogTextEdit(parent=parent) # promote to self defined LogTextEdit(QPlainTextEdit)
return super().createWidget(className, parent, name)
loader = UiLoader()
self.window = loader.load(ui_file, self)
self.path_fiji = os.path.join(os.path.dirname(__file__), 'Fiji.app')
self.IJ = imagej.init(self.path_fiji, headless=False)
# Menu
# File
self.window.actionLoad.triggered.connect(self.loadDataPath)
# Analysis
# DFL
self.window.actionRun_analysis_DFLSP.triggered.connect(self.clickDFLSPRun)
self.window.actionGenerate_reports_DFLSP.triggered.connect(self.clickDFLSPGenerateReports)
self.window.actionRead_tagged_results_DFLSP.triggered.connect(self.clickDFLSPReadTaggedResults)
# Liposome Assay
self.window.actionRun_analysis_LipoAssay.triggered.connect(self.clickLipoAssayRun)
self.window.actionGenerate_report_LipoAssay.triggered.connect(self.clickLipoAssayGenerateReport)
# SR
self.window.actionRun_reconstruction_SR.triggered.connect(self.clickSRRun)
self.window.actionRun_drift_correction_SR.triggered.connect(self.clickSRfidCorr)
self.window.actionRun_clustering_SR.triggered.connect(self.clickSRClustering)
# Tools
# Folder Splitter
self.window.actionFolder_Splitter.triggered.connect(self.clickFolderSplitter)
# Help
self.window.actionComDet.triggered.connect(self.helpComDet)
self.window.actionTrevor.triggered.connect(self.helpTrevor)
self.window.actionProgram_frozen.triggered.connect(self.helpFrozen)
self.window.actionLiposome_Assay.triggered.connect(self.helpLiposomeAssay)
self.window.actionSuper_resolution_Image_Analysis.triggered.connect(self.helpSuperRes)
# DFLSP window widgets
self.window.DFLSP_runButton.clicked.connect(self.clickDFLSPRun)
self.window.DFLSP_tagButton.clicked.connect(self.clickDFLSPTag)
self.window.DFLSP_oaButton.clicked.connect(self.clickDFLSPOA)
# LipoAssay window widgets
self.window.LipoAssay_runButton.clicked.connect(self.clickLipoAssayRun)
# SR window widgets
self.window.SupRes_runReconstructionButton.clicked.connect(self.clickSRRun)
self.window.SupRes_methodSelector.currentIndexChanged.connect(self._methodOptSR)
self.window.SupRes_FidCorrMethodSelector.currentIndexChanged.connect(self._methodOptSRFidCorr)
self.window.SupRes_loadButton.clicked.connect(self.clickLoadSRPreviousAttempts)
self.window.SupRes_previousReconstructionAttemptSelector.currentIndexChanged.connect(self._SRPreviousReconstructionAttemptSelected)
self.window.SupRes_runFidCorrButton.clicked.connect(self.clickSRfidCorr)
self.window.SupRes_previousCorrectionAttemptsSelector.currentIndexChanged.connect(self._SRPreviousCorrectionAttemptSelected)
self.window.SupRes_DBSCANCheck.stateChanged.connect(self._SRClusteringDBSCANSelection)
self.window.SupRes_filteringCheck.stateChanged.connect(self._SRClusteringFilteringSelection)
self.window.SupRes_lengthCalCheck.stateChanged.connect(self._SRLengthCalSelection)
self.window.SupRes_runClusteringButton.clicked.connect(self.clickSRClustering)
ui_file.close()
if not self.window:
print(loader.errorString())
sys.exit(-1)
self.window.show()
sys.exit(app.exec())
def updateLog(self, message):
self.window.main_logBar.insertPlainText(message + '\n')
self.window.main_logBar.verticalScrollBar().setValue(
self.window.main_logBar.verticalScrollBar().maximum()) # auto scroll down to the newest message
def initialiseProgress(self, work, workload):
self.window.progressBar.setMaximum(workload)
self.window.progressBar.setValue(0)
self.window.progressBarLabel.setText(work)
def updateProgress(self, progress):
self.window.progressBar.setValue(progress)
def resetProgress(self):
self.window.progressBarLabel.setText('No work in process.')
self.window.progressBar.reset()
def showMessage(self, msg_type, message):
msgBox = QMessageBox(self.window)
if msg_type == 'c':
msgBox.setIcon(QMessageBox.Critical)
msgBox.setWindowTitle('Critical Error')
elif msg_type == 'w':
msgBox.setIcon(QMessageBox.Warning)
msgBox.setWindowTitle('Warning')
elif msg_type == 'i':
msgBox.setIcon(QMessageBox.Information)
msgBox.setWindowTitle('Information')
msgBox.setText(message)
returnValue = msgBox.exec()
def loadDataPath(self):
data_path = QFileDialog.getExistingDirectory(parent=self.window, caption='Browse path for data.', dir=os.path.dirname(__file__))
self.window.DFLSP_pathEntry.setText(data_path)
self.window.LipoAssay_pathEntry.setText(data_path)
self.window.SupRes_pathEntry.setText(data_path)
#* set all paths
# Diffraction Limited SiMPull Analysis
def clickDFLSPRun(self):
guard = self._checkDFLSPParameters()
if guard == 1:
guard = self._runDFLSPAnalysis()
def clickDFLSPGenerateReports(self):
guard = self._checkDFLSPParameters()
if guard == 1:
if not os.path.isdir(self.project.path_result_main):
self.showMessage('w', 'This dataset has not been analysed. Please run analysis.')
else:
self.updateLog('Data path set to '+ self.data_path)
self._generateDFLSPReports()
def clickDFLSPReadTaggedResults(self):
guard = self._checkDFLSPParameters()
if guard == 1:
if not os.path.isdir(self.project.path_result_main):
self.showMessage('w', 'This dataset has not been analysed. Please run analysis.')
else:
self.updateLog('Data path set to '+ self.data_path)
self._showDFLSPResult()
self.window.DFLSP_tagButton.setEnabled(True)
self.window.DFLSP_oaButton.setEnabled(True)
def _checkDFLSPParameters(self):
# Check if data path exists
data_path = self.window.DFLSP_pathEntry.text()
if os.path.isdir(data_path) == False:
self.showMessage('w', 'Path to folder not found.')
return 0
else:
self.data_path = data_path
# Get the method for analysis
self.method = self.window.DFLSP_methodSelector.currentText()
# Check input: threshold
try:
self.threshold = int(self.window.DFLSP_thresholdEntry.text())
self.window.DFLSP_thresholdEntry.setText(str(self.threshold))
except ValueError:
self.showMessage('c', 'Please input a number for threshold.')
return 0
if self.threshold <= 2 or self.threshold >= 20:
self.updateLog('Threshold set as '+str(self.threshold)+' SD. Suggested range would be 3-20 SD.')
else:
self.updateLog('Threshold set at '+str(self.threshold)+' SD.')
# Check input: estimated size
try:
self.size = int(self.window.DFLSP_sizeEntry.text())
self.window.DFLSP_sizeEntry.setText(str(self.size))
except ValueError:
self.showMessage('c', 'Please input a number for estimated particle size.')
return 0
if self.size >= 15:
self.updateLog('Estimated particle size set as '+str(self.size)+' pixels which is quite high. Pariticles close to each other might be considered as one.')
else:
self.updateLog('Estimated particle size set as '+str(self.size)+' pixels.')
self.parameters = '_' + self.method + '_' + str(self.threshold) + '_' + str(self.size)
self.data_path = self.data_path.replace('_results' + self.parameters, '')
self.window.DFLSP_pathEntry.setText(self.data_path)
self.updateLog('Data path set to '+data_path)
self.project = DiffractionLimitedAnalysis(self.data_path, self.parameters) # Creat DiffractionLimitedAnalysis object
if self.project.error == 1:
return 1
else:
self.showMessage('c', self.project.error)
def _runDFLSPAnalysis(self):
self.initialiseProgress('Locating particles...', len(self.project.fov_paths))
# Create a QThread object
self.PFThread = QThread()
# Create a worker object
self.particleFinder = toolbox.DFLParticleFinder(self.method, self.project, self.size, self.threshold, self.IJ)
# Connect signals and slots
self.PFThread.started.connect(self.particleFinder.run)
self.particleFinder.finished.connect(self.PFThread.quit)
self.particleFinder.finished.connect(self.particleFinder.deleteLater)
self.PFThread.finished.connect(self.PFThread.deleteLater)
# Move worker to the thread
self.particleFinder.moveToThread(self.PFThread)
# Connect progress signal to GUI
self.particleFinder.progress.connect(self.updateProgress)
# Start the thread
self.PFThread.start()
self.updateLog('Start to locate particles...')
# UI response
self.window.DFLSP_runButton.setEnabled(False) # Block 'Run' button
self.PFThread.finished.connect(
lambda: self.window.DFLSP_runButton.setEnabled(True) # Reset 'Run' button
)
self.PFThread.finished.connect(
lambda: self.updateLog('Particles in images are located.')
)
self.PFThread.finished.connect(
lambda: self.resetProgress()
) # Reset progress bar to rest
try:
self.PFThread.finished.connect(
lambda: self._generateDFLSPReports()
) # Generate reports
except:
print(sys.exc_info())
def _generateDFLSPReports(self):
self.initialiseProgress('Generating reports...', 3*len(self.project.wells))
# Generate sample summaries, Summary.csv and QC.csv
self.reportThread = QThread()
self.reportWriter = toolbox.ReportWriter(self.project)
self.reportThread.started.connect(self.reportWriter.run)
self.reportWriter.finished.connect(self.reportThread.quit)
self.reportWriter.finished.connect(self.reportWriter.deleteLater)
self.reportThread.finished.connect(self.reportThread.deleteLater)
self.reportWriter.moveToThread(self.reportThread)
self.reportWriter.progress.connect(self.updateProgress)
self.reportThread.start()
self.updateLog('Start to generate reports...')
self.window.DFLSP_runButton.setEnabled(False) # Block 'Run' button
self.reportThread.finished.connect(
lambda: self.window.DFLSP_runButton.setEnabled(True) # Reset 'Run' button
)
self.reportThread.finished.connect(
lambda: self.window.DFLSP_tagButton.setEnabled(True)
)
self.reportThread.finished.connect(
lambda: self.updateLog('Reports generated at: ' + self.project.path_result_main)
)
self.reportThread.finished.connect(
lambda: self.resetProgress()
) # Reset progress bar to rest
try:
self.reportThread.finished.connect(
lambda: self._showDFLSPResult()
)
except:
print(sys.exc_info())
def _showDFLSPResult(self):
df = pd.read_csv(self.project.path_result_main + '/Summary.csv')
model = toolbox.PandasModel(df)
self.window.DFLSP_resultTable.setModel(model)
def clickDFLSPTag(self):
self.tagdatapopup = TagDataPopup(parent=self)
self.tagdatapopup.window.show()
self.tagdatapopup.finished.connect(
lambda: self._showDFLSPResult()
)
self.tagdatapopup.finished.connect(self.tagdatapopup.window.close)
self.tagdatapopup.finished.connect(
lambda: self.updateLog('Tagged data saved at: ' + self.project.path_result_main)
)
self.tagdatapopup.finished.connect(
lambda: self.window.DFLSP_oaButton.setEnabled(True)
)
def clickDFLSPOA(self):
self.groupingpopup = GroupingPopup(parent=self)
self.groupingpopup.window.show()
self.groupingpopup.output.connect(self._oaProcess)
self.groupingpopup.finished.connect(self.groupingpopup.window.close)
def _oaProcess(self, experimentSelection, xaxisSelection):
df = pd.read_csv(self.project.path_result_main + '/QC.csv')
if experimentSelection == 'None':
self.oapopup = OrthogonalAnalysisPopup(task='All', df=df, xaxis=xaxisSelection, parent=self)
self.oapopup.window.show()
self.oapopup.finished.connect(self.oapopup.window.close)
else:
tasks = list(df[experimentSelection].unique())
for t in tasks:
t_df = df.loc[df[experimentSelection] == t]
self.oapopup = OrthogonalAnalysisPopup(task=t, df=t_df, xaxis=xaxisSelection, parent=self)
self.oapopup.window.show()
self.oapopup.finished.connect(self.oapopup.window.close)
# Liposome Assay Analysis
def clickLipoAssayRun(self):
guard = self._checkLipoAssayParameters()
if guard == 1:
guard = self._runLipoAssayAnalysis()
def clickLipoAssayGenerateReport(self):
data_path = self.window.LipoAssay_pathEntry.text()
self.data_path = data_path.replace('_results', '')
self.window.LipoAssay_pathEntry.setText(self.data_path)
guard = self._checkLipoAssayParameters()
if guard == 1:
if os.path.isdir(self.data_path + '_results') ==False:
self.showMessage('w', 'This dataset has not been analysed. Please run analysis.')
else:
self.updateLog('Data path set to '+data_path)
self._generateLipoAssayReports()
def _checkLipoAssayParameters(self):
#Check if data path exists
data_path = self.window.LipoAssay_pathEntry.text()
if os.path.isdir(data_path) == False:
self.showMessage('w', 'Path to folder not found.')
return 0
else:
self.data_path = data_path
self.window.LipoAssay_pathEntry.setText(self.data_path)
self.updateLog('Data path set to '+data_path)
#Check input: threshold
try:
self.threshold = int(self.window.LipoAssay_thresholdEntry.text())
self.window.LipoAssay_thresholdEntry.setText(str(self.threshold))
except ValueError:
self.showMessage('c', 'Please input a number for threshold.')
return 0
if self.threshold <= 20 or self.threshold >= 160:
self.updateLog('Threshold set as '+str(self.threshold)+'. Suggested range would be 20-160.')
else:
self.updateLog('Threshold set at '+str(self.threshold)+'.')
self.project = LiposomeAssayAnalysis(self.data_path) # Create project for liposome assay analysis
return 1
def _runLipoAssayAnalysis(self):
self.initialiseProgress('Analysing liposomes...', len(self.project.samples))
# Create a QThread object
self.lipoThread = QThread()
# Create a worker object
self.lipoWorker = toolbox.LipoAssayWorker(self.project, self.threshold)
# Connect signals and slots
self.lipoThread.started.connect(self.lipoWorker.run)
self.lipoWorker.finished.connect(self.lipoThread.quit)
self.lipoWorker.finished.connect(self.lipoWorker.deleteLater)
self.lipoThread.finished.connect(self.lipoThread.deleteLater)
# Move worker to the thread
self.lipoWorker.moveToThread(self.lipoThread)
# Connect progress signal to GUI
self.lipoWorker.progress.connect(self.updateProgress)
self.lipoWorker.log.connect(self.updateLog)
# Start the thread
self.lipoThread.start()
self.updateLog('Start to locate particles...')
# UI response
self.window.LipoAssay_runButton.setEnabled(False) # Block 'Run' button
self.lipoThread.finished.connect(
lambda: self.window.LipoAssay_runButton.setEnabled(True) # Reset 'Run' button
)
self.lipoThread.finished.connect(
lambda: self.updateLog('Liposome analysis finished.')
)
self.lipoThread.finished.connect(
lambda: self.resetProgress()
) # Reset progress bar to rest
try:
self.lipoThread.finished.connect(
lambda: self._generateLipoAssayReports()
) # Generate reports
except:
print(sys.exc_info())
def _generateLipoAssayReports(self):
self.initialiseProgress('Generating reports...', len(self.project.samples))
# Generate Summary.csv
self.reportThread = QThread()
self.reportWriter = toolbox.ReportWriter(self.project)
self.reportThread.started.connect(self.reportWriter.run)
self.reportWriter.finished.connect(self.reportThread.quit)
self.reportWriter.finished.connect(self.reportWriter.deleteLater)
self.reportThread.finished.connect(self.reportThread.deleteLater)
self.reportWriter.moveToThread(self.reportThread)
self.reportWriter.progress.connect(self.updateProgress)
self.reportThread.start()
self.updateLog('Start to generate reports...')
self.window.LipoAssay_runButton.setEnabled(False) # Block 'Run' button
self.reportThread.finished.connect(
lambda: self.window.LipoAssay_runButton.setEnabled(True) # Reset 'Run' button
)
self.reportThread.finished.connect(
lambda: self.updateLog('Reports generated at: ' + self.project.path_result_main)
)
self.reportThread.finished.connect(
lambda: self.resetProgress()
) # Reset progress bar to rest
try:
self.reportThread.finished.connect(
lambda: self._showLipoAssayResult()
)
except:
print(sys.exc_info())
def _showLipoAssayResult(self):
df = pd.read_csv(self.project.path_result_main + '/Summary.csv')
model = toolbox.PandasModel(df)
self.window.LipoAssay_resultTable.setModel(model)
# Super-resolution Anlaysis
def _updateSRPreviousReconstructionAttempts(self):
"""
This function updates the items in SupRes_previousReconstructionAttemptSelector, by listing all the directories parallel to the data path.
"""
previous_reconstruction_attempts = [i for i in os.listdir(os.path.dirname(self.data_path)) if os.path.isdir(os.path.join(os.path.dirname(self.data_path), i))] # Find all previous reconstruction attempts and only keep folders
previous_reconstruction_attempts = [i for i in previous_reconstruction_attempts if i.startswith(os.path.basename(self.data_path))] # Remove unrelated folders
previous_reconstruction_attempts.remove(os.path.basename(self.data_path)) # Remove original path from the list
if len(previous_reconstruction_attempts) != 0:
self.updateLog(str(len(previous_reconstruction_attempts)) + ' previous attempts are found.')
self.previous_reconstruction_attempts = dict() # attempt name: attempt folder path
# Clear the combo box and create items for each attempt
self.window.SupRes_previousReconstructionAttemptSelector.clear()
self.window.SupRes_previousReconstructionAttemptSelector.addItem("New")
for i in previous_reconstruction_attempts:
self.previous_reconstruction_attempts[i] = os.path.join(os.path.dirname(self.data_path), i).replace('\\', '/')
self.window.SupRes_previousReconstructionAttemptSelector.addItem(i)
self.window.SupRes_previousReconstructionAttemptSelector.setCurrentIndex(self.window.SupRes_previousReconstructionAttemptSelector.count() - 1) # Set the latest item as selection
else:
self.updateLog('No previous reconstruction attempt found for this data.')
def clickLoadSRPreviousAttempts(self):
# Check if data path exists
data_path = self.window.SupRes_pathEntry.text()
if os.path.isdir(data_path) == False:
self.showMessage('w', 'Path to folder not found.')
return 0
else:
self.data_path = data_path.replace('\\', '/')
self.window.SupRes_pathEntry.setText(self.data_path)
self.updateLog('Loading previous attempts from ' + self.data_path)
if self.data_path.endswith('/'):
self.data_path = self.data_path[:-1]
self._createSRProject()
self._updateSRPreviousReconstructionAttempts()
def _updateSRPreviousCorrectionAttempts(self):
"""
This function updates the items in SupRes_previousCorrectionAttemptsSelector, by listing all the directories present in the result path.
"""
selected_attempt = self.window.SupRes_previousReconstructionAttemptSelector.currentText()
previous_drift_attempts = [i for i in os.listdir(self.previous_reconstruction_attempts[selected_attempt]) if os.path.isdir(os.path.join(self.previous_reconstruction_attempts[selected_attempt], i))] # Only keep folders
if len(previous_drift_attempts) != 0:
self.window.SupRes_previousCorrectionAttemptsSelector.setEnabled(True)
self.updateLog(str(len(previous_drift_attempts)) + ' previous drift correction attempts were found for this reconstruction attempt.')
self.previous_drift_attempts = dict() # attempt name: attempt folder path
# Clear the combo box and create items for each attempt
self.window.SupRes_previousCorrectionAttemptsSelector.clear()
for i in previous_drift_attempts:
self.previous_drift_attempts[i] = os.path.join(os.path.join(os.path.dirname(self.data_path), selected_attempt), i).replace('\\', '/')
self.window.SupRes_previousCorrectionAttemptsSelector.addItem(i)
self.window.SupRes_previousCorrectionAttemptsSelector.setCurrentIndex(self.window.SupRes_previousCorrectionAttemptsSelector.count() - 1) # Set the latest item as selection
else:
pass
def _SRPreviousReconstructionAttemptSelected(self):
selected_attempt = self.window.SupRes_previousReconstructionAttemptSelector.currentText()
if selected_attempt == '':
pass # avoid KeyError triggered when clearing combobox
elif selected_attempt != "New":
# Create project for super resolution analysis
self.project.path_result_main = self.previous_reconstruction_attempts[selected_attempt]
self.project.path_result_raw = self.project.path_result_main + '/raw'
# Check if the parameter log for the previous attempt is available
try:
with open(os.path.join(self.previous_reconstruction_attempts[selected_attempt], 'parameters.txt'), 'r') as js_file:
self.SRparameters = json.load(js_file)
except FileNotFoundError:
self.showMessage('w', 'Parameter info for selected attempt not found. Default parameters used.')
return 0
except KeyError:
self.window.SupRes_runFidCorrButton.setEnabled(False)
self.window.SupRes_previousCorrectionAttemptsSelector.clear()
self.window.SupRes_previousCorrectionAttemptsSelector.setEnabled(False)
return 1
ind = self.window.SupRes_methodSelector.findText(self.SRparameters['method'])
if ind >= 0:
self.window.SupRes_methodSelector.setCurrentIndex(ind)
if self.SRparameters['method'] == 'ThunderSTORM':
self.window.SupRes_QEEntry.setText(str(self.SRparameters['quantum_efficiency']))
self.window.SupRes_PixelSizeEntry.setText(str(self.SRparameters['pixel_size']))
self.window.SupRes_CamBiasEntry.setText(str(self.SRparameters['camera_bias']))
self.window.SupRes_CamGainEntry.setText(str(self.SRparameters['camera_gain']))
self.window.SupRes_ExpTimeEntry.setText(str(self.SRparameters['exposure_time']))
self.window.SupRes_SRScaleEntry.setText(str(self.SRparameters['scale']))
self.window.SupRes_runFidCorrButton.setEnabled(True)
self._updateSRPreviousCorrectionAttempts()
else:
pass
return 1
def _SRPreviousCorrectionAttemptSelected(self):
selected_attempt = self.window.SupRes_previousCorrectionAttemptsSelector.currentText()
try:
self.project.path_result_fid = self.previous_drift_attempts[selected_attempt]
except KeyError:
pass
if selected_attempt == 'raw':
ind = self.window.SupRes_FidCorrMethodSelector.findText('')
self.window.SupRes_FidCorrMethodSelector.setCurrentIndex(ind)
return 1
else:
correction_info = selected_attempt.split('_')
if correction_info[0] == 'ThunderSTORM':
if correction_info[1] == 'CrossCorrelation':
ind = self.window.SupRes_FidCorrMethodSelector.findText('Cross-correlation - ThunderSTORM')
self.window.SupRes_FidCorrMethodSelector.setCurrentIndex(ind)
self.window.SupRes_FidCorrParaEntry1.setText(correction_info[2])
self.window.SupRes_FidCorrParaEntry2.setText(correction_info[3])
return 1
elif correction_info[1] == 'FidMarker':
ind = self.window.SupRes_FidCorrMethodSelector.findText('Fiducial marker - ThunderSTORM')
self.window.SupRes_FidCorrMethodSelector.setCurrentIndex(ind)
self.window.SupRes_FidCorrParaEntry1.setText(correction_info[2])
self.window.SupRes_FidCorrParaEntry2.setText(correction_info[3])
return 1
else:
pass # Space for other drift correction methods
else:
pass
def _SRClusteringDBSCANSelection(self):
if self.window.SupRes_DBSCANCheck.isChecked():
self.window.SupRes_runClusteringButton.setEnabled(True)
self.window.SupRes_EPSLabel.setEnabled(True)
self.window.SupRes_EPSEntry.setEnabled(True)
self.window.SupRes_minSampleLabel.setEnabled(True)
self.window.SupRes_minSampleEntry.setEnabled(True)
self.window.SupRes_filteringCheck.setEnabled(True)
self.window.SupRes_lengthCalCheck.setEnabled(True)
else:
self.window.SupRes_runClusteringButton.setEnabled(False)
self.window.SupRes_EPSLabel.setEnabled(False)
self.window.SupRes_EPSEntry.setEnabled(False)
self.window.SupRes_minSampleLabel.setEnabled(False)
self.window.SupRes_minSampleEntry.setEnabled(False)
self.window.SupRes_filteringCheck.setChecked(False)
self.window.SupRes_filteringCheck.setEnabled(False)
self.window.SupRes_lengthCalCheck.setChecked(False)
self.window.SupRes_lengthCalCheck.setEnabled(False)
def _SRLengthCalSelection(self):
if self.window.SupRes_lengthCalCheck.isChecked():
self.showMessage('w', 'The cluster length calculation method is a beta feature. It might require a large amount of computational power and time. Please see the README on github for more information.')
else:
pass
def _SRClusteringFilteringSelection(self):
if self.window.SupRes_filteringCheck.isChecked():
self.window.SupRes_precisionLabel.setEnabled(True)
self.window.SupRes_precisionEntry.setEnabled(True)
self.window.SupRes_sigmaLabel.setEnabled(True)
self.window.SupRes_sigmaEntry.setEnabled(True)
self.window.SupRes_keepFrameFromLabel.setEnabled(True)
self.window.SupRes_keepFrameFromEntry.setEnabled(True)
self.window.SupRes_keepFrameToLabel.setEnabled(True)
self.window.SupRes_keepFrameToEntry.setEnabled(True)
else:
self.window.SupRes_precisionLabel.setEnabled(False)
self.window.SupRes_precisionEntry.setEnabled(False)
self.window.SupRes_sigmaLabel.setEnabled(False)
self.window.SupRes_sigmaEntry.setEnabled(False)
self.window.SupRes_keepFrameFromLabel.setEnabled(False)
self.window.SupRes_keepFrameFromEntry.setEnabled(False)
self.window.SupRes_keepFrameToLabel.setEnabled(False)
self.window.SupRes_keepFrameToEntry.setEnabled(False)
def _methodOptSR(self):
"""
Block/Release parameter entry when a method is selected
Change the options for fiducial correction for different reconstruction method
"""
GDSC_fid_corr_methods = ['', 'Fiducial marker - ThunderSTORM', 'Cross-correlation - ThunderSTORM'] # The methods listed will be deleted when ThunderSTROM is selected ##'Auto fiducial
ThunderSTORM_fid_corr_methods = ['', 'Fiducial marker - ThunderSTORM', 'Cross-correlation - ThunderSTORM']
if self.window.SupRes_methodSelector.currentText() == 'GDSC SMLM 1':
self.window.SupRes_QELabel.setEnabled(False)
self.window.SupRes_QEEntry.setEnabled(False)
self.window.SupRes_FidCorrMethodSelector.clear()
for i in GDSC_fid_corr_methods:
self.window.SupRes_FidCorrMethodSelector.addItem(i)
elif self.window.SupRes_methodSelector.currentText() == 'ThunderSTORM':
self.window.SupRes_QELabel.setEnabled(True)
self.window.SupRes_QEEntry.setEnabled(True)
self.window.SupRes_FidCorrMethodSelector.clear()
for i in ThunderSTORM_fid_corr_methods:
self.window.SupRes_FidCorrMethodSelector.addItem(i)
def _methodOptSRFidCorr(self):
"""
Change the parameter required for fiducial correction methods.
"""
if self.window.SupRes_FidCorrMethodSelector.currentText() == '':
self.window.SupRes_FidCorrParaLabel1.setEnabled(False)
self.window.SupRes_FidCorrParaLabel2.setEnabled(False)
self.window.SupRes_FidCorrParaEntry1.setEnabled(False)
self.window.SupRes_FidCorrParaEntry2.setEnabled(False)
else:
self.window.SupRes_FidCorrParaLabel1.setEnabled(True)
self.window.SupRes_FidCorrParaLabel2.setEnabled(True)
self.window.SupRes_FidCorrParaEntry1.setEnabled(True)
self.window.SupRes_FidCorrParaEntry2.setEnabled(True)
if self.window.SupRes_FidCorrMethodSelector.currentText() == 'Auto fiducial':
self.window.SupRes_FidCorrParaLabel1.setText('Brightness')
self.window.SupRes_FidCorrParaLabel2.setText('Last Time/frames')
self.window.SupRes_FidCorrParaEntry1.setText('10000')
self.window.SupRes_FidCorrParaEntry2.setText('500')
elif self.window.SupRes_FidCorrMethodSelector.currentText() == 'Fiducial marker - ThunderSTORM':
self.window.SupRes_FidCorrParaLabel1.setText('Max distance/nm')
self.window.SupRes_FidCorrParaLabel2.setText('Min visibility ratio')
self.window.SupRes_FidCorrParaEntry1.setText('40.0')
self.window.SupRes_FidCorrParaEntry2.setText('0.1')
elif self.window.SupRes_FidCorrMethodSelector.currentText() == 'Cross-correlation - ThunderSTORM':
self.window.SupRes_FidCorrParaLabel1.setText('Bin size')
self.window.SupRes_FidCorrParaLabel2.setText('Magnification')
self.window.SupRes_FidCorrParaEntry1.setText('10')
self.window.SupRes_FidCorrParaEntry2.setText('8.0')
def clickSRRun(self):
self._createSRProject()
guard = self._checkSRParameters()
if guard == 1:
self._runSRReconstruction()
def clickSRfidCorr(self):
if self.window.SupRes_FidCorrMethodSelector.currentText() == '':
self.showMessage('w', 'No drift correction method was selected.')
else:
try:
guard = self._checkSRParameters()
except AttributeError:
self.updateLog('Data at providing path was not super-resolved. Please click Reconstruction to start with.')
if guard == 1:
self._runSRFidCorr()
def clickSRClustering(self):
try:
guard = self._checkSRParameters()
except AttributeError:
self.updateLog('Data at providing path was not super-resolved. Please click Reconstruction to start with.')
if guard == 1:
self._runClustering()
def _checkSRParameters(self):
# Check if data path exists
data_path = self.window.SupRes_pathEntry.text()
if os.path.isdir(data_path) == False:
self.showMessage('w', 'Path to folder not found.')
return 0
else:
self.data_path = data_path.replace('\\', '/')
self.window.SupRes_pathEntry.setText(self.data_path)
self.updateLog('Data path set to ' + self.data_path)
try: # Obtain methods and reconstruction parameters from UI
self.SRparameters = {
'method' : self.window.SupRes_methodSelector.currentText(),
'pixel_size' : float(self.window.SupRes_PixelSizeEntry.text()),
'camera_bias' : float(self.window.SupRes_CamBiasEntry.text()),
'camera_gain' : float(self.window.SupRes_CamGainEntry.text()),
'exposure_time' : float(self.window.SupRes_ExpTimeEntry.text()),
'scale' : int(round(float(self.window.SupRes_SRScaleEntry.text()))),
'fid_method' : self.window.SupRes_FidCorrMethodSelector.currentText(),
'signal_strength' : 40,
'precision': 20.0,
'min_photons': 0,
'smoothing_factor': 0.25
}
if self.SRparameters['method'] == 'ThunderSTORM': # Quantum efficiency is solely required for ThunderSTORM
self.SRparameters['quantum_efficiency'] = float(self.window.SupRes_QEEntry.text())
# Obtain the corresponding parameters for the drift correction method selected
if self.SRparameters['fid_method'] == 'Auto fiducial':
self.SRparameters['fid_brightness'] = float(self.window.SupRes_FidCorrParaEntry1.text())
self.SRparameters['fid_time'] = float(self.window.SupRes_FidCorrParaEntry2.text())
elif self.SRparameters['fid_method'] == 'Fiducial marker - ThunderSTORM':
self.SRparameters['max_distance'] = float(self.window.SupRes_FidCorrParaEntry1.text())
self.SRparameters['min_visibility'] = float(self.window.SupRes_FidCorrParaEntry2.text())
elif self.SRparameters['fid_method'] == 'Cross-correlation - ThunderSTORM':
self.SRparameters['bin_size'] = int(self.window.SupRes_FidCorrParaEntry1.text())
self.SRparameters['magnification'] = float(self.window.SupRes_FidCorrParaEntry2.text())
else:
pass
if self.window.SupRes_filteringCheck.isChecked(): # Obtain parameters for data filtering if the method is required
self.SRparameters['filter'] = {
"precision": float(self.window.SupRes_precisionEntry.text()), # in nm
"sigma": float(self.window.SupRes_sigmaEntry.text()), # in pixel
"keepFrom": float(self.window.SupRes_keepFrameFromEntry.text()),
"keepTo": float(self.window.SupRes_keepFrameToEntry.text())
}
if self.window.SupRes_DBSCANCheck.isChecked():# Obtain parameters for DBSCAN if the method is required
self.SRparameters['DBSCAN'] = {
"eps": float(self.window.SupRes_EPSEntry.text()), # in nm
"min_sample": int(round(float(self.window.SupRes_minSampleEntry.text())))
}
if self.window.SupRes_lengthCalCheck.isChecked(): # Check if length calculation is required
self.SRparameters['length_calculation'] = True
else:
self.SRparameters['length_calculation'] = False
except ValueError:
self.showMessage('w', 'The parameters must be numbers.')
return 0
self.project.update_parameters(self.SRparameters)
return 1
def _createSRProject(self):
self.project = SuperResAnalysis(self.window.SupRes_pathEntry.text()) # Create project for super resolution analysis
if self.project.error != 1:
self.showMessage('c', self.project.error)
self.project.error = 1
return 0
else:
return 1
def _runSRReconstruction(self):
self.initialiseProgress('Reconstructing SR images...', len(self.project.fov_paths))
# Create a QThread object
self.SRThread = QThread()
# Create a worker object
self.SRWorker = toolbox.SRWorker('Reconstruction', self.project, self.IJ)
# Connect signals and slots
self.SRThread.started.connect(self.SRWorker.run)
self.SRWorker.finished.connect(self.SRThread.quit)
self.SRWorker.finished.connect(self.SRWorker.deleteLater)
self.SRThread.finished.connect(self.SRThread.deleteLater)
# Move worker to the thread
self.SRWorker.moveToThread(self.SRThread)
# Connect progress signal to GUI
self.SRWorker.progress.connect(self.updateProgress)
# Start the thread
self.SRThread.start()
self.updateLog('Starting reconstruction...')
# UI response
self.window.SupRes_runReconstructionButton.setEnabled(False) # Block 'Run Reconstruction' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_runReconstructionButton.setEnabled(True) # Reset 'Run Reconstruction' button
)
self.window.SupRes_loadButton.setEnabled(False) # Block 'Load' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_loadButton.setEnabled(True) # Reset 'Load' button
)
self.window.SupRes_runFidCorrButton.setEnabled(False) # Block 'Run Fiducial Correction' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_runFidCorrButton.setEnabled(True) # Enable 'Run fiducial correction' button
)
self.window.SupRes_runClusteringButton.setEnabled(False) # Block 'Run Clustering' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_runClusteringButton.setEnabled(True) # Reset 'Run Clustering' button
)
self.SRThread.finished.connect(
lambda: self._updateSRPreviousReconstructionAttempts() # Refresh previous reconstruction attempt list
)
# Passing next job
self.SRThread.finished.connect(
lambda: self.updateLog('Reconstruction completed.')
)
self.SRThread.finished.connect(
lambda: self.updateLog(self.project.error) if self.project.error != 1 else False
)
self.SRThread.finished.connect(
lambda: self.resetProgress()
) # Reset progress bar to rest
if self.SRparameters['fid_method'] == '': # if no fid method selected, skip. Otherwise trigger drift correction
pass
else:
try:
self.SRThread.finished.connect(
lambda: self._runSRFidCorr()
)
except:
print(sys.exc_info())
def _runSRFidCorr(self):
self.initialiseProgress('Drift correcting...', len(self.project.fov_paths))
# Create a QThread object
self.SRThread = QThread()
# Create a worker object
self.SRWorker = toolbox.SRWorker('FiducialCorrection', self.project, self.IJ)
# Connect signals and slots
self.SRThread.started.connect(self.SRWorker.run)
self.SRWorker.finished.connect(self.SRThread.quit)
self.SRWorker.finished.connect(self.SRWorker.deleteLater)
self.SRThread.finished.connect(self.SRThread.deleteLater)
# Move worker to the thread
self.SRWorker.moveToThread(self.SRThread)
# Connect progress signal to GUI
self.SRWorker.progress.connect(self.updateProgress)
# Start the thread
self.SRThread.start()
self.updateLog('Starting drift correction by ' + self.SRparameters['fid_method'] + '...')
# UI response
self.window.SupRes_runReconstructionButton.setEnabled(False) # Block 'Run Reconstruction' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_runReconstructionButton.setEnabled(True) # Reset 'Run Reconstruction' button
)
self.window.SupRes_loadButton.setEnabled(False) # Block 'Load' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_loadButton.setEnabled(True) # Reset 'Load' button
)
self.window.SupRes_runFidCorrButton.setEnabled(False) # Block 'Run Fiducial Correction' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_runFidCorrButton.setEnabled(True) # Reset 'Fiducial Correction' button
)
self.window.SupRes_runClusteringButton.setEnabled(False) # Block 'Run Clustering' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_runClusteringButton.setEnabled(True) # Reset 'Run Clustering' button
)
self.SRThread.finished.connect(
lambda: self._updateSRPreviousCorrectionAttempts# Add work to attempt list
)
# Passing next job
self.SRThread.finished.connect(
lambda: self.updateLog('Drift correction completed.')
)
self.SRThread.finished.connect(
lambda: self.resetProgress()
) # Reset progress bar to rest
if 'DBSCAN' not in self.SRparameters.keys():
pass
else:
try:
self.SRThread.finished.connect(
lambda: self._runClustering()
)
except:
print(sys.exc_info())
def _runClustering(self):
self.initialiseProgress('Analysing clusters...', len(self.project.fov_paths))
# Create a QThread object
self.SRThread = QThread()
# Create a worker object
self.SRWorker = toolbox.SRWorker('Clustering', self.project, self.IJ)
# Connect signals and slots
self.SRThread.started.connect(self.SRWorker.run)
self.SRWorker.finished.connect(self.SRThread.quit)
self.SRWorker.finished.connect(self.SRWorker.deleteLater)
self.SRThread.finished.connect(self.SRThread.deleteLater)
# Move worker to the thread
self.SRWorker.moveToThread(self.SRThread)
# Connect progress signal to GUI
self.SRWorker.progress.connect(self.updateProgress)
# Start the thread
self.SRThread.start()
self.updateLog('Starting cluster analysis with DBSCAN...')
# UI response
self.window.SupRes_runReconstructionButton.setEnabled(False) # Block 'Run Reconstruction' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_runReconstructionButton.setEnabled(True) # Reset 'Run Reconstruction' button
)
self.window.SupRes_loadButton.setEnabled(False) # Block 'Load' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_loadButton.setEnabled(True) # Reset 'Load' button
)
self.window.SupRes_runFidCorrButton.setEnabled(False) # Block 'Run Fiducial Correction' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_runFidCorrButton.setEnabled(True) # Reset 'Fiducial Correction' button
)
self.window.SupRes_runClusteringButton.setEnabled(False) # Block 'Run Clustering' button
self.SRThread.finished.connect(
lambda: self.window.SupRes_runClusteringButton.setEnabled(True) # Reset 'Run Clustering' button
)
# Passing next job
self.SRThread.finished.connect(
lambda: self.updateLog('Cluster analysis completed.')
)
self.SRThread.finished.connect(
lambda: self.resetProgress()