__main__.py 16 KB
Newer Older
Yan's avatar
Yan committed
1
2
3
4
5
#!/usr/bin/env python3

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.widgets import SpanSelector
Yan's avatar
Yan committed
6
from matplotlib.gridspec import GridSpec
Yan's avatar
Yan committed
7
8
from PyQt5 import QtCore
from PyQt5 import QtWidgets
Yan's avatar
Yan committed
9
from PyQt5 import QtGui
10
from PyQt5 import QtPrintSupport
Yan's avatar
Yan committed
11
from rawprasslib import load_raw
Yan's avatar
Yan committed
12
from rawprasslib import rawprasslib
Yan's avatar
Yan committed
13
from prasopes.predictmz import predict as getmzpattern
Yan's avatar
Yan committed
14
15
16
17
18
try:
    from rawautoparams import load_params
    autoparams = True
except:
    autoparams = False
Yan's avatar
Yan committed
19
import numpy as np
Yan's avatar
Yan committed
20
import prasopes.config as cf
21
import prasopes.datatools as dt
Yan's avatar
Yan committed
22
import prasopes.drltools as drl
Yan's avatar
Yan committed
23
import prasopes.filetools as ft
Yan's avatar
Yan committed
24
25
import prasopes.graphtools as gt
import prasopes.imagetools as imgt
Yan's avatar
Yan committed
26
import prasopes.zcetools as zce
Yan's avatar
Yan committed
27
import prasopes.docks as docks
Yan's avatar
Yan committed
28
import prasopes.tangoicons
Yan's avatar
Yan committed
29
30
31
import sys
import matplotlib
import logging
3Yan's avatar
3Yan committed
32
import os.path
Yan's avatar
Yan committed
33
34
35
matplotlib.use("Qt5Agg")


36
37
38
39
class update_signal(QtCore.QObject):
    signal = QtCore.pyqtSignal()


40
41
42
43
class QStatusBarLogger(logging.Handler):
    def __init__(self, parent=None):
        super().__init__()
        self.statusBar = QtWidgets.QStatusBar(parent)
Yan's avatar
Yan committed
44
45
        self.trigger = update_signal()
        self.msg = str("")
46
47

    def emit(self, record):
Yan's avatar
Yan committed
48
49
        self.msg = self.format(record)
        self.trigger.signal.emit()
50
51


52
def load_file(parent, chrom_plot, spc, d_set, ms_s, fn, chrom_s,
53
              update, settings, loadthread, filename=None):
Yan's avatar
Yan committed
54
    """populates dataset and plots it"""
3Yan's avatar
3Yan committed
55
56
57
    directory=settings.value("open_folder")
    if fn[0] is not None:
        directory=fn[0]
Yan's avatar
Yan committed
58
59
    if filename == None:
        filename = QtWidgets.QFileDialog.getOpenFileName(
3Yan's avatar
3Yan committed
60
61
62
            caption="Open spectrum",
            directory=directory,
            filter="Finnigan RAW files (*.raw, *.RAW)")[0]
63
64
    if filename is not '' and os.path.isfile(filename)\
                          and not os.path.isdir(filename):
Yan's avatar
Yan committed
65
66
        error = update_signal()
        errormsg = []
67
        def runfnc():
Yan's avatar
Yan committed
68
            try:
Yan's avatar
Yan committed
69
70
                [i.clear() for i in (
                    d_set, chrom_s['timesarg'], ms_s['params'],ms_s['headers'])]
71
72
73
                [d_set.append(dict(chrom_dat=i[0], masses=i[1], matrix=i[2]))
                    for i in load_raw(filename, settings.value("tmp_location"))]
            except rawprasslib.ParsingException as pex:
Yan's avatar
Yan committed
74
75
                errormsg.append("Opening of the file has failed!")
                errormsg.append(
76
77
                    "File is incompatible with the rawprasslib, "
                    "canceling request!\n\n"
Yan's avatar
Yan committed
78
                    "Error message:\n{}".format(pex.args[0]))
