-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPOTATO_GUI.py
1619 lines (1306 loc) · 65.4 KB
/
POTATO_GUI.py
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
"""Copyright 2021 Helmholtz-Zentrum für Infektionsforschung GmbH"""
""" POTATO -- 2022-12-13 -- Version 1.6
Developed by Lukáš Pekárek and Stefan Buck at the Helmholtz Institute for RNA-based Infection Research
In the research group REMI - Recoding Mechanisms in Infections
Supervisor - Jun. Prof. Neva Caliskan """
""" This script processes Force-Distance Optical Tweezers data in an automated way, to find unfolding events """
""" The script is developed to handle h5 raw data, produced from the C-Trap OT machine from Lumicks,
as well as any other FD data prepared in a csv file (2 columns: Force(pN) - Distance(um)) """
""" Furthermore the script can analyse single constant force files """
""" The parameters can be changed in the GUI before each run.
Alternatively they can be changed permanently in the POTATO_config file"""
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from matplotlib.lines import Line2D
from tkinter import ttk
from PIL import ImageTk, Image
import pandas as pd
import numpy as np
import os
import glob
import time
import multiprocessing as mp
import json
# relative imports
from POTATO_ForceRamp import start_subprocess, read_in_data, show_h5_structure
from POTATO_preprocessing import create_derivative
from POTATO_config import default_values_HF, default_values_LF, default_values_CSV, default_values_FIT, default_values_constantF
from POTATO_constantF import get_constantF, display_constantF, fit_constantF
from POTATO_fitting import fitting_ds, fitting_ss
from POTATO_find_steps import calc_integral
# To avoid blurry GUI - DPI scaling
import ctypes
awareness = ctypes.c_int()
errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(1)
"""define the functions used in the GUI"""
# get settings, get folder directory, create analysis results folder
def start_analysis():
global p0
global analysis_folder
# check user input
input_settings, input_format, export_data, input_fitting, input_constantF = check_settings()
# ask wich directory should be analysed
folder = tk.filedialog.askdirectory()
root.title('POTATO -- ' + str(folder))
# decide which input format was choosen
if input_format['CSV'] == 1:
folder_path = str(folder + "/*.csv")
else:
folder_path = str(folder + "/*.h5")
Files = glob.glob(folder_path)
# print number of files to analyse, if no files found give an error
print('Files to analyse', len(Files))
output_window.insert("end", 'Files to analyse: ' + str(len(Files)) + "\n")
output_window.see("end")
if not len(Files) == 0:
output_window.insert("end", 'Analysis in progress. Please do not close the program! \n')
# print starting time of the analysis
timestamp = time.strftime("%Y%m%d-%H%M%S")
print("Timestamp: " + timestamp)
output_window.insert("end", 'Start of analysis: ' + str(timestamp) + "\n")
output_window.see("end")
# create a folder for the analysis results
analysis_folder = str(folder + '/Analysis_' + timestamp)
os.mkdir(analysis_folder)
# export configuration file with used parameters
export_settings(analysis_folder, timestamp, input_settings, input_fitting)
# start analysis in a new process
p0 = mp.Process(target=start_subprocess, name='Process-0', args=(
analysis_folder,
timestamp,
Files,
input_settings,
input_format,
export_data,
input_fitting,
output_q,
))
p0.daemon = True
p0.start()
else:
output_window.insert("end", 'No file of the selected data type in the folder! \n')
output_window.see("end")
# display default values in the GUI
def parameters(default_values, default_fit, default_constantF):
if not default_values == 0:
downsample_value.set(default_values['Downsampling rate'])
Filter_degree.set(default_values['Butterworth filter degree'])
Filter_cut_off.set(default_values['Cut-off frequency'])
Force_Min.set(default_values['Force threshold, pN'])
Z_score_force.set(default_values['Z-score force'])
Z_score_distance.set(default_values['Z-score distance'])
augment_factor_value.set(2)
step_d_variable.set(str(default_values['Step d']))
window_size_variable.set(str(default_values['Moving median window size']))
STD_difference_variable.set(str(default_values['STD difference threshold']))
Frequency_variable.set(str(default_values['Data frequency, Hz']))
dsLp_variable.set(str(default_fit['Persistance-Length ds, nm']))
dsLp_up_variable.set(str(default_fit['Persistance-Length ds, upper bound, nm']))
dsLp_low_variable.set(str(default_fit['Persistance-Length ds, lower bound, nm']))
ssLp_variable.set(str(default_fit['Persistance-Length ss, nm']))
dsLc_variable.set(str(default_fit['Contour-Length ds, nm']))
ssLc_variable.set(str(default_fit['Contour-Length ss, nm']))
ssLc_up_variable.set(str(default_fit['Contour-Length ss, upper bound, nm']))
stiff_ds_variable.set(str(default_fit['Stiffness ds, pN']))
stiff_ds_up_variable.set(str(default_fit['Stiffness ds, upper bound, pN']))
stiff_ds_low_variable.set(str(default_fit['Stiffness ds, lower bound, pN']))
stiff_ss_variable.set(str(default_fit['Stiffness ss, pN']))
stiff_ss_up_variable.set(str(default_fit['Stiffness ss, upper bound, pN']))
stiff_ss_low_variable.set(str(default_fit['Stiffness ss, lower bound, pN']))
f_off_variable.set(str(default_fit['Force offset, pN']))
f_off_up_variable.set(str(default_fit['Force offset, upper bound, pN']))
f_off_low_variable.set(str(default_fit['Force offset, lower bound, pN']))
d_off_variable.set(str(default_fit['Distance offset, nm']))
d_off_up_variable.set(str(default_fit['Distance offset, upper bound, nm']))
d_off_low_variable.set(str(default_fit['Distance offset, lower bound, nm']))
x_min.delete(0, "end")
x_min.insert("end", str(default_constantF['x min']))
x_max.delete(0, "end")
x_max.insert("end", str(default_constantF['x max']))
y_min.delete(0, "end")
y_min.insert("end", str(default_constantF['y min']))
y_max.delete(0, "end")
y_max.insert("end", str(default_constantF['y max']))
number_gauss.delete(0, "end")
number_gauss.insert("end", str(default_constantF['Number gauss']))
mean_gauss.delete(0, "end")
mean_gauss.insert("end", str(default_constantF['Mean']))
STD_gauss.delete(0, "end")
STD_gauss.insert("end", str(default_constantF['STD']))
amplitude_gauss.delete(0, "end")
amplitude_gauss.insert("end", str(default_constantF['Amplitude']))
# get all settings from the user input before start of the analysis
def check_settings():
input_settings = {
'downsample_value': int(downsample_value2.get()),
'filter_degree': int(Filter_degree2.get()),
'filter_cut_off': float(Filter_cut_off2.get()),
'F_min': float(Force_Min2.get()),
'step_d': int(step_d_value.get()),
'z-score_f': float(Z_score_force2.get()),
'z-score_d': float(Z_score_distance2.get()),
'window_size': int(window_size_value.get()),
'data_frequency': float(Frequency_value.get()),
'STD_diff': float(STD_difference_value.get()),
'augment_factor': augment_factor_value.get()
}
input_format = {
'HF': check_box_HF.get(),
'LF': check_box_LF.get(),
'CSV': check_box_CSV.get(),
'Augment': check_box_augment.get(),
'Trap': check_box_Trap1.get(),
'length_measure': check_box_um.get(),
'MultiH5': check_box_multiH5.get(),
'preprocess': check_box_preprocess.get()
}
export_data = {
'export_SMOOTH': check_box_smooth_data.get(),
'export_PLOT': check_box_plot.get(),
'export_STEPS': check_box_steps.get(),
'export_TOTAL': check_box_total_results.get(),
'export_FIT': check_box_fitting.get()
}
input_fitting = {
'WLC+WLC': int(check_box_WLC.get()),
'WLC+FJC': int(check_box_FJC.get()),
'lp_ds': float(dsLp.get()),
'lp_ds_up': float(dsLp_up.get()),
'lp_ds_low': float(dsLp_low.get()),
'lc_ds': float(dsLc.get()),
'lp_ss': float(ssLp.get()),
'lc_ss': float(ssLc.get()),
'lc_ss_up': float(ssLc_up.get()),
'ds_stiff': float(stiff_ds.get()),
'ds_stiff_up': float(stiff_ds_up.get()),
'ds_stiff_low': float(stiff_ds_low.get()),
'ss_stiff': float(stiff_ss.get()),
'ss_stiff_up': float(stiff_ss_up.get()),
'ss_stiff_low': float(stiff_ss_low.get()),
'offset_f': float(f_off.get()),
'offset_f_up': float(f_off_up.get()),
'offset_f_low': float(f_off_low.get()),
'offset_d': float(d_off.get()),
'offset_d_up': float(d_off_up.get()),
'offset_d_low': float(d_off_low.get())
}
input_constantF = {
'x min': int(x_min.get()),
'x max': int(x_max.get()),
'y min': int(y_min.get()),
'y max': int(y_max.get()),
'Number gauss': int(number_gauss.get()),
'Mean': mean_gauss.get(),
'STD': STD_gauss.get(),
'Amplitude': amplitude_gauss.get()
}
return input_settings, input_format, export_data, input_fitting, input_constantF
# export parameters used for the analysis in a txt file
def export_settings(analysis_path, timestamp, input_1, input_2):
with open(str(analysis_path + '/parameters_' + timestamp + '.txt'), 'w') as config_used:
config_used.write('Data processing:\n')
config_used.write(json.dumps(input_1, indent=4, sort_keys=False))
config_used.write('\n\n')
config_used.write('Fitting parameters:\n')
config_used.write(json.dumps(input_2, indent=4, sort_keys=False))
# Looks for output of the subprocess
def refresh():
global new_image
while output_q.empty() is False:
output = output_q.get()
output_window.insert("end", "\n" + output + "\n")
output_window.see("end")
try:
images = str(analysis_folder + "/*plot*.png")
list_images = glob.glob(images)
img = Image.open(list_images[-1].replace("\\", "\\\\"))
resized = img.resize((1000, 650), Image.ANTIALIAS)
new_image = ImageTk.PhotoImage(resized)
figure_frame.create_image((0, 0), image=new_image, anchor="nw")
except:
pass
def readme():
with open("POTATO_readme.txt", "r") as f:
help_text = f.read()
help_window = tk.Toplevel(root)
help_window.title("Readme")
text = tk.Text(help_window, height=25, width=200)
text.grid(row=0, column=0, sticky="nw")
text.insert("end", help_text)
# display a single file (tab2)
def get_single_file(format):
if format == 'csv':
if not check_box_CSV.get() == 1:
check_box_CSV.set(value=1)
select_box(check_box_CSV, check_box_HF, check_box_LF)
parameters(default_values_CSV, default_values_FIT, default_values_constantF)
else:
pass
input_settings, input_format, export_data, input_fitting, input_constantF = check_settings()
import_file_path = tk.filedialog.askopenfilename()
input_format['preprocess'] = 0
FD_raw, FD_raw_um, Frequency_value, filename = read_in_data(0, [import_file_path], input_settings, input_format)
input_format['preprocess'] = 1
FD, FD_um, Frequency_value, filename = read_in_data(0, [import_file_path], input_settings, input_format)
display_RAW_FD(FD[:, 0], FD[:, 1], FD_raw[:, 0], FD_raw[:, 1], filename)
def show_h5():
import_file_path = tk.filedialog.askopenfilename()
h5_structure = show_h5_structure(import_file_path)
h5_structure_window = tk.Toplevel(root)
h5_structure_window.title("H5 structure")
text = tk.Text(h5_structure_window, height=50, width=200)
scroll_bar = tk.Scrollbar(h5_structure_window, command=text.yview)
scroll_bar.pack(side=tk.RIGHT, fill=tk.Y)
text['yscrollcommand'] = scroll_bar.set
text.pack(side=tk.LEFT, fill=tk.Y)
text.insert("end", h5_structure)
# create the plot for tab2
def display_RAW_FD(processed_F, processed_D, raw_F, raw_D, filename):
global figure_raw
try:
figure_raw.get_tk_widget().destroy()
except:
pass
single_fd = Figure(figsize=(10, 6), dpi=100)
subplot1 = single_fd.add_subplot(111)
legend_elements = [
Line2D([0], [0], color='C0', lw=4),
Line2D([0], [0], color='C1', lw=4)
]
subplot1.set_title(str(filename))
subplot1.set_xlabel("Distance (nm)")
subplot1.set_ylabel("Force (pN)")
subplot1.scatter(raw_D, raw_F, alpha=0.8, color='C0', s=0.1, zorder=0)
subplot1.scatter(processed_D, processed_F, marker='.', s=0.1, linewidths=None, alpha=1, color='C1', zorder=1)
subplot1.legend(legend_elements, ['Downsampled FD-Data', 'Filtered FD-Data'])
figure_raw = FigureCanvasTkAgg(single_fd, figure_frame2)
figure_raw.get_tk_widget().grid(row=0, column=0, sticky='wens')
tabControl.select(tab2)
def start_constantF():
input_settings, input_format, export_data, input_fitting, input_constantF = check_settings()
Force_Distance, Force_Distance_um, frequency, filename, analysis_path, timestamp = get_constantF(input_settings, input_format, input_constantF)
fig_constantF, hist_D, filteredDistance_ready = display_constantF(Force_Distance, Force_Distance_um, frequency, input_settings, input_constantF)
os.mkdir(analysis_path)
export_settings(analysis_path, timestamp, input_settings, input_constantF)
fig_constantF = fit_constantF(hist_D, Force_Distance, filteredDistance_ready, frequency, input_settings, input_constantF, filename, timestamp)
fig_constantF_tk = FigureCanvasTkAgg(fig_constantF, figure_frame_tab4)
fig_constantF_tk.get_tk_widget().grid(row=0, column=0, sticky='wens')
tabControl.select(tab4)
def show_constantF():
input_settings, input_format, export_data, input_fitting, input_constantF = check_settings()
Force_Distance, Force_Distance_um, frequency, filename, analysis_path, timestamp = get_constantF(input_settings, input_format, input_constantF)
fig_constantF, hist_D, filteredDistance_ready = display_constantF(Force_Distance, Force_Distance_um, frequency, input_settings, input_constantF)
fig_constantF_tk = FigureCanvasTkAgg(fig_constantF, figure_frame_tab4)
fig_constantF_tk.get_tk_widget().grid(row=0, column=0, sticky='wens')
tabControl.select(tab4)
def on_closing():
# makes sure all python processes/loops are cancelled before exiting
if tk.messagebox.askokcancel("Quit", "Do you really want to quit?"):
root.quit()
################ TOMATO ###############################
from POTATO_TOMATO import plot_TOMATO
############# define the functions for TOMATO ##################
def open_folder():
global filename_TOMATO
global Force_Distance_TOMATO
global der_arr_TOMATO
global TOMATO_fig1
global Files
global FD_number
# check user input
input_settings, input_format, export_data, input_fitting, input_constantF = check_settings()
# ask wich directory should be analysed
folder = tk.filedialog.askdirectory()
root.title('POTATO -- ' + str(folder))
# decide which input format was choosen
if input_format['CSV'] == 1:
folder_path = str(folder + "/*.csv")
else:
folder_path = str(folder + "/*.h5")
Files = glob.glob(folder_path)
FD_number = 0
Force_Distance_TOMATO, Force_Distance_um_TOMATO, Frequency_value, filename_TOMATO = read_in_data(FD_number, Files, input_settings, input_format)
der_arr_TOMATO = create_derivative(input_settings, Frequency_value, Force_Distance_TOMATO[:, 0], Force_Distance_TOMATO[:, 1], 0)
entryText_filename.set(filename_TOMATO)
try:
TOMATO_fig1.get_tk_widget().destroy()
except:
pass
fig = plot_TOMATO(Force_Distance_TOMATO)
TOMATO_fig1 = FigureCanvasTkAgg(fig, TOMATO_figure_frame)
TOMATO_fig1.get_tk_widget().grid(row=0, column=0, sticky='wens')
toolbarFrame = tk.Frame(master=TOMATO_figure_frame)
toolbarFrame.grid(row=2, column=0)
toolbar = NavigationToolbar2Tk(TOMATO_fig1, toolbarFrame)
def change_FD(direction):
global TOMATO_fig1
global filename_TOMATO
global FD_number
global Force_Distance_TOMATO
global orientation
FD_number = FD_number + direction
if FD_number == len(Files):
FD_number = FD_number - len(Files)
if FD_number < 0:
FD_number = FD_number + len(Files)
delete_all_steps()
input_settings, input_format, export_data, input_fitting, input_constantF = check_settings()
Force_Distance_TOMATO, Force_Distance_um_TOMATO, Frequency_value, filename_TOMATO = read_in_data(FD_number, Files, input_settings, input_format)
orientation = 'forward'
if Force_Distance_TOMATO[0, 1] > Force_Distance_TOMATO[-1, 1]: # reverse
Force_Distance_TOMATO = np.flipud(Force_Distance_TOMATO)
Force_Distance_um_TOMATO = np.flipud(Force_Distance_um_TOMATO)
orientation = 'reverse'
entryText_filename.set(filename_TOMATO)
parameters(0, default_values_FIT, default_values_constantF)
TOMATO_fig1.get_tk_widget().destroy()
fig = plot_TOMATO(Force_Distance_TOMATO)
TOMATO_fig1 = FigureCanvasTkAgg(fig, TOMATO_figure_frame)
TOMATO_fig1.get_tk_widget().grid(row=0, column=0, sticky='wens')
toolbarFrame = tk.Frame(master=TOMATO_figure_frame)
toolbarFrame.grid(row=2, column=0)
toolbar = NavigationToolbar2Tk(TOMATO_fig1, toolbarFrame)
# key binding wrapper functions
def previous_FD_key(event):
change_FD(-1)
def next_FD_key(event):
change_FD(+1)
def save_step_key(event):
save_step()
def start_analysis_key(event):
analyze_steps()
def start_click_key(event):
start_click()
def end_click_key(event):
end_click()
def start_click():
global cid
cid = TOMATO_fig1.mpl_connect('button_press_event', lambda event, arg=1: onclick_start_end(event, arg))
def end_click():
global cid
cid = TOMATO_fig1.mpl_connect('button_press_event', lambda event, arg=0: onclick_start_end(event, arg))
def onclick_start_end(event, pos):
global cid
PD_position, F_position = float(event.xdata), float(event.ydata)
if pos == 1:
entryText_startF.set(round(F_position, 1))
entryText_startD.set(round(PD_position, 1))
elif pos == 0:
entryText_endF.set(round(F_position, 1))
entryText_endD.set(round(PD_position, 1))
TOMATO_fig1.mpl_disconnect(cid)
def save_step():
global step_number
try:
tree_steps.insert('', 'end', values=(step_number, entryText_startF.get(), entryText_endF.get(), entryText_startD.get(), entryText_endD.get()))
step_number += 1
except:
print('Please make sure step start and step end are selected!')
def analyze_steps():
global TOMATO_fig1
global subplot1
global tree_results
# get input settings
input_settings, input_format, export_data, input_fitting, input_constantF = check_settings()
timestamp = time.strftime("%Y%m%d-%H%M%S")
# write step list into pandas dataframe
row_list = []
columns = ('Step number', 'F start', 'F end', 'Step start', 'Step end')
for row in tree_steps.get_children():
row_list.append(tree_steps.item(row)["values"])
treeview_df = pd.DataFrame(row_list, columns=columns)
# iterate through dataframe and fit each part of the curve
TOMATO_fig1.get_tk_widget().destroy()
figure1 = plot_TOMATO(Force_Distance_TOMATO)
diff_colors = ['b', 'r', 'c', 'g', 'y', 'm', 'b', 'r', 'c', 'g', 'y', 'm', 'b', 'r', 'c', 'g', 'y', 'm', 'b', 'r', 'c', 'g', 'y', 'm']
subplot1 = figure1.add_subplot(111)
subplot1.plot(Force_Distance_TOMATO[:, 1], Force_Distance_TOMATO[:, 0], color='gray')
distance = np.arange(min(Force_Distance_TOMATO[:, 1]), max(Force_Distance_TOMATO[:, 1]) + 50, 2)
export_fit = []
fit = []
start_force_ss = []
start_distance_ss = []
integral_ss_fit_start = []
integral_ss_fit_end = []
for i in treeview_df.index:
# part before first step is fitted with a single WLC model (ds part)
if treeview_df['Step number'][i] == 1:
j = treeview_df['Step number'][i]
ds_fit_dict_TOMATO, TOMATO_area_ds, real_step_start = fitting_ds(filename_TOMATO, input_settings, export_data, input_fitting, float(treeview_df['Step start'][i]), Force_Distance_TOMATO, der_arr_TOMATO, [], 1)
ds_fit_region_end = real_step_start
dsLp_variable.set(ds_fit_dict_TOMATO['Lp_ds'])
f_off_variable.set(ds_fit_dict_TOMATO['f_offset'])
d_off_variable.set(ds_fit_dict_TOMATO["d_offset"])
dsLc_variable.set(ds_fit_dict_TOMATO['Lc_ds'])
stiff_ds_variable.set(ds_fit_dict_TOMATO['St_ds'])
tree_results.insert("", "end", iid='{}no step'.format(timestamp), values=(
entryText_filename.get(),
i,
'',
'',
'',
'',
'',
'',
dsLc_variable.get(),
dsLp_variable.get(),
stiff_ds_variable.get(),
'',
'',
'',
f_off_variable.get(),
d_off_variable.get(),
'',
''
)
)
export_fit.append(ds_fit_dict_TOMATO)
F_ds_model = ds_fit_dict_TOMATO['model_ds'](distance, ds_fit_dict_TOMATO['fit_model'].params)
# plot the marked ds region and fits
subplot1.plot(Force_Distance_TOMATO[:, 1][:real_step_start], Force_Distance_TOMATO[:, 0][:real_step_start], color=diff_colors[i])
subplot1.plot(distance, F_ds_model, marker=None, linestyle='dashed', linewidth=1, color="black")
# fit the other ss parts
elif treeview_df['Step number'][i] > 1:
j = treeview_df['Step number'][i]
fit_ss, f_fitting_region_ss, d_fitting_region_ss, ss_fit_dict_TOMATO, area_ss_fit_start, area_ss_fit_end = fitting_ss(filename_TOMATO, input_settings, export_data, input_fitting, float(treeview_df['Step end'][i - 1]), float(treeview_df['Step start'][i]), Force_Distance_TOMATO, 1, 1, der_arr_TOMATO, [], 1)
fit.append(fit_ss)
start_force_ss.append(f_fitting_region_ss)
start_distance_ss.append(d_fitting_region_ss)
export_fit.append(ss_fit_dict_TOMATO)
integral_ss_fit_start.append(area_ss_fit_start)
integral_ss_fit_end.append(area_ss_fit_end)
ssLp_variable.set(ss_fit_dict_TOMATO['Lp_ss'])
f_off_variable.set(ss_fit_dict_TOMATO['f_offset'])
d_off_variable.set(ss_fit_dict_TOMATO["d_offset"])
ssLc_variable.set(ss_fit_dict_TOMATO['Lc_ss'])
stiff_ss_variable.set(ss_fit_dict_TOMATO['St_ss'])
tree_results.insert("", "end", iid='{}step{}'.format(timestamp, j-1), values=(
entryText_filename.get(),
i,
Force_Distance_TOMATO[real_step_start, 0],
f_fitting_region_ss[0],
(f_fitting_region_ss[0] + Force_Distance_TOMATO[real_step_start, 0]) / 2,
Force_Distance_TOMATO[real_step_start, 1],
d_fitting_region_ss[0],
d_fitting_region_ss[0] - Force_Distance_TOMATO[real_step_start, 1],
'',
'',
'',
ssLc_variable.get(),
ssLp_variable.get(),
stiff_ss_variable.get(),
f_off_variable.get(),
d_off_variable.get(),
'',
''
)
)
real_step_start = np.where(Force_Distance_TOMATO[:, 0] == f_fitting_region_ss[-1])
real_step_start = real_step_start[0][0]
# plot the marked regions and fits
# model data
F_ss_model = ss_fit_dict_TOMATO['model_ss'](distance, fit_ss.params)
# plot the marked ss region and fits
subplot1.plot(d_fitting_region_ss[:], f_fitting_region_ss, color=diff_colors[i])
subplot1.plot(distance, F_ss_model, marker=None, linewidth=1, linestyle='dashed', color="black")
# fit the last part of the curve
fit_ss, f_fitting_region_ss, d_fitting_region_ss, ss_fit_dict_TOMATO, area_ss_fit_start, area_ss_fit_end = fitting_ss(
filename_TOMATO,
input_settings,
export_data,
input_fitting,
float(treeview_df['Step end'][len(treeview_df) - 1]),
max(Force_Distance_TOMATO[:, 1]),
Force_Distance_TOMATO,
1,
1,
der_arr_TOMATO,
[],
1
)
fit.append(fit_ss)
start_force_ss.append(f_fitting_region_ss)
start_distance_ss.append(d_fitting_region_ss)
export_fit.append(ss_fit_dict_TOMATO)
integral_ss_fit_start.append(area_ss_fit_start)
integral_ss_fit_end.append(area_ss_fit_end)
ssLp_variable.set(ss_fit_dict_TOMATO['Lp_ss'])
f_off_variable.set(ss_fit_dict_TOMATO['f_offset'])
d_off_variable.set(ss_fit_dict_TOMATO["d_offset"])
ssLc_variable.set(ss_fit_dict_TOMATO['Lc_ss'])
stiff_ss_variable.set(ss_fit_dict_TOMATO['St_ss'])
tree_results.insert("", "end", iid='{}step{}'.format(timestamp, j), values=(
entryText_filename.get(),
j,
Force_Distance_TOMATO[:, 0][real_step_start],
f_fitting_region_ss[0],
(f_fitting_region_ss[0] + Force_Distance_TOMATO[:, 0][real_step_start]) / 2,
Force_Distance_TOMATO[:, 1][real_step_start],
d_fitting_region_ss[0],
d_fitting_region_ss[0] - Force_Distance_TOMATO[:, 1][real_step_start],
'',
'',
'',
ssLc_variable.get(),
ssLp_variable.get(),
stiff_ss_variable.get(),
f_off_variable.get(),
d_off_variable.get(),
'',
''
)
)
work_first_step, kT_1 = calc_integral(
TOMATO_area_ds,
integral_ss_fit_start[0],
Force_Distance_TOMATO[ds_fit_region_end, 1],
start_distance_ss[0][0],
Force_Distance_TOMATO[ds_fit_region_end, 0],
start_force_ss[0][0]
)
tree_results.set('{}step1'.format(timestamp), column='Work [pN*nm]', value=work_first_step)
tree_results.set('{}step1'.format(timestamp), column='Work [kT]', value=kT_1)
if j > 1:
for n in range(1, j):
print(start_distance_ss[n - 1][-1])
print(start_distance_ss[n][0])
work_step_n, kT_n = calc_integral(
integral_ss_fit_end[n - 1],
integral_ss_fit_start[n],
start_distance_ss[n - 1][-1],
start_distance_ss[n][0],
start_force_ss[n - 1][-1],
start_force_ss[n][0]
)
print('WORK', work_step_n)
tree_results.set('{}step{}'.format(timestamp, n+1), column='Work [pN*nm]', value=work_step_n)
tree_results.set('{}step{}'.format(timestamp, n+1), column='Work [kT]', value=kT_n)
# plot the marked regions and fits
# model data
F_ss_model = ss_fit_dict_TOMATO['model_ss'](distance, fit_ss.params)
# plot the marked ss region and fits
subplot1.plot(d_fitting_region_ss[:], f_fitting_region_ss, color=diff_colors[j + 1])
subplot1.plot(distance, F_ss_model, marker=None, linewidth=1, linestyle='dashed', color="black")
subplot1.set_ylim([min(Force_Distance_TOMATO[:, 0]), max(Force_Distance_TOMATO[:, 0])])
subplot1.set_xlim([min(Force_Distance_TOMATO[:, 1]) - 10, max(Force_Distance_TOMATO[:, 1]) + 10])
subplot1.tick_params('both', direction='in')
TOMATO_fig1 = FigureCanvasTkAgg(figure1, TOMATO_figure_frame)
TOMATO_fig1.get_tk_widget().grid(row=0, column=0)
toolbarFrame = tk.Frame(master=TOMATO_figure_frame)
toolbarFrame.grid(row=2, column=0)
toolbar = NavigationToolbar2Tk(TOMATO_fig1, toolbarFrame)
def delete_step():
global step_number
list_items = tree_steps.get_children("")
tree_steps.delete(list_items[-1])
step_number -= 1
def delete_all_steps():
global step_number
tree_steps.delete(*tree_steps.get_children())
step_number = 1
def delete_result(event):
selected_items = tree_results.selection()
for selected_item in selected_items:
tree_results.delete(selected_item)
def clear_table():
global tree_results
list_items = tree_results.get_children("")
for item in list_items:
tree_results.delete(item)
def clear_table_last():
global tree_results
list_items = tree_results.get_children("")
tree_results.delete(list_items[-1])
def export_table():
global tree_results
global name
global Fit_results
''' exporting the table results '''
results = []
for child in tree_results.get_children():
results.append(tree_results.item(child)['values'])
Fit_results = pd.DataFrame(results, columns=[
'Filename',
'step number',
'Force step start [pN]',
'Force step end [pN]',
'mean force [pN]',
'extension step start [nm]',
'extension step end [nm]',
'Step length [nm]',
'ds contour length',
'ds persistance Length',
'ds stiffness (K0) [pN]',
'ss contour Length',
'ss persistance Length',
'ss stiffness (K0) [pN]',
'Force offset',
'Distance offset',
'Work [pN*nm]',
'Work [kT]'
])
name = tk.filedialog.asksaveasfile(mode='w', defaultextension=".csv")
Fit_results.to_csv(name.name, index=False, header=True)
def tab_bind(event=None):
if tabControl.index(tabControl.select()) == 4:
root.bind("<Right>", next_FD_key)
root.bind("<Left>", previous_FD_key)
root.bind("<s>", start_click_key)
root.bind("<e>", end_click_key)
root.bind("<Control-s>", save_step_key)
root.bind("<Control-f>", start_analysis_key)
root.bind("<Delete>", delete_result)
else:
root.unbind("<Right>")
root.unbind("<Left>")
root.unbind("<s>")
root.unbind("<e>")
root.unbind("<Control-s>")
root.unbind("<Control-f>")
root.unbind("<Delete>")
############## TOMATO functions end ###################
""" start the main process and Tkinter application """
if __name__ == '__main__':
mp.freeze_support()
root = tk.Tk()
root.iconbitmap('POTATO.ico')
root.title("POTATO -- Practical Optical Tweezers Analysis TOol")
output_q = mp.Queue()
# create a drop down menu
drop_down_menu = tk.Menu(root)
root.config(menu=drop_down_menu)
# first drop down possibility: File
file_menu = tk.Menu(drop_down_menu, tearoff=0)
drop_down_menu.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='Analyse folder (FD curves)', command=start_analysis)
file_menu.add_command(label='Display single FD curve (h5)', command=lambda: get_single_file('h5'))
file_menu.add_command(label='Display single FD curve (csv)', command=lambda: get_single_file('csv'))
file_menu.add_command(label='Show h5 file structure', command=lambda: show_h5())
file_menu.add_separator()
file_menu.add_command(label='Display constant force', command=show_constantF)
file_menu.add_command(label='Fit constant force', command=start_constantF)
# second drop down possibility: Settings
settings_menu = tk.Menu(drop_down_menu, tearoff=0)
drop_down_menu.add_cascade(label='Settings', menu=settings_menu)
settings_menu.add_command(label='Set advanced settings', command=lambda: tabControl.select(tab3))
# third drop down possibility: Help
help_menu = tk.Menu(drop_down_menu, tearoff=0)
drop_down_menu.add_cascade(label='Help', menu=help_menu)
help_menu.add_command(label='Readme', command=readme)
# Create different GUI tabs
tabControl = ttk.Notebook(root)
tabControl.grid(row=0, column=0, padx=2, pady=2)
tab1 = ttk.Frame(tabControl, width=800, height=600)
tab2 = ttk.Frame(tabControl, width=800, height=600)
tab3 = ttk.Frame(tabControl, width=800, height=600)
tab4 = ttk.Frame(tabControl, width=800, height=600)
tab5 = ttk.Frame(tabControl, width=800, height=600)
# ATTENTION - tab3 and tab4 are displayed the other way round in the GUI
tabControl.add(tab1, text="Folder Analysis")
tabControl.add(tab2, text="Show Single File")
tabControl.add(tab4, text="Constant Force Analysis")
tabControl.add(tab3, text="Advanced Settings")
tabControl.add(tab5, text="Manual Analysis - TOMATO")
tabControl.pack(expand=4, fill='both')
root.bind('<<NotebookTabChanged>>', tab_bind)
""" divide the tab1 into frames """
# output window
output_frame = tk.Frame(tab1, height=50)
output_frame.grid(row=0, column=0)
output_window = tk.Text(output_frame, height=6, width=115)
output_window.grid(row=0, column=0)
output_window.insert(
"end",
"Welcome to POTATO! \n"
"Please make sure to select the right datatype -----------------------------------------------------------------> \n"
"Parameters should be adjusted prior to analysis.\n"
"Folders with multiple files can be analysed at once.\n"
)
refresh_button = tk.Button(
output_frame,
text='Refresh',
command=refresh,
bg='#df4c4c',
activebackground='#eaa90d',
font='Helvetica 7 bold',
height=3,
width=6,
cursor="exchange"
)
refresh_button.grid(row=0, column=1, padx=5)
# check boxes
check_box = tk.Frame(tab1)
check_box.grid(row=0, column=1)
def select_box(*check_box):
for i in check_box:
if i.get() == 1:
for n in check_box:
if not n == i:
n.set(value=0)
boxes = [check_box[x].get() for x in range(len(check_box))]
if all(boxes) == 0:
check_box[0].set(value=1)
check_box_HF = tk.IntVar(value=1)
check_box_LF = tk.IntVar()
check_box_CSV = tk.IntVar()
check_box_augment = tk.IntVar()
check_box_Trap1 = tk.IntVar()
check_box_Trap2 = tk.IntVar(value=1)
check_box_um = tk.IntVar(value=1)
check_box_nm = tk.IntVar()
check_box_multiH5 = tk.IntVar()
check_box_preprocess = tk.IntVar(value=1)
check_HF = tk.Checkbutton(
check_box,
text="High Frequency (Piezo Distance)",
variable=check_box_HF,
command=lambda: [select_box(check_box_HF, check_box_LF, check_box_CSV), parameters(default_values_HF, default_values_FIT, default_values_constantF)]
).grid(row=0, column=0, sticky='W')
check_LF = tk.Checkbutton(
check_box,
text="Low Frequency",
variable=check_box_LF,
command=lambda: [select_box(check_box_LF, check_box_HF, check_box_CSV), parameters(default_values_LF, default_values_FIT, default_values_constantF)]
).grid(row=1, column=0, sticky='W')
check_CSV = tk.Checkbutton(
check_box,
text="CSV (F(pN) | d)",
variable=check_box_CSV,
command=lambda: [select_box(check_box_CSV, check_box_HF, check_box_LF), parameters(default_values_CSV, default_values_FIT, default_values_constantF)]
).grid(row=2, column=0, sticky='W')
check_augment = tk.Checkbutton(
check_box,
text="Data Augmentation",
variable=check_box_augment,
command=lambda: show_augment()
).grid(row=3, column=0, sticky='W')
check_Trap1 = tk.Checkbutton(
check_box,
text="Trap 1x",
variable=check_box_Trap1,
command=lambda: select_box(check_box_Trap1, check_box_Trap2)
).grid(row=0, column=1, padx=8, sticky='W')
check_Trap2 = tk.Checkbutton(
check_box,
text="Trap 2x",
variable=check_box_Trap2,
command=lambda: select_box(check_box_Trap2, check_box_Trap1)
).grid(row=1, column=1, padx=8, sticky='W')
check_um = tk.Checkbutton(
check_box,
text="µm input",
variable=check_box_um,
command=lambda: select_box(check_box_um, check_box_nm)
).grid(row=2, column=1, padx=8, sticky='W')
check_nm = tk.Checkbutton(
check_box,
text="nm input",
variable=check_box_nm,
command=lambda: select_box(check_box_nm, check_box_um)
).grid(row=3, column=1, padx=8, sticky='W')
check_Multi = tk.Checkbutton(
check_box,
text="MultiH5",
variable=check_box_multiH5
).grid(row=4, column=0, sticky='W')
figure_frame = tk.Canvas(tab1, height=650, width=1000, borderwidth=1, relief='ridge')
figure_frame.grid(row=1, column=0)
parameter_frame = tk.Frame(tab1)
parameter_frame.grid(row=1, column=1, sticky='NE')
""" parameter frame """
Cluster_preprocessing = tk.Label(parameter_frame, text='PREPROCESSING', font='Helvetica 9 bold')
check_preprocess = tk.Checkbutton(
parameter_frame,
variable=check_box_preprocess
).grid(row=0, column=1, pady=(20, 2), sticky='W')
Label_downsample = tk.Label(parameter_frame, text='Downsampling rate')
Label_Filter1 = tk.Label(parameter_frame, text='Butterworth filter degree')
Label_Filter2 = tk.Label(parameter_frame, text='Cut-off frequency')