-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathExTrack_GUI.py
More file actions
2098 lines (1846 loc) · 107 KB
/
Copy pathExTrack_GUI.py
File metadata and controls
2098 lines (1846 loc) · 107 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 copy
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
# Small persistent settings (currently the last dataset path), kept in the user
# folder so they survive from one instance of the GUI to the next. The location
# can be overridden with the EXTRACK_GUI_CONFIG environment variable (used by
# the tests to stay away from the real file).
import json
CONFIG_PATH = os.environ.get('EXTRACK_GUI_CONFIG',
os.path.join(os.path.expanduser('~'), '.extrack_gui.json'))
def load_gui_config():
try:
with open(CONFIG_PATH, encoding='utf-8') as f:
config = json.load(f)
return config if type(config) == dict else {}
except Exception: # no config yet, or an unreadable one: start fresh
return {}
def save_gui_config(**updates):
config = load_gui_config()
config.update(updates)
try:
with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
json.dump(config, f)
except Exception as error: # never let a settings write break the GUI
print('Could not save the GUI settings to %s: %s'%(CONFIG_PATH, error))
def initialdir_from(current_path):
"""the folder containing the current path, for the Browse dialogs to start in"""
current_path = current_path.strip()
if os.path.isdir(current_path):
return current_path
parent = os.path.dirname(current_path)
if os.path.isdir(parent):
return parent
return os.path.expanduser('~')
def default_save_folder(path):
"""
Where the analyses propose to write their results: the PARENT of the folder
holding the dataset. A batch reads a folder of replicates, so writing next
to them would mix results into the data; one level up keeps the two apart
and gathers the replicates of one experiment in a single place. Falls back
to the dataset folder when there is no usable parent (a drive root).
"""
path = os.path.normpath(path.strip())
folder = path if os.path.isdir(path) else os.path.dirname(path)
parent = os.path.dirname(folder)
if parent and parent != folder and os.path.isdir(parent):
return parent
if os.path.isdir(folder):
return folder
return os.path.expanduser('~')
def open_analysis_window():
global previous_window
path = path_entry.get()
save_gui_config(last_path=path) # remembered for the next instance of the GUI
print(os.path.normpath(path))
savepath = default_save_folder(path)
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)
elif analysis_type in BATCH_STAGES:
create_batch_window(analysis_window, path, savepath, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps, analysis_type)
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 equilibrium_fractions(transition_probs, nb_substeps = 1):
"""
Steady-state occupancy of each state implied by the transition probabilities,
using the exact convention of the model (extrack.tracking.extract_params,
Matrix_type = 1): per-substep probabilities 1 - exp(-rate/nb_substeps) off
the diagonal, the remainder on it. Solved exactly as the left eigenvector of
the transition matrix, so arbitrarily slow rates converge too.
"""
nb_states = len(transition_probs)
TrMat = 1 - np.exp(-np.asarray(transition_probs, dtype = float) / nb_substeps)
TrMat[np.arange(nb_states), np.arange(nb_states)] = 0
TrMat[np.arange(nb_states), np.arange(nb_states)] = 1 - np.sum(TrMat, 1)
M = TrMat.T - np.identity(nb_states)
M[-1] = 1 # replaces one redundant equation by sum = 1
b = np.zeros(nb_states)
b[-1] = 1
return np.linalg.solve(M, b)
def load_dataset_or_error(window, path, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps):
"""
Read the dataset behind the four analysis windows. Any problem -- a path that
is not set correctly, a file that does not read, no track passing the length
filters -- raises an error panel (show_error_url) instead of a console
traceback, and returns None so the caller can simply return.
Returns (tracks, frames, opt_metrics, input_LocErr) on success.
"""
if os.path.isdir(path):
path = glob(path + '/*.csv')
if 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 None
elif not os.path.exists(path):
show_error_url(window, "The informed dataset path does not exist:\n%s\nPlease verify the Path field of the previous window.\n"%path, url=None)
return None
elif not path.endswith('.csv'):
show_error_url(window, "Please select a csv file with an extention '.csv'.\n", url=None)
return None
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 in the 3rd column of the "Type of localization error" row, exemple: QUALITY.')
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]
if sum(len(tracks[l]) for l in tracks) == 0:
raise ValueError('No track was loaded: verify the headers and the minimum/maximum track lengths.')
except Exception as error:
show_error_url(window, "The dataset could not be read correctly.\nVerify that the headers for the x positions, y positions, frame number and track ID are correctly informed, as well as the minimum and maximum track lengths. 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 in the 3rd column of the 'Type of localization error' row, exemple: QUALITY.\n\nError: %s\n"%error, url=None)
return None
return tracks, frames, opt_metrics, input_LocErr
# Explanations shown by the '?' cells next to each hyperparameter.
HYPERPARAM_INFO = {
'nb_states': (
"Number of motion states of the model (e.g. 2 for an immobile and a mobile "
"state). Each state has its own diffusion coefficient and fraction, with "
"transition probabilities between states, all set in the Parameter Window. "
"The computation time increases steeply with the number of states (see the "
"fusion model box)."),
'dt': (
"Time between two consecutive frames of the movie, in seconds. It converts "
"the fitted diffusion coefficients (um2/s) and the per-step transition "
"probabilities into physical units."),
'window_length': (
"Number of consecutive time points over which the sequences of states are "
"treated exactly. Longer windows are more accurate but more costly: the "
"multi-transition model scales as nb_states ** window_length, the "
"mono-transition model as window_length * nb_states**2."),
'nb_substeps': (
"Number of transition steps considered between two consecutive positions. "
"1 assumes at most one transition per frame; higher values refine the "
"timing of the transitions at a multiplied cost. The mono-transition "
"fusion model requires 1."),
'threshold': (
"Sequences of states whose means and standard deviations differ by less "
"than this fraction of sigma are fused (multi-transition model only). "
"Lower values are more accurate but keep more sequences; it is increased "
"by 20% automatically whenever the number of sequences exceeds the "
"maximum."),
'max_nb_sequences': (
"Cap on the number of sequences of states kept per track (multi-transition "
"model only). When the cap is exceeded, the fusion threshold is increased "
"by 20% until the number of sequences fits. Lower values are faster but "
"coarser."),
'depth_of_field': (
"Depth of the observable volume in micrometers (e.g. ~0.3 for TIRF, ~0.8 "
"for HILO). It models the probability that a particle leaves the field of "
"view, which corrects the bias of the observed tracks towards slow "
"particles."),
'nb_iters': (
"Number of times the fit is repeated, each round restarting from the "
"previous optimum (first round with the Powell method, later rounds with "
"BFGS). More iterations improve convergence at a proportional cost."),
'draw_plot': (
"If Yes, a plot of the results is displayed at the end of the analysis."),
'initial_fractions': (
"Fraction of the particles in each state at the FIRST time point of the "
"tracks. This is the initial occupancy, not the steady state: along the "
"tracks the occupancies relax towards the equilibrium fractions set by "
"the transition probabilities."),
'batch_files': (
"Every listed file is processed independently, each starting from the "
"parameters of the Parameter Window: fitting first (its fitted "
"parameters feed the later stages of that same file), then depending on "
"the chosen analysis: state labeling, lifetime histograms and position "
"refinement. One csv per stage is written in the save folder, prefixed "
"by the input file name. A file that fails is reported and the batch "
"continues with the next one. Plots are disabled in batch mode, the "
"labeling/histogram sequence caps reuse the values of the single-file "
"windows, and the global parameters are restored at the end of the "
"batch."),
'equilibrium_fractions': (
"Steady-state occupancy of each state implied by the transition "
"probabilities below (read-only, updated live as they are edited). If "
"the tracking starts at steady state, the initial fractions should be "
"close to these values."),
}
def add_param_info(window, row, key, column=2):
"""
A small '?' cell to the right of a hyperparameter value. Clicking it expands
the explanation from HYPERPARAM_INFO next to it; clicking again collapses it.
"""
info_label = tk.Label(window, text=HYPERPARAM_INFO[key], justify='left',
wraplength=340, relief='groove', borderwidth=1,
padx=6, pady=4, bg='#f3f4f6')
expanded = {'on': False}
def toggle():
if expanded['on']:
info_label.grid_remove()
else:
info_label.grid(row=row, column=column+1, padx=padx, pady=2, sticky='w')
expanded['on'] = not expanded['on']
info_button = ttk.Button(window, text='?', width=2, command=toggle)
info_button.grid(row=row, column=column, sticky='w', padx=2)
return info_button
def show_progress_window(window, message):
"""
Transient window shown while an analysis runs ('Fitting on-going...'). The
analyses run in the interface's own thread, so the window is drawn once
(update) before the computation starts and refreshed at the end by
finish_progress_window.
"""
progress_window = tk.Toplevel(window)
progress_window.title("ExTrack")
label = tk.Label(progress_window, text=message, wraplength=380,
justify='center', padx=25, pady=20)
label.pack(expand=True)
progress_window.lift()
progress_window.update()
return progress_window, label
def finish_progress_window(progress_window, label, message):
"""Turn the on-going window into a completion message with an OK button."""
label.config(text=message)
ok_button = ttk.Button(progress_window, text="OK",
command=progress_window.destroy)
ok_button.pack(pady=(0, 12))
progress_window.lift()
progress_window.update()
# Name of the file gathering the fitting results of a whole batch, written in
# the save folder next to the per-replicate outputs.
BATCH_SUMMARY_NAME = 'batch_fitting_summary.csv'
# A batch writes several files per replicate, so it gets a folder of its own
# rather than dropping them straight into the parent of the dataset folder: one
# experiment can then hold several dataset folders without their outputs mixing.
BATCH_RESULTS_DIRNAME = 'Results'
def batch_save_folder(savepath):
"""The save folder a batch proposes: a Results directory inside `savepath`,
which default_save_folder has already set to the parent of the folder the
datasets are read from. Created by run_batch, not here, so that merely
opening the batch window leaves no folder behind."""
return os.path.join(savepath, BATCH_RESULTS_DIRNAME)
# Suffix of the one track file a batch writes per replicate: the state
# predictions and the refined positions in the same table, so that a replicate
# leaves one track file behind instead of one per stage.
BATCH_TRACKS_SUFFIX = '_tracks.csv'
def merge_track_tables(labeled, refined):
"""
One track table out of the labeling and the refinement outputs: the state
predictions beside the refined positions and their localization error, with
the positions, frames, track IDs and optional metrics they have in common
written once. Either side may be None -- the batch mode did not run that
stage -- and the other is then returned unchanged.
Both tables are built by flattening the same tracks dictionary in the same
order, so their rows correspond one to one. That is verified on FRAME and
TRACK_ID rather than assumed, with a merge on those two keys as the fall
back if they ever stop lining up.
"""
if labeled is None or refined is None:
return refined if labeled is None else labeled
keys = [k for k in ['TRACK_ID', 'FRAME'] if k in labeled.columns and k in refined.columns]
if len(keys) != 2:
raise ValueError('the labeling and refinement tables share no TRACK_ID/FRAME columns to merge on: %s vs %s'
%(list(labeled.columns), list(refined.columns)))
extra = [c for c in refined.columns if c not in labeled.columns] # the Refined_* columns
lined_up = len(labeled) == len(refined) and all(
np.array_equal(labeled[k].values.astype(float), refined[k].values.astype(float)) for k in keys)
if lined_up:
merged = labeled.copy()
for c in extra:
merged[c] = refined[c].values
return merged
print('Batch: the labeling and refinement rows do not line up; merging on %s'%keys)
right = refined[keys + extra].copy()
for k in keys: # the refinement table carries the keys as floats, the labeling one as ints
right[k] = right[k].astype(labeled[k].dtype)
return labeled.merge(right, on = keys, how = 'left')
def collect_fitting_summary(fitted, save_folder, filename = BATCH_SUMMARY_NAME):
"""
Gather the one-row fitting result of every replicate of a batch into a single
table and write it to the save folder. `fitted` is the list of (file name,
one-row dataframe returned by _run_fitting_core) of the files that fitted.
This file REPLACES the per-replicate fitting csv, which a batch no longer
writes. Returns (DataFrame, path written), or (None, None) if nothing fitted.
"""
rows = []
for name, row in fitted:
if row is None or len(row) == 0:
print('Batch: no fitting result to summarise for %s'%name)
continue
row = row.drop(columns = ['exp'], errors = 'ignore') # the single-file savepath
row.insert(0, 'dataset', name)
rows.append(row)
if len(rows) == 0:
return None, None
summary = pd.concat(rows, ignore_index = True)
path = os.path.join(save_folder, filename)
try:
summary.to_csv(path, index = False)
except Exception as error:
print('Batch: could not write the fitting summary: %s'%error)
return summary, None
return summary, path
def format_summary_cell(value):
"""Table cells: 4 significant digits for the fitted values, text as it comes."""
try:
value = float(value)
except (TypeError, ValueError):
return str(value)
if not np.isfinite(value):
return str(value)
return '%.4g'%value
def show_fitting_summary(window, summary, max_rows = 12):
"""
The fitted parameters of every replicate, as a table inside the window that
announces the end of the batch. It scrolls in both directions: a fit of n
states carries n**2 + 3n + 3 columns, and a batch has one row per file it
could read.
"""
frame = ttk.Frame(window)
frame.pack(fill = 'both', expand = True, padx = 10, pady = (0, 10))
columns = [str(c) for c in summary.columns]
tree = ttk.Treeview(frame, columns = columns, show = 'headings',
height = min(max_rows, max(1, len(summary))))
cells = [[format_summary_cell(v) for v in row] for row in summary.values]
for i, col in enumerate(columns):
tree.heading(col, text = col)
widest = max([len(col)] + [len(row[i]) for row in cells])
tree.column(col, width = min(200, max(60, 8 * widest + 16)),
anchor = 'w' if col == 'dataset' else 'center', stretch = False)
for row in cells:
tree.insert('', 'end', values = row)
vsb = ttk.Scrollbar(frame, orient = 'vertical', command = tree.yview)
hsb = ttk.Scrollbar(frame, orient = 'horizontal', command = tree.xview)
tree.configure(yscrollcommand = vsb.set, xscrollcommand = hsb.set)
tree.grid(row = 0, column = 0, sticky = 'nsew')
vsb.grid(row = 0, column = 1, sticky = 'ns')
hsb.grid(row = 1, column = 0, sticky = 'ew')
frame.rowconfigure(0, weight = 1)
frame.columnconfigure(0, weight = 1)
# the window was already realised around the message alone: let it grow to
# the table rather than clipping its last row
window.update_idletasks()
window.geometry('')
return tree
# The stages each batch analysis runs on every file of the folder, in order.
# Fitting always comes first: its fitted parameters feed the later stages.
BATCH_STAGES = {"Batch Fitting": ['fitting'],
"Batch Fitting + Labeling": ['fitting', 'labeling'],
"Batch All": ['fitting', 'labeling', 'histogram', 'refinement']}
def read_dataset_file(path, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps):
"""
Read one dataset file, csv (read_table, using the informed headers) or
TrackMate xml (read_trackmate_xml). Raises on any problem; the batch loop
catches per file. Returns (tracks, frames, opt_metrics, input_LocErr).
"""
per_peak = LocErr_type != "Fitted parameter"
if per_peak and 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')
opt_names = Optional_input_name + (LocErr_input_name if per_peak else [])
if path.endswith('.csv'):
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 = opt_names)
else:
tracks, frames, opt_metrics = extrack.readers.read_trackmate_xml(path,
lengths=np.arange(min_length, max_length+1),
dist_th=max_dist,
frames_boundaries=[-np.inf, np.inf],
remove_no_disp=remove_no_disps,
opt_metrics_names = opt_names,
opt_metrics_types = ['float64']*len(opt_names))
input_LocErr = None
if per_peak:
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]
if sum(len(tracks[l]) for l in tracks) == 0:
raise ValueError('No track was loaded: verify the headers and the minimum/maximum track lengths.')
return tracks, frames, opt_metrics, input_LocErr
def browse_savefolder(entry_widget):
folder = filedialog.askdirectory(initialdir=initialdir_from(entry_widget.get()), title="Select Folder")
if folder:
entry_widget.delete(0, tk.END)
entry_widget.insert(tk.END, folder)
# The two ways ExTrack can fuse the sequences of states, mapped to the
# `sequence_scheme` argument of extrack.tracking.param_fitting / predict_Bs.
FUSION_MODELS = {"Multi-transition": "sequences",
"Mono-transition": "ages"}
fusion_model_info = (
"Multi-transition: every sequence of states within the window is considered, "
"so several transitions per window can be resolved. More accurate, but it "
"scales poorly with the number of states: time proportional to "
"nb_states ** window_length.\n"
"Mono-transition: only the time since the last transition is kept. Time "
"proportional to window_length * nb_states**2, so it stays fast with many "
"states or long windows, at the cost of a coarser approximation.")
HYPERPARAM_INFO['fusion_model'] = fusion_model_info
def add_fusion_model_selector(window, row, default):
"""
Dropdown to pick the fusion model, with a '?' cell on the same row that
expands the multi- vs mono-transition trade-off, like the other
hyperparameters. Returns the tk.StringVar holding the selection;
FUSION_MODELS maps it to the sequence_scheme argument of
param_fitting / predict_Bs.
"""
fusion_label = ttk.Label(window, text="Fusion model")
fusion_label.grid(row=row, column=0, sticky = 'e', padx = padx, pady = pady)
fusion_var = tk.StringVar(window)
fusion_var.set(default)
fusion_dropdown = ttk.OptionMenu(window, fusion_var, fusion_var.get(),
*FUSION_MODELS.keys(),
style='My.TMenubutton')
fusion_dropdown.config(width=15)
fusion_dropdown.grid(row=row, column=1)
add_param_info(window, row, 'fusion_model')
return fusion_var
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))
loaded = load_dataset_or_error(window, path, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps)
if loaded is None: # an error panel explains what went wrong
return
tracks, frames, opt_metrics, input_LocErr = loaded
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']))
add_param_info(window, 0, 'nb_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']))
add_param_info(window, 2, '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']))
add_param_info(window, 3, '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']))
add_param_info(window, 4, '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']))
add_param_info(window, 5, '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']))
add_param_info(window, 6, 'max_nb_sequences')
# 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']))
add_param_info(window, 7, 'depth_of_field')
# 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']))
add_param_info(window, 8, 'nb_iters')
# Fusion model (multi- vs mono-transition) and its explanation box
fusion_model_var = add_fusion_model_selector(window, 9, params['fusion_model'])
# Savepath Input
savepath_label = ttk.Label(window, text="Save Path:")
savepath_label.grid(row=11, column=0, sticky = 'e', padx = padx, pady = pady)
savepath_entry = ttk.Entry(window, width=50)
savepath_entry.grid(row=11, 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=11, 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(),
fusion_model = fusion_model_var.get()))
run_button.grid(row=12, 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=12, 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, fusion_model = 'Multi-transition'):
progress_window, progress_label = show_progress_window(window, "Fitting on-going...")
try:
result = _run_fitting_core(window, tracks, dt, nb_states, nb_iterations, nb_substeps, frame_len, cell_dims, LocErr_type, input_LocErr, threshold, max_nb_states, savepath, fusion_model)
except Exception as error:
finish_progress_window(progress_window, progress_label, "Fitting failed:\n%s"%error)
raise
if result is None: # the analysis was refused before starting; an error window explains why
progress_window.destroy()
return
finish_progress_window(progress_window, progress_label, "Fitting finished.\nResults saved to:\n%s"%savepath)
def _run_fitting_core(window, tracks, dt, nb_states, nb_iterations, nb_substeps, frame_len, cell_dims, LocErr_type, input_LocErr, threshold, max_nb_states, savepath, fusion_model = 'Multi-transition'):
# Run the Brownian motion analysis
#tracks = tracks[str(length)]
global params
fusion_scheme = FUSION_MODELS[fusion_model]
if fusion_scheme == 'ages' and nb_substeps != 1:
show_error_url(window, "The mono-transition fusion model does not support substeps.\nSet 'Number of substeps' to 1 or select the multi-transition model.", url=None)
return
params['fusion_model'] = fusion_model
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,
sequence_scheme = fusion_scheme)
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,
sequence_scheme = fusion_scheme)
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
if savepath is not None: # only the batch passes None; its replicates share one summary file
data.to_csv(savepath)
lmfit_params_to_params(lmfit_params)
print("Fitting analysis completed%s"%(" and results saved to %s"%savepath if savepath is not None else ""))
print(data)
return 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):
loaded = load_dataset_or_error(window, path, min_length, max_length, LocErr_type, LocErr_input_name, Optional_input_name, headers, max_dist, remove_no_disps)
if loaded is None: # an error panel explains what went wrong
return
tracks, frames, opt_metrics, input_LocErr = loaded
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']))
add_param_info(window, 0, 'nb_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']))
add_param_info(window, 2, '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']))
add_param_info(window, 3, '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']))
add_param_info(window, 5, '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']))
add_param_info(window, 6, 'max_nb_sequences')
# 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']))
add_param_info(window, 7, 'depth_of_field')
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')
# gridded like the other hyperparameter values (plain column 1, no sticky
# east and no extra padding) so the menu lines up with the entry column
Draw_plot_dropdown.config(width=10)
Draw_plot_dropdown.grid(row=8, column=1)
add_param_info(window, 8, 'draw_plot')
# Fusion model (multi- vs mono-transition) and its explanation box
fusion_model_var = add_fusion_model_selector(window, 9, params['fusion_model'])
# Savepath Input
savepath_label = ttk.Label(window, text="Save Path:")
savepath_label.grid(row=11, column=0, sticky = 'e', padx = padx, pady = pady)
savepath_entry = ttk.Entry(window, width=50)
savepath_entry.grid(row=11, 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=11, 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(),
fusion_model = fusion_model_var.get()))
run_button.grid(row=12, column=1, columnspan=1)
# Previous Button
previous_button = ttk.Button(window, text="Previous", command=lambda: go_to_previous_window(window))
previous_button.grid(row=12, 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, fusion_model = 'Multi-transition'):
progress_window, progress_label = show_progress_window(window, "State labeling on-going...")
try:
result = _run_predictions_core(window, tracks, frames, opt_metrics, dt, nb_states, frame_len, cell_dims, LocErr_type, input_LocErr, threshold, max_nb_states, savepath, Draw_plot, fusion_model)
except Exception as error:
finish_progress_window(progress_window, progress_label, "State labeling failed:\n%s"%error)
raise
if result is None: # the analysis was refused before starting; an error window explains why
progress_window.destroy()
return
finish_progress_window(progress_window, progress_label, "State labeling finished.\nResults saved to:\n%s"%savepath)
def _run_predictions_core(window, tracks, frames, opt_metrics, dt, nb_states, frame_len, cell_dims, LocErr_type, input_LocErr, threshold, max_nb_states, savepath, Draw_plot, fusion_model = 'Multi-transition'):
# Run the Brownian motion analysis
#tracks = tracks[str(length)]
global params
fusion_scheme = FUSION_MODELS[fusion_model]
params['fusion_model'] = fusion_model
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,
sequence_scheme = fusion_scheme)
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))
# Distinct tracks only. Drawing ID = np.random.randint(len(track_list))
# independently for every one of the nb_rows**2 slots samples WITH
# replacement, so the same track was shown several times: with certainty
# when fewer than nb_rows**2 tracks are loaded (example_tracks.csv loads
# 35 for 64 slots), and with high probability otherwise (birthday
# effect). When the data set is smaller than the grid, only that many
# tracks are drawn.
nb_shown = min(nb_rows**2, len(track_list))
shown_IDs = np.random.choice(len(track_list), size = nb_shown, replace = False)
for k, ID in enumerate(shown_IDs):
i, j = k // nb_rows, k % nb_rows
track = track_list[ID]
track = track - np.mean(track, 0, keepdims = True) + [[lim*i, lim*j]]
pred = pred_list[ID]