Yan's avatar
Yan committed
79
                error.signal.emit()
80
81
82
                return
            if autoparams == True:
                try:
83
                    ms_s['params'], rawheaders, chrom_s['machtype'] = load_params(filename)
84
                    segments = [len(subset['chrom_dat'][0]) for subset in d_set]
Yan's avatar
Yan committed
85
                    indicies = [sum(segments[:i+1]) for i in range(len(segments))]
86
87
                    ms_s['headers'] = np.split(rawheaders, indicies)[:-1]
                except Exception as pex:
Yan's avatar
Yan committed
88
89
90
91
92
                    errormsg.append("File is incompatible with the rawautoparams,")
                    errormsg.append(
                            "no parameters loaded!\n\n"
                            "Error message:\n{}".format(pex.args[0]))
                    error.signal.emit()
93
94
95
96
97
            gt.populate(chrom_plot, spc, d_set, ms_s, chrom_s)
            fn[0] = filename
            parent.setWindowTitle("Prasopes - {}".format(
                os.path.basename(filename)))
            update.signal.emit()
Yan's avatar
Yan committed
98
99
        error.signal.connect(lambda:
            QtWidgets.QMessageBox.critical(parent, errormsg[0], errormsg[1]))
100
101
        loadthread.run = runfnc
        loadthread.start()
3Yan's avatar
3Yan committed
102

Yan's avatar
Yan committed
103

Yan's avatar
Yan committed
104
def print_graph(data_set, mass_spec, chrom_spec, spect, fn, table):
Yan's avatar
Yan committed
105
    def printimage(printdevice, img):
Yan's avatar
Yan committed
106
        printer.setResolution(600)
Yan's avatar
Yan committed
107
        painter = QtGui.QPainter(printdevice)
Yan's avatar
Yan committed
108
109
110
111
        font = painter.font()
        linesize = printer.resolution()/15
        font.setPixelSize(linesize)
        painter.setFont(font)
Yan's avatar
Yan committed
112
        painter.drawImage(0,0,img)
Yan's avatar
Yan committed
113
114
115
116
117
118
119
120
        offset = img.size().height()
        line = 1
        spacing = 1.5
        for row in range(table.rowCount()):
            if table.cellWidget(row,0).checkState() == 2:
                text = table.item(row,1).text() + table.item(row,2).text()
                painter.drawText(300,int(offset+line*linesize*spacing), text)
                line += 1
Yan's avatar
Yan committed
121
122
        painter.end()
    #TODO: substitute the QPrintPreviewDialog with QPrintPreviewWidget
123
124
    printPreview = QtPrintSupport.QPrintPreviewDialog()
    printer = printPreview.printer()
Yan's avatar
Yan committed
125
126
    printer.setPageSize(printer.A5)
    printer.setDuplex(printer.DuplexNone)
Yan's avatar
Yan committed
127
    image = imgt.paint_image(mass_spec, spect, printer)
Yan's avatar
Yan committed
128
    printPreview.paintRequested.connect(lambda:
Yan's avatar
Yan committed
129
                                        printimage(printer, image))
130
131
132
    printPreview.exec()


Yan's avatar
Yan committed
133
134
def update_spectrum(chromatogram, spect, ds, ms, fn, chrom, config):
    if fn[0] is not None:
Yan's avatar
Yan committed
135
        slims = [spect.get_xlim(), spect.get_ylim()]
3Yan's avatar
3Yan committed
136
137
138
        ds.clear()
        [ds.append(dict(chrom_dat=i[0], masses=i[1], matrix=i[2])) for i
                in load_raw(fn[0], config.value("tmp_location"))]
Yan's avatar
Yan committed
139
140
141
        gt.populate(chromatogram, spect, ds, ms, chrom)
        spect.set_xlim(slims[0])
        spect.set_ylim(slims[1])
Yan's avatar
Yan committed
142
        gt.ann_spec(spect, ms)
Yan's avatar
Yan committed
143
144
145
        spect.get_figure().canvas.draw()


