-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
executable file
·755 lines (647 loc) · 32.4 KB
/
main.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
# coding: utf-8
import pandas as pd
import janitor
import tkinter as tk
from datetime import datetime
from pandas import ExcelWriter
from tkinter import scrolledtext
from utils import *
from models import DataFile
from PIL.ImageTk import PhotoImage
from webbrowser import open as url_open
SEARCH_URL = "https://google.com.au/search?q=molar mass of "
IMPLEMENTED = [
('Bruker', 'Amino Acids'),
('Waters', 'Tryptophan'),
('Waters', 'Bile Acids'),
('WConversion', 'Conversion'),
]
COMPOUNDS_FILE = "compounds.json"
class CustomDialog:
def __init__(self, master):
self.dialog = tk.Toplevel(master)
self.dialog_image = tk.Label(self.dialog)
self.dialog_image.pack(padx=(10, 10), pady=2, side=tk.LEFT)
self.dialog_label = tk.Label(self.dialog, text="")
self.dialog_label.pack(padx=(10, 15), pady=15, side=tk.LEFT)
self.dialog_button = tk.Button(self.dialog, text="OK", command=lambda: self.dialog.withdraw())
self.dialog_button.pack(padx=5, pady=5, side=tk.BOTTOM)
self.dialog.wm_protocol("WM_DELETE_WINDOW", lambda: master.on_delete_child(self.dialog))
def _set_label(self, message, bg):
self.dialog_label.configure(text=f"\n{message}\n", bg=bg)
def error(self, message, title="Error"):
self.dialog.wm_title(title)
self.dialog.title(title)
my_image = tk.PhotoImage(file="error_icon.png")
self.dialog_image.configure(image=my_image, bg="#ffe8f5")
self.dialog_image.photo = my_image
self._set_label(message, '#ffe8f5')
self.dialog.configure(bg="#ffe8f5")
def success(self, message, title="Success"):
self.dialog.wm_title(title)
self.dialog.title(title)
my_image = tk.PhotoImage(file="success_icon.png")
self.dialog_image.configure(image=my_image, bg="#eeffdd")
self.dialog_image.photo = my_image
self._set_label(message, '#eeffdd')
self.dialog.configure(bg="#eeffdd")
def bring_to_top(self):
self.dialog.attributes('-topmost', 'true')
self.dialog.deiconify()
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.menubar = None
self.missing_compound = tk.StringVar()
self.missing_compound_mass = tk.StringVar()
self.input_box = None
self.optionsbar = None
self.selections_machine_text = None
self.selections_folder_text = None
self.selections_file_text = None
self.selections_analysis_text = None
self.status_message = None
self.process_button = None
self.selected_cwd = False
self.pack(fill='both', padx=2, pady=2)
self.master.title('ANPC - Flip L2W')
self.machine_type = tk.StringVar(value="Bruker")
self.analysis_type = tk.StringVar(value="Amino Acids")
self.load_config()
self.create_widgets()
self.df = pd.DataFrame()
self.config_window = False
self.messagebox = None
self.compounds = self.load_compounds()
self.cwd_lf = None
self.dir_lf = None
self.data_lf = None
self.data_frame = None
self.data_label = None
self.change_color()
def load_compounds(self):
if os.path.isfile(COMPOUNDS_FILE):
with open(COMPOUNDS_FILE) as f:
compounds = json.load(f)
return compounds
def load_config(self):
self.config = get_config()
def get_current_dir(self):
return self.config["cwd"]
def disable_analysis_types(self):
for w in self.analysis_lf.winfo_children():
w.configure(state=tk.DISABLED)
def show_bruker_analysis_types(self):
self.analysis_lf.configure(text="Analysis (Bruker)")
self.disable_analysis_types()
for w in self.analysis_lf.winfo_children():
if w['text'] in self.bruker_analysis_types:
w.configure(state=tk.NORMAL)
def show_waters_analysis_types(self):
self.analysis_lf.configure(text="Analysis (Waters)")
self.disable_analysis_types()
for w in self.analysis_lf.winfo_children():
if w['text'] in self.waters_analysis_types:
w.configure(state=tk.NORMAL)
def show_sciex_analysis_types(self):
self.analysis_lf.configure(text="Analysis (Sciex)")
self.disable_analysis_types()
for w in self.analysis_lf.winfo_children():
if w['text'] in self.sciex_analysis_types:
w.configure(state=tk.NORMAL)
def show_conversion_analysis_types(self):
self.analysis_lf.configure(text="Conversion")
self.disable_analysis_types()
for w in self.analysis_lf.winfo_children():
if w['text'] in self.wconversion_analysis_types:
w.configure(state=tk.NORMAL)
def toggle_unit_conc(self, enable):
if enable:
self.unit_conc_lf.configure(text="Tryptophan")
for w in self.unit_conc_lf.winfo_children():
w.configure(state=tk.NORMAL)
else:
self.unit_conc_lf.configure(text=" ")
for w in self.unit_conc_lf.winfo_children():
w.configure(state=tk.DISABLED)
def toggle_unit_conc_micro(self, enable):
if enable:
self.unit_conc_lf.configure(text="Tryptophan")
for w in self.unit_conc_lf.winfo_children():
w.configure(state=tk.NORMAL)
else:
self.unit_conc_lf.configure(text=" ")
for w in self.unit_conc_lf.winfo_children():
w.configure(state=tk.DISABLED)
def toggle_double_conc(self, enable):
if enable:
self.double_conc_lf.configure(text="Amino Acids")
for w in self.double_conc_lf.winfo_children():
w.configure(state=tk.NORMAL)
else:
self.double_conc_lf.configure(text=" ")
for w in self.double_conc_lf.winfo_children():
w.configure(state=tk.DISABLED)
def set_processing_options(self):
analysis_type = self.get_analysis_type()
if analysis_type == "Tryptophan":
self.toggle_unit_conc(True)
self.toggle_double_conc(False)
elif analysis_type == "Amino Acids":
self.toggle_double_conc(True)
self.toggle_unit_conc(False)
elif analysis_type == "Conversion":
self.toggle_double_conc(False)
self.toggle_unit_conc(True)
else:
self.toggle_double_conc(False)
self.toggle_unit_conc(False)
def set_selections_text(self):
self.status_message.configure(text=f" ", fg="#000")
machine = self.machine_type.get()
if machine == 'Waters':
self.show_waters_analysis_types()
if machine == 'Sciex':
self.show_sciex_analysis_types()
if machine == 'Bruker':
self.show_bruker_analysis_types()
if machine == 'WConversion':
self.show_conversion_analysis_types()
analysis_type = self.get_analysis_type()
message = f"Folder: {self.get_current_dir()}"
self.selections_folder_text.configure(text=message)
message = f"Machine: {machine}"
self.selections_machine_text.configure(text=message)
message = f"File type: .{self.get_file_type()}"
self.selections_file_text.configure(text=message)
message = f"Analysis: {analysis_type}"
self.selections_analysis_text.configure(text=message)
self.set_processing_options()
def fill_analyte_name(self, df):
analytes = df.loc[df['analyte_name'].str.startswith('Compound'), ['analyte_name']]['analyte_name'].tolist()
analytes_index = 0
fill_value = analytes[analytes_index].split(':')[1].strip()
for i in range(2, len(df.index)):
if not str(df['analyte_name'][i]).startswith('Compound'):
df.at[i, 'analyte_name'] = fill_value
else:
analytes_index += 1
fill_value = analytes[analytes_index].split(':')[1].strip()
return df
def double_quantity_bruker(self, df_quantity):
if self.double_conc.get():
for col in df_quantity.columns.to_list():
df_quantity[col] = df_quantity[col].apply(double_it)
return df_quantity
def not_implemented(self):
pass
def process_bruker(self, df):
analysis_type = self.analysis_type.get()
if analysis_type == 'Amino Acids':
df = janitor.clean_names(df, remove_special=True, case_type='snake')
try:
df = df[BRUKER_VARIABLES]
except Exception as e:
return 'wrong parameters', str(e)
df['quantity_units'] = pd.to_numeric(df['quantity_units'], errors='coerce')
df_area = df.pivot_table(index=['data_set', 'sample_type'], columns='analyte_name', values='area_of_pi')
df_quantity = df.pivot_table(index=['data_set', 'sample_type'], columns='analyte_name',
values='quantity_units')
df_rt = df.pivot_table(index=['data_set', 'sample_type'], columns='analyte_name', values='rt_min')
df_quantity = self.double_quantity_bruker(df_quantity)
return df_area, df_quantity, df_rt
def unit_conversion_waters(self, df_quantity):
try:
if self.unit_conc.get():
for col in df_quantity.columns.to_list():
if col != "Sample ID":
mol_weight = self.compounds[col.lower()]
df_quantity[col] = df_quantity[col].apply(unit_conc, args=(mol_weight,))
if self.unit_conc_micro.get():
for col in df_quantity.columns.to_list():
if col != "Sample ID":
mol_weight = self.compounds[col.lower()]
df_quantity[col] = df_quantity[col].apply(unit_conc_micro, args=(mol_weight,))
return df_quantity, None
except KeyError as ke:
missing_compound = str(ke).strip("'")
return "missing compound", missing_compound
def process_conversion(self, df_quantity):
result = self.unit_conversion_waters(df_quantity)
if isinstance(result[0], str):
return "missing compound", result[1]
return result
def process_waters(self, df):
analysis_type = self.analysis_type.get()
if analysis_type == 'Tryptophan' or \
analysis_type == 'Bile Acids':
try:
headers = df.loc[5].values.flatten().tolist() # get the 5th row as headers
headers[0] = 'analyte_name'
headers[1] = 'hash'
df.columns = headers
df = janitor.clean_names(df, remove_special=True, case_type='snake')
headers = df.columns.to_list()
headers = [x.strip('_') for x in headers] # remove leading and trailing '_' in variables
df.columns = headers
df.dropna(subset=['analyte_name'], inplace=True) # drop empty rows
df.reset_index(drop=True, inplace=True) # reindex after dropping rows
df = self.fill_analyte_name(df) # Compound: tryptophan occurs only once, fill it in rows below it
df = df[WATERS_VARIABLES] # ---------Note: for any new columns update this in utils and use it below--
df['conc'] = pd.to_numeric(df['conc'], errors='coerce')
df["area"] = pd.to_numeric(df["area"], errors='coerce')
df["rt"] = pd.to_numeric(df["rt"], errors='coerce')
# ---------Note: for any new columns update WATERS_VARIABLES and use it below------
df_area = df.pivot_table(index=['sample_text', 'type'], columns='analyte_name', values='area')
df_quantity = df.pivot_table(index=['sample_text', 'type'], columns='analyte_name', values='conc')
df_rt = df.pivot_table(index=['sample_text', 'type'], columns='analyte_name', values='rt')
result = self.unit_conversion_waters(df_quantity)
if isinstance(result[0], str):
return "missing compound", result[1]
df_grouped_conc = self.group_conc_waters(df)
return df_area, df_quantity, df_rt, df_grouped_conc
except Exception as e:
return "wrong parameters", str(e)
def group_conc_waters(self, df):
df1 = df.loc[df["sample_text"] != "Double Blank"]
df1 = df1.sort_values(by=['analyte_name', 'sample_text'], ignore_index=True)
an = None
st = None
suffix = 0
for index, row in df1.iterrows():
if row['analyte_name'] != an:
suffix = 0
an = row['analyte_name']
st = None
if row['sample_text'] != st:
st = row['sample_text']
suffix = 0
else:
suffix += 1
if suffix > 0:
df1.at[index, 'sample_text'] = row['sample_text'] + str(suffix)
df_out = df1.pivot_table(index=['sample_text'], columns='analyte_name', values='conc')
return df_out
def get_file_type(self):
file_type = 'TXT'
machine_type = self.machine_type.get()
if machine_type == 'Bruker':
file_type = 'xlsx'
if machine_type == 'WConversion':
file_type = 'xlsx'
return file_type
def get_analysis_type(self):
return self.analysis_type.get()
def machine_change(self):
self.analysis_type.set(" ")
self.set_selections_text()
def process_files(self):
current_dir = self.get_current_dir()
machine_type = self.machine_type.get()
analysis_type = self.analysis_type.get()
if analysis_type == ' ':
message = f"Analysis type not selected."
self.status_message.configure(text=message, fg="red")
self.show_messagebox(message, message_type="error")
return
if (machine_type, analysis_type) not in IMPLEMENTED:
message = f"{machine_type}-{analysis_type} not implemented."
self.status_message.configure(text=message, fg="red")
self.show_messagebox(message, message_type="error")
return
file_type = self.get_file_type()
files = get_files(current_dir, "." + file_type)
sheet_name1 = 'Area'
sheet_name2 = 'Conc'
sheet_name3 = 'RT'
sheet_name4 = 'Conc Grouped'
if machine_type == 'Bruker':
sheet_name1 = 'Area of PI'
sheet_name2 = 'Quantity Units'
today = datetime.today()
timestamp = f"{today.year}{today.month:02}{today.day:02}_{today.hour:02}{today.minute:02}{today.second:02}"
if len(files):
data_file = DataFile()
for file in files:
if '_flipped' not in file:
df_grouped = None
df = data_file.read(file, file_type)
if machine_type == 'Bruker':
result = self.process_bruker(df)
if isinstance(result[0], str) and result[0] == 'wrong parameters':
return result
df_area, df_quantity, df_rt = result[0], result[1], result[2]
elif machine_type == 'WConversion':
result = self.process_conversion(df)
if isinstance(result[0], str) and (result[0] == 'missing compound' or
result[0] == 'wrong parameters'):
return result
out_filename = f"{file}_{timestamp}_converted.xlsx"
output_path = os.path.join(current_dir, out_filename)
with ExcelWriter(output_path) as writer:
result[0].to_excel(writer, "converted")
writer.save()
return 'completed'
else:
result = self.process_waters(df)
if isinstance(result[0], str) and (result[0] == 'missing compound' or
result[0] == 'wrong parameters'):
return result
df_area, df_quantity, df_rt, df_grouped = result[0], result[1], result[2], result[3]
out_filename = f"{file}_{timestamp}_flipped.xlsx"
output_path = os.path.join(current_dir, out_filename)
with ExcelWriter(output_path) as writer:
df_area.to_excel(writer, sheet_name1)
df_quantity.to_excel(writer, sheet_name2)
df_rt.to_excel(writer, sheet_name3)
if len(result) == 4:
df_grouped.to_excel(writer, sheet_name4)
writer.save()
else:
return 'not found'
return 'completed'
def show_messagebox(self, message, message_type="error"):
if self.messagebox:
try:
self.messagebox.bring_to_top()
except Exception:
self.messagebox = None
if not self.messagebox:
self.messagebox = CustomDialog(self)
if message_type == "error":
self.messagebox.error(message)
else:
self.messagebox.success(message)
return
def long_to_wide(self):
self.status_message.configure(text=f"Processing...", fg="#000066", bg="#ddd")
self.selected_cwd = True
result = self.process_files()
if result == 'completed':
message1 = f"Completed processing."
message2 = f"\n\nPlease check the folder:\n{self.config['cwd']}"
self.status_message.configure(text=message1, fg="#006600", bg="#ddd")
self.show_messagebox(message1 + message2, message_type="success")
elif result == 'not found':
message1 = f"Files of type .{self.get_file_type()} not found in the directory"
message2 = f"\n{self.config['cwd']}\nPlease select correct options"
self.status_message.configure(text=message1, fg="#ff0000", bg="#ddd")
self.show_messagebox(message1 + message2, message_type="error")
elif isinstance(result[0], str) and result[0] == 'wrong parameters':
message1 = f"Please check your selections / file structure."
message2 = f"\nLook for missing columns, if you have modified the exported file."
self.status_message.configure(text=message1, fg="#ff0000", bg="#ddd")
self.show_messagebox(message1 + message2, message_type="error")
elif isinstance(result[0], str) and result[0] == 'missing compound':
self.status_message.configure(text=f"Missing compound: {result[1]}", fg="#ff0000", bg="#ddd")
self.get_mol_mass(result[1])
def select_cwd(self):
old = self.config["cwd"]
new = open_dir(old)
self.selected_cwd = True
if new:
set_config("cwd", new)
self.config["cwd"] = new
self.status_message.configure(text="New folder selected")
if old != new:
self.dir_lf.configure(text="", fg="#000")
else:
self.dir_lf.configure(text="", fg="#000")
elif old:
self.dir_lf.configure(text="", fg="#000")
self.status_message.configure(text=f"Selected same folder: {old}")
for w in self.machine_lf.winfo_children():
w.configure(state=tk.NORMAL)
self.process_button.configure(state=tk.NORMAL)
self.set_selections_text()
def change_color(self):
current_fg = "red"
if self.dir_lf:
current_fg = self.dir_lf.cget("foreground")
other = "#aaa"
if not self.selected_cwd and current_fg in ["red", other]:
next_fg = other if current_fg == "red" else "red"
self.dir_lf.configure(fg=next_fg)
root.after(600, self.change_color)
def add_feedback_controls(self):
feedback_lf = tk.LabelFrame(self.master, text="Your selections:", fg='#444', bg="#ccc", relief=tk.FLAT)
feedback_lf.pack(side=tk.TOP, pady=10)
f = tk.Frame(feedback_lf, bg="#ddd")
f.pack(pady=3)
self.selections_folder_text = tk.Label(f, bg="#ddd", fg="#222", font=("Arial", 10), anchor="w")
self.selections_folder_text.pack(side=tk.TOP, padx=2, pady=1, fill=tk.BOTH, expand=1)
h = 15
w = 180
f = tk.Frame(feedback_lf, height=h, width=w, bg="#eee")
f.pack()
f.pack_propagate(0)
self.selections_machine_text = tk.Label(f, bg="#eee", fg="#222", font=("Arial", 10), anchor="w")
self.selections_machine_text.pack(side=tk.TOP, padx=2, pady=1, fill=tk.BOTH, expand=1)
f = tk.Frame(feedback_lf, height=h, width=w, bg="#ddd")
f.pack()
f.pack_propagate(0)
self.selections_file_text = tk.Label(f, bg="#ddd", fg="#222", font=("Arial", 10), anchor="w")
self.selections_file_text.pack(side=tk.TOP, padx=2, pady=1, fill=tk.BOTH, expand=1)
f = tk.Frame(feedback_lf, height=h, width=w, bg="#eee")
f.pack()
f.pack_propagate(0)
self.selections_analysis_text = tk.Label(f, bg="#eee", fg="#222", font=("Arial", 10), anchor="w")
self.selections_analysis_text.pack(side=tk.TOP, padx=2, pady=1, fill=tk.BOTH, expand=1)
def add_data_entry_controls(self):
self.data_frame = tk.LabelFrame(self.master, text="", relief=tk.FLAT)
self.data_frame.pack(padx=2, pady=2, side=tk.TOP)
self.data_lf = tk.LabelFrame(self.data_frame, text="", fg='#444', bg="#ccc", relief=tk.FLAT)
label_lf = tk.LabelFrame(self.data_lf, text="Enter molecular mass for the compound",
fg='#444', bg="#ccc", relief=tk.FLAT)
label_lf.pack(padx=2, pady=2, side=tk.LEFT)
self.data_label = tk.Text(label_lf, height=1, borderwidth=0)
self.data_label.pack(padx=2, pady=2, side=tk.LEFT)
input_lf = tk.LabelFrame(self.data_lf, text="Mass", fg='#444', bg="#ccc", relief=tk.FLAT)
input_lf.pack(padx=2, pady=2, side=tk.LEFT)
input_box = tk.Entry(input_lf, textvariable=self.missing_compound_mass, width=6)
input_box.pack(padx=2, pady=2, side=tk.LEFT)
button = tk.Button(self.data_lf, text="Save", command=self.validate_mass)
button.pack(padx=2, pady=2, side=tk.LEFT)
def hide_data_lf(self):
self.data_lf.pack_forget()
def show_data_lf(self, missing_compound):
self.missing_compound.set(missing_compound)
self.data_label.delete("1.0", tk.END)
self.missing_compound_mass.set("")
self.data_label.insert(1.0, missing_compound)
self.process_button.configure(state=tk.DISABLED)
self.data_lf.pack(side=tk.TOP, padx=2, pady=2)
def validate_mass(self):
missing_compound_mass = self.missing_compound_mass.get()
if missing_compound_mass and missing_compound_mass.isnumeric() and float(missing_compound_mass) > 0:
self.hide_data_lf()
self.add_compound()
self.long_to_wide()
self.process_button.configure(state=tk.NORMAL)
else:
self.missing_compound_mass.set("")
def add_compound(self):
self.compounds[self.missing_compound.get()] = float(self.missing_compound_mass.get())
with open(COMPOUNDS_FILE, "w+") as f:
json.dump(self.compounds, f, indent=4)
return
def add_process_controls(self):
status_bar = tk.LabelFrame(self.master, text="", padx=2, pady=2, relief=tk.FLAT, bg="#b3cccc")
status_bar.pack(side=tk.BOTTOM, padx=0, pady=0, fill=tk.X)
self.process_button = tk.Button(status_bar, text="Go", activebackground='palegreen', width=20,
command=self.long_to_wide, state=tk.DISABLED, font=("Arial", 12))
self.process_button.pack(side=tk.TOP, padx=2, pady=(0, 20))
self.status_message = tk.Label(status_bar, fg="green", bg="#ddd", font=("Arial", 10))
self.status_message.pack(side=tk.BOTTOM, padx=0, pady=0, fill=tk.X)
def add_help(self):
help_lf = tk.LabelFrame(self.cwd_lf, text="", padx=2, pady=2, relief=tk.FLAT, bg="#ccc")
help_lf.pack(side=tk.TOP, padx=1, pady=(1, 10))
help_text = f"Please copy your files to an empty folder and select that folder " + \
f"(Each file will be processed separately)\n\n"
help_text += f"Files should have the columns:\n"
help_text += f"Bruker (xlsx): {BRUKER_VARIABLES}\n"
help_text += f"Waters (TXT) : {WATERS_HELP_VARIABLES} (analyte names appear on " + \
f"separate lines, eg. Compound: tryptophan){' '*32}\n"
help_text += f"For unit conversion, Waters flipped/wide file should be in xlsx format.\n"
help_message = tk.Label(help_lf, bg="#ccc", fg="#222", font=("Arial", 10), justify=tk.LEFT, text=help_text)
help_message.pack(side=tk.TOP, padx=10, pady=0)
def _add_machine_selector(self):
self.machine_lf = tk.LabelFrame(self.cwd_lf, text="Machine", padx=2, pady=2, relief=tk.FLAT, bg="#ccc")
self.machine_lf.pack(side=tk.LEFT, padx=8, pady=2)
machines = [
("Bruker", "Bruker"),
("Waters", "Waters"),
("Sciex", "Sciex"),
("WConversion", "WConversion"),
]
for name, code in machines:
tk.Radiobutton(self.machine_lf, text=name, variable=self.machine_type, bd=0, command=self.machine_change,
activebackground='palegreen', state=tk.DISABLED,
value=code, relief=tk.SOLID).pack(anchor=tk.W, padx=2, pady=2)
def _add_analysis_type(self):
self.analysis_lf = tk.LabelFrame(self.cwd_lf, text="Analysis", padx=2, pady=2, relief=tk.FLAT, bg="#ccc")
self.analysis_lf.pack(side=tk.LEFT, padx=8, pady=2)
self.bruker_analysis_types = [
"Amino Acids",
]
self.sciex_analysis_types = [
"Targeted Lipids",
"Lipid Mediators",
]
self.waters_analysis_types = [
"Tryptophan",
"Bile Acids",
"Paracetamol",
"SCFAs",
]
self.wconversion_analysis_types = [
"Conversion",
]
analysis_types = self.bruker_analysis_types + self.waters_analysis_types + self.sciex_analysis_types + \
self.wconversion_analysis_types
for name in analysis_types:
tk.Radiobutton(self.analysis_lf, text=name, variable=self.analysis_type, bd=0,
command=self.set_selections_text,
activebackground='palegreen', state=tk.DISABLED,
value=name, relief=tk.SOLID).pack(anchor=tk.W, padx=2, pady=2)
def _add_double_conc_selector(self):
self.double_conc_lf = tk.LabelFrame(self.cwd_lf, text=" ", padx=2, pady=2, relief=tk.FLAT, bg="#ccc")
self.double_conc_lf.pack(side=tk.LEFT, padx=8, pady=2)
self.double_conc = tk.IntVar(value=1)
tk.Checkbutton(self.double_conc_lf, text="Double Qty.", state=tk.DISABLED, variable=self.double_conc,
bg="#ddd", activebackground="palegreen").pack(side=tk.LEFT, padx=2, pady=2)
def _add_unit_conc_selectors(self):
self.unit_conc_lf = tk.LabelFrame(self.cwd_lf, text=" ", padx=2, pady=2, relief=tk.FLAT, bg="#ccc")
self.unit_conc_lf.pack(side=tk.LEFT, padx=8, pady=2)
self.unit_conc = tk.IntVar(value=1)
tk.Checkbutton(self.unit_conc_lf, text="Conc. Unit (ng/mL to mMol)", state=tk.DISABLED,
variable=self.unit_conc,
bg="#ddd", activebackground="palegreen").pack(side=tk.TOP, padx=2, pady=2)
self.unit_conc_micro = tk.IntVar(value=1)
tk.Checkbutton(self.unit_conc_lf, text="Conc. Unit (ng/mL to uMol)", state=tk.DISABLED,
variable=self.unit_conc_micro,
bg="#ddd", activebackground="palegreen").pack(side=tk.TOP, padx=2, pady=2)
def add_controls(self):
self.dir_lf = tk.LabelFrame(self.cwd_lf, text='Select', padx=2, pady=2, relief=tk.FLAT, bg="#ccc", fg="red")
self.dir_lf.pack(side=tk.LEFT, padx=8, pady=2)
cwd_button = tk.Button(self.dir_lf, text="Folder", command=self.select_cwd, activebackground='palegreen')
cwd_button.pack(side=tk.LEFT, padx=2, pady=2)
self._add_machine_selector()
self._add_analysis_type()
self._add_double_conc_selector()
self._add_unit_conc_selectors()
self.add_process_controls()
self.add_feedback_controls()
self.add_data_entry_controls()
def exit(self):
self.master.destroy()
def on_delete_child(self, w):
w.destroy()
self.config_window = None
def help(self, _):
self.show_help()
def get_search_url(self, missing_compound):
return SEARCH_URL + missing_compound
def get_mol_mass(self, missing_compound):
self.show_data_lf(missing_compound)
url_open(self.get_search_url(missing_compound.replace('_', ' ')))
def raise_above_all(self, window):
window.lift()
def show_help(self):
if not self.config_window:
self.config_window = tk.Toplevel(self)
self.config_window.wm_title("Help")
self.config_window.wm_protocol("WM_DELETE_WINDOW", lambda: self.on_delete_child(self.config_window))
help_text = f"Flip L2W Instructions:\n"
tk.Label(self.config_window, text=help_text, bg="#ddd", font=("Arial", 12), anchor="w").pack(fill=tk.X)
help_text = f"\nPlease copy your files to an empty folder and select that folder."
help_text += f"\nEach file will be processed separately and each will be saved as an xlsx.\n"
tk.Label(self.config_window, text=help_text, bg="#ddd", font=("Arial", 10), justify="left").pack(fill=tk.X)
help_text = f"\nFiles should have these columns:\n\n"
help_text += f"Bruker (xlsx): {BRUKER_VARIABLES}\n"
help_text += f"Waters (TXT) : {WATERS_HELP_VARIABLES} " + \
f"(analyte names appear on separate lines, eg. Compound: tryptophan)\n"
tk.Label(self.config_window, text=help_text, bg="#ddd", font=("Arial", 10), justify="left").pack()
tk.Label(self.config_window, text="Molecular weights:",
bg="#ddd", font=("Arial", 12), anchor="w").pack(fill=tk.X)
ctext = scrolledtext.ScrolledText(self.config_window, height=20, font=('Courier', 10))
ctext.pack(padx=3, pady=3, fill=tk.BOTH)
mol_list = [f"{k: <50}- {self.compounds[k]}\n" for k in self.compounds.keys()]
help_text = "".join(mol_list)
ctext.insert("end", help_text)
else:
self.raise_above_all(self.config_window)
def close(self, _):
self.exit()
def add_options_bar(self):
tk.Label(self, text="Flip L2W", bg="#b3cccc", font=("Arial", 16)).pack(side=tk.TOP, fill=tk.X)
tk.Label(self, text="(Cast Long to Wide)", bg="#b3cccc", font=("Arial", 11)).pack(side=tk.TOP, fill=tk.X)
self.optionsbar = tk.Frame(self, bd=1, relief=tk.FLAT, bg="#ddd")
self.optionsbar.pack(side=tk.TOP, fill=tk.X)
self.cwd_lf = tk.Frame(self.optionsbar, bg="#ddd", padx=4, pady=2, relief=tk.FLAT)
self.cwd_lf.pack(side=tk.LEFT, fill=tk.X)
self.add_help()
self.add_controls()
def create_widgets(self):
self.menubar = tk.Menu(master=self.master, bg="#aaa")
self.master.config(menu=self.menubar)
filemenu = tk.Menu(self.menubar, tearoff=0)
filemenu.add_command(label=f"Help F1", command=self.show_help, activebackground="palegreen")
filemenu.add_separator()
filemenu.add_command(label=f"Exit Esc", command=self.exit, activebackground="palegreen")
self.menubar.add_cascade(label="File", menu=filemenu)
self.add_options_bar()
self.status_message.configure(text=f"Last used folder: {self.config['cwd']}", fg="#666")
self.master.bind('<Escape>', self.close)
self.master.bind('<F1>', self.help)
self.select_cwd()
def main():
root = tk.Tk()
img = PhotoImage(file='icon.ico')
root.tk.call('wm', 'iconphoto', root._w, img)
app = Application(root)
root.geometry("900x680")
root.configure(background='#b3cccc')
root.mainloop()
if __name__=="__main__":
main()