forked from tristanwallis/smlm_clustering
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegnastic2c_gui.py
More file actions
3382 lines (3195 loc) · 132 KB
/
segnastic2c_gui.py
File metadata and controls
3382 lines (3195 loc) · 132 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
# -*- coding: utf-8 -*-
'''
SEGNASTIC2C_GUI
FREESIMPLEGUI BASED GUI FOR SPATIOTEMPORAL INDEXING CLUSTERING OF MOLECULAR TRAJECTORY SEGMENT DATA - 2 COLOR VERSION
Design and coding: Tristan Wallis
Additional coding: Kyle Young, Alex McCann
Debugging: Sophie Huiyi Hou, Kye Kudo, Alex McCann
Queensland Brain Institute
The University of Queensland
Fred Meunier: f.meunier@uq.edu.au
REQUIRED:
Python 3.8 or greater
python -m pip install scipy numpy matplotlib scikit-learn rtree freesimplegui colorama
INPUT:
TRXYT trajectory files
Space separated: TRajectory# X-position(um) Y-position(um) Time(sec)
No headers
1 9.0117 39.86 0.02
1 8.9603 39.837 0.04
1 9.093 39.958 0.06
1 9.0645 39.975 0.08
2 9.1191 39.932 0.1
2 8.9266 39.915 0.12
etc
NOTES:
This script has been tested and will run as intended on Windows 7/10, with minor interface anomalies on Linux, and possible tk GUI performance issues on MacOS.
The script will fork to multiple CPU cores for the heavy number crunching routines (this also prevents it from being packaged as an exe using pyinstaller).
Feedback, suggestions and improvements are welcome. Sanctimonious critiques on the pythonic inelegance of the coding are not.
CHECK FOR UPDATES:
https://github.com/tristanwallis/smlm_clustering/releases
'''
last_changed = "20250724"
# MULTIPROCESSING FUNCTIONS
from scipy.spatial import ConvexHull
import multiprocessing
import numpy as np
import math
from math import dist
import functools
import webbrowser
import warnings
warnings.filterwarnings("ignore")
def metrics(data):
points,minlength,centroid=data
# MSD over time
msds = []
for i in range(1,minlength,1):
all_diff_sq = []
for j in range(0,i):
msdpoints = points[j::i]
diff = [dist(msdpoints[k][:2],msdpoints[k-1][:2]) for k in range(1,len(msdpoints))] # displacement
diff_sq = np.array(diff)**2 # square displacement
[all_diff_sq.append(x) for x in diff_sq]
msd = np.average(all_diff_sq)
msds.append(msd)
# Instantaneous diffusion coefficient
diffcoeff = (msds[3]-msds[0])
return [points,msds,centroid,diffcoeff]
def multi(allpoints):
with multiprocessing.Pool() as pool:
allmetrics = pool.map(metrics,allpoints)
return allmetrics
# MAIN PROG AND FUNCTIONS
if __name__ == "__main__": # has to be called this way for multiprocessing to work
# LOAD MODULES
import FreeSimpleGUI as sg
from colorama import init as colorama_init
from colorama import Fore
from colorama import Style
import os
sg.set_options(dpi_awareness=True) # turns on DPI awareness (Windows only)
sg.theme('DARKGREY11')
colorama_init()
os.system('cls' if os.name == 'nt' else 'clear')
print(f'{Fore.GREEN}============================================================={Style.RESET_ALL}')
print(f'{Fore.GREEN}SEGNASTIC2C {last_changed} initialising...{Style.RESET_ALL}')
print(f'{Fore.GREEN}============================================================={Style.RESET_ALL}')
popup = sg.Window("Initialising...",[[sg.T("SEGNASTIC2C initialising...",font=("Arial bold",18))]],finalize=True,no_titlebar = True,alpha_channel=0.9)
import random
from scipy.spatial import ConvexHull
from scipy.stats import gaussian_kde
from scipy.stats import variation
from sklearn.cluster import DBSCAN
from sklearn import datasets, decomposition, ensemble, random_projection
import numpy as np
from rtree import index
import matplotlib
matplotlib.use('TkAgg') # prevents Matplotlib related crashes --> self.tk.call('image', 'delete', self.name)
import matplotlib.pyplot as plt
from matplotlib.widgets import LassoSelector
from matplotlib import path
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.colors as cols
from mpl_toolkits.mplot3d import art3d
import math
from math import dist
import time
import datetime
import pickle
import io
from functools import reduce
import warnings
import multiprocessing
warnings.filterwarnings("ignore")
# NORMALIZE
def normalize(lst):
s = sum(lst)
return map(lambda x: float(x)/s, lst)
# CUSTOM COLORMAP
def custom_colormap(colorlist,segments):
cmap = LinearSegmentedColormap.from_list('mycmap', colorlist) # gradient cmap
N = segments
colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
colors_rgba = cmap(colors_i)
indices = np.linspace(0, 1., N+1)
cdict = {}
for ki,key in enumerate(('red','green','blue')):
cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in range(N+1) ]
cmap_s = cols.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024) # segmented colormap
return cmap,cmap_s
# SIMPLE CONVEX HULL AROUND SPLASH CLUSTERS
def hull(points):
points = np.array(points)
hull = ConvexHull(points)
hullarea = hull.volume
vertices = hull.vertices
vertices = np.append(vertices,vertices[0])
hullpoints = np.array(points[hull.vertices])
return hullpoints,hullarea
# DBSCAN
def dbscan(points,epsilon,minpts):
db = DBSCAN(eps=epsilon, min_samples=minpts).fit(points)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_ # which sample belongs to which cluster
clusterlist = list(set(labels)) # list of clusters
return labels,clusterlist
# CREATE AND DISPLAY EACH SPLASH MOLECULE
def initialise_particles(graph):
colors = ["#0f0","#010"]
particles=100
particle_size=1
xmin =-180
xmax=180
ymin=-100
ymax=100
obj_list = []
fill,line=colors
for i in range(particles):
startpos = [random.randint(xmin,xmax),random.randint(ymin,ymax)]
obj = graph.draw_circle(startpos,particle_size,fill_color=fill,line_color=line,line_width=0)
xm = random.uniform(-1, 1)
ym = random.uniform(-1, 1)
obj_list.append([obj,startpos,xm,ym])
return obj_list
# CREATE ANIMATED SPLASH
def create_splash():
stepsize=4
slowdown = 15
xmin =-300
xmax=300
ymin=-100
ymax=100
epsilon=10
minpts=3
timeout=50
clusters = []
cluster_update = 250
cluster_color = "#900"
canvas="#000"
ct = 0
sg.theme('DARKGREY11')
graph = sg.Graph((xmax-xmin,ymax-ymin),graph_bottom_left = (xmin,ymin),graph_top_right = (xmax,ymax),background_color=canvas,key="-GRAPH-",pad=(0,0))
layout = [
[graph],
[sg.Button("OK",key="-OK-")]
]
splash = sg.Window("Cluster Sim",layout, no_titlebar = True,finalize=True,alpha_channel=0.9,grab_anywhere=True,element_justification="c")
obj_list=initialise_particles(graph)
graph.DrawText("S E G N A S T I C 2 C v{}".format(last_changed),(0,70),color="white",font=("Any",16),text_location="center")
graph.DrawText("Design and coding: Tristan Wallis",(0,45),color="white",font=("Any",10),text_location="center")
graph.DrawText("Additional coding: Kyle Young, Alex McCann",(0,30),color="white",font=("Any",10),text_location="center")
graph.DrawText("Debugging: Sophie Huiyi Hou, Kye Kudo, Alex McCann",(0,15),color="white",font=("Any",10),text_location="center")
graph.DrawText("Queensland Brain Institute",(0,0),color="white",font=("Any",10),text_location="center")
graph.DrawText("The University of Queensland",(0,-15),color="white",font=("Any",10),text_location="center")
graph.DrawText("Fred Meunier f.meunier@uq.edu.au",(0,-30),color="white",font=("Any",10),text_location="center")
graph.DrawText("FreeSimpleGUI: https://pypi.org/project/FreeSimpleGUI/",(0,-55),color="white",font=("Any",10),text_location="center")
graph.DrawText("Rtree: https://pypi.org/project/Rtree/",(0,-75),color="white",font=("Any",10),text_location="center")
while True:
# READ AND UPDATE VALUES
event, values = splash.read(timeout=timeout)
ct += timeout
# Exit
if event in (sg.WIN_CLOSED, '-OK-'):
break
# UPDATE EACH PARTICLE
dists = [] # distances travelled by all particles
# Dbscan to check for interacting points
allpoints = [i[1] for i in obj_list]
labels,clusterlist = dbscan(allpoints,epsilon,minpts)
# Alter particle movement
for num,obj in enumerate(obj_list):
dot,pos,xm,ym = obj
splash["-GRAPH-"].move_figure(dot,xm,ym)
pos[0]+=xm
pos[1]+=ym
# Closed universe
if pos[0] > xmax:
pos[0] = xmin
splash["-GRAPH-"].RelocateFigure(dot,pos[0],pos[1])
if pos[0] < xmin:
pos[0] = xmax
splash["-GRAPH-"].RelocateFigure(dot,pos[0],pos[1])
if pos[1] > ymax:
pos[1] = ymin
splash["-GRAPH-"].RelocateFigure(dot,pos[0],pos[1])
if pos[1] < ymin:
pos[1] = ymax
splash["-GRAPH-"].RelocateFigure(dot,pos[0],pos[1])
# Lower speed in a cluster
if labels[num] > -1:
obj[2] = random.uniform(-(slowdown/100)*stepsize, (slowdown/100)*stepsize)
obj[3] = random.uniform(-(slowdown/100)*stepsize, (slowdown/100)*stepsize)
# Randomly change direction and speed
else:
obj[2] = random.uniform(-stepsize, stepsize)
obj[3] = random.uniform(-stepsize, stepsize)
# Draw borders around clusters
if ct > cluster_update:
ct = 0
if len(clusters) > 0:
for cluster in clusters:
splash["-GRAPH-"].delete_figure(cluster)
clusters = []
allpoints = [i[1] for i in obj_list]
labels,clusterlist = dbscan(allpoints,epsilon*1.5,minpts)
clusterdict = {i:[] for i in clusterlist}
for num,obj in enumerate(obj_list):
clusterdict[labels[num]].append(obj[1])
for clust in clusterdict:
if clust > -1:
clusterpoints = clusterdict[clust]
try:
hullpoints,hullarea = hull(clusterpoints)
cluster = splash["-GRAPH-"].draw_polygon(hullpoints,line_width=2,line_color=cluster_color,fill_color=canvas)
splash["-GRAPH-"].send_figure_to_back(cluster)
clusters.append(cluster)
except:
pass
return splash
# USE HARD CODED DEFAULTS
def reset_defaults():
print ("Using default GUI settings...")
global traj_prob,detection_alpha,minlength,maxlength,acq_time,time_threshold,segment_threshold,canvas_color,plot_trajectories,plot_centroids,plot_clusters,plot_colorbar,line_width,line_alpha,line_color,line_color2,centroid_size,centroid_alpha,centroid_color,cluster_alpha,cluster_linetype,cluster_width,saveformat,savedpi,savetransparency,savefolder,selection_density,autoplot,autocluster,cluster_fill,auto_metric,overlap_override,plotxmin,plotxmax,plotymin,plotymax,frame_time,tmin,tmax,cluster_colorby,plot_hotspots,hotspot_alpha,hotspot_linetype,hotspot_width,hotspot_color,hotspot_radius,balance,axes_3d,radius_thresh,msd_filter, pixel
traj_prob = 1
detection_alpha = 0.05
selection_density = 0
minlength = 8
maxlength = 1000
acq_time = 320
frame_time = 0.02
time_threshold = 20
segment_threshold = 1
overlap_override = 0
canvas_color = "black"
plot_trajectories = True
plot_centroids = False
plot_clusters = True
plot_hotspots= True
plot_colorbar = True
line_width = 1.5
line_alpha = 0.25
line_color = "cyan"
line_color2 = "magenta"
centroid_size = 5
centroid_alpha = 0.75
centroid_color = "white"
cluster_colorby = "time"
cluster_width = 2
cluster_alpha = 1
cluster_linetype = "solid"
cluster_fill = False
saveformat = "png"
savedpi = 300
savetransparency = False
autoplot=True
autocluster=True
radius_thresh = 0.2
auto_metric=False
plotxmin=""
plotxmax=""
plotymin=""
plotymax=""
msd_filter = False
hotspot_width = 2.5
hotspot_alpha = 1
hotspot_linetype = "dotted"
hotspot_color = "white"
hotspot_radius = 1.0
balance =True
axes_3d = True
pixel = 0.106
return
# SAVE SETTINGS
def save_defaults():
print ("Saving GUI settings to segnastic2c_gui.defaults...")
with open("segnastic2c_gui.defaults","w") as outfile:
outfile.write("{}\t{}\n".format("Trajectory probability",traj_prob))
outfile.write("{}\t{}\n".format("Raw trajectory detection plot opacity",detection_alpha))
outfile.write("{}\t{}\n".format("Selection density",selection_density))
outfile.write("{}\t{}\n".format("Trajectory minimum length",minlength))
outfile.write("{}\t{}\n".format("Trajectory maximum length",maxlength))
outfile.write("{}\t{}\n".format("Acquisition time (s)",acq_time))
outfile.write("{}\t{}\n".format("Frame time (s)",frame_time))
outfile.write("{}\t{}\n".format("Time threshold (s)",time_threshold))
outfile.write("{}\t{}\n".format("Segment threshold",segment_threshold))
outfile.write("{}\t{}\n".format("Overlap override",overlap_override))
outfile.write("{}\t{}\n".format("Canvas color",canvas_color))
outfile.write("{}\t{}\n".format("Plot trajectories",plot_trajectories))
outfile.write("{}\t{}\n".format("Plot centroids",plot_centroids))
outfile.write("{}\t{}\n".format("Plot clusters",plot_clusters))
outfile.write("{}\t{}\n".format("Plot hotspots",plot_hotspots))
outfile.write("{}\t{}\n".format("Plot colorbar",plot_colorbar))
outfile.write("{}\t{}\n".format("Trajectory line width",line_width))
outfile.write("{}\t{}\n".format("Trajectory line color",line_color))
outfile.write("{}\t{}\n".format("Trajectory line color 2",line_color2))
outfile.write("{}\t{}\n".format("Trajectory line opacity",line_alpha))
outfile.write("{}\t{}\n".format("Centroid size",centroid_size))
outfile.write("{}\t{}\n".format("Centroid color",centroid_color))
outfile.write("{}\t{}\n".format("Centroid opacity",centroid_alpha))
outfile.write("{}\t{}\n".format("Cluster fill",cluster_fill))
outfile.write("{}\t{}\n".format("Cluster color by",cluster_colorby))
outfile.write("{}\t{}\n".format("Cluster line width",cluster_width))
outfile.write("{}\t{}\n".format("Cluster line opacity",cluster_alpha))
outfile.write("{}\t{}\n".format("Cluster line type",cluster_linetype))
outfile.write("{}\t{}\n".format("Hotspot line width",hotspot_width))
outfile.write("{}\t{}\n".format("Hotspot line opacity",hotspot_alpha))
outfile.write("{}\t{}\n".format("Hotspot line type",hotspot_linetype))
outfile.write("{}\t{}\n".format("Hotspot radius",hotspot_radius))
outfile.write("{}\t{}\n".format("Hotspot color",hotspot_color))
outfile.write("{}\t{}\n".format("Plot save format",saveformat))
outfile.write("{}\t{}\n".format("Plot save dpi",savedpi))
outfile.write("{}\t{}\n".format("Plot background transparent",savetransparency))
outfile.write("{}\t{}\n".format("Auto cluster",autocluster))
outfile.write("{}\t{}\n".format("Auto plot",autoplot))
outfile.write("{}\t{}\n".format("Cluster radius screen",radius_thresh))
outfile.write("{}\t{}\n".format("Auto metric",auto_metric))
outfile.write("{}\t{}\n".format("MSD filter",msd_filter))
outfile.write("{}\t{}\n".format("Color balance",balance))
outfile.write("{}\t{}\n".format("3D axes",axes_3d))
outfile.write("{}\t{}\n".format("Pixel size (um)",pixel))
return
# LOAD DEFAULTS
def load_defaults():
global defaultdict,traj_prob,detection_alpha,minlength,maxlength,acq_time,time_threshold,segment_threshold,canvas_color,plot_trajectories,plot_centroids,plot_clusters,plot_colorbar,line_width,line_alpha,line_color,line_color2,centroid_size,centroid_alpha,centroid_color,cluster_alpha,cluster_linetype,cluster_width,saveformat,savedpi,savetransparency,savefolder,selection_density,autoplot,autocluster,cluster_fill,auto_metric,overlap_override,plotxmin,plotxmax,plotymin,plotymax,frame_time,tmin,tmax,cluster_colorby,plot_hotspots,hotspot_alpha,hotspot_linetype,hotspot_width,hotspot_color,hotspot_radius,balance,axes_3d,radius_thresh,msd_filter, pixel
try:
with open ("segnastic2c_gui.defaults","r") as infile:
print ("Loading GUI settings from segnastic2c_gui.defaults...")
defaultdict = {}
for line in infile:
spl = line.split("\t")
defaultdict[spl[0]] = spl[1].strip()
traj_prob = float(defaultdict["Trajectory probability"])
detection_alpha = float(defaultdict["Raw trajectory detection plot opacity"])
selection_density = float(defaultdict["Selection density"])
minlength = int(defaultdict["Trajectory minimum length"])
maxlength = int(defaultdict["Trajectory maximum length"])
acq_time = int(defaultdict["Acquisition time (s)"])
frame_time = float(defaultdict["Frame time (s)"])
time_threshold = int(defaultdict["Time threshold (s)"])
segment_threshold = int(defaultdict["Segment threshold"])
overlap_override = int(defaultdict["Overlap override"])
canvas_color = defaultdict["Canvas color"]
plot_trajectories = defaultdict["Plot trajectories"]
if plot_trajectories == "True":
plot_trajectories = True
if plot_trajectories == "False":
plot_trajectories = False
plot_centroids = defaultdict["Plot centroids"]
if plot_centroids == "True":
plot_centroids = True
if plot_centroids == "False":
plot_centroids = False
plot_clusters = defaultdict["Plot clusters"]
if plot_clusters == "True":
plot_clusters = True
if plot_clusters == "False":
plot_clusters = False
plot_colorbar = defaultdict["Plot colorbar"]
if plot_colorbar == "True":
plot_colorbar = True
if plot_colorbar == "False":
plot_colorbar = False
plot_hotspots = defaultdict["Plot hotspots"]
if plot_hotspots == "True":
plot_hotspots = True
if plot_hotspots == "False":
plot_hotspots = False
line_width = float(defaultdict["Trajectory line width"])
line_alpha = float(defaultdict["Trajectory line opacity"])
line_color = defaultdict["Trajectory line color"]
line_color2 = defaultdict["Trajectory line color 2"]
centroid_size = int(defaultdict["Centroid size"])
centroid_alpha = float(defaultdict["Centroid opacity"])
centroid_color = defaultdict["Centroid color"]
cluster_colorby = defaultdict["Cluster color by"]
cluster_width = float(defaultdict["Cluster line width"])
cluster_alpha = float(defaultdict["Cluster line opacity"])
cluster_linetype = defaultdict["Cluster line type"]
cluster_fill = defaultdict["Cluster fill"]
if cluster_fill == "True":
cluster_fill = True
if cluster_fill == "False":
cluster_fill = False
hotspot_color = defaultdict["Hotspot color"]
hotspot_radius = defaultdict["Hotspot radius"]
hotspot_width = float(defaultdict["Hotspot line width"])
hotspot_alpha = float(defaultdict["Hotspot line opacity"])
hotspot_linetype = defaultdict["Hotspot line type"]
saveformat = defaultdict["Plot save format"]
savedpi = defaultdict["Plot save dpi"]
savetransparency = defaultdict["Plot background transparent"]
if savetransparency == "True":
savetransparency = True
if savetransparency == "False":
savetransparency = False
autoplot = defaultdict["Auto plot"]
if autoplot == "True":
autoplot = True
if autoplot == "False":
autoplot = False
autocluster = defaultdict["Auto cluster"]
if autocluster == "True":
autocluster = True
if autocluster == "False":
autocluster = False
radius_thresh = defaultdict["Cluster radius screen"]
auto_metric = defaultdict["Auto metric"]
if auto_metric == "True":
auto_metric = True
if auto_metric == "False":
auto_metric = False
plotxmin=""
plotxmax=""
plotymin=""
plotymax=""
msd_filter = defaultdict["MSD filter"]
if msd_filter == "True":
msd_filter = True
if msd_filter == "False":
msd_filter = False
balance = defaultdict["Color balance"]
if balance == "True":
balance = True
if balance == "False":
balance = False
axes_3d = defaultdict["3D axes"]
if axes_3d == "True":
axes_3d = True
if axes_3d == "False":
axes_3d = False
pixel = defaultdict["Pixel size (um)"]
except:
print ("Settings could not be loaded")
reset_defaults()
return
# UPDATE GUI BUTTONS
def update_buttons():
if len(infilename) > 0 and len(infilename2) > 0:
window.Element("-PLOTBUTTON-").update(button_color=("white","#111111"),disabled=False)
window.Element("-INFILE-").InitialFolder = os.path.dirname(infilename)
window.Element("-INFILE2-").InitialFolder = os.path.dirname(infilename2)
else:
window.Element("-PLOTBUTTON-").update(button_color=("white","gray"),disabled=True)
if len(trajdict) > 0:
for buttonkey in ["-R1-","-R2-","-R3-","-R4-","-R5-","-R6-","-R7-","-R8-"]:
window.Element(buttonkey).update(disabled=False)
else:
for buttonkey in ["-R1-","-R2-","-R3-","-R4-","-R5-","-R6-","-R7-","-R8-"]:
window.Element(buttonkey).update(disabled=True)
if len(roi_list) > 0:
window.Element("-SELECTBUTTON-").update(button_color=("white","#111111"),disabled=False)
else:
window.Element("-SELECTBUTTON-").update(button_color=("white","gray"),disabled=True)
if len(sel_traj) > 0:
window.Element("-CLUSTERBUTTON-").update(button_color=("white","#111111"),disabled=False)
else:
window.Element("-CLUSTERBUTTON-").update(button_color=("white","gray"),disabled=True)
if len(clusterdict) > 0:
window.Element("-DISPLAYBUTTON-").update(button_color=("white","#111111"),disabled=False)
if plotflag:
window.Element("-SAVEBUTTON-").update(button_color=("white","#111111"),disabled=False)
window.Element("-CANVASCOLORCHOOSE-").update(disabled=False)
window.Element("-LINECOLORCHOOSE-").update(disabled=False)
window.Element("-LINECOLORCHOOSE2-").update(disabled=False)
window.Element("-CENTROIDCOLORCHOOSE-").update(disabled=False)
window.Element("-HOTSPOTCOLORCHOOSE-").update(disabled=False)
window.Element("-SAVEANALYSES-").update(button_color=("white","#111111"),disabled=False)
for buttonkey in ["-M1-","-M2-","-M3-","-M4-","-M5-","-M6-","-M7-","-M8-"]:
window.Element(buttonkey).update(disabled=False)
else:
window.Element("-DISPLAYBUTTON-").update(button_color=("white","gray"),disabled=True)
window.Element("-SAVEBUTTON-").update(button_color=("white","gray"),disabled=True)
window.Element("-CANVASCOLORCHOOSE-").update(disabled=True)
window.Element("-LINECOLORCHOOSE-").update(disabled=True)
window.Element("-LINECOLORCHOOSE2-").update(disabled=True)
window.Element("-CENTROIDCOLORCHOOSE-").update(disabled=True)
window.Element("-HOTSPOTCOLORCHOOSE-").update(disabled=True)
window.Element("-SAVEANALYSES-").update(button_color=("white","gray"),disabled=True)
for buttonkey in ["-M1-","-M2-","-M3-","-M4-","-M5-","-M6-","-M7-","-M8-"]:
window.Element(buttonkey).update(disabled=True)
window.Element("-TRAJPROB-").update(traj_prob)
window.Element("-DETECTIONALPHA-").update(detection_alpha)
window.Element("-SELECTIONDENSITY-").update(selection_density)
window.Element("-MINLENGTH-").update(minlength)
window.Element("-MAXLENGTH-").update(maxlength)
window.Element("-ACQTIME-").update(acq_time)
window.Element("-FRAMETIME-").update(frame_time)
window.Element("-TIMETHRESHOLD-").update(time_threshold)
window.Element("-SEGMENTTHRESHOLD-").update(segment_threshold)
window.Element("-OVERRIDE-").update(overlap_override)
window.Element("-CANVASCOLORCHOOSE-").update("Choose",button_color=("gray",canvas_color))
window.Element("-CANVASCOLOR-").update(canvas_color)
window.Element("-TRAJECTORIES-").update(plot_trajectories)
window.Element("-CENTROIDS-").update(plot_centroids)
window.Element("-CLUSTERS-").update(plot_clusters)
window.Element("-HOTSPOTS-").update(plot_hotspots)
window.Element("-COLORBAR-").update(plot_colorbar)
window.Element("-LINEWIDTH-").update(line_width)
window.Element("-LINEALPHA-").update(line_alpha)
window.Element("-LINECOLORCHOOSE-").update("Choose",button_color=("gray",line_color))
window.Element("-LINECOLORCHOOSE2-").update("Choose",button_color=("gray",line_color2))
window.Element("-LINECOLOR-").update(line_color)
window.Element("-LINECOLOR2-").update(line_color2)
window.Element("-CENTROIDSIZE-").update(centroid_size)
window.Element("-CENTROIDALPHA-").update(centroid_alpha)
window.Element("-CENTROIDCOLORCHOOSE-").update("Choose",button_color=("gray",centroid_color))
window.Element("-CENTROIDCOLOR-").update(centroid_color)
window.Element("-CLUSTERWIDTH-").update(cluster_width)
window.Element("-CLUSTERCOLORBY-").update(cluster_colorby)
window.Element("-CLUSTERALPHA-").update(cluster_alpha)
window.Element("-CLUSTERLINETYPE-").update(cluster_linetype)
window.Element("-CLUSTERFILL-").update(cluster_fill)
window.Element("-HOTSPOTCOLORCHOOSE-").update("Choose",button_color=("gray",hotspot_color))
window.Element("-HOTSPOTCOLOR-").update(hotspot_color)
window.Element("-HOTSPOTWIDTH-").update(hotspot_width)
window.Element("-HOTSPOTALPHA-").update(hotspot_alpha)
window.Element("-HOTSPOTLINETYPE-").update(hotspot_linetype)
window.Element("-HOTSPOTRADIUS-").update(hotspot_radius)
window.Element("-SAVEFORMAT-").update(saveformat)
window.Element("-SAVETRANSPARENCY-").update(savetransparency)
window.Element("-SAVEDPI-").update(savedpi)
window.Element("-SAVEFOLDER-").update(savefolder)
window.Element("-RADIUSTHRESH-").update(radius_thresh)
window.Element("-AUTOCLUSTER-").update(autocluster)
window.Element("-AUTOPLOT-").update(autoplot)
window.Element("-AUTOMETRIC-").update(auto_metric)
window.Element("-PLOTXMIN-").update(plotxmin)
window.Element("-PLOTXMAX-").update(plotxmax)
window.Element("-PLOTYMIN-").update(plotymin)
window.Element("-PLOTYMAX-").update(plotymax)
window.Element("-MSDFILTER-").update(msd_filter)
window.Element("-TMIN-").update(tmin)
window.Element("-TMAX-").update(tmax)
window.Element("-BALANCE-").update(balance)
window.Element("-AXES3D-").update(axes_3d)
window.Element("-PIXEL-").update(pixel)
return
# CHECK VARIABLES
def check_variables():
global traj_prob,detection_alpha,minlength,maxlength,acq_time,time_threshold,segment_threshold,canvas_color,plot_trajectories,plot_centroids,plot_clusters,line_width,line_alpha,line_color,line_color2,centroid_size,centroid_alpha,centroid_color,cluster_alpha,cluster_linetype,cluster_width,saveformat,savedpi,savetransparency,savefolder,selection_density,overlap_override,plotxmin,plotxmax,plotymin,plotymax,frame_time,tmin,tmax,cluster_colorby,plot_hotspots,hotspot_alpha,hotspot_linetype,hotspot_width,hotspot_color,hotspot_radius,radius_thresh,balance,pixel
if traj_prob not in [0.01,0.05,0.1,0.25,0.5,0.75,1.0]:
traj_prob = 1.0
if detection_alpha not in [0.01,0.05,0.1,0.25,0.5,0.75,1.0]:
detection_alpha = 0.25
try:
selection_density = float(selection_density)
if selection_density < 0:
selection_density = 0
except:
selection_density = 0
try:
minlength = int(minlength)
if minlength < 5:
minlength = 5
except:
minlength = 5
try:
maxlength = int(maxlength)
except:
maxlength = 1000
if minlength > maxlength:
minlength = 5
maxlength = 1000
try:
pixel = float(pixel)
if pixel <= 0:
pixel = 0.106
except:
pixel = 0.106
try:
acq_time = int(acq_time)
if acq_time < 1:
acq_time = 1
except:
acq_time = 320
try:
frame_time = float(frame_time)
if frame_time <= 0:
frame_time = 0.02
except:
frame_time = 0.02
try:
time_threshold = int(time_threshold)
if time_threshold < 1:
time_threshold = 1
except:
time_threshold = 20
try:
segment_threshold = int(segment_threshold)
if segment_threshold < 1:
segment_threshold = 1
except:
segment_threshold = 1
try:
overlap_override = int(overlap_override)
if overlap_override < 0:
overlap_override = 0
except:
overlap_override = 0
try:
radius_thresh = float(radius_thresh)
if radius_thresh < 0.001:
radius_thresh = 0.2
except:
radius_thresh = 0.2
if line_width not in [0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0]:
line_width = 0.25
if line_alpha not in [0.01,0.05,0.1,0.25,0.5,0.75,1.0]:
line_alpha = 0.25
if centroid_size not in [1,2,5,10,20,50]:
centroid_size = 5
if centroid_alpha not in [0.01,0.05,0.1,0.25,0.5,0.75,1.0]:
centroid_alpha = 0.75
if cluster_width not in [0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0]:
cluster_width = 1.5
if cluster_colorby not in ["time","composition"]:
cluster_colorby = "time"
if cluster_alpha not in [0.01,0.05,0.1,0.25,0.5,0.75,1.0]:
cluster_alpha = 1.0
if cluster_linetype not in ["solid","dotted","dashed"]:
cluster_linetype = "solid"
if hotspot_width not in [0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0]:
hotspot_width = 1.5
if hotspot_alpha not in [0.01,0.05,0.1,0.25,0.5,0.75,1.0]:
hotspot_alpha = 1.0
if hotspot_linetype not in ["solid","dotted","dashed"]:
hotspot_linetype = "dotted"
if hotspot_radius not in [0.1,0.25,0.5,1.0,1.25,1.5,1.75,2.0]:
hotspot_radius = 1.0
if saveformat not in ["eps","pdf","png","ps","svg"]:
saveformat = "png"
if savedpi not in [50,100,300,600,1200]:
savedpi = 300
if savefolder == "":
savefolder = os.path.dirname(infilename)
# If user presses cancel when choosing a color
if canvas_color == "None":
try:
canvas_color = defaultdict["Canvas color"]
except:
canvas_color = "black"
if line_color == "None":
try:
line_color = defaultdict["Trajectory line color 1"]
except:
line_color = "cyan"
if line_color2 == "None":
try:
line_color2 = defaultdict["Trajectory line color 2"]
except:
line_color2 = "magenta"
if centroid_color == "None":
try:
centroid_color = defaultdict["Centroid color"]
except:
centroid_color = "white"
if hotspot_color == "None":
try:
hotspot_color = defaultdict["Hotspot color"]
except:
hotspot_color = "white"
try:
plotxmin = float(plotxmin)
except:
plotxmin = ""
try:
plotxmax = float(plotxmax)
except:
plotxmax = ""
try:
plotymin = float(plotymin)
except:
plotymin = ""
try:
plotymax = float(plotymax)
except:
plotymax = ""
try:
tmin = float(tmin)
if tmin < 0 or tmin > acq_time:
tmin = 0
except:
tmin = 0
try:
tmax = float(tmax)
if tmax < 0 or tmax > acq_time:
tmax = acq_time
except:
tmin = acq_time
return
# GET DIMENSIONS OF ZOOM
def ondraw(event):
global selverts
zx = ax0.get_xlim()
zy = ax0.get_ylim()
selverts = [[zx[0],zy[0]],[zx[0],zy[1]],[zx[1],zy[1]],[zx[1],zy[0]],[zx[0],zy[0]]]
selarea =PolyArea(list(zip(*selverts))[0],list(zip(*selverts))[1])
return
# GET HAND DRAWN REGION
def onselect(verts):
global selverts
# remove negative x,y values
for num,vert in enumerate(verts):
x_vert = vert[0]
y_vert = vert[1]
if x_vert < 0:
x_vert = 0.0
if y_vert < 0:
y_vert = 0.0
verts[num] = (x_vert,y_vert)
p = path.Path(verts)
selverts = verts[:]
selverts.append(selverts[0])
selarea =PolyArea(list(zip(*selverts))[0],list(zip(*selverts))[1])
return
# AREA IN POLYGON
def PolyArea(x,y):
return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))
# USE SELECTION AREA
def use_roi(selverts,color):
all_selverts.append(selverts)
vx,vy = list(zip(*selverts))
roi, = ax0.plot(vx,vy,linewidth=2,c=color,alpha=1)
roi_list.append(roi)
plt.xlim(xlims)
plt.ylim(ylims)
plt.show(block=False)
if len(roi_list) <= 1:
window.Element("-SEPARATE-").update(disabled = True)
elif len(roi_list) >1:
window.Element("-SEPARATE-").update(disabled = False)
return
# READ ROI DATA
def read_roi():
#Check for ROI file type
roi_file_split = roi_file.split(".")
if roi_file_split[-1] == "rgn":
#PalmTracer .rgn file
window.Element("-PIXEL_TEXT-").update(visible = True)
window.Element("-PIXEL-").update(visible = True)
window.Element("-REPLOT_ROI-").update(visible = True)
with open (roi_file, "r") as infilename:
RGN_data = infilename.read()
RGN_list = [x.split(", ") for x in RGN_data.split("\n")] #Info for each ROI is listed on a new line -> separate ROI info in list
ROI_n = 0
ROI_X_Y = np.array([[0,0,0],[0,0,0]])
for ROI in RGN_list:
if ROI[0] != "":
ROI_n = ROI_n +1
col_6_data = ROI[6]
space2comma = col_6_data.split(" ") #Data in this column is separated by spaces
n_coord_pairs = space2comma[1] #This position contains the number of coordinate pairs
x_coord_pix = []
y_coord_pix = []
x_coord_pix.append(space2comma[2::2]) #File contains alternating x,y coordinates
x_coord_pix = x_coord_pix.pop()
x_coord_pix = ([int(x) for x in x_coord_pix])
y_coord_pix.append(space2comma[3::2])
y_coord_pix = y_coord_pix.pop()
y_coord_pix = ([int(y) for y in y_coord_pix])
#Convert pixels to microns
x_coord_micron_list = []
y_coord_micron_list = []
ROI_list = []
for i in range(0, len(x_coord_pix)):
x_coord_micron_list.append(float(pixel)*x_coord_pix[i])
y_coord_micron_list.append(float(pixel)*y_coord_pix[i])
ROI_list.append(0)
int_n_coord_pairs = int(n_coord_pairs)
output_file = np.zeros((int_n_coord_pairs+1, 3))
cnt = 0
while cnt < int_n_coord_pairs:
for r in output_file:
output_file[cnt,0] = int(ROI_n-1)
cnt+=1
if cnt == int_n_coord_pairs:
output_file[cnt,0] = int(ROI_n-1)
cnt = 0
while cnt < len(x_coord_micron_list):
for x in x_coord_micron_list:
output_file[cnt,1] = x
cnt+=1
if cnt == int_n_coord_pairs:
output_file[cnt,1] = x_coord_micron_list[0]
cnt = 0
while cnt < len(y_coord_micron_list):
for y in y_coord_micron_list:
output_file[cnt,2] = y
cnt+=1
if cnt == int_n_coord_pairs:
output_file[cnt,2] = y_coord_micron_list[0]
ROI_X_Y = np.append(ROI_X_Y, output_file, axis = 0)
else:
break
ROI_X_Y = np.delete(ROI_X_Y, 0, 0)
ROI_X_Y = np.delete(ROI_X_Y, 0, 0)
roidict = {}
spl = []
for line in ROI_X_Y:
try:
roi = int(float(line[0]))
x = float(line[1])
y = float(line[2])
try:
roidict[roi].append([x,y])
except:
roidict[roi] = []
roidict[roi].append([x,y])
except:
pass
if len(roidict) == 0:
sg.Popup("Alert", "No ROIs found")
else:
for roi in roidict:
selverts = roidict[roi]
use_roi(selverts,"orange")
return
return
elif roi_file_split[-1] == "csv":
#FIJI .csv file
window.Element("-PIXEL_TEXT-").update(visible = True)
window.Element("-PIXEL-").update(visible = True)
window.Element("-REPLOT_ROI-").update(visible = True)
roidict = {}
ct = 0
with open (roi_file, "r") as infilename:
for line in infilename:
ct+=1
if ct >1:
if len(line) > 2:
csv_split = line.split(',')
roi = 0
x = float(csv_split[0])
y = float(csv_split[1])
x_um = x*float(pixel)
y_um = y*float(pixel)
try:
roidict[roi].append([x_um,y_um])
except:
roidict[roi] = []
roidict[roi].append([x_um,y_um])
if len(roidict) == 0:
sg.Popup("Alert", "No ROIs found")
else:
selverts = roidict[roi]
use_roi(selverts,"orange")
return
return
else:
#NASTIC roi_coordinates.tsv file / SEGNASTIC roi_coordinates.tsv file
window.Element("-PIXEL_TEXT-").update(visible=False)
window.Element("-PIXEL-").update(visible=False)
window.Element("-REPLOT_ROI-").update(visible = False)
roidict = {}
try:
with open (roi_file,"r") as infile:
for line in infile:
spl = line.split("\t")
try:
roi = int(spl[0])
x = float(spl[1])
y = float(spl[2])
try:
roidict[roi].append([x,y])
except:
roidict[roi] = []
roidict[roi].append([x,y])
except:
pass
if len(roidict) == 0:
sg.Popup("Alert","No ROIs found")
else:
for roi in roidict:
selverts =roidict[roi]
use_roi(selverts,"orange")
except:
pass
return
# CONVEX HULL OF EXTERNAL POINTS, AND THEN INTERNAL POINTS
def double_hull(points):
# Get the hull of the original points
all_points = np.array(points)
ext_hull = ConvexHull(all_points)
ext_area = ext_hull.volume
vertices = ext_hull.vertices
vertices = np.append(vertices,vertices[0])
ext_x = [all_points[vertex][0] for vertex in vertices]
ext_y = [all_points[vertex][1] for vertex in vertices]
ext_points = np.array(all_points[ext_hull.vertices])
# Get the hull of the points inside the hull
int_points = np.array([x for x in all_points if x not in ext_points])
try:
int_hull = ConvexHull(int_points)
int_area = int_hull.volume
vertices = int_hull.vertices
vertices = np.append(vertices,vertices[0])
int_x = [int_points[vertex][0] for vertex in vertices]
int_y = [int_points[vertex][1] for vertex in vertices]
except:
int_x,int_y,int_area = ext_x,ext_y,ext_area
return ext_x,ext_y,ext_area,int_x,int_y,int_area
# DISTILL OVERLAPPING LISTS
def distill_list(overlappers):
sets = [set(x) for x in overlappers]
allelts = set.union(*sets)
components = {x: {x} for x in allelts}
component = {x: x for x in allelts}
for s in sets:
comp = sorted({component[x] for x in s})
mergeto = comp[0]
for mergefrom in comp[1:]:
components[mergeto] |= components[mergefrom]
for x in components[mergefrom]:
component[x] = mergeto
del components[mergefrom]
distilled = components.values()
distilled = [list(x) for x in distilled]
return distilled
# FIND SEGMENTS WHOSE BOUNDING BOXES OVERLAP IN SPACE AND TIME
def segment_overlap(segdict,time_threshold,av_msd):
# Create and populate 3D r-tree
p = index.Property()
p.dimension=3
idx_3d = index.Index(properties=p)
intree = []
indices = segdict.keys()
for idx in indices:
if segdict[idx]["msds"][0] < av_msd: # potentially screen by MSD of parent traj