146
def dropped(event, parent, chromatogram, spectrum, ds, ms, filename,
147
            chrom, update, config, loadthread):
148
    dropurl = event.mimeData().urls()[0].toLocalFile()
149
    load_file(parent, chromatogram, spectrum, ds, ms, filename,
150
              chrom, update, config, loadthread, filename=dropurl)
Yan's avatar
Yan committed
151
152
153
154


def drag_entered(event):
    if event.mimeData().hasUrls() and event.mimeData().urls()[0]\
155
        .toLocalFile().lower().endswith('.raw'):
Yan's avatar
Yan committed
156
157
158
        event.accept()


Yan's avatar
Yan committed
159
160
161
162
163
164
165
166
167
168
169
170
171
def predictmz(form, chromatogram, spect, ds, ms, chrom):
    text = form.text()
    if text == "":
        ms["predict"] = None
        return
    slims = [spect.get_xlim(), spect.get_ylim()]
    ms["predict"] = getmzpattern(text)
    gt.populate(chromatogram, spect, ds, ms, chrom)
    spect.set_xlim(slims[0])
    spect.set_ylim(slims[1])
    spect.get_figure().canvas.draw()


3Yan's avatar
3Yan committed
172
173
174
175
176
177
def oddeven_changed(chromatogram, spectrum, ds, ms, filename, chrom, config,
        oddevenact):
    config.setValue("view/oddeven", oddevenact.isChecked())
    update_spectrum(chromatogram, spectrum, ds, ms, filename, chrom, config)


Yan's avatar
Yan committed
178
def key_pressed(event, chrom, spect, ds, ms_ds, fn, chrom_ds, config):
Yan's avatar
Yan committed
179
180
    if event.key() == QtCore.Qt.Key_F5:
        update_spectrum(chrom, spect, ds, ms_ds, fn, chrom_ds, config)
181
182
183
184
185
186
    if event.key() == QtCore.Qt.Key_C:
        if event.modifiers().__int__() == QtCore.Qt.ControlModifier:
            imgt.clip_spect_img(ms_ds, spect)
        if event.modifiers().__int__() == QtCore.Qt.ControlModifier+\
                                          QtCore.Qt.ShiftModifier:
            dt.clip_spectstr(spect, chrom_ds, fn)
Yan's avatar
Yan committed
187
188
    if event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right):
        gt.shift_times(event, spect, chrom, ds, ms_ds, chrom_ds)
Yan's avatar
Yan committed
189
190


Yan's avatar
Yan committed
191
192
193
194
195
def about(parent):
    """constructs window with "about" info"""
    QtWidgets.QMessageBox.information(
            parent, "About Prasopes",
            "Prasopes Finnigan raw file viewer\n\n"
196
            "Version: 0.0.12 (alpha)")
Yan's avatar
Yan committed
197
198


Yan's avatar
Yan committed
199
def main():
200
    app = QtWidgets.QApplication(sys.argv)
201
    loadthread = QtCore.QThread()
202

3Yan's avatar
3Yan committed
203
204
    ds = []
    ms = dict(annotation=[], name="Spectrum", xlabel="m/z",
Yan's avatar
Yan committed
205
              ylabel="ion count", xtics=20, predict=None,
206
              params=[], headers=[], texts=[])
207
    chrom = dict(x=[0], y=[0], t_start=None, t_end=None, machtype=None,
Yan's avatar
Yan committed
208
                 name="Chromatogram", xlabel="time(min)",
3Yan's avatar
3Yan committed
209
                 ylabel="total ion count", timesarg=[])
Yan's avatar
Yan committed
210
    filename = [None]
3Yan's avatar
3Yan committed
211
    drlcache = [None, None]
212
    update = update_signal()
Yan's avatar
Yan committed
213

Yan's avatar
Yan committed
214
215
    config = cf.settings()

216
    barHandler = QStatusBarLogger()
