forked from tristanwallis/smlm_clustering
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvoronoi_gui.py
More file actions
1748 lines (1603 loc) · 67.3 KB
/
voronoi_gui.py
File metadata and controls
1748 lines (1603 loc) · 67.3 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 -*-
'''
VORONOI_GUI
FREESIMPLEGUI BASED GUI FOR VORONOI CLUSTERING OF MOLECULAR TRAJECTORY DATA
Design and code: Tristan Wallis
Debugging: Sophie Huiyi Hou
Queensland Brain Institute
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 freesimplegui colorama
INPUT:
TRXYT trajectory files from Matlab
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 pythonic critiques on the 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 warnings
import math
from math import dist
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)
return [points,msds,centroid]
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
import os
from colorama import init as colorama_init
from colorama import Fore
from colorama import Style
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}VORONOI {last_changed} initialising...{Style.RESET_ALL}')
print(f'{Fore.GREEN}=================================================={Style.RESET_ALL}')
# POPUP WINDOW
popup = sg.Window("Initialising...",[[sg.T("VORONOI initialising...",font=("Arial bold",18))]],finalize=True,no_titlebar = True,alpha_channel=0.9)
import random
from sklearn.cluster import DBSCAN
from scipy.spatial import Voronoi, voronoi_plot_2d,ConvexHull
from scipy.stats import gaussian_kde
import numpy as np
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
import math
from math import dist
import time
import datetime
import os
import sys
import pickle
import io
from functools import reduce
import collections
import webbrowser
import warnings
warnings.filterwarnings("ignore")
# FUNCTIONS
# 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 =-180
xmax=180
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("VORONOI v{}".format(last_changed),(0,70),color="white",font=("Any",16),text_location="center")
graph.DrawText("Code and design: Tristan Wallis",(0,45),color="white",font=("Any",10),text_location="center")
graph.DrawText("Debugging: Sophie Huiyi Hou",(0,30),color="white",font=("Any",10),text_location="center")
graph.DrawText("Queensland Brain Institute",(0,15),color="white",font=("Any",10),text_location="center")
graph.DrawText("University of Queensland",(0,0),color="white",font=("Any",10),text_location="center")
graph.DrawText("Fred Meunier f.meunier@uq.edu.au",(0,-15),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")
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,int(minpts))
clusterdict = {i:[] for i in clusterlist}
clust_traj = [i for i in labels if i > -1]
clust_radii = []
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,voronoi_threshold,minpts,canvas_color,plot_trajectories,plot_centroids,plot_clusters,line_width,line_alpha,line_color,centroid_size,centroid_alpha,centroid_color,cluster_alpha,cluster_linetype,cluster_width,cluster_color,saveformat,savedpi,savetransparency,savefolder,selection_density,autoplot,autocluster,radius_thresh,cluster_fill,auto_metric,plotxmin,plotxmax,plotymin,plotymax
traj_prob = 1
detection_alpha = 0.1
selection_density = 0
minlength = 8
maxlength = 100
voronoi_threshold = 0.01
minpts = 3
canvas_color = "black"
plot_trajectories = True
plot_centroids = False
plot_clusters = True
line_width = 1.5
line_alpha = 0.25
line_color = "white"
centroid_size = 5
centroid_alpha = 0.75
centroid_color = "white"
cluster_width = 1.5
cluster_alpha = 1
cluster_linetype = "solid"
cluster_color = "orange"
cluster_fill = False
saveformat = "png"
savedpi = 300
savetransparency = False
autoplot=True
autocluster=True
radius_thresh=0.15
auto_metric = False
plotxmin=""
plotxmax=""
plotymin=""
plotymax=""
return
# SAVE SETTINGS
def save_defaults():
print ("Saving GUI settings to voronoi_gui.defaults...")
with open("voronoi_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("Voronoi threshold",voronoi_threshold))
outfile.write("{}\t{}\n".format("MinPts",minpts))
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("Trajectory line width",line_width))
outfile.write("{}\t{}\n".format("Trajectory line color",line_color))
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 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("Cluster line color",cluster_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("Cluster fill",cluster_fill))
outfile.write("{}\t{}\n".format("Auto metric",auto_metric))
return
# LOAD DEFAULTS
def load_defaults():
global defaultdict,traj_prob,detection_alpha,minlength,maxlength,voronoi_threshold,minpts,canvas_color,plot_trajectories,plot_centroids,plot_clusters,line_width,line_alpha,line_color,centroid_size,centroid_alpha,centroid_color,cluster_alpha,cluster_linetype,cluster_width,cluster_color,saveformat,savedpi,savetransparency,savefolder,selection_density,autoplot,autocluster,radius_thresh,cluster_fill,auto_metric,plotxmin,plotxmax,plotymin,plotymax
try:
with open ("voronoi_gui.defaults","r") as infile:
print ("Loading GUI settings from voronoi_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"])
voronoi_threshold = float(defaultdict["Voronoi threshold"])
minpts = int(defaultdict["MinPts"])
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
line_width = float(defaultdict["Trajectory line width"])
line_alpha = float(defaultdict["Trajectory line opacity"])
line_color = defaultdict["Trajectory line color"]
centroid_size = int(defaultdict["Centroid size"])
centroid_alpha = float(defaultdict["Centroid opacity"])
centroid_color = defaultdict["Centroid color"]
cluster_width = float(defaultdict["Cluster line width"])
cluster_alpha = float(defaultdict["Cluster line opacity"])
cluster_linetype = defaultdict["Cluster line type"]
cluster_color = defaultdict["Cluster line color"]
cluster_fill = defaultdict["Cluster fill"]
if cluster_fill == "True":
cluster_fill = True
if cluster_fill == "False":
cluster_fill = False
saveformat = defaultdict["Plot save format"]
savedpi = defaultdict["Plot save dpi"]
savetransparency = defaultdict["Plot background transparent"]
autoplot = defaultdict["Auto plot"]
autocluster = defaultdict["Auto cluster"]
radius_thresh = defaultdict["Cluster radius screen"]
if savetransparency == "True":
savetransparency = True
if savetransparency == "False":
savetransparency = False
if autocluster == "True":
autocluster = True
if autocluster == "False":
autocluster = False
if autoplot == "True":
autoplot = True
if autoplot == "False":
autoplot = False
auto_metric = defaultdict["Auto metric"]
if auto_metric == "True":
auto_metric = True
if auto_metric == "False":
auto_metric = False
plotxmin=""
plotxmax=""
plotymin=""
plotymax=""
except:
print ("Settings could not be loaded")
return
# UPDATE GUI BUTTONS
def update_buttons():
if len(infilename) > 0:
window.Element("-PLOTBUTTON-").update(button_color=("white","#111111"),disabled=False)
window.Element("-INFILE-").InitialFolder = os.path.dirname(infilename)
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("-CENTROIDCOLORCHOOSE-").update(disabled=False)
window.Element("-CLUSTERCOLORCHOOSE-").update(disabled=False)
window.Element("-SAVEANALYSES-").update(button_color=("white","#111111"),disabled=False)
for buttonkey in ["-M1-","-M2-","-M3-"]:
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("-CENTROIDCOLORCHOOSE-").update(disabled=True)
window.Element("-CLUSTERCOLORCHOOSE-").update(disabled=True)
window.Element("-SAVEANALYSES-").update(button_color=("white","gray"),disabled=True)
for buttonkey in ["-M1-","-M2-","-M3-"]:
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("-VOR_THRESH-").update(voronoi_threshold)
window.Element("-MINPTS-").update(minpts)
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("-LINEWIDTH-").update(line_width)
window.Element("-LINEALPHA-").update(line_alpha)
window.Element("-LINECOLORCHOOSE-").update("Choose",button_color=("gray",line_color))
window.Element("-LINECOLOR-").update(line_color)
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("-CLUSTERALPHA-").update(cluster_alpha)
window.Element("-CLUSTERCOLORCHOOSE-").update("Choose",button_color=("gray",cluster_color))
window.Element("-CLUSTERLINETYPE-").update(cluster_linetype)
window.Element("-CLUSTERFILL-").update(cluster_fill)
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("-AUTOMETRIC-").update(auto_metric)
window.Element("-PLOTXMIN-").update(plotxmin)
window.Element("-PLOTXMAX-").update(plotxmax)
window.Element("-PLOTYMIN-").update(plotymin)
window.Element("-PLOTYMAX-").update(plotymax)
return
# CHECK VARIABLES
def check_variables():
global traj_prob,detection_alpha,minlength,maxlength,voronoi_threshold,minpts,canvas_color,plot_trajectories,plot_centroids,plot_clusters,line_width,line_alpha,line_color,centroid_size,centroid_alpha,centroid_color,cluster_alpha,cluster_linetype,cluster_width,cluster_color,saveformat,savedpi,savetransparency,savefolder,selection_density,plotxmin,plotxmax,plotymin,plotymax
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 < 8:
minlength = 8
except:
minlength = 8
try:
maxlength = int(maxlength)
except:
maxlength = 100
if minlength > maxlength:
minlength = 8
maxlength = 100
try:
voronoi_threshold = float(voronoi_threshold)
if voronoi_threshold < 0.0001:
voronoi_threshold = 0.0001
except:
voronoi_threshold = 0.01
try:
minpts = int(minpts)
if minpts < 2:
minpts = 2
except:
minpts = 3
try:
radius_thresh = float(radius_thresh)
if radius_thresh < 0.001:
radius_thresh = 0.15
except:
radius_thresh = 0.15
if line_width not in [0.5,1.0,1.5,2.0,2.5,3.5,4.0,4.5,5.0]:
line_width = 1
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.5,4.0,4.5,5.0]:
cluster_width = 1.5
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 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"]
except:
line_color = "white"
if centroid_color == "None":
try:
centroid_color = defaultdict["Centroid color"]
except:
centroid_color = "white"
if cluster_color == "None":
try:
cluster_color = defaultdict["Cluster color"]
except:
cluster_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 = ""
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
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)
return
# READ ROI DATA
def read_roi():
roidict = {}
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")
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
# VORONOI TRAJECTORY DATA, EXTRACT POLYGONS
def voronoi_tessellate_data(pointarray):
vor = Voronoi(pointarray)
# Determine Voronoi polygon area associated with each point
vertices = vor.vertices.tolist()
for i in range(len(pointarray)):
region = vor.point_region[i]
indices = vor.regions[region]
if -1 not in indices: # No infinite polygons
polygon = [vertices[idx] for idx in indices]
hull = ConvexHull(polygon)
area= hull.volume # area of polygon (hull.volume gives area, hull.area gives circumference!)
'''
for selverts in all_selverts:
p = path.Path(selverts)
pointarray = [point for point in polygon if p.contains_point(point)] # screen for
if len(pointarray) < len(polygon): # no polygons protruding outside selection window
area = -1
polygon = []
'''
else:
area = -1
polygon = []
if len(polygon) > 2:
polygon.append(polygon[0])
seldict[i]["polyarea"] = area
seldict[i]["polygon"] = polygon
# LOAD AND PLOT TRXYT TAB
def trxyt_tab():
# Reset variables
global all_selverts,all_selareas,roi_list,trajdict,sel_traj,lastfile,seldict,clusterdict,x_plot,y_plot,xlims,ylims,savefolder,buf
all_selverts = [] # all ROI vertices
all_selareas = [] # all ROI areas
roi_list = [] # ROI artists
trajdict = {} # Dictionary holding raw trajectory info
sel_traj = [] # Selected trajectory indices
lastfile = "" # Force the program to load a fresh TRXYT
seldict = {} # Selected trajectories and metrics
clusterdict = {} # Cluster information
# Close open windows
for i in [1,2,3,4,5,6,7,8,9,10]:
try:
plt.close(i)
except:
pass
# Close all buffers
try:
buf0.close()
except:
pass
try:
buf1.close()
except:
pass
try:
buf2.close()
except:
pass
try:
buf3.close()
except:
pass
try:
buf4.close()
except:
pass
try:
buf5.close()
except:
pass
try:
buf6.close()
except:
pass
try:
buf7.close()
except:
pass
try:
buf8.close()
except:
pass
try:
buf9.close()
except:
pass
try:
buf10.close()
except:
pass
'''
IMPORTANT: It appears that some matlab processing of trajectory data converts trajectory numbers > 99999 into scientific notation with insufficient decimal points. eg 102103 to 1.0210e+05, 102104 to 1.0210e+05. This can cause multiple trajectories to be incorrectly merged intoa single trajectory.
For trajectories > 99999 we empirically determine whether detections are within 0.32u of each other, and assign them into a single trajectory accordingly. For trajectories <99999 we honour the existing trajectory number.
'''
if infilename != lastfile:
# Read file into dictionary
lastfile=infilename
print("Loading raw trajectory data from {}...".format(infilename))
t1=time.time()
rawtrajdict = {}
ct = 99999
x0 = -10000
y0 = -10000
with open (infilename,"r") as infile:
for line in infile:
try:
line = line.replace("\n","").replace("\r","")
spl = line.split(" ")
n = int(float(spl[0]))
x = float(spl[1])
y = float(spl[2])
t = float(spl[3])
if n > 99999:
if abs(x-x0) < 0.32 and abs(y-y0) < 0.32:
rawtrajdict[ct]["points"].append([x,y,t])
x0 = x
y0= y
else:
ct += 1
rawtrajdict[ct]= {"points":[[x,y,t]]}
x0 = x
y0=y
else:
try:
rawtrajdict[n]["points"].append([x,y,t])
except:
rawtrajdict[n]= {"points":[[x,y,t]]}
except:
pass
print("{} trajectories".format(len(rawtrajdict)))
# Don't bother with anything else if there's no trajectories
if len(rawtrajdict) == 0:
sg.popup("Alert","No trajectory information found")
else:
# Screen and display
for traj in rawtrajdict:
points = rawtrajdict[traj]["points"]
if len(points) >=minlength and len(points) <=maxlength:
trajdict[traj] = rawtrajdict[traj]
print("Plotting detections...")
ct = 0
ax0.cla() # clear last plot if present
detpoints = []
for num,traj in enumerate(trajdict):
if num%10 == 0:
bar = 100*num/(len(trajdict))
window['-PROGBAR-'].update_bar(bar)
if random.random() <= traj_prob:
ct+=1
[detpoints.append(i) for i in trajdict[traj]["points"]]
x_plot,y_plot,t_plot=zip(*detpoints)
ax0.scatter(x_plot,y_plot,c="w",s=3,linewidth=0,alpha=detection_alpha)
ax0.set_facecolor("k")
#ax0.set_title(infilename.split("/")[-1])
ax0.set_xlabel("X")
ax0.set_ylabel("Y")
xlims = plt.xlim()
ylims = plt.ylim()
# Force correct aspect using imshow - very proud of discovering this by accident
ax0.imshow([[0,1], [0,1]],
extent = (xlims[0],xlims[1],ylims[0],ylims[1]),
cmap = cmap,
interpolation = 'bicubic',
alpha=0)
plt.tight_layout()
plt.show(block=False)
window['-PROGBAR-'].update_bar(0)
t2 = time.time()
print("{} detections from {} trajectories plotted in {} sec".format(len(x_plot),ct,round(t2-t1,3)))
# Pickle this raw image
buf = io.BytesIO()
pickle.dump(ax0, buf)
buf.seek(0)
# Clear the variables for ROI selection
all_selverts = [] # all ROI vertices
all_selareas = [] # all ROI areas
roi_list = [] # ROI artists
window["-TABGROUP-"].Widget.select(1)
return
# ROI SELECTION TAB
def roi_tab():
global selverts,all_selverts,all_selareas,roi_list,trajdict,sel_traj,sel_centroids,all_selverts_copy,all_selverts_bak
# Load and apply ROIs
if event == "-R2-" and roi_file != "Load previously defined ROIs":
all_selverts_bak = [x for x in all_selverts]
roidict = read_roi()
# Clear all ROIs
if event == "-R3-" and len(roi_list) > 0:
all_selverts_bak = [x for x in all_selverts]
for roi in roi_list:
roi.remove()
roi_list = []
all_selverts = []
selverts = []
sel_traj = []
plt.show(block=False)
# Remove last added ROI
if event == "-R6-" and len(roi_list) > 0:
all_selverts_bak = [x for x in all_selverts]
roi_list[-1].remove()
roi_list.pop(-1)
all_selverts.pop(-1)
selverts = []
plt.show(block=False)
# Add ROI encompassing all detections
if event == "-R4-":
all_selverts_bak = [x for x in all_selverts]
for roi in roi_list:
roi.remove()
roi_list = list()
xmin = min(x_plot)
xmax = max(x_plot)
ymin = min(y_plot)
ymax = max(y_plot)
all_selverts = []
selverts = [[xmin,ymin],[xmax,ymin],[xmax,ymax],[xmin,ymax],[xmin,ymin]]
use_roi(selverts,"orange")
# Add current ROI
if event == "-R5-" and len(selverts) > 3:
all_selverts_bak = [x for x in all_selverts]
if selverts[0][0] != xlims[0] and selverts[0][1] != ylims[0]: # don't add entire plot
use_roi(selverts,"orange")
# Undo last ROI change
if event == "-R7-" and len(all_selverts_bak) > 0:
if len(roi_list) > 0:
for roi in roi_list:
roi.remove()
roi_list = list()
plt.show(block=False)
all_selverts = []
for selverts in all_selverts_bak:
use_roi(selverts,"orange")
# Save current ROIs
if event == "-R8-" and len(all_selverts) > 0:
stamp = '{:%Y%m%d-%H%M%S}'.format(datetime.datetime.now())
roi_save = "{}_roi_coordinates.tsv".format(stamp)
with open(roi_save,"w") as outfile:
outfile.write("ROI\tx(um)\ty(um)\n")
for roi,selverts in enumerate(all_selverts):
for coord in selverts:
outfile.write("{}\t{}\t{}\n".format(roi,coord[0],coord[1]))
print ("Current ROIs saved as {}_roi_coordinates.tsv".format(stamp))
# Select trajectories within ROIs
if event == "-SELECTBUTTON-" and len(roi_list) > 0:
print ("Selecting trajectories within {} ROIs...".format(len(roi_list)))
t1=time.time()
# Centroids for each trajectory
all_centroids = []
for num,traj in enumerate(trajdict):
if num%10 == 0:
bar = 100*num/(len(trajdict))
window['-PROGBAR-'].update_bar(bar)
points = trajdict[traj]["points"]
x,y,t=list(zip(*points))
xmean = np.average(x)
ymean = np.average(y)
tmean = np.average(t)
centroid = [xmean,ymean,tmean]
trajdict[traj]["centroid"] = centroid
all_centroids.append([centroid[0],centroid[1],traj])