-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathExTrack_GUI.py
More file actions
1336 lines (1122 loc) · 65.3 KB
/
ExTrack_GUI.py
File metadata and controls
1336 lines (1122 loc) · 65.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 -*-
"""
Created on Fri Feb 14 19:15:37 2025
@author: Franc
This code enables to use the Graphical User interface of ExTrack.
To create a stand alone version of ExTrack:
1) pip install pyinstaller
2) pyinstaller --onedir path\ExTrack_GUI.py
3) Copy the .ddl files starting with mkl into the dist\ExTrack_GUI\_internal (the mkl files can be found in C:\ Users\Franc\anaconda3\Library\bin in my case)
4) execute dist\ExTrack_GUI.exe to run the stand alone software
test commit
"""
import os
import tkinter as tk
from tkinter import filedialog
import numpy as np
print('tkinter',tk)
from tkinter import ttk
import webbrowser
import extrack
import pandas as pd
import matplotlib.pyplot as plt
from glob import glob
#ttk = tk.ttk
padx = 10 # spacing between cells of the grid in x
pady = 10 # spacing between cells of the grid in y
previous_window = None
def open_analysis_window():
global previous_window
path = path_entry.get()
print(os.path.normpath(path))
if path.endswith('.csv'):
savepath = os.path.normpath(path).rsplit(os.sep, 2)[0]
else:
savepath = os.path.normpath(path).rsplit(os.sep, 1)[0]
min_length = int(min_length_entry.get())
max_length = int(max_length_entry.get())
analysis_type = analysis_type_var.get()
LocErr_type = LocErr_type_var.get()
LocErr_input_name = LocErr_input_entry.get().split(',')
if LocErr_input_name == ['']:
LocErr_input_name = []
Optional_input_name = Optional_input_entry.get().split(',')
if Optional_input_name == ['']:
Optional_input_name = []
headers = [x_pos_entry.get(), y_pos_entry.get(), frame_entry.get(), ID_entry.get()]
max_dist = float(max_dist_entry.get())
remove_no_disps = bool(remove_no_disp_entry.get())
root.withdraw()
previous_window = root
analysis_window = tk.Tk()
analysis_window.title("Anomalous Analysis - {}".format(analysis_type))
if analysis_type == 'Model Fitting':
create_fitting_window(analysis_window, path, savepath, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps)
elif analysis_type == 'State Labeling':
create_prediction_window(analysis_window, path, savepath, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps)
elif analysis_type == 'State Lifetime Histogram':
create_lifetime_window(analysis_window, path, savepath, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps)
elif analysis_type == 'Position Refinement':
create_refinement_window(analysis_window, path, savepath, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps)
def show_loading_window(root):
loading_window = tk.Toplevel(root)
loading_window.title("Loading")
loading_window.geometry("200x100")
label = tk.Label(loading_window, text="Loading, please wait...")
label.pack(pady=10)
progress = ttk.Progressbar(loading_window, mode='indeterminate')
progress.pack(pady=10)
progress.start()
return loading_window, progress
def go_to_previous_window(window):
window.destroy()
if previous_window:
previous_window.deiconify()
def show_error_url(window, message, url=None):
window.withdraw()
error_window = tk.Toplevel(window)
error_window.title("Error")
text = tk.Text(error_window, height=10, width=80, wrap="word")
text.grid(row=0, column=0, padx=20, pady=10)
text.insert(tk.END, message)
if url:
text.insert(tk.END, "https://github.com/FrancoisSimon/aTrack", "link")
text.tag_config("link", foreground="blue", underline=True)
text.tag_bind("link", "<Button-1>", lambda e, link=url: webbrowser.open(link))
text.config(state="disabled")
previous_button = ttk.Button(error_window, text="Previous", command=lambda: go_to_previous_window(window))
previous_button.grid(row=1, column=0)
def create_fitting_window(window, path, savepath, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps):
#try:
print('path', path, type(path))
print('headers', headers, type(headers), type(headers[0]))
print('remove_no_disp', remove_no_disps, type(remove_no_disps))
print('Optional_input_name', Optional_input_name, type(Optional_input_name))
print('max_dist', max_dist, type(max_dist))
if os.path.isdir(path):
path = glob(path + '/*.csv')
if type(path) == str:
if not path.endswith('.csv') :
show_error_url(window, "Please select a csv file with an extention '.csv'.\n", url=None)
return
elif len(path)==0:
show_error_url(window, "No csv file detected in the informed directory. Make sure the csv files end with the extention '.csv'.\n", url=None)
return
try:
if LocErr_type == "Fitted parameter":
tracks, frames, opt_metrics = extrack.readers.read_table(path,
lengths=np.arange(min_length, max_length+1),
dist_th=max_dist,
frames_boundaries=[-np.inf, np.inf], fmt='csv',
colnames = headers,
remove_no_disp=remove_no_disps,
opt_colnames = Optional_input_name)
input_LocErr = None
else:
if LocErr_input_name == []:
raise ValueError('If selecting localization errors "Inputing the Localization error" or "Inputing a quality metric for each peak", you must provide the name of the column that informs on the localization error of each peaks')
#print('If selecting localization errors "Inputing the Localization error" or "Inputing a quality metric for each peak", you must provide the name of the column that informs on the localization error of each peaks')
#go_to_previous_window(window)
tracks, frames, opt_metrics = extrack.readers.read_table(path,
lengths=np.arange(min_length, max_length+1),
dist_th=max_dist,
frames_boundaries=[-np.inf, np.inf], fmt='csv',
colnames = headers,
remove_no_disp=remove_no_disps,
opt_colnames = Optional_input_name + LocErr_input_name)
# then, we retreive input_LocErr from the optional metrics
input_LocErr = {}
for l in tracks:
input_LocErr[l] = np.zeros(tracks[l].shape[:2] + (len(LocErr_input_name),))
for i, name in enumerate(LocErr_input_name):
for l in tracks:
input_LocErr[l][:,:,i] = opt_metrics[name][l]
del opt_metrics[name]
except:
print('ERROR: The data did not load correctly. Verify that the headers for the x positions, y positions, frame number and track ID are correctly informed. If selecting localization errors "Inputing the Localization error" or "Inputing a quality metric for each peak", you must provide the name of the column that informs on the localization error of each peaks')
go_to_previous_window(window)
#except Exception as e:
#show_error_url(window, "The csv file could not be read correctly.\nVerify that your file has columns named: 'POSITION_X', 'POSITION_Y', 'FRAME', 'TRACK_ID'\nFor more details, click here:", "https://github.com/FrancoisSimon/aTrack")
#return
global params
# Initial number of states
NbStates_label = ttk.Label(window, text="Number of states:")
NbStates_label.grid(row=0, column=0, sticky = 'e', padx = padx, pady = pady)
NbStates_entry = ttk.Entry(window, width=13)
NbStates_entry.grid(row=0, column=1)
NbStates_entry.insert(tk.END, str(params['num_states']))
open_button = ttk.Button(window, text="Open Parameter Window", command=lambda: ParameterWindow(window, int(NbStates_entry.get())))
#ParameterWindow(window, int(NbStates_entry.get())))
open_button.grid(row=1, column=0, sticky = 'e', padx = padx, pady = pady)
# Frame time
frametime_label = ttk.Label(window, text="Frame time (in s)")
frametime_label.grid(row=2, column=0, sticky = 'e', padx = padx, pady = pady)
frametime_entry = ttk.Entry(window, width=13)
frametime_entry.grid(row=2, column=1)
frametime_entry.insert(tk.END, str(params['dt']))
# Window length
windowlength_label = ttk.Label(window, text="Window length")
windowlength_label.grid(row=3, column=0, sticky = 'e', padx = padx, pady = pady)
windowlength_entry = ttk.Entry(window, width=13)
windowlength_entry.grid(row=3, column=1)
windowlength_entry.insert(tk.END, str(params['fitting_window_length']))
# Number of substeps
nb_substeps_label = ttk.Label(window, text="Number of substeps")
nb_substeps_label.grid(row=4, column=0, sticky = 'e', padx = padx, pady = pady)
nb_substeps_entry = ttk.Entry(window, width=13)
nb_substeps_entry.grid(row=4, column=1)
nb_substeps_entry.insert(tk.END, str(params['nb_substeps']))
# Threshold to fuse sequences of states
Threshold_label = ttk.Label(window, text="Threshold")
Threshold_label.grid(row=5, column=0, sticky = 'e', padx = padx, pady = pady)
Threshold_entry = ttk.Entry(window, width=13)
Threshold_entry.grid(row=5, column=1)
Threshold_entry.insert(tk.END, str(params['threshold']))
# Maximum number of states
Max_nb_sequences_label = ttk.Label(window, text="Maximum number of sequences")
Max_nb_sequences_label.grid(row=6, column=0, sticky = 'e', padx = padx, pady = pady)
Max_nb_sequences_entry = ttk.Entry(window, width=13)
Max_nb_sequences_entry.grid(row=6, column=1)
Max_nb_sequences_entry.insert(tk.END, str(params['max_nb_sequ']))
# Depth of field
Depth_of_field_label = ttk.Label(window, text="Depth of field")
Depth_of_field_label.grid(row=7, column=0, sticky = 'e', padx = padx, pady = pady)
Depth_of_field_entry = ttk.Entry(window, width=13)
Depth_of_field_entry.grid(row=7, column=1)
Depth_of_field_entry.insert(tk.END, str(params['cell_dims']))
# number of iterations of the fitting methods
nb_iter_label = ttk.Label(window, text="Number of iterations")
nb_iter_label.grid(row=8, column=0, sticky = 'e', padx = padx, pady = pady)
nb_iter_entry = ttk.Entry(window, width=13)
nb_iter_entry.grid(row=8, column=1)
nb_iter_entry.insert(tk.END, str(params['nb_iters']))
# Savepath Input
savepath_label = ttk.Label(window, text="Save Path:")
savepath_label.grid(row=9, column=0, sticky = 'e', padx = padx, pady = pady)
savepath_entry = ttk.Entry(window, width=50)
savepath_entry.grid(row=9, column=1)
savepath_entry.insert(tk.END, os.path.join(savepath, 'saved_fitting_results.csv'))
savepath_button = ttk.Button(window, text="Browse", command=lambda: browse_savepath(savepath_entry))
savepath_button.grid(row=9, column=2)
# Run Button
run_button = ttk.Button(window, text="Start fitting", command=lambda: run_fitting(window,
tracks,
dt = float(frametime_entry.get()),
nb_states = int(NbStates_entry.get()),
nb_iterations = int(nb_iter_entry.get()),
nb_substeps = int(nb_substeps_entry.get()),
frame_len = int(windowlength_entry.get()),
cell_dims = float(Depth_of_field_entry.get()),
LocErr_type = LocErr_type,
input_LocErr = input_LocErr,
threshold = float(Threshold_entry.get()),
max_nb_states = int(Max_nb_sequences_entry.get()),
savepath = savepath_entry.get()))
run_button.grid(row=10, column=1, columnspan=1)
# Previous Button
previous_button = ttk.Button(window, text="Other analyses", command=lambda: go_to_previous_window(window))
previous_button.grid(row=10, column=0, columnspan=1)
def run_fitting(window, tracks, dt, nb_states, nb_iterations, nb_substeps, frame_len, cell_dims, LocErr_type, input_LocErr, threshold, max_nb_states, savepath):
# Run the Brownian motion analysis
#tracks = tracks[str(length)]
global params
params['dt'] = dt
params['fitting_window_length'] = frame_len
params['cell_dims'] = cell_dims
params['max_nb_sequ'] = max_nb_states
params['threshold'] = threshold
params['nb_iters'] = nb_iterations
params['nb_substeps'] = nb_substeps
if params['num_states'] != nb_states:
get_new_params(nb_states)
if LocErr_type == "Inputing a quality metric for each peak":
try:
for l in input_LocErr:
input_LocErr[l] = 1/input_LocErr[l]**0.5
except:
raise ValueError("If you chose to estimate the localization error from a quality metric, the quality metrics must all be numerical and strictly positive")
lmfit_params = params_to_lmfit_params(params, LocErr_type)
print('lmfit_params', lmfit_params)
#print('tracks', tracks)
print('input_LocErr', input_LocErr)
print('nb_states', nb_states, type(nb_states))
for l in tracks:
print(tracks[l].shape)
model_fit = extrack.tracking.param_fitting(tracks,
dt,
params = lmfit_params,
nb_states = nb_states,
nb_substeps = nb_substeps,
frame_len = frame_len,
verbose = 0,
workers = 1,
Matrix_type = 1,
method = 'powell',
steady_state = False,
cell_dims = [cell_dims], # list of dimensions limit for the field of view (FOV) of the cell in um, a membrane protein in a typical e-coli cell in tirf would have a cell_dims = [0.5,3], in case of cytosolic protein one should imput the depth of the FOV e.g. [0.3] for tirf or [0.8] for hilo
input_LocErr = input_LocErr,
threshold = threshold,
max_nb_states = max_nb_states)
print('likelihood iteration 0:', - model_fit.residual[0])
for k in range(nb_iterations-1):
model_fit = extrack.tracking.param_fitting(tracks,
dt,
params = model_fit.params,
nb_states = nb_states,
nb_substeps = nb_substeps,
frame_len = frame_len,
verbose = 0,
workers = 1,
Matrix_type = 1,
method = 'bfgs',
steady_state = False,
cell_dims = [cell_dims], # list of dimensions limit for the field of view (FOV) of the cell in um, a membrane protein in a typical e-coli cell in tirf would have a cell_dims = [0.5,3], in case of cytosolic protein one should imput the depth of the FOV e.g. [0.3] for tirf or [0.8] for hilo
input_LocErr = input_LocErr,
threshold = threshold,
max_nb_states = max_nb_states)
print('likelihood iteration %s:'%(k+1), - model_fit.residual[0])
lmfit_params = model_fit.params
TrMat = np.zeros((nb_states, nb_states))
for i in range(nb_states):
for j in range(nb_states):
if i!=j:
TrMat[i,j] = model_fit.params['p%s%s'%(i,j)].value/100
TrMat[i,i] = 1-np.sum(TrMat[i])
A0 = np.ones((1,nb_states))/nb_states
for k in range(200000):
A0 = A0 @ TrMat
equilibrium_Fraction_names = []
for s in range(nb_states):
equilibrium_Fraction_names.append('equilibrium_F%s'%s)
data = pd.DataFrame([], columns = ['exp', 'likelihood'] + list(lmfit_params.keys()) + equilibrium_Fraction_names)
vals = [savepath, - model_fit.residual[0]]
for param in lmfit_params:
vals.append(lmfit_params[param].value)
for Fi in A0[0]:
vals.append(Fi)
data.loc[len(data.index)] = vals
data.to_csv(savepath)
lmfit_params_to_params(lmfit_params)
print("Fitting analysis completed and results saved to %s"%savepath)
print(data)
def create_prediction_window(window, path, savepath, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps):
if os.path.isdir(path):
path = glob(path + '/*.csv')
if type(path) == str:
if not path.endswith('.csv') :
show_error_url(window, "Please select a csv file with an extention '.csv'.\n", url=None)
return
elif len(path)==0:
show_error_url(window, "No csv file detected in the informed directory. Make sure the csv files end with the extention '.csv'.\n", url=None)
return
if LocErr_type == "Fitted parameter":
tracks, frames, opt_metrics = extrack.readers.read_table(path,
lengths=np.arange(min_length, max_length+1),
dist_th=max_dist,
frames_boundaries=[-np.inf, np.inf], fmt='csv',
colnames = headers,
remove_no_disp=remove_no_disps,
opt_colnames = Optional_input_name)
input_LocErr = None
else:
if LocErr_input_name == []:
raise ValueError('If selecting localization errors "Inputing the Localization error" or "Inputing a quality metric for each peak", you must provide the name of the column that informs on the localization error of each peaks')
tracks, frames, opt_metrics = extrack.readers.read_table(path,
lengths=np.arange(min_length, max_length+1),
dist_th=max_dist,
frames_boundaries=[-np.inf, np.inf], fmt='csv',
colnames = headers,
remove_no_disp=remove_no_disps,
opt_colnames = Optional_input_name + LocErr_input_name)
# then, we retreive input_LocErr from the optional metrics
input_LocErr = {}
for l in tracks:
input_LocErr[l] = np.zeros(tracks[l].shape[:2] + (len(LocErr_input_name),))
for i, name in enumerate(LocErr_input_name):
for l in tracks:
input_LocErr[l][:,:,i] = opt_metrics[name][l]
del opt_metrics[name]
global params
# Initial number of states
NbStates_label = ttk.Label(window, text="Number of states:")
NbStates_label.grid(row=0, column=0, sticky = 'e', padx = padx, pady = pady)
NbStates_entry = ttk.Entry(window, width=13)
NbStates_entry.grid(row=0, column=1)
NbStates_entry.insert(tk.END, str(params['num_states']))
open_button = ttk.Button(window, text="Open Parameter Window", command=lambda: ParameterWindow(window, int(NbStates_entry.get())))
#ParameterWindow(window, int(NbStates_entry.get())))
open_button.grid(row=1, column=0, sticky = 'e', padx = padx, pady = pady)
# Frame time
frametime_label = ttk.Label(window, text="Frame time (in s)")
frametime_label.grid(row=2, column=0, sticky = 'e', padx = padx, pady = pady)
frametime_entry = ttk.Entry(window, width=13)
frametime_entry.grid(row=2, column=1)
frametime_entry.insert(tk.END, str(params['dt']))
# Window length
windowlength_label = ttk.Label(window, text="Window length")
windowlength_label.grid(row=3, column=0, sticky = 'e', padx = padx, pady = pady)
windowlength_entry = ttk.Entry(window, width=13)
windowlength_entry.grid(row=3, column=1)
windowlength_entry.insert(tk.END, str(params['labeling_window_length']))
# Threshold to fuse sequences of states
Threshold_label = ttk.Label(window, text="Threshold")
Threshold_label.grid(row=5, column=0, sticky = 'e', padx = padx, pady = pady)
Threshold_entry = ttk.Entry(window, width=13)
Threshold_entry.grid(row=5, column=1)
Threshold_entry.insert(tk.END, str(params['threshold']))
# Maximum number of states
Max_nb_sequences_label = ttk.Label(window, text="Maximum number of sequences")
Max_nb_sequences_label.grid(row=6, column=0, sticky = 'e', padx = padx, pady = pady)
Max_nb_sequences_entry = ttk.Entry(window, width=13)
Max_nb_sequences_entry.grid(row=6, column=1)
Max_nb_sequences_entry.insert(tk.END, str(params['max_nb_sequ_labeling']))
# Depth of field
Depth_of_field_label = ttk.Label(window, text="Depth of field")
Depth_of_field_label.grid(row=7, column=0, sticky = 'e', padx = padx, pady = pady)
Depth_of_field_entry = ttk.Entry(window, width=13)
Depth_of_field_entry.grid(row=7, column=1)
Depth_of_field_entry.insert(tk.END, str(params['cell_dims']))
Draw_plot_label = ttk.Label(window, text="Plot labeled tracks")
Draw_plot_label.grid(row=8, column=0, padx = padx, pady = pady, sticky = 'e')
Draw_plot_var = tk.StringVar(window)
Draw_plot_var.set(params['draw_plot'])
Draw_plot_dropdown = ttk.OptionMenu(window, Draw_plot_var, Draw_plot_var.get(),
"Yes",
"No",
style='My.TMenubutton')
#Draw_plot_dropdown.config(width=15)
Draw_plot_dropdown.grid(row=8, column=1, padx = padx, pady = pady, sticky="e")
# Savepath Input
savepath_label = ttk.Label(window, text="Save Path:")
savepath_label.grid(row=9, column=0, sticky = 'e', padx = padx, pady = pady)
savepath_entry = ttk.Entry(window, width=50)
savepath_entry.grid(row=9, column=1)
savepath_entry.insert(tk.END, os.path.join(savepath, 'saved_track_predictions.csv'))
savepath_button = ttk.Button(window, text="Browse", command=lambda: browse_savepath(savepath_entry))
savepath_button.grid(row=9, column=2)
# Run Button
run_button = ttk.Button(window,
text="Start state predictions",
command=lambda: run_predictions(window,
tracks,
frames,
opt_metrics,
dt = float(frametime_entry.get()),
nb_states = int(NbStates_entry.get()),
frame_len = int(windowlength_entry.get()),
cell_dims = float(Depth_of_field_entry.get()),
LocErr_type = LocErr_type,
input_LocErr = input_LocErr,
threshold = float(Threshold_entry.get()),
max_nb_states = int(Max_nb_sequences_entry.get()),
savepath = savepath_entry.get(),
Draw_plot = Draw_plot_var.get()))
run_button.grid(row=10, column=1, columnspan=1)
# Previous Button
previous_button = ttk.Button(window, text="Previous", command=lambda: go_to_previous_window(window))
previous_button.grid(row=10, column=0, columnspan=1)
def run_predictions(window, tracks, frames, opt_metrics, dt, nb_states, frame_len, cell_dims, LocErr_type, input_LocErr, threshold, max_nb_states, savepath, Draw_plot):
# Run the Brownian motion analysis
#tracks = tracks[str(length)]
global params
params['dt'] = dt
params['labeling_window_length'] = frame_len
params['cell_dims'] = cell_dims
params['max_nb_sequ_labeling'] = max_nb_states
params['threshold'] = threshold
if params['num_states'] != nb_states:
get_new_params(nb_states)
nb_states
if LocErr_type == "Inputing a quality metric for each peak":
try:
for l in input_LocErr:
input_LocErr[l] = 1/input_LocErr[l]**0.5
except:
raise ValueError("If you chose to estimate the localization error from a quality metric, the quality metrics must all be numerical and strictly positive")
lmfit_params = params_to_lmfit_params(params, LocErr_type)
#print('tracks', tracks)
#print('input_LocErr', input_LocErr)
preds = extrack.tracking.predict_Bs(tracks,
dt,
lmfit_params,
cell_dims=[cell_dims],
nb_states=nb_states,
frame_len=frame_len,
max_nb_states = max_nb_states,
threshold = threshold,
workers = 1,
input_LocErr = input_LocErr,
verbose = 0,
nb_max = 1)
if Draw_plot == 'Yes':
track_list = []
pred_list = []
for l in tracks:
track_list = track_list + list(tracks[l])
pred_list = pred_list + list(preds[l])
stds = np.zeros(100)
for k in range(100):
ID = np.random.randint(len(track_list))
stds[k] = np.mean(np.std(track_list[ID], 0))
lim = 10*np.mean(stds)
nb_rows = 8
def rgb_cm(pred, nb_states):
pred2color = np.zeros((1, nb_states, 3))
for state in range(nb_states):
x = state/(nb_states-1)
r = np.clip(1-2*x, 0, 1)
if x <0.5:
g = 2*x
else:
g = 1 - 2*(x-0.5)
b = np.clip(2*x - 1, 0, 1)
pred2color[0, state] = [r, g, b]
return np.sum(pred[:,:,None]*pred2color, 1)
plt.figure(figsize = (10,10))
for i in range(nb_rows):
for j in range(nb_rows):
ID = np.random.randint(len(track_list))
track = track_list[ID]
track = track - np.mean(track, 0, keepdims = True) + [[lim*i, lim*j]]
pred = pred_list[ID]
plt.plot(track[:, 0], track[:, 1], ':k')
if nb_states == 2:
current_colors = plt.cm.brg(pred[:,0]/2)
if nb_states == 3:
current_colors = rgb_cm(pred, nb_states)
if nb_states > 3:
current_colors = rgb_cm(pred, nb_states)
plt.scatter(track[:, 0], track[:, 1], c = current_colors, s = 8)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
DATA = extrack.exporters.extrack_2_pandas(tracks, preds, frames = frames, opt_metrics = opt_metrics)
DATA.to_csv(savepath)
print("State labeling completed and results saved to %s."%savepath)
def create_lifetime_window(window, path, savepath, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps):
if os.path.isdir(path):
path = glob(path + '/*.csv')
if type(path) == str:
if not path.endswith('.csv') :
show_error_url(window, "Please select a csv file with an extention '.csv'.\n", url=None)
return
elif len(path)==0:
show_error_url(window, "No csv file detected in the informed directory. Make sure the csv files end with the extention '.csv'.\n", url=None)
return
if LocErr_type == "Fitted parameter":
tracks, frames, opt_metrics = extrack.readers.read_table(path,
lengths=np.arange(min_length, max_length+1),
dist_th=max_dist,
frames_boundaries=[-np.inf, np.inf], fmt='csv',
colnames = headers,
remove_no_disp=remove_no_disps,
opt_colnames = Optional_input_name)
input_LocErr = None
else:
if LocErr_input_name == []:
raise ValueError('If selecting localization errors "Inputing the Localization error" or "Inputing a quality metric for each peak", you must provide the name of the column that informs on the localization error of each peaks')
tracks, frames, opt_metrics = extrack.readers.read_table(path,
lengths=np.arange(min_length, max_length+1),
dist_th=max_dist,
frames_boundaries=[-np.inf, np.inf], fmt='csv',
colnames = headers,
remove_no_disp=remove_no_disps,
opt_colnames = Optional_input_name + LocErr_input_name)
# then, we retreive input_LocErr from the optional metrics
input_LocErr = {}
for l in tracks:
input_LocErr[l] = np.zeros(tracks[l].shape[:2] + (len(LocErr_input_name),))
for i, name in enumerate(LocErr_input_name):
for l in tracks:
input_LocErr[l][:,:,i] = opt_metrics[name][l]
del opt_metrics[name]
global params
# Initial number of states
NbStates_label = ttk.Label(window, text="Number of states:")
NbStates_label.grid(row=0, column=0, sticky = 'e', padx = padx, pady = pady)
NbStates_entry = ttk.Entry(window, width=13)
NbStates_entry.grid(row=0, column=1)
NbStates_entry.insert(tk.END, str(params['num_states']))
open_button = ttk.Button(window, text="Open Parameter Window", command=lambda: ParameterWindow(window, int(NbStates_entry.get())))
#ParameterWindow(window, int(NbStates_entry.get())))
open_button.grid(row=1, column=0, sticky = 'e', padx = padx, pady = pady)
# Frame time
frametime_label = ttk.Label(window, text="Frame time (in s)")
frametime_label.grid(row=2, column=0, sticky = 'e', padx = padx, pady = pady)
frametime_entry = ttk.Entry(window, width=13)
frametime_entry.grid(row=2, column=1)
frametime_entry.insert(tk.END, str(params['dt']))
# Maximum number of states
Max_nb_sequences_label = ttk.Label(window, text="Maximum number of sequences")
Max_nb_sequences_label.grid(row=6, column=0, sticky = 'e', padx = padx, pady = pady)
Max_nb_sequences_entry = ttk.Entry(window, width=13)
Max_nb_sequences_entry.grid(row=6, column=1)
Max_nb_sequences_entry.insert(tk.END, str(params['max_nb_sequ_histograms']))
# Depth of field
Depth_of_field_label = ttk.Label(window, text="Depth of field")
Depth_of_field_label.grid(row=7, column=0, sticky = 'e', padx = padx, pady = pady)
Depth_of_field_entry = ttk.Entry(window, width=13)
Depth_of_field_entry.grid(row=7, column=1)
Depth_of_field_entry.insert(tk.END, str(params['cell_dims']))
Draw_plot_label = ttk.Label(window, text="Plot lifetime histograms")
Draw_plot_label.grid(row=8, column=0, padx = padx, pady = pady, sticky = 'e')
Draw_plot_var = tk.StringVar(window)
Draw_plot_var.set(params['draw_plot'])
Draw_plot_dropdown = ttk.OptionMenu(window, Draw_plot_var, Draw_plot_var.get(),
"Yes",
"No",
style='My.TMenubutton')
#Draw_plot_dropdown.config(width=15)
Draw_plot_dropdown.grid(row=8, column=1, padx = padx, pady = pady, sticky="e")
# Savepath Input
savepath_label = ttk.Label(window, text="Save Path:")
savepath_label.grid(row=9, column=0, sticky = 'e', padx = padx, pady = pady)
savepath_entry = ttk.Entry(window, width=50)
savepath_entry.grid(row=9, column=1)
savepath_entry.insert(tk.END, os.path.join(savepath, 'saved_lifetimes.csv'))
savepath_button = ttk.Button(window, text="Browse", command=lambda: browse_savepath(savepath_entry))
savepath_button.grid(row=9, column=2)
# Run Button
run_button = ttk.Button(window,
text="Compute lifetime histogram",
command=lambda: run_lifetime(window,
tracks,
dt = float(frametime_entry.get()),
nb_states = int(NbStates_entry.get()),
cell_dims = float(Depth_of_field_entry.get()),
LocErr_type = LocErr_type,
input_LocErr = input_LocErr,
max_nb_states = int(Max_nb_sequences_entry.get()),
draw_plot = Draw_plot_var.get(),
savepath = savepath_entry.get()))
run_button.grid(row=10, column=1, columnspan=1)
# Previous Button
previous_button = ttk.Button(window, text="Previous", command=lambda: go_to_previous_window(window))
previous_button.grid(row=10, column=0, columnspan=1)
def run_lifetime(window, tracks, dt, nb_states, cell_dims, LocErr_type, input_LocErr, max_nb_states, draw_plot, savepath):
# Run the Brownian motion analysis
#tracks = tracks[str(length)]
global params
params['dt'] = dt
params['cell_dims'] = cell_dims
params['max_nb_sequ_histograms'] = max_nb_states
params['draw_plot'] = draw_plot
if params['num_states'] != nb_states:
get_new_params(nb_states)
if LocErr_type == "Inputing a quality metric for each peak":
#print('input_LocErr', input_LocErr)
try:
for l in input_LocErr:
input_LocErr[l] = 1/input_LocErr[l]**0.5
except:
raise ValueError("If you chose to estimate the localization error from a quality metric, the quality metrics must all be numerical and strictly positive")
lmfit_params = params_to_lmfit_params(params, LocErr_type)
hists = extrack.histograms.len_hist(tracks,
lmfit_params,
dt,
cell_dims=[cell_dims],
nb_states=nb_states,
max_nb_states = max_nb_states,
workers = 1,
nb_substeps=1,
input_LocErr = input_LocErr
)
columns = ['Segment length']
for state in range(nb_states):
columns.append('State %s'%state)
DATA = pd.DataFrame(np.concatenate((np.arange(1,len(hists)+1)[:,None], hists), axis = 1, dtype = 'str'), columns = columns)
DATA.to_csv(savepath)
print("State labeling completed and results saved to %s."%savepath)
if draw_plot=='Yes':
plt.figure(figsize = (4.8,3.5))
plt.title('Plot of the lifetime histograms of the different states', font = "Arial", fontsize = 12)
plt.plot(np.arange(1,len(hists)+1)[:,None]*dt, hists)
plt.ylabel('Counts')
plt.xlabel('Time in s')
plt.legend(np.arange(nb_states), title = 'State')
plt.tight_layout()
plt.figure(figsize = (4.8,3.5))
plt.title('Log Plot of the lifetime histograms of the different states', font = "Arial", fontsize = 12)
plt.plot(np.arange(1,len(hists)+1)[:,None]*dt, hists)
plt.ylabel('Counts')
plt.xlabel('Time in s')
plt.yscale('log')
plt.legend(np.arange(nb_states), title = 'State')
plt.tight_layout()
plt.show()
def create_refinement_window(window, path, savepath, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps):
if os.path.isdir(path):
path = glob(path + '/*.csv')
if type(path) == str:
if not path.endswith('.csv') :
show_error_url(window, "Please select a csv file with an extention '.csv'.\n", url=None)
return
elif len(path)==0:
show_error_url(window, "No csv file detected in the informed directory. Make sure the csv files end with the extention '.csv'.\n", url=None)
return
if LocErr_type == "Fitted parameter":
tracks, frames, opt_metrics = extrack.readers.read_table(path,
lengths=np.arange(min_length, max_length+1),
dist_th=max_dist,
frames_boundaries=[-np.inf, np.inf], fmt='csv',
colnames = headers,
remove_no_disp=remove_no_disps,
opt_colnames = Optional_input_name)
input_LocErr = None
else:
if LocErr_input_name == []:
raise ValueError('If selecting localization errors "Inputing the Localization error" or "Inputing a quality metric for each peak", you must provide the name of the column that informs on the localization error of each peaks')
tracks, frames, opt_metrics = extrack.readers.read_table(path,
lengths=np.arange(min_length, max_length+1),
dist_th=max_dist,
frames_boundaries=[-np.inf, np.inf], fmt='csv',
colnames = headers,
remove_no_disp=remove_no_disps,
opt_colnames = Optional_input_name + LocErr_input_name)
# then, we retreive input_LocErr from the optional metrics
input_LocErr = {}
for l in tracks:
input_LocErr[l] = np.zeros(tracks[l].shape[:2] + (len(LocErr_input_name),))
for i, name in enumerate(LocErr_input_name):
for l in tracks:
input_LocErr[l][:,:,i] = opt_metrics[name][l]
del opt_metrics[name]
global params
# Initial number of states
NbStates_label = ttk.Label(window, text="Number of states:")
NbStates_label.grid(row=0, column=0, sticky = 'e', padx = padx, pady = pady)
NbStates_entry = ttk.Entry(window, width=13)
NbStates_entry.grid(row=0, column=1)
NbStates_entry.insert(tk.END, str(params['num_states']))
open_button = ttk.Button(window, text="Open Parameter Window", command=lambda: ParameterWindow(window, int(NbStates_entry.get())))
#ParameterWindow(window, int(NbStates_entry.get())))
open_button.grid(row=1, column=0, sticky = 'e', padx = padx, pady = pady)
# Frame time
frametime_label = ttk.Label(window, text="Frame time (in s)")
frametime_label.grid(row=2, column=0, sticky = 'e', padx = padx, pady = pady)
frametime_entry = ttk.Entry(window, width=13)
frametime_entry.grid(row=2, column=1)
frametime_entry.insert(tk.END, str(params['dt']))
# Window length
windowlength_label = ttk.Label(window, text="Window length")
windowlength_label.grid(row=3, column=0, sticky = 'e', padx = padx, pady = pady)
windowlength_entry = ttk.Entry(window, width=13)
windowlength_entry.grid(row=3, column=1)
windowlength_entry.insert(tk.END, str(params['labeling_window_length']))
# Threshold to fuse sequences of states
Threshold_label = ttk.Label(window, text="Threshold")
Threshold_label.grid(row=5, column=0, sticky = 'e', padx = padx, pady = pady)
Threshold_entry = ttk.Entry(window, width=13)
Threshold_entry.grid(row=5, column=1)
Threshold_entry.insert(tk.END, str(params['threshold']))
# Maximum number of sequences of states
Max_nb_sequences_label = ttk.Label(window, text="Maximum number of sequences")
Max_nb_sequences_label.grid(row=6, column=0, sticky = 'e', padx = padx, pady = pady)
Max_nb_sequences_entry = ttk.Entry(window, width=13)
Max_nb_sequences_entry.grid(row=6, column=1)
Max_nb_sequences_entry.insert(tk.END, str(params['max_nb_sequ_histograms']))
# Depth of field
Depth_of_field_label = ttk.Label(window, text="Depth of field")
Depth_of_field_label.grid(row=7, column=0, sticky = 'e', padx = padx, pady = pady)
Depth_of_field_entry = ttk.Entry(window, width=13)
Depth_of_field_entry.grid(row=7, column=1)
Depth_of_field_entry.insert(tk.END, str(params['cell_dims']))
# Savepath Input
savepath_label = ttk.Label(window, text="Save Path:")
savepath_label.grid(row=9, column=0, sticky = 'e', padx = padx, pady = pady)
savepath_entry = ttk.Entry(window, width=50)
savepath_entry.grid(row=9, column=1)
savepath_entry.insert(tk.END, os.path.join(savepath, 'saved_tracks_with_position_refinement.csv'))
savepath_button = ttk.Button(window, text="Browse", command=lambda: browse_savepath(savepath_entry))
savepath_button.grid(row=9, column=2)
# Run Button
run_button = ttk.Button(window,
text="Start position refinement",
command=lambda: run_refinement(window,
tracks,
frames,
opt_metrics,
dt = float(frametime_entry.get()),
nb_states = int(NbStates_entry.get()),
frame_len = int(windowlength_entry.get()),
cell_dims = float(Depth_of_field_entry.get()),
LocErr_type = LocErr_type,
input_LocErr = input_LocErr,
threshold = float(Threshold_entry.get()),
max_nb_states = int(Max_nb_sequences_entry.get()),
savepath = savepath_entry.get()))
run_button.grid(row=10, column=1, columnspan=1)
# Previous Button
previous_button = ttk.Button(window, text="Previous", command=lambda: go_to_previous_window(window))
previous_button.grid(row=10, column=0, columnspan=1)
def run_refinement(window, tracks, frames, opt_metrics, dt, nb_states, frame_len, cell_dims, LocErr_type, input_LocErr, threshold, max_nb_states, savepath):
# Run the Brownian motion analysis
#tracks = tracks[str(length)]
global params
params['dt'] = dt
params['labeling_window_length'] = frame_len
params['cell_dims'] = cell_dims
params['max_nb_sequ_histograms'] = max_nb_states
params['threshold'] = threshold
if params['num_states'] != nb_states:
get_new_params(nb_states)
if LocErr_type == "Inputing a quality metric for each peak":
#print('input_LocErr', input_LocErr)
try:
for l in input_LocErr:
input_LocErr[l] = 1/input_LocErr[l]**0.5
except:
raise ValueError("If you chose to estimate the localization error from a quality metric, the quality metrics must all be numerical and strictly positive")
lmfit_params = params_to_lmfit_params(params, LocErr_type)
if LocErr_type == "Inputing a quality metric for each peak" or LocErr_type == "Inputing the Localization error":
new_input_LocErr = []
for l in input_LocErr:
new_input_LocErr.append(input_LocErr[l])
else:
new_input_LocErr = None
nb_substeps = 1
LocErr, ds, Fs, TrMat, pBL = extrack.tracking.extract_params(lmfit_params, dt, nb_states, nb_substeps, new_input_LocErr)
LocErr = LocErr[0]
if LocErr_type == "Inputing a quality metric for each peak" or LocErr_type == "Inputing the Localization error":
LocErr = input_LocErr
mus, sigs = extrack.refined_localization.position_refinement(tracks,
LocErr,
ds,
Fs,
TrMat,
frame_len = frame_len,
threshold = threshold,
max_nb_states = max_nb_states)
n = 0
for l in tracks:
n+= tracks[l].shape[0]*tracks[l].shape[1]
nb_dims = tracks[l].shape[2]
flat_tracks = np.zeros((n, tracks[l].shape[2]))
flat_frames = np.zeros((n, 1))
flat_Track_IDs = np.zeros((n, 1))
flat_opt_metrics = np.zeros((n, len(opt_metrics.keys())))
flat_refined_values = np.zeros((n, nb_dims+1))
if LocErr_type == "Inputing a quality metric for each peak" or LocErr_type == "Inputing the Localization error":
flat_LocErr = np.zeros((n, nb_dims))
track_ID = 0
k = 0
for l in tracks:
for i, (track, f, m, s) in enumerate(zip(tracks[l], frames[l], mus[l], sigs[l])):
track_length = track.shape[0]
flat_tracks[k:k+track_length] = track
flat_frames[k:k+track_length] = f[:, None]
flat_Track_IDs[k:k+track_length] = track_ID
flat_refined_values[k:k+track_length] = np.concatenate(( m, s[:, None]), axis = 1)
if LocErr_type == "Inputing a quality metric for each peak" or LocErr_type == "Inputing the Localization error":
flat_LocErr[k:k+track_length] = LocErr[l][i]
for j, metric in enumerate(opt_metrics):
flat_opt_metrics[k:k+track_length, j] = opt_metrics[metric][l][i]
k+=track_length
track_ID+=1
arr = np.concatenate((flat_tracks, flat_frames, flat_Track_IDs, flat_opt_metrics, flat_refined_values), axis = 1)
columns = ['POSITION_X', 'POSITION_Y', 'POSITION_Z'][:nb_dims] + ['FRAME', 'TRACK_ID'] + list(opt_metrics.keys()) + ['Refined_position_X', 'Refined_position_Y', 'Refined_position_Z'][:nb_dims] + ['Refined_localization_error']
dataframe = pd.DataFrame(arr, columns = columns)
dataframe.to_csv(savepath)
print('Position refinement finished and saved at "%s"'%savepath)
'''
predict_Bs(all_tracks,
dt,
params,
cell_dims=[1],
nb_states=4,
frame_len=5,
max_nb_states = 200,
threshold = 0.1,
workers = 1,
input_LocErr = None,
verbose = 0)
'''
def params_to_lmfit_params(params, LocErr_type):
print('params[num_states]', params['num_states'], type(params['num_states']))
if LocErr_type == "Fitted parameter":
LocErr_type = 1
slope_offsets_estimates = None