Yan's avatar
Yan committed
217
218
    barHandler.trigger.signal.connect(lambda:
            barHandler.statusBar.showMessage(barHandler.msg))
219

Yan's avatar
Yan committed
220
    p_logger = logging.getLogger('parseLogger')
221
    params_logger = logging.getLogger('acqLogLogger')
Yan's avatar
Yan committed
222
    drl_logger = logging.getLogger('drlLogger')
223
    zce_logger = logging.getLogger('zceLogger')
Yan's avatar
Yan committed
224
225
    #mpl_logger = logging.getLogger('matplotlib')
    #mpl_logger.setLevel("DEBUG")
Yan's avatar
Yan committed
226
    logging.basicConfig()
Yan's avatar
Yan committed
227
    #p_logger.setLevel("WARN")
Yan's avatar
Yan committed
228
    #p_logger.setLevel("DEBUG")
Yan's avatar
Yan committed
229
    #drl_logger.setLevel("INFO")
Yan's avatar
Yan committed
230
    drl_logger.setLevel("DEBUG")
231
    zce_logger.setLevel("DEBUG")
232
    params_logger.setLevel("DEBUG")
233
234
    p_logger.addHandler(barHandler)
    zce_logger.addHandler(barHandler)
235
236
    params_logger.addHandler(barHandler)
    barHandler.setLevel("DEBUG")
Yan's avatar
Yan committed
237

Yan's avatar
Yan committed
238
239
240
    paramstable = dt.table(["","name","value"], 100)
    paramstable.horizontalHeader().setSectionResizeMode(
            0, QtWidgets.QHeaderView.ResizeToContents)
Yan's avatar
Yan committed
241
    graph = Figure(figsize=(5, 4), dpi=100, facecolor="None", constrained_layout=True)
Yan's avatar
Yan committed
242
243
244
    grid = graph.add_gridspec(2, 1)
    chromatogram = graph.add_subplot(grid[0,0], facecolor=(1, 1, 1, 0.8))
    spectrum = graph.add_subplot(grid[1,0], facecolor=(1, 1, 1, 0.8))
Yan's avatar
Yan committed
245
246
247
248
249
250
251
252
    mpl_canvas = FigureCanvas(graph)
    mpl_canvas.setStyleSheet("background-color:transparent;")
    mpl_canvas.setAutoFillBackground(False)
    
    gt.pan_factory(chromatogram)
    gt.zoom_factory(chromatogram, 1.15)
    gt.pan_factory(spectrum, ms)
    gt.zoom_factory(spectrum, 1.15, ms)
253
    gt.textedit_factory(spectrum, ms)
Yan's avatar
Yan committed
254
    mass_selector = gt.AugSpanSelector(spectrum, ms)
255
256
257
258
    time_selector = SpanSelector(chromatogram, lambda x_min, x_max:
            gt.pick_times( x_min, x_max, spectrum, ds, chromatogram, ms, chrom,
                paramstable), 'horizontal', useblit=True, rectprops=dict(
                    alpha=0.15, facecolor='purple'), button=3)
Yan's avatar
Yan committed
259
    main_window = QtWidgets.QMainWindow(windowTitle="Prasopes")
Yan's avatar
Yan committed
260

Yan's avatar
Yan committed
261
262
263
    if QtGui.QIcon.themeName() is "":
        QtGui.QIcon.setThemeName("TangoMFK")

Yan's avatar
Yan committed
264
265
266
267
268
269
270
271
272
    consoledock = docks.consoleDockWidget(
            locals(), "&Console", "view/consolevisible")
    treedock = docks.treeDockWidget(
            load_file, update, "&File browser", "view/filebrowservisible")
    paramsdock = docks.augDock("Acquisition parameters", "&Acq parameters",
            "view/acqparvisible")
    update.signal.connect(lambda: gt.update_paramstable(paramstable, ms, chrom))
    paramsdock.setWidget(paramstable)

Yan's avatar
Yan committed
273
    openact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
274
        "document-open"), "&Open...", None)
