/
MassyTools.py
458 lines (392 loc) · 16.5 KB
/
MassyTools.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
#! /usr/bin/env python
#
# Copyright 2014-2020 Bas C. Jansen
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# You should have received a copy of the Apache 2.0 license along
# with this program; if not, see
# http://www.apache.org/licenses/LICENSE-2.0
# Standard Library Imports
import logging
from pathlib import Path
# Third Party Imports
from matplotlib import image, figure
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk
)
import os
import tkinter as tk
from tkinter import filedialog, messagebox
# Application Specific Imports
import MassyTools.gui.version as version
import MassyTools.util.requirement_checker as req_check
import MassyTools.util.functions as functions
import MassyTools.util.classification as classification
from MassyTools.gui.batch_window import BatchWindow
from MassyTools.gui.output_window import OutputWindow
from MassyTools.gui.progress_bar import ProgressBar
from MassyTools.gui.settings_window import SettingsWindow
from MassyTools.gui.experimental_settings_window import ExperimentalSettingsWindow
from MassyTools.gui.about_window import AboutWindow
from MassyTools.gui.cite_window import CiteWindow
from MassyTools.bin.mass_spectrum import MassSpectrum, finalize_plot
from MassyTools.bin.output import Output
from MassyTools.bin.process_parameters import ProcessParameters
from MassyTools.bin.output_parameters import OutputParameters
from MassyTools.bin.settings import Settings
# Platform specific bits
if os.name == 'posix':
import matplotlib
matplotlib.use('TkAgg')
class MassyToolsGui(object):
@classmethod
def run(cls):
root = tk.Tk()
MassyToolsGui(root)
root.mainloop()
def __init__(self, master):
# Inherit Tk() root object
self.master = master
self.read_building_blocks()
# Define task_label for progress bar functionality
task_label = tk.StringVar()
task_label.set('Idle')
# LOGGING
logging.basicConfig(
filename='MassyTools.log',
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M', filemode='a',
level=logging.WARNING)
req_check.check_requirements()
# CANVAS
fig = figure.Figure(figsize=(12, 6))
axes = fig.add_subplot(111)
axes.axis('off')
canvas = FigureCanvasTkAgg(fig, master=master)
NavigationToolbar2Tk(canvas, master)
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=tk.YES)
canvas.draw()
# FRAME
tk.Frame(master)
master.title('MassyTools '+str(version.version) +
' (Build '+str(version.build)+')')
iconbitmap = Path.cwd() / 'MassyTools' / 'gui' / 'assets' / 'Icon.ico'
backgroundimage = Path.cwd() / 'MassyTools' / 'gui' / 'assets' / 'UI.png'
try:
master.iconbitmap(default=iconbitmap)
except tk.TclError as e:
logging.getLogger(__name__).warning(e)
if backgroundimage.is_file():
img = image.imread(str(backgroundimage))
axes.imshow(img)
axes.set_aspect('auto')
task = tk.Label(master, textvariable=task_label, width=30)
task.pack()
progress = ProgressBar(self.master)
progress.bar.pack(fill=tk.X)
# QUIT
master.protocol('WM_DELETE_WINDOW', self.close)
# MENU
menu = tk.Menu(master)
master.config(menu=menu)
file_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='Open Input File',
command=self.open_mass_spectrum)
file_menu.add_command(label='Baseline Correct',
command=self.baseline_correct)
file_menu.add_command(label='Normalize',
command=self.normalize_mass_spectrum)
file_menu.add_command(label='Save',
command=self.save_mass_spectrum)
adv_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='Advanced', menu=adv_menu)
adv_menu.add_command(label='Classify Mass Spectra',
command=self.classify_mass_spectra)
calib_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='Calibration', menu=calib_menu)
calib_menu.add_command(label='Open Calibration File',
command=self.open_calibration_file)
calib_menu.add_command(label='Open Exclusion File',
command=self.foo)
calib_menu.add_command(label='Calibrate',
command=self.calibrate_mass_spectrum)
quantitation_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='Quantitation', menu=quantitation_menu)
quantitation_menu.add_command(label='Open Quantitation File',
command=self.open_quantitation_file)
quantitation_menu.add_command(label='Specify Outputs',
command=self.open_output_window)
quantitation_menu.add_command(label='Quantify',
command=self.quantify_mass_spectrum)
quality_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='QC', menu=quality_menu)
quality_menu.add_command(label='Open Quality Control File',
command=self.foo)
quality_menu.add_command(label='Calculate QC', command=self.foo)
batch_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='Batch Process', menu=batch_menu)
batch_menu.add_command(label='Batch Process',
command=self.batch_process)
curation_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='Data Curation', menu=curation_menu)
curation_menu.add_command(label='Spectral Curation',
command=self.foo)
curation_menu.add_command(label='Analyte Curation',
command=self.foo)
settings_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='Settings', menu=settings_menu)
settings_menu.add_command(label='MassyTools Settings',
command=self.settings_window)
settings_menu.add_command(
label='Experimental Settings',
command=self.experimental_settings_window)
info_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label='Information', menu=info_menu)
info_menu.add_command(label='About MassyTools',
command=self.about_window)
info_menu.add_command(label='Citing MassyTools',
command=self.cite_window)
# INHERITANCE
self.logger = logging.getLogger(__name__)
self.base_dir = Path.cwd()
self.settings = Settings()
self.process_parameters = ProcessParameters()
self.output_parameters = OutputParameters()
self.axes = axes
self.canvas = canvas
self.progress = progress
self.task_label = task_label
# Placeholder
def foo(self):
raise NotImplementedError
# Actual Functions
def about_window(self):
try:
AboutWindow()
except Exception as e:
self.logger.error(e)
def baseline_correct(self):
try:
self.axes.clear()
self.progress.reset_bar()
self.task_label.set('Baseline Correcting Mass Spectra')
for index, mass_spectrum in enumerate(self.mass_spectra):
mass_spectrum.baseline_correct()
mass_spectrum.plot_mass_spectrum()
self.progress.counter.set(
(float(index) / len(self.mass_spectra))*100)
self.progress.update_progress_bar()
self.task_label.set('Idle')
self.progress.fill_bar()
finalize_plot(self)
except Exception as e:
self.logger.error(e)
def batch_process(self):
try:
BatchWindow(self)
except Exception as e:
self.logger.error(e)
def calibrate_mass_spectrum(self):
try:
self.progress.reset_bar()
self.process_parameters.calibration = True
peak_list = functions.get_peak_list(
self.process_parameters.calibration_file)
self.peak_list = peak_list
self.task_label.set('Calibrating Mass Spectra')
for index, mass_spectrum in enumerate(self.mass_spectra):
mass_spectrum.process_mass_spectrum()
mass_spectrum.calibrate()
self.progress.counter.set(
(float(index) / len(self.mass_spectra))*100)
self.progress.update_progress_bar()
self.task_label.set('Idle')
self.progress.fill_bar()
self.axes.clear()
for mass_spectrum in self.mass_spectra:
mass_spectrum.plot_mass_spectrum()
finalize_plot(self)
self.process_parameters.calibration = False
if not self.process_parameters.calibration_file:
messagebox.showinfo('Warning', 'No Calibration File ' +
'Selected')
except Exception as e:
self.logger.error(e)
def classify_mass_spectra(self):
try:
classification.classify_mass_spectra(self.mass_spectra)
self.axes.clear()
for mass_spectrum in self.mass_spectra:
mass_spectrum.plot_mass_spectrum()
finalize_plot(self)
except Exception as e:
self.logger.error(e)
def close(self):
self.master.destroy()
self.master.quit()
def generate_pdf_report(self):
try:
self.task_label.set('Generating PDF reports')
for index, mass_spectrum in enumerate(self.mass_spectra):
self.progress.counter.set(
(float(index) / len(self.mass_spectra))*100)
self.progress.update_progress_bar()
mass_spectrum.generate_pdf_report()
self.task_label.set('Idle')
self.progress.fill_bar()
except Exception as e:
self.logger.error(e)
def quantify_mass_spectrum(self):
try:
self.progress.reset_bar()
self.process_parameters.quantitation = True
peak_list = functions.get_peak_list(
self.process_parameters.quantitation_file)
self.peak_list = peak_list
self.process_mass_spectrum()
self.task_label.set('Quantifying Analytes')
for index, mass_spectrum in enumerate(self.mass_spectra):
self.progress.counter.set(
(float(index) / len(self.mass_spectra))*100)
self.progress.update_progress_bar()
mass_spectrum.quantify_mass_spectrum()
self.task_label.set('Idle')
self.progress.fill_bar()
if self.output_parameters.pdf_report.get():
self.generate_pdf_report()
self.output = Output(self)
self.output.init_output_file()
self.output.build_header()
self.output.build_output_file()
self.process_parameters.quantitation = False
except Exception as e:
self.logger.error(e)
def experimental_settings_window(self):
try:
ExperimentalSettingsWindow(self)
except Exception as e:
self.logger.error(e)
def process_mass_spectrum(self):
try:
self.task_label.set('Processing Mass Spectra')
for index, mass_spectrum in enumerate(self.mass_spectra):
self.progress.counter.set(
(float(index) / len(self.mass_spectra))*100)
self.progress.update_progress_bar()
mass_spectrum.process_mass_spectrum()
self.task_label.set('Idle')
except Exception as e:
self.logger.error(e)
def cite_window(self):
try:
CiteWindow()
except Exception as e:
self.logger.erorr(e)
def normalize_mass_spectrum(self):
try:
for mass_spectrum in self.mass_spectra:
mass_spectrum.normalize_mass_spectrum()
if self.mass_spectra:
self.axes.clear()
for mass_spectrum in self.mass_spectra:
mass_spectrum.plot_mass_spectrum()
finalize_plot(self)
except Exception as e:
self.logger.error(e)
def open_calibration_file(self):
try:
cal_file = filedialog.askopenfilename(title='Select ' +
'Calibration File')
self.process_parameters.calibration_file = cal_file
except Exception as e:
self.logger.error(e)
def open_mass_spectrum(self):
try:
self.progress.reset_bar()
data_buffer = []
files = filedialog.askopenfilenames(title='Select Mass ' +
'Spectrum File(s)')
self.task_label.set('Opening Mass Spectra')
for index, file in enumerate(files):
self.progress.counter.set(
(float(index) / len(files))*100)
self.progress.update_progress_bar()
self.filename = file
mass_spec_buffer = MassSpectrum(self)
mass_spec_buffer.open_mass_spectrum()
data_buffer.append(mass_spec_buffer)
self.mass_spectra = data_buffer
self.task_label.set('Idle')
self.progress.fill_bar()
self.task_label.set('Plotting Mass Spectra')
if self.mass_spectra:
self.axes.clear()
for index, mass_spectrum in enumerate(self.mass_spectra):
self.progress.counter.set(
(float(index) / len(files))*100)
self.progress.update_progress_bar()
mass_spectrum.plot_mass_spectrum()
finalize_plot(self)
self.task_label.set('Idle')
self.progress.fill_bar()
except Exception as e:
messagebox.showinfo('Warning', 'The selected files could ' +
'not be opened.')
self.logger.error(e)
def open_output_window(self):
OutputWindow(self)
def open_quantitation_file(self):
try:
quant_file = filedialog.askopenfilename(
title='Select Quantitation File')
self.process_parameters.quantitation_file = quant_file
except Exception as e:
self.logger.error(e)
def read_building_blocks(self):
building_blocks = {}
block_folder = Path.cwd() / 'blocks'
for file in block_folder.glob('*.block'):
block = Path(file).stem
keys = []
values = []
with open(file, 'r') as fr:
for line in fr:
foo = line.rstrip().split()
key = foo[0]
value = " ".join(foo[1:])
keys.append(key)
try:
float(value)
try:
value = int(value)
except ValueError:
value = float(value)
except ValueError:
value = str(value)
values.append(value)
building_blocks[block] = dict(zip(keys, values))
self.building_blocks = building_blocks
def save_mass_spectrum(self):
try:
for mass_spectrum in self.mass_spectra:
mass_spectrum.save_mass_spectrum()
except Exception as e:
self.logger.error(e)
def settings_window(self):
try:
SettingsWindow(self)
except Exception as e:
self.logger.error(e)
if __name__ == "__main__":
MassyToolsGui.run()