-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
3037 lines (2534 loc) · 133 KB
/
main.py
File metadata and controls
3037 lines (2534 loc) · 133 KB
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 sys
import os
import csv
import re
import time
import traceback
# Third-party imports for data and analysis
import flowio
import flowkit as fk
import numpy as np
import pandas as pd # Example: Though unused directly, good to have for clarity if debugging
from scipy.stats import kendalltau
from sklearn.metrics import pairwise_distances,adjusted_mutual_info_score
from sklearn_extra.cluster import KMedoids
from sklearn.preprocessing import StandardScaler
import leidenalg as la
import igraph as ig
# Third-party imports for GUI
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QCheckBox, QPushButton, QProgressBar, QLabel, QFileDialog, QScrollArea, QFrame,
QAction, QMessageBox,QComboBox,QTabWidget,QSplitter, QFileSystemModel,QTreeView,QSlider,QMenu,QTextEdit,QSizePolicy,QDialog,QActionGroup, QDialogButtonBox, QGridLayout, QProgressDialog, QSplashScreen)
from PyQt5.QtCore import QThread, pyqtSignal, QTimer, Qt, QDir
from PyQt5.QtGui import QPixmap, QImage, QIcon, QPainter, QBrush, QPen, QColor
import matplotlib
import matplotlib.colors as mcolors
# Third-party imports for image processing (Feature Design)
import tifffile
import cv2
from scipy.ndimage import binary_fill_holes, binary_erosion, distance_transform_edt
from skimage.filters import threshold_otsu,gaussian
from skimage.morphology import binary_opening,binary_closing,disk,remove_small_objects
from skimage.measure import label, regionprops
from skimage.segmentation import watershed
from skimage.feature import peak_local_max,canny
from scipy.stats import skew, binned_statistic
EVAL = False
#SIM = False
BOOT = 200
CLUSTERS = 3
MEDS = CLUSTERS
BOOTSIZE = 1000
THRESHOLD = 1e-5
# KFRAC = 1./3
alpha = 5
# KFRAC = 1./10
BOOTSTAT = 10000
FOOTPRINT = disk(4)
SQUARE = np.ones((4,4))
NOISETHRESHOLD = 0.0
LEFTCROP = 10
RIGHTCROP = 0
TOPCROP = 0
BOTTOMCROP = 0
NOWAVEFRONT = 0
SMALL = 20
DISTANCES = [1,2]
ANGLES = [0,np.pi/2]
PROPERTIES = ['ASM']
AKERNEL = (5, 3) # OpenCV takes (width, height)
SIG_X = 5/2 # Suggested based on the 3x5 filter
SIG_Y = .8
PAR = 1.2
PAR /= 4.
KERNEL = (3,3)
SIG2 = 3/2
# K = 5 # Recommended in original paper 2007
K = 15 # For similarity to standard UMAP parameters
# %matplotlib ipympl
matplotlib.use('Qt5Agg')
excludedcols = ['Saturated', 'Time', 'Sorted', 'Row', 'Column']
excludedcols += ['Protocol', 'EventLabel', 'Regions0', 'Regions1', 'Regions2',
'Regions3', 'Gates', 'IndexSort', 'SaturatedChannels', 'PhaseOffset',
'PlateLocationX', 'PlateLocationY', 'EventNumber0', 'EventNumber1',
'DeltaTime0', 'DeltaTime1', 'DropId', 'SaturatedChannels1',
'SaturatedChannels2', 'SpectralEventWidth', 'EventWidthInDrops',
'SpectralUnmixingFlags', 'WaveformPresent']
class OperationHistory(QWidget):
info_updated = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self.history_text_edit = QTextEdit()
self.history_text_edit.setReadOnly(True)
self.layout = QVBoxLayout(self)
self.layout.addWidget(QLabel("Operation History:"))
self.layout.addWidget(self.history_text_edit)
self.setLayout(self.layout)
def add_operation(self, operation_description):
current_text = self.history_text_edit.toPlainText()
new_text = f"{current_text}\n{operation_description}".strip()
self.history_text_edit.setText(new_text)
self.history_text_edit.verticalScrollBar().setValue(self.history_text_edit.verticalScrollBar().maximum())
def update_info(self,info):
self.info_updated.emit(info)
# Path to the global CSV file containing feature names
class BarWidget(QWidget):
def __init__(self, mean, color, low_ci=None, upper_ci=None, stroke_color="black", parent=None):
super().__init__(parent)
self.mean = mean
self.color = color
self.low_ci = low_ci
self.upper_ci = upper_ci
self.stroke_color = stroke_color
self.setFixedHeight(20)
self.setFixedWidth(300)
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
w = self.width()
h = self.height()
# Dimensions
ci_h = 14
solid_h = 6
y_ci = (h - ci_h) // 2
y_solid = (h - solid_h) // 2
c = QColor(self.color)
# Handle NaNs by checking if values are finite
if self.low_ci is not None and self.upper_ci is not None and np.isfinite(self.low_ci) and np.isfinite(self.upper_ci):
l = max(0, min(1, self.low_ci)) if np.isfinite(self.low_ci) else 0
u = max(0, min(1, self.upper_ci)) if np.isfinite(self.upper_ci) else 0
m = max(0, min(1, self.mean)) if np.isfinite(self.mean) else 0
x_start = int(l * w)
x_end = int(u * w)
x_mean = int(m * w)
# Draw solid bar from 0 to mean (thinner)
painter.setBrush(QBrush(c))
painter.setPen(Qt.NoPen)
if x_mean > 0:
painter.drawRect(0, y_solid, x_mean, solid_h)
# Draw transparent bar from low_ci to upper_ci (thicker)
c_trans = QColor(c)
c_trans.setAlpha(100)
painter.setBrush(QBrush(c_trans))
width_ci = max(x_end - x_start, 2) # Ensure at least 2px width
painter.drawRect(x_start, y_ci, width_ci, ci_h)
# Draw Mean stroke
s_c = QColor(self.stroke_color)
painter.setPen(QPen(s_c, 3))
painter.drawLine(x_mean, y_ci - 2, x_mean, y_ci + ci_h + 2)
else:
m = max(0, min(1, self.mean)) if np.isfinite(self.mean) else 0
width_bar = int(m * w)
painter.setBrush(QBrush(c))
painter.setPen(Qt.NoPen)
painter.drawRect(0, y_solid, width_bar, solid_h)
class WorkerThread(QThread):
progress_update = pyqtSignal(int)
intermediate_result = pyqtSignal(dict)
result_ready = pyqtSignal()
def __init__(self, data, boots=BOOT, bootsize=BOOTSIZE, conv_check=True, conv_threshold=THRESHOLD):
super().__init__()
self.data = data
N = self.data.shape[0]
self.n = bootsize
self.boots = boots
if N<self.n:
self.n = int(max([N / 2, 2]))
self.boots = N
# self.k = max([int(self.n*KFRAC),1])
self.k = K
self.mode = 'cosine'
self.t = 1
self.progress = 0
self.early = 0
self.conv_check = conv_check
self.conv_threshold = conv_threshold
# Initialize accumulators for convergence check
self.feature_averages = np.zeros((self.data.shape[1], self.boots))
self.calculated = np.zeros((self.boots))
self.medoids = np.zeros((self.data.shape[1], self.boots))
self.memberships = np.zeros((self.data.shape[1], self.boots))
def run(self):
for i in range(self.boots):
result = self.process_part(i)
# Accumulate results
value = result['value']
self.medoids[list(result['medoids'].astype(int)), i] += 1
self.memberships[:, i] = result['membership']
self.feature_averages[:, i] = value
self.calculated[i] = 1
# Convergence check
if self.conv_check and np.sum(self.calculated) > 10:
non0 = self.calculated > 0
imp_calculated = self.feature_averages[:, non0]
isconv, inds1, inds2 = self.splittest(imp_calculated, th=self.conv_threshold)
if isconv:
isclust = self.consensusclustering_test(inds1, inds2, th=self.conv_threshold)
if isclust:
self.early = 1
self.intermediate_result.emit(result)
self.progress += 1
if self.early:
break
self.result_ready.emit()
# Function to allow for possible multithread parrallelisation
def process_part(self, i):
ls,medoids,medlabels = self.get_ulscore_parralel()
return {"value": ls,"i": i,"medoids": medoids,"membership":medlabels}
# Leidenalg cluster function based on medoids memberships so far
def getclust(self,mems):
memlabels = np.unique(mems.flatten())
D = np.zeros([mems.shape[0],mems.shape[0]])
for m in memlabels:
mem = (mems == m)*1.
D += mem @ mem.T
np.fill_diagonal(D,0)
return np.array(la.find_partition(ig.Graph.Adjacency(D), la.ModularityVertexPartition).membership)
# kMedoids for cluster finding on PWD matrix
def kmedoids(self,X):
if CLUSTERS*10>=self.data.shape[1]:
clusters = CLUSTERS
else:
clusters = int(self.data.shape[1]/10)
model = KMedoids(n_clusters=clusters,method='pam').fit(X)
medoids = model.medoid_indices_
medlabels = model.labels_
return medoids,medlabels
# Partially paralllelised feature scoring (TO DO: Vectorise feature by feature scoring for full max parr)
def get_ulscore_parralel(self):
n = self.n
ones = np.ones((n,1))
sample = np.random.choice(self.data.shape[0],n)
Xsub = self.data[sample,:]
Wsub = self.get_similaritymatrix(Xsub)
Dsub = np.diagflat(np.sum(Wsub,axis=0))
Lsub = Dsub - Wsub
LSsub = np.zeros(Xsub.shape[1])
for r in range(Xsub.shape[1]):#iterate over features
fsubr = Xsub[:,r].reshape([-1,1])
neighb_est = ((fsubr.T @ Dsub @ ones).item()/ (ones.T @ Dsub @ ones).item())*ones
fsubr_est = (fsubr - neighb_est)#subtract nbh mean est of feature to centre feature vector
d = (fsubr_est.T @ Dsub @ fsubr_est).item()
num = (fsubr_est.T @ Lsub @ fsubr_est).item()
if d > 0 and num>0:
LSsub[r] = num/d
elif num==0 and d>0:
LSsub[r] = 0.
else:
LSsub[r] = 0.
medoids,medlabels = self.kmedoids(Xsub.T)
return LSsub,medoids,medlabels
def get_similaritymatrix(self, X):
"""
Optimized similarity matrix calculation for GUI classes.
Uses np.partition for O(N) neighbor thresholding and
ensures graph symmetry.
"""
t = self.t
k = self.k
n = X.shape[0]
mode = self.mode
# 1. Compute pairwise distances using the existing UI mode
# Assuming self.getpwd is available in your class as defined previously
D = self.getpwd(X, mode)
# 2. Optimized k-nearest neighbor thresholding
# k+1 because the first neighbor is always the point itself (dist=0)
k_effective = min(k + 1, n - 1)
# np.partition is faster than np.sort for finding the k-th element
# Get the distance to the k-th neighbor for every row
kn_dist = np.partition(D, k_effective, axis=1)[:, k_effective].reshape(-1, 1)
# 3. Adjacency Logic
# Compare each row's distances to its specific k-th neighbor threshold
G = D <= kn_dist
# Ensure Symmetry: If A is a neighbor of B OR B is a neighbor of A
# This prevents 'one-way' edges which can lead to lead to non-physical LS results
G = np.logical_or(G, G.T)
# Remove self-loops (diagonal)
np.fill_diagonal(G, 0)
# 4. Weighting
W = np.zeros([n, n])
if mode == 'heat':
W[G] = np.exp(-D[G]**2 / (2 * t**2))
else:
# Cosine/Standard mode: Similarity = 1 - Distance
# Using abs(1-D) ensures positive weights even with slight float errors
W[G] = np.abs(1 - D[G])
return W
def getpwd(self,X,mode='cosine'):
if mode == 'heat':#heat kernel based pwd (euclidean)
D = pairwise_distances(X)
if mode == 'cosine':#cosine pwd
D = pairwise_distances(X,metric='cosine')
return D
def splittest(self,data,th):
shape = data.shape[1]
inds = np.arange(shape)
np.random.shuffle(inds)
data = data[:,inds]
splitat = int(shape/2)
inds1 = inds[:splitat]
inds2 = inds[splitat:]
data1 = np.mean(data[:,inds1],axis=1)
data2 = np.mean(data[:,inds2],axis=1)
kt = kendalltau(data1,data2)
kt = kt.statistic
if 1-kt<=th:
return True,inds1,inds2
else:
return False,inds1,inds2
def consensusclustering_test(self,inds1,inds2,th):
mems = self.memberships[:,self.calculated>0]
mems1 = mems[:,inds1]
mems2 = mems[:,inds2]
membership1 = self.getclust(mems1)
membership2 = self.getclust(mems2)
ami = adjusted_mutual_info_score(membership1,membership2)
return ami>th
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("FlowFI: Flow cytometry Feature Importance")
# Set window icon.
# To use your own logo, create a 'logo.png' file (64x64 pixels is a good size)
# and place it in the same directory as this script.
logo_path = 'logo.png'
if os.path.exists(logo_path):
self.setWindowIcon(QIcon(logo_path))
self.setGeometry(100, 100, 800, 600)
self.boots_param = BOOT
self.bootsize_param = BOOTSIZE
self.ci_alpha = alpha
self.ci_boots = BOOTSTAT
self.convergence_check = True
self.convergence_threshold = THRESHOLD
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.layout = QVBoxLayout()
self.tabs = QTabWidget()
self.tabs.tabBar().setElideMode(Qt.ElideNone)
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.addTab(self.tab2, " Design ")
self.tabs.addTab(self.tab1, " Refine ")
self.tab1.layout = QVBoxLayout(self.tab1)
self.tab2.layout = QVBoxLayout(self.tab2)
self.layout.addWidget(self.tabs)
# TAB-1 LAYOUT: ANALYSIS
# Input field for filepath
self.filepath_input = QLineEdit()
self.filepath_input.setPlaceholderText("Enter file path here")
self.browse_button = QPushButton("Browse")
self.browse_button.clicked.connect(self.browse_file)
self.input_layout = QHBoxLayout()
self.input_layout.addWidget(self.filepath_input)
self.input_layout.addWidget(self.browse_button)
# Button to execute the function
self.execute_button = QPushButton("Execute")
self.execute_button.clicked.connect(self.execute_function)
self.checkbox_layout = QHBoxLayout()
self.ftypes = ['UV','V','B','YG','R','ImgB','Imaging','Misc']
self.colors = ['green','darkviolet','blue','darkgoldenrod','darkred','saddlebrown','teal','black']
self.clustercolors = ['lightcoral','palegoldenrod','palegreen','lightblue','aquamarine','dimgray','peru','darkseagreen','white','cornflowerblue','green','darkviolet','blue','darkgoldenrod','darkred','saddlebrown','teal','black']
self.selected_feature_types = self.ftypes
self.feature_checkboxes = {}
for i,feature_type in enumerate(self.ftypes):
checkbox = QCheckBox(feature_type)
checkbox.setChecked(True)
checkbox.stateChanged.connect(self.update_display)
checkbox.setStyleSheet("color: " + self.colors[i])
self.feature_checkboxes[feature_type] = checkbox
self.checkbox_layout.addWidget(checkbox)
centrality_checkbox = QCheckBox('CEN ONLY')
centrality_checkbox.setChecked(False)
centrality_checkbox.stateChanged.connect(self.update_display)
self.centrality_checkbox = centrality_checkbox
self.checkbox_layout.addWidget(self.centrality_checkbox)
# Progress bar
self.progress_bar = QProgressBar()
self.progress_bar.setValue(0)
# Output display panel
self.output_panel = QScrollArea()
self.output_widget = QWidget()
self.output_layout = QVBoxLayout()
self.output_widget.setLayout(self.output_layout)
self.output_panel.setWidget(self.output_widget)
self.output_panel.setWidgetResizable(True)
# Sorting dropdown box
self.sort_dropdown = QComboBox()
self.sort_dropdown.addItem("Sort by: Importance (features that are important to the data structure)")
self.sort_dropdown.addItem("Sort by: Type (UV, V, etc.)")
self.sort_dropdown.addItem("Sort by: Cluster (similar features)")
self.sort_dropdown.addItem("Sort by: Centrality (featuress typical of a cluster)")
self.sort_dropdown.addItem("Sort by: Change from Previous Importance (contrast scores against previous run)")
# self.sort_dropdown.setItemData(4, False, Qt.ItemIsEnabled)
self.sort_dropdown.currentIndexChanged.connect(self.attempt_sort)
self.tab1.layout.addLayout(self.checkbox_layout)
self.tab1.layout.addLayout(self.input_layout)
self.tab1.layout.addWidget(self.execute_button)
self.tab1.layout.addWidget(self.progress_bar)
self.tab1.layout.addWidget(self.sort_dropdown)
self.tab1.layout.addWidget(QLabel("Feature/Importance:"))
self.tab1.layout.addWidget(self.output_panel)
self.finalcluster = False
self.tab1.setLayout(self.tab1.layout)
self.central_widget.setLayout(self.layout)
#TAB-2 DESIGN LAYOUT
self.operation_history = []
self.operations_performed = 0
self.current_channel = None
self.current_image_array = None
self.processed_image = None
self.agg_operation = None
self.agg_channels = None
self.previous_agg_operation = None
self.previous_agg_channels = None
# Define which aggregation operations are multi-channel
self.multi_channel_ops = {'scorr', 'coloc', 'containment', 'relativeskew', 'angular_momentum', 'angular_entropy'}
# Root directory input
root_path_layout = QHBoxLayout()
self.root_path_input = QLineEdit(QDir.homePath())
self.root_path_input.returnPressed.connect(self.set_tree_root)
self.change_root_button = QPushButton("Change Root")
self.change_root_button.clicked.connect(self.browse_for_root)
root_path_layout.addWidget(self.root_path_input)
root_path_layout.addWidget(self.change_root_button)
self.tab2.layout.addLayout(root_path_layout)
# File system tree
self.model = QFileSystemModel()
self.model.setRootPath(QDir.homePath())
self.model.setNameFilters(["*.tiff", "*.tif"])
self.model.setNameFilterDisables(False)
self.tree = QTreeView()
self.tree.setModel(self.model)
self.tree.setRootIndex(self.model.index(QDir.homePath()))
# Image display (left)
self.image_label = QLabel()
self.image_label.setAlignment(Qt.AlignCenter)
self.image_label.setFrameShape(QFrame.StyledPanel)
self.image_label.setScaledContents(True)
# Processed image display (right)
self.processed_image_label = QLabel()
self.processed_image_label.setAlignment(Qt.AlignCenter)
self.processed_image_label.setFrameShape(QFrame.StyledPanel)
self.processed_image_label.setText("Processed Image") # Initial text
self.processed_image_label.setScaledContents(True)
# Channel slider
self.channel_label = QLabel("Channel: ")
self.channel_label.setAlignment(Qt.AlignCenter)
self.channel_slider = QSlider(Qt.Vertical)
self.channel_slider.valueChanged.connect(self.update_displayed_channel)
self.channel_slider.setEnabled(False) # Disable initially
# Create a vertical layout for each side of the split
left_image_panel = QWidget()
left_layout = QVBoxLayout(left_image_panel)
left_layout.addWidget(self.image_label)
right_image_panel = QWidget()
right_layout = QVBoxLayout(right_image_panel)
right_layout.addWidget(self.processed_image_label)
# Create a vertical layout for each side of the split
channel_panel = QWidget()
channel_layout = QVBoxLayout(channel_panel)
channel_layout.addWidget(self.channel_label)
channel_layout.addWidget(self.channel_slider)
# Create a horizontal splitter for the image panels
self.image_splitter = QSplitter(Qt.Horizontal)
self.image_splitter.addWidget(left_image_panel)
self.image_splitter.addWidget(right_image_panel)
self.image_splitter.addWidget(channel_panel)
self.image_splitter.setStretchFactor(0, 1) # Image 1 expands
self.image_splitter.setStretchFactor(1, 1) # Image 2 expands equally
self.image_splitter.setStretchFactor(2, 0) # Slider is fixed size
self.image_splitter.setSizes([300, 300, 10]) # Set initial proportions
self.terminal = OperationHistory()
self.reset_operations_button = QPushButton("Reset")
self.reset_operations_button.clicked.connect(self.reset_operations)
# Container for top part of right panel
top_right_container = QWidget()
top_right_layout = QVBoxLayout(top_right_container)
top_right_layout.addWidget(self.image_splitter)
top_right_layout.setContentsMargins(0,0,0,0)
right_panel = QWidget()
right_layout = QVBoxLayout(right_panel) # This will hold the vertical splitter
splitter = QSplitter(Qt.Horizontal)
splitter.addWidget(self.tree)
splitter.addWidget(right_panel)
splitter.setSizes([200, 400]) # Revert to original horizontal split
self.tab2.layout.addWidget(splitter) # Add the splitter to the tab's layout
# Vertical splitter for the right panel
right_v_splitter = QSplitter(Qt.Vertical)
right_v_splitter.addWidget(top_right_container)
right_v_splitter.addWidget(self.terminal)
right_v_splitter.setSizes([400, 150]) # Revert to original vertical split
# Bottom bar for info label and reset button
bottom_bar_layout = QHBoxLayout()
self.info_label = QLabel("No Image Loaded")
bottom_bar_layout.addWidget(self.info_label)
bottom_bar_layout.addStretch()
bottom_bar_layout.addWidget(self.reset_operations_button)
right_layout.addWidget(right_v_splitter)
right_layout.addLayout(bottom_bar_layout)
# Connect the tree view's double-click signal to the image loading function
self.tree.doubleClicked.connect(self.load_tiff_image)
# Connect terminal's info update to the new label
self.terminal.info_updated.connect(self.info_label.setText)
# Borrow font size from tree view for other elements
font = self.tree.font()
fsize = font.pointSize()
if fsize > 0:
fs_str = f"{fsize}pt"
elif font.pixelSize() > 0:
fs_str = f"{font.pixelSize()}px"
else:
fs_str = "10pt"
font.setPointSize(10)
self.tabs.setFont(font)
self.setStyleSheet(f"QLabel, QTextEdit, QLineEdit, QCheckBox, QComboBox, QProgressBar, QPushButton {{ font-size: {fs_str}; }} QTabBar::tab {{ font-size: {fs_str}; padding: 10px 30px; }}")
# Menu bar
self.create_menus()
self.update_timer = QTimer()
self.update_timer.timeout.connect(self.update_display)
# self.update_timer.timeout.connect(self.update_progress)
#TAB-2 Image Analysis
# Select root folder for tiff images
def browse_for_root(self):
directory = QFileDialog.getExistingDirectory(self, "Select New Root Directory",
self.root_path_input.text(),
QFileDialog.ShowDirsOnly)
if directory:
self.root_path_input.setText(directory)
self.set_tree_root()
# Set file tree for exploration
def set_tree_root(self):
root_path = self.root_path_input.text()
if QDir(root_path).exists():
self.model.setRootPath(root_path)
self.tree.setRootIndex(self.model.index(root_path))
else:
print(f"Error: Root path '{root_path}' does not exist.")
# Loads image from suitable tiff file
def load_tiff_image(self, index):
self.processed_image = None
self.operations_performed = 0
file_path = self.model.filePath(index)
self.tree.scrollTo(index)
self.tree.setCurrentIndex(index)
if file_path.lower().endswith(('.tiff', '.tif')):
try:
tif_image = tifffile.imread(file_path)
self.current_image_array = np.array(tif_image)
if self.current_image_array.ndim >= 3:
# Assuming channels are the first or last dimension
# You might need to adjust this based on your TIFF structure
if self.current_image_array.shape[0] > 1:
self.num_channels = self.current_image_array.shape[0]
elif self.current_image_array.shape[-1] > 1:
self.num_channels = self.current_image_array.shape[-1]
else:
self.num_channels = 1
self.current_image_array = np.expand_dims(self.current_image_array, axis=0) # Add a channel dimension
self.channel_slider.setMinimum(0)
self.channel_slider.setMaximum(self.num_channels - 1)
self.channel_slider.setEnabled(True)
if self.current_channel is None:
self.channel_slider.setValue(0)
self.update_displayed_channel(0) # Display the first channel
else:
if self.num_channels>self.current_channel>=0:#if channel does not exist for new image
self.channel_slider.setValue(self.current_channel)
self.update_displayed_channel(self.current_channel)
else:
self.channel_slider.setValue(0)
self.update_displayed_channel(0) # Display the first channel
self.terminal.add_operation('Image Set: ' + os.path.basename(file_path))
self.terminal.update_info(f"Array Info: Shape={self.current_image_array.shape}, Dtype={self.current_image_array.dtype}")
elif self.current_image_array.ndim == 2:
self.current_image_array = np.expand_dims(self.current_image_array, axis=0) # Treat as single channel
self.num_channels = 1
self.channel_slider.setEnabled(False)
self.update_displayed_channel(0)
self.terminal.add_operation('Image Set: ' + os.path.basename(file_path))
self.terminal.update_info(f"Array Info: Shape={self.current_image_array.shape}, Dtype={self.current_image_array.dtype}")
else:
self.terminal.add_operation("Not a suitable image format for channel viewing.")
self.channel_slider.setEnabled(False)
self.terminal.update_info("No Image Loaded")
self.current_image_array = None
self.num_channels = 0
if self.current_image_array is not None:
self.preprocessing_menu.setEnabled(True)
self.quantify_menu.setEnabled(True)
self.parameters_menu.setEnabled(True)
except ImportError:
self.image_label.setText("Error: Required library not found.")
except Exception as e:
self.image_label.setText(f"Error loading TIFF file: {e}")
self.channel_slider.setEnabled(False)
self.current_image_array = None
self.num_channels = 0
else:
self.image_label.clear()
self.channel_slider.setEnabled(False)
self.current_image_array = None
self.num_channels = 0
# General update code including preprocessing operations
def update_displayed_channel(self, channel_index):
self.operations_performed = 0
if self.current_image_array is not None and 0 <= channel_index < self.num_channels:
self.terminal.add_operation(f"Channel Set to: {channel_index+1}")
self.channel_label.setText(f"Channel: {channel_index + 1}/{self.num_channels}")
self.current_channel = channel_index
self.processed_image = self.current_image_array[self.current_channel]
# Normalize and convert to 8-bit grayscale for display
normalized_array = self.norm(self.current_image_array[channel_index])
height, width = normalized_array.shape
self.current_q_image = QImage(normalized_array.data, width, height, width, QImage.Format_Grayscale8)
self.update_left_image_label()
self.process_image()
# Image Update Panel when new image selected
def update_left_image_label(self):
if self.current_q_image is not None:
pixmap = QPixmap.fromImage(self.current_q_image)
self.image_label.setPixmap(pixmap)
else:
self.image_label.clear()
# Reset Preprocessing Operations
def reset_operations(self):
self.operation_history = []
self.operations_performed = 0
self.processed_image = self.current_image_array[self.current_channel]
self.terminal.add_operation('Reset Preprocessing Operations')
self.process_image()
# Normalise to 8-bit range and/or 8-bit type
def norm(self,array,eightbit=True):
array -= np.min(array)
max_val = np.max(array)
if max_val > 0:
array /= max_val
array *= 255
if eightbit:
array = np.round(array).astype('uint8')
return array
# Enable the selected aggregation action
def enable_aggregation(self,action):
# Store the previous state in case the user cancels a dialog
self.previous_agg_operation = self.agg_operation
self.previous_agg_channels = self.agg_channels
if action == self.count_action:
self.enable_count()
elif action == self.mean_action:
self.enable_mean()
elif action == self.area_action:
self.enable_area()
elif action == self.solidity_action:
self.enable_solidity()
elif action == self.scorr_action:
self.open_multi_channel_dialog('scorr', ['Mask (Optional)', 'Channel 1', 'Channel 2'], disable_snr_checks=True)
elif action == self.coloc_action:
self.open_multi_channel_dialog('coloc', ['Signal', 'Mask'])
elif action == self.containment_action:
self.open_multi_channel_dialog('containment', ['Signal', 'Container', 'Global Mask (Optional)'])
elif action == self.relativeskew_action:
self.open_multi_channel_dialog('relativeskew', ['Signal', 'Reference', 'Global Mask (Optional)'])
elif action == self.angular_momentum_action:
self.open_multi_channel_dialog('angular_momentum', ['Signal', 'Reference', 'Global Mask (Optional)'])
elif action == self.angular_entropy_action:
self.open_multi_channel_dialog('angular_entropy', ['Signal', 'Reference', 'Global Mask (Optional)'])
def enable_area(self):
self.agg_operation = 'area'
self.terminal.add_operation('Feature set to: Area')
self.process_image()
def enable_mean(self):
self.agg_operation = 'mean'
self.terminal.add_operation('Feature set to: Mean')
self.process_image()
def enable_count(self):
self.agg_operation = 'count'
self.terminal.add_operation('Feature set to: Count')
self.process_image()
def revert_to_previous_aggregation(self):
"""Reverts the aggregation operation to the previously selected one."""
self.agg_operation = self.previous_agg_operation
self.agg_channels = self.previous_agg_channels
# Find and re-check the action corresponding to the previous operation
if self.agg_operation:
previous_action = self.findChild(QAction, f"{self.agg_operation}_action")
if previous_action:
previous_action.setChecked(True)
else: # If there was no previous operation, default to count
self.count_action.setChecked(True)
self.enable_count()
# Do aggregation for given image stack
def do_aggregation(self):
uniq = np.unique(self.processed_image)
luniq = len(uniq)
if luniq>1:
if self.agg_operation == 'area':
if 0 in uniq:
area = self.get_area(self.processed_image)
self.terminal.add_operation(f"Area is: {area}")
if self.agg_operation == 'mean':
mean = self.get_mean(self.processed_image)
self.terminal.add_operation(f"Mean is: {mean}")
if self.agg_operation == 'count':
count = self.get_count(self.processed_image)
self.terminal.add_operation(f"Count is: {count}")
if self.agg_operation == 'scorr':
mask_channel = self.agg_channels.get('Mask (Optional)')
mask_img = self.process_image_for_channel(mask_channel) if mask_channel is not None else None
ch1_img = self.process_image_for_channel(self.agg_channels['Channel 1'])
ch2_img = self.process_image_for_channel(self.agg_channels['Channel 2'])
scorr = self.get_spatial_correlation(ch1_img, ch2_img, mask_img=mask_img)
self.terminal.add_operation(f"Spatial Correlation is: {scorr:.4f}")
if self.agg_operation == 'solidity':
solidity = self.get_solidity(self.processed_image)
self.terminal.add_operation(f"Solidity is: {solidity:.4f}")
if self.agg_operation == 'coloc':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'])
mask_img = self.process_image_for_channel(self.agg_channels['Mask'])
coloc = self.get_coloc(signal_img, mask_img)
self.terminal.add_operation(f"Colocalisation is: {coloc:.4f}")
if self.agg_operation == 'containment':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'])
container_img = self.process_image_for_channel(self.agg_channels['Container'])
global_mask_channel = self.agg_channels.get('Global Mask (Optional)')
global_mask = self.process_image_for_channel(global_mask_channel) if global_mask_channel is not None else None
containment = self.get_containment(signal_img, container_img, global_mask=global_mask)
self.terminal.add_operation(f"Containment is: {containment:.4f}")
if self.agg_operation == 'relativeskew':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'])
ref_img = self.process_image_for_channel(self.agg_channels['Reference'])
global_mask_channel = self.agg_channels.get('Global Mask (Optional)')
global_mask = self.process_image_for_channel(global_mask_channel) if global_mask_channel is not None else None
relskew = self.get_relativeskew(signal_img, ref_img, global_mask=global_mask)
self.terminal.add_operation(f"Relative Skewness is: {relskew:.4f}")
if self.agg_operation == 'angular_momentum':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'])
ref_img = self.process_image_for_channel(self.agg_channels['Reference'])
snr_checks = {'Signal': self.agg_channels['snr_checks']['Signal'], 'Reference': self.agg_channels['snr_checks']['Reference']}
global_mask_channel = self.agg_channels.get('Global Mask (Optional)')
global_mask = self.process_image_for_channel(global_mask_channel) if global_mask_channel is not None else None
ang_mom = self.get_angular_momentum(signal_img, ref_img, global_mask=global_mask, snr_checks=snr_checks)
self.terminal.add_operation(f"Angular Momentum is: {ang_mom:.4f}")
if self.agg_operation == 'angular_entropy':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'])
ref_img = self.process_image_for_channel(self.agg_channels['Reference'])
snr_checks = {'Signal': self.agg_channels['snr_checks']['Signal'], 'Reference': self.agg_channels['snr_checks']['Reference']}
global_mask_channel = self.agg_channels.get('Global Mask (Optional)')
global_mask = self.process_image_for_channel(global_mask_channel) if global_mask_channel is not None else None
ang_ent = self.get_angular_entropy(signal_img, ref_img, global_mask=global_mask, snr_checks=snr_checks)
self.terminal.add_operation(f"Angular Entropy is: {ang_ent:.4f}")
# Do silent aggregation over a give image (for largescale compiling)
def do_aggregation_silent(self,image):
score = np.nan
# Prepare optional global mask if it exists
global_mask_channel = self.agg_channels.get('Global Mask (Optional)')
global_mask = None
if global_mask_channel is not None:
global_mask = self.process_image_for_channel(global_mask_channel, source_image_array=image)
# Multi-channel operations handle their own channel extraction and processing
if self.agg_operation in self.multi_channel_ops:
if self.agg_operation == 'scorr':
# For batch processing, 'image' is the full multi-channel image
mask_channel = self.agg_channels.get('Mask (Optional)')
mask_img = self.process_image_for_channel(mask_channel, source_image_array=image) if mask_channel is not None else None
ch1_img = self.process_image_for_channel(self.agg_channels['Channel 1'], source_image_array=image)
ch2_img = self.process_image_for_channel(self.agg_channels['Channel 2'], source_image_array=image)
score = self.get_spatial_correlation(ch1_img, ch2_img, mask_img=mask_img)
elif self.agg_operation == 'coloc':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'], source_image_array=image)
mask_img = self.process_image_for_channel(self.agg_channels['Mask'], source_image_array=image)
score = self.get_coloc(signal_img, mask_img)
elif self.agg_operation == 'containment':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'], source_image_array=image)
container_img = self.process_image_for_channel(self.agg_channels['Container'], source_image_array=image)
score = self.get_containment(signal_img, container_img, global_mask=global_mask)
elif self.agg_operation == 'relativeskew':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'], source_image_array=image)
ref_img = self.process_image_for_channel(self.agg_channels['Reference'], source_image_array=image)
snr_checks = {'Signal': self.agg_channels['snr_checks']['Signal'], 'Reference': self.agg_channels['snr_checks']['Reference']}
score = self.get_relativeskew(signal_img, ref_img, global_mask=global_mask, snr_checks=snr_checks)
elif self.agg_operation == 'angular_momentum':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'], source_image_array=image)
ref_img = self.process_image_for_channel(self.agg_channels['Reference'], source_image_array=image)
snr_checks = {'Signal': self.agg_channels['snr_checks']['Signal'], 'Reference': self.agg_channels['snr_checks']['Reference']}
score = self.get_angular_momentum(signal_img, ref_img, global_mask=global_mask, snr_checks=snr_checks)
elif self.agg_operation == 'angular_entropy':
signal_img = self.process_image_for_channel(self.agg_channels['Signal'], source_image_array=image)
ref_img = self.process_image_for_channel(self.agg_channels['Reference'], source_image_array=image)
snr_checks = {'Signal': self.agg_channels['snr_checks']['Signal'], 'Reference': self.agg_channels['snr_checks']['Reference']}
score = self.get_angular_entropy(signal_img, ref_img, global_mask=global_mask, snr_checks=snr_checks)
# Single-channel operations work on a pre-processed image
elif self.agg_operation == 'solidity':
score = self.get_solidity(image)
# Single-channel operations work on a pre-processed image
else:
uniq = np.unique(image)
luniq = len(uniq)
if luniq > 1:
if self.agg_operation == 'area':
if 0 in uniq:
score = self.get_area(image)
elif self.agg_operation == 'mean':
score = self.get_mean(image)
elif self.agg_operation == 'count':
score = self.get_count(image)
else: #default to count
score = self.get_count(image)
else:
score = np.nan
if np.isnan(score):
return 0
else:
return score
# Preprocess images according to selected operations
def process_image(self):
self.perform_operations()
height, width = self.processed_image.shape
pimage = self.norm(self.processed_image).data
self.processed_q_image = QImage(pimage, width, height, width, QImage.Format_Grayscale8)
self.update_right_image_label()
# Show preprocessed image in imag panel right
def update_right_image_label(self):
if self.processed_q_image is not None:
pixmap = QPixmap.fromImage(self.processed_q_image)
self.processed_image_label.setPixmap(pixmap)
else:
self.processed_image_label.clear()
# Perform operations and aggregation on current image
def perform_operations(self):
nops = len(self.operation_history)
for i in range(self.operations_performed,nops):
self.do_operation(i)
self.operations_performed = nops
if self.agg_operation is not None:
self.do_aggregation()
# Perform given preprocessing operation
def do_operation(self,opindex):
operation = self.operation_history[opindex]
if operation[0]=='gauss':
self.processed_image = self.gaussblur(self.processed_image, float(operation[1])) # Call self.gauss
self.terminal.add_operation(f'Gaussian Blur: {np.round(float(operation[1]),2)} Channel: {self.current_channel+1}')
elif operation[0]=='mask':
self.processed_image = self.get_mask(self.processed_image.astype(float)).astype(float)
self.terminal.add_operation(f'Mask Channel: {self.current_channel+1}')
elif operation[0]=='label':
self.processed_image = self.get_label(self.processed_image.astype(int)).astype(float)
self.terminal.add_operation(f'Label Channel: {self.current_channel+1}')
elif operation[0]=='segment':
self.processed_image = self.get_segment(self.processed_image.astype(float)).astype(float)
self.terminal.add_operation(f'Segment Channel: {self.current_channel+1}')
elif operation[0]=='preset1':
# preset1_preprocess returns the processed image and a threshold mask. We only need the image here.
self.processed_image, _ = self.preset1_preprocess(self.processed_image)
self.terminal.add_operation(f'Preset 1 Preprocess Channel: {self.current_channel+1}')
elif operation[0] == 'crop':
top, bottom, left, right = operation[1]
self.processed_image = self.crop_image(self.processed_image, top, bottom, left, right)
self.terminal.add_operation(f'Crop: T={top}, B={bottom}, L={left}, R={right} on Channel: {self.current_channel+1}')
elif operation[0] == 'rescale':
scale_x, scale_y, interpolation_method = operation[1]
self.processed_image = self.rescale_image(self.processed_image, scale_x, scale_y, interpolation_method)
self.terminal.add_operation(f'Rescale: X={scale_x}, Y={scale_y} on Channel: {self.current_channel+1}')
def crop_image(self, image, top, bottom, left, right):
h, w = image.shape
return image[top:h-bottom, left:w-right]
# Perform operation without terminal reporting for given image (for multi-image processing)
def do_operation_silent(self,index,image):
operation = self.operation_history[index]
if operation[0]=='gauss':