Yan's avatar
Yan committed
275
276
    openact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_O)
    openact.triggered.connect(lambda: load_file(
277
        main_window, chromatogram, spectrum, ds, ms, filename, chrom,
278
        update, config, loadthread))
Yan's avatar
Yan committed
279
    exportact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
280
        "document-save-as"), "&Export...", None)
Yan's avatar
Yan committed
281
282
    exportact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_E)
    exportact.triggered.connect(lambda: ft.export_dial(
283
        spectrum, chrom, filename, main_window))
284
285
286
    printact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
        "document-print"), "&Print", None)
    printact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_P)
Yan's avatar
Yan committed
287
    printact.triggered.connect(lambda: print_graph(
Yan's avatar
Yan committed
288
        ds, ms, chrom, spectrum, filename, paramstable))
Yan's avatar
Yan committed
289
    settingsact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
290
        "preferences-system"), "&Settings...", None)
Yan's avatar
Yan committed
291
292
    settingsact.triggered.connect(lambda: cf.dial(main_window))
    quitact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
293
        "application-exit"), "&Quit", None)
Yan's avatar
Yan committed
294
295
296
    quitact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
    quitact.triggered.connect(main_window.close)
    zceact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
297
        "applications-utilities"), "&TSQ zce...", None)
Yan's avatar
Yan committed
298
299
    zceact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_T)
    zceact.triggered.connect(lambda: zce.dialog(
300
        main_window, ds, filename, update))
Yan's avatar
Yan committed
301
    drlact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
302
        "applications-utilities"), "&DRL...", None)
Yan's avatar
Yan committed
303
304
    drlact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_D)
    drlact.triggered.connect(lambda: drl.main_window(
305
        main_window, ds, filename, drlcache, update))
Yan's avatar
Yan committed
306
307
    aboutact = QtWidgets.QAction("&About Prasopes", None)
    aboutact.triggered.connect(lambda: about(main_window))
Yan's avatar
Yan committed
308
    autozoomy = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
309
310
311
312
        "zoom-original"), "Auto Zoom Y", None, checkable=True,
        checked=config.value("view/autozoomy", type=bool))
    autozoomy.triggered.connect(lambda: config.setValue(
                                "view/autozoomy", autozoomy.isChecked()))
313
314
315
316
317
318
319
320
321
322
323
    autozoomy.triggered.connect(lambda: gt.autozoomy(spectrum))
    intensitiesact = QtWidgets.QAction("&Show intensities", None,
            checkable=True, checked=config.value("view/intensities",
                type=bool))
    intensitiesact.triggered.connect(lambda: config.setValue(
        "view/intensities", intensitiesact.isChecked()))
    intensitiesact.triggered.connect(lambda: gt.ann_spec(spectrum, ms))
    intensitiesact.triggered.connect(lambda: spectrum.figure.canvas.draw())
    oddevenact = QtWidgets.QAction("&Odd / even", None, checkable=True,
            checked=config.value("view/oddeven", type=bool))
    oddevenact.triggered.connect(lambda:
3Yan's avatar
3Yan committed
324
325
        oddeven_changed(chromatogram, spectrum, ds, ms, filename, chrom,
            config, oddevenact))
Yan's avatar
Yan committed
326

Yan's avatar
Yan committed
327
328
329
330
    predictform = QtWidgets.QLineEdit(maximumWidth=150)
    predictform.editingFinished.connect(lambda: predictmz(
        predictform, chromatogram, spectrum, ds, ms, chrom))

Yan's avatar
Yan committed
331
332
    file_menu = QtWidgets.QMenu('&File', main_window)
    main_window.menuBar().addMenu(file_menu)
Yan's avatar
Yan committed
333
334
335
    file_menu.addAction(openact)
    file_menu.addAction(exportact)
    file_menu.addSeparator()
336
337
    file_menu.addAction(printact)
    file_menu.addSeparator()
Yan's avatar
Yan committed
338
339
340
    file_menu.addAction(settingsact)
    file_menu.addSeparator()
    file_menu.addAction(quitact)
Yan's avatar
Yan committed
341
342
    tools_menu = QtWidgets.QMenu('&Tools', main_window)
    main_window.menuBar().addMenu(tools_menu)
Yan's avatar
Yan committed
343
344
    tools_menu.addAction(zceact)
    tools_menu.addAction(drlact)
345
    tools_menu.addSeparator()
Yan's avatar
Yan committed
346
    view_menu = QtWidgets.QMenu('&View', main_window)
Yan's avatar
Yan committed
347
348
    [view_menu.addAction(i.action) for i in (treedock, paramsdock, consoledock)]
    [view_menu.addAction(i) for i in (autozoomy, intensitiesact)]
349
350
    view_menu.addSeparator()
    view_menu.addAction(oddevenact)
Yan's avatar
Yan committed
351
    main_window.menuBar().addMenu(view_menu)
Yan's avatar
Yan committed
352
353
354
    help_menu = QtWidgets.QMenu('&Help', main_window)
    main_window.menuBar().addMenu(help_menu)
    help_menu.addAction(aboutact)
Yan's avatar
Yan committed
355

356
    main_window.setCentralWidget(mpl_canvas)
Yan's avatar
Yan committed
357

Yan's avatar
Yan committed
358
359
360
361
362
    toolBar = QtWidgets.QToolBar(main_window)
    toolBar.setAllowedAreas(QtCore.Qt.TopToolBarArea)
    toolBar.setFloatable(False)
    toolBar.setMovable(False)
    toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
Yan's avatar
Yan committed
363

Yan's avatar
Yan committed
364
365
366
    toolBar.addAction(openact)
    toolBar.addAction(exportact)
    toolBar.addSeparator()
Yan's avatar
Yan committed
367
368
369
    toolBar.addWidget(QtWidgets.QLabel("Predict Formula:"))
    toolBar.addWidget(predictform)
    toolBar.addSeparator()
Yan's avatar
Yan committed
370
371
    toolBar.addAction(zceact)
    toolBar.addAction(drlact)
Yan's avatar
Yan committed
372
373
    toolBar.addSeparator()
    toolBar.addAction(autozoomy)
Yan's avatar
Yan committed
374

Yan's avatar
Yan committed
375
376
    main_window.dragEnterEvent = lambda event: drag_entered(event)
    main_window.dropEvent = lambda event: dropped(
377
        event, main_window, chromatogram, spectrum, ds, ms, filename,
3Yan's avatar
3Yan committed
378
        chrom, update, config)
Yan's avatar
Yan committed
379
    main_window.setAcceptDrops(True)
Yan's avatar
Yan committed
380
    main_window.keyPressEvent = lambda event: key_pressed(event, chromatogram,
Yan's avatar
Yan committed
381
            spectrum, ds, ms, filename, chrom, config)
Yan's avatar
Yan committed
382

383
384
    main_window.addToolBar(QtCore.Qt.TopToolBarArea, toolBar)
    main_window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, treedock)
Yan's avatar
Yan committed
385
    main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, paramsdock)
Yan's avatar
Yan committed
386
    main_window.addDockWidget(QtCore.Qt.RightDockWidgetArea, consoledock)
387
    main_window.setStatusBar(barHandler.statusBar)
388
389
390

    main_window.setFocus()

Yan's avatar
Yan committed
391
    if len(sys.argv) == 2:
392
        load_file(main_window, chromatogram, spectrum, ds, ms,
393
394
                  filename, chrom, update, config, loadthread,
                  filename=sys.argv[1])
Yan's avatar
Yan committed
395
    else:
3Yan's avatar
3Yan committed
396
397
        gt.pop_plot(0, 0, spectrum, ms)
        gt.pop_plot(0, 0, chromatogram, chrom)
Yan's avatar
Yan committed
398
399
400

    main_window.show()
    sys.exit(app.exec_())
Yan's avatar
Yan committed
401

402

Yan's avatar
Yan committed
403
404
if __name__ == "__main__":
    main()