__main__.py 10.3 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
Yan's avatar
Yan committed
10
from rawprasslib import load_raw
Yan's avatar
Yan committed
11
from rawprasslib import rawprasslib
Yan's avatar
Yan committed
12
13
import prasopes.graphtools as gt
import prasopes.filetools as ft
Yan's avatar
Yan committed
14
import prasopes.zcetools as zce
Yan's avatar
Yan committed
15
import prasopes.drltools as drl
Yan's avatar
Yan committed
16
import prasopes.config as cf
Yan's avatar
Yan committed
17
import prasopes.tangoicons
Yan's avatar
Yan committed
18
19
20
import sys
import matplotlib
import logging
3Yan's avatar
3Yan committed
21
import os.path
Yan's avatar
Yan committed
22
23
24
matplotlib.use("Qt5Agg")


25
26
27
28
class update_signal(QtCore.QObject):
    signal = QtCore.pyqtSignal()


29
def load_file(parent, chrom_plot, spc, d_set, ms_s, fn, chrom_s,
30
              update, settings, filename=None):
Yan's avatar
Yan committed
31
    """populates dataset and plots it"""
3Yan's avatar
3Yan committed
32
33
34
    directory=settings.value("open_folder")
    if fn[0] is not None:
        directory=fn[0]
Yan's avatar
Yan committed
35
36
    if filename == None:
        filename = QtWidgets.QFileDialog.getOpenFileName(
3Yan's avatar
3Yan committed
37
38
39
            caption="Open spectrum",
            directory=directory,
            filter="Finnigan RAW files (*.raw, *.RAW)")[0]
3Yan's avatar
3Yan committed
40
    if filename is not '' and os.path.isfile(filename):
Yan's avatar
Yan committed
41
42
43
44
45
46
47
48
49
50
51
        try:
            d_set['chrom_dat'], d_set['masses'], d_set['matrix'] \
                = load_raw(filename, settings.value("tmp_location"))
        except rawprasslib.ParsingException as pex:
            QtWidgets.QMessageBox.critical(
                parent, "Opening of the file has failed!",
                "File is incompatible with the rawprasslib, "
                "canceling request!\n\n"
                "Error message:\n{}".format(pex.args[0]))
            return

Yan's avatar
Yan committed
52
        gt.populate(chrom_plot, spc, d_set, ms_s, chrom_s)
3Yan's avatar
3Yan committed
53
        fn[0] = filename
54
55
        parent.setWindowTitle("Prasopes - {}".format(
            os.path.basename(filename)))
56
        update.signal.emit()
3Yan's avatar
3Yan committed
57

Yan's avatar
Yan committed
58

Yan's avatar
Yan committed
59
60
61
62
63
64
65
66
67
68
69
70
def update_spectrum(event, chromatogram, spect, ds,
                    ms, fn, chrom, config):
    if fn[0] is not None and event.key is "f5":
        slims = [spect.get_xlim(), spect.get_ylim()]
        ds['chrom_dat'], ds['masses'], ds['matrix'] \
            = load_raw(fn[0], config.value("tmp_location"))
        gt.populate(chromatogram, spect, ds, ms, chrom)
        spect.set_xlim(slims[0])
        spect.set_ylim(slims[1])
        spect.get_figure().canvas.draw()


71
def dropped(event, parent, chromatogram, spectrum, ds, ms, filename,
3Yan's avatar
3Yan committed
72
            chrom, update, config):
73
    dropurl = event.mimeData().urls()[0].toLocalFile()
74
    load_file(parent, chromatogram, spectrum, ds, ms, filename,
3Yan's avatar
3Yan committed
75
              chrom, update, config, filename=dropurl)
Yan's avatar
Yan committed
76
77
78
79


def drag_entered(event):
    if event.mimeData().hasUrls() and event.mimeData().urls()[0]\
80
        .toLocalFile().lower().endswith('.raw'):
Yan's avatar
Yan committed
81
82
83
        event.accept()


Yan's avatar
Yan committed
84
85
86
87
88
def about(parent):
    """constructs window with "about" info"""
    QtWidgets.QMessageBox.information(
            parent, "About Prasopes",
            "Prasopes Finnigan raw file viewer\n\n"
89
            "Version: 0.0.8 (alpha)")
Yan's avatar
Yan committed
90
91


Yan's avatar
Yan committed
92
def main():
Yan's avatar
Yan committed
93
94
95
    # ds for data_set, ms for mass_spec_dataset, chrom for chrom_dataset
    ds = dict(chrom_dat=None, masses=None, matrix=None)
    ms = dict(x=[0], y=[0], line=None, annotation=[],
Yan's avatar
Yan committed
96
              name="Spectrum", xlabel="m/z", ylabel="ion count",
Yan's avatar
Yan committed
97
              xtics=20, autoy=True)
Yan's avatar
Yan committed
98
99
    chrom = dict(x=[0], y=[0], line=None, t_start=None, t_end=None,
                 name="Chromatogram", xlabel="time(min)",
100
                 ylabel="total ion count", timesarg=None)
Yan's avatar
Yan committed
101
    filename = [None]
3Yan's avatar
3Yan committed
102
    drlcache = [None, None]
103
    update = update_signal()
Yan's avatar
Yan committed
104

Yan's avatar
Yan committed
105
106
    config = cf.settings()

Yan's avatar
Yan committed
107
    p_logger = logging.getLogger('parseLogger')
Yan's avatar
Yan committed
108
    drl_logger = logging.getLogger('drlLogger')
109
    zce_logger = logging.getLogger('zceLogger')
Yan's avatar
Yan committed
110
111
    logging.basicConfig()
    p_logger.setLevel("WARN")
Yan's avatar
Yan committed
112
113
    #drl_logger.setLevel("INFO")
    drl_logger.setLevel("DEBUG")
114
    zce_logger.setLevel("DEBUG")
Yan's avatar
Yan committed
115

Yan's avatar
Yan committed
116
    graph = Figure(figsize=(5, 4), dpi=100, facecolor="None")
Yan's avatar
Yan committed
117
118
119
    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
120
121
122
123
124
125
126
127
    graph.tight_layout()
    mpl_canvas = FigureCanvas(graph)
    mpl_canvas.setStyleSheet("background-color:transparent;")
    mpl_canvas.setAutoFillBackground(False)
    mpl_canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
    
    gt.pan_factory(chromatogram)
    gt.zoom_factory(chromatogram, 1.15)
128
    gt.arrow_factory(spectrum, chromatogram, ds, ms, chrom)
Yan's avatar
Yan committed
129
130
    gt.pan_factory(spectrum, ms)
    gt.zoom_factory(spectrum, 1.15, ms)
131
    mass_selector = SpanSelector(
Yan's avatar
Yan committed
132
        spectrum, lambda x_min, x_max: gt.pick_masses(
133
134
135
            x_min, x_max, spectrum, ms), 'horizontal', minspan=0.01,
        useblit=True, rectprops=dict(alpha=0.15, facecolor='purple'),
        button=3)
136
    time_selector = SpanSelector(
Yan's avatar
Yan committed
137
138
139
140
141
142
         chromatogram, lambda x_min, x_max: gt.pick_times(
             x_min, x_max, spectrum, ds, chromatogram, ms, chrom), 
         'horizontal', useblit=True, rectprops=dict(
             alpha=0.15, facecolor='purple'), button=3)

    app = QtWidgets.QApplication(sys.argv)
Yan's avatar
Yan committed
143
    main_window = QtWidgets.QMainWindow(windowTitle="Prasopes")
Yan's avatar
Yan committed
144

Yan's avatar
Yan committed
145
146
147
    if QtGui.QIcon.themeName() is "":
        QtGui.QIcon.setThemeName("TangoMFK")

Yan's avatar
Yan committed
148
    openact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
149
        "document-open"), "&Open...", None)
Yan's avatar
Yan committed
150
151
    openact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_O)
    openact.triggered.connect(lambda: load_file(
152
        main_window, chromatogram, spectrum, ds, ms, filename, chrom,
153
        update, config))
Yan's avatar
Yan committed
154
    exportact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
155
        "document-save-as"), "&Export...", None)
Yan's avatar
Yan committed
156
157
158
159
    exportact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_E)
    exportact.triggered.connect(lambda: ft.export_dial(
        ms, chrom, filename, main_window))
    settingsact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
160
        "preferences-system"), "&Settings...", None)
Yan's avatar
Yan committed
161
162
    settingsact.triggered.connect(lambda: cf.dial(main_window))
    quitact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
163
        "application-exit"), "&Quit", None)
Yan's avatar
Yan committed
164
165
166
    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
167
        "applications-utilities"), "&TSQ zce...", None)
Yan's avatar
Yan committed
168
169
    zceact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_T)
    zceact.triggered.connect(lambda: zce.dialog(
170
        main_window, ds, filename, update))
Yan's avatar
Yan committed
171
    drlact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
Yan's avatar
Yan committed
172
        "applications-utilities"), "&DRL...", None)
Yan's avatar
Yan committed
173
174
    drlact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_D)
    drlact.triggered.connect(lambda: drl.main_window(
175
        main_window, ds, filename, drlcache, update))
Yan's avatar
Yan committed
176
177
    aboutact = QtWidgets.QAction("&About Prasopes", None)
    aboutact.triggered.connect(lambda: about(main_window))
Yan's avatar
Yan committed
178
    autozoomy = QtWidgets.QAction(QtGui.QIcon.fromTheme(
179
        "zoom-original"), "Auto Zoom Y", None, checkable=True, checked=True)
Yan's avatar
Yan committed
180
181
    autozoomy.triggered.connect(lambda: gt.autozoomy(
        autozoomy.isChecked(), spectrum, ms))
182
183
184
185
186
    filebrowseract = QtWidgets.QAction("&File browser", None,
                                       checkable=True, checked=True)
    filebrowseract.triggered.connect(
        lambda: treedock.show() if filebrowseract.isChecked() == True
                else treedock.hide())
Yan's avatar
Yan committed
187

Yan's avatar
Yan committed
188
189
    file_menu = QtWidgets.QMenu('&File', main_window)
    main_window.menuBar().addMenu(file_menu)
Yan's avatar
Yan committed
190
191
192
193
194
195
    file_menu.addAction(openact)
    file_menu.addAction(exportact)
    file_menu.addSeparator()
    file_menu.addAction(settingsact)
    file_menu.addSeparator()
    file_menu.addAction(quitact)
Yan's avatar
Yan committed
196
197
    tools_menu = QtWidgets.QMenu('&Tools', main_window)
    main_window.menuBar().addMenu(tools_menu)
Yan's avatar
Yan committed
198
199
    tools_menu.addAction(zceact)
    tools_menu.addAction(drlact)
200
201
    tools_menu.addSeparator()
    tools_menu.addAction(filebrowseract)
Yan's avatar
Yan committed
202
203
204
    help_menu = QtWidgets.QMenu('&Help', main_window)
    main_window.menuBar().addMenu(help_menu)
    help_menu.addAction(aboutact)
Yan's avatar
Yan committed
205
206
207
208

    main_widget = QtWidgets.QWidget(main_window)
    main_window.setCentralWidget(main_widget)

Yan's avatar
Yan committed
209
210
211
212
213
    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
214

Yan's avatar
Yan committed
215
216
217
218
219
    toolBar.addAction(openact)
    toolBar.addAction(exportact)
    toolBar.addSeparator()
    toolBar.addAction(zceact)
    toolBar.addAction(drlact)
Yan's avatar
Yan committed
220
221
    toolBar.addSeparator()
    toolBar.addAction(autozoomy)
Yan's avatar
Yan committed
222

3Yan's avatar
3Yan committed
223
    fileModel = QtWidgets.QFileSystemModel()
224
225
    fileModel.setRootPath('')
    activeDir = fileModel.index(config.value("open_folder"))
3Yan's avatar
3Yan committed
226
227
228
229
230
231
232
233
234
235
236
    treeview = QtWidgets.QTreeView()
    treeview.setModel(fileModel)
    treeview.setCurrentIndex(activeDir)
    treeview.expand(activeDir)
    treedock = QtWidgets.QDockWidget()
    treedock.setWidget(treeview)
    update.signal.connect(
        lambda: treeview.setCurrentIndex(fileModel.index(filename[0])))
    treeview.doubleClicked.connect(lambda index: load_file(
        main_window, chromatogram, spectrum, ds, ms, filename, chrom,
        update, config, filename=fileModel.filePath(index)))
237
238
239
240
241
242
    def closeOverride(event, dock, action):
        action.setChecked(False)
        dock.hide()
        event.ignore()
    treedock.closeEvent = lambda event: closeOverride(
            event, treedock, filebrowseract)
3Yan's avatar
3Yan committed
243
244
    main_window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, treedock)

Yan's avatar
Yan committed
245
    layout = QtWidgets.QVBoxLayout(main_widget)
Yan's avatar
Yan committed
246
    layout.addWidget(toolBar)
Yan's avatar
Yan committed
247
248
249
    layout.addWidget(mpl_canvas)
    mpl_canvas.setFocus()

3Yan's avatar
3Yan committed
250

251
    mpl_canvas.mpl_connect('key_press_event', lambda event:
Yan's avatar
Yan committed
252
253
        update_spectrum(event, chromatogram, spectrum, ds, ms,
                        filename, chrom, config))
Yan's avatar
Yan committed
254
255
    main_window.dragEnterEvent = lambda event: drag_entered(event)
    main_window.dropEvent = lambda event: dropped(
256
        event, main_window, chromatogram, spectrum, ds, ms, filename,
3Yan's avatar
3Yan committed
257
        chrom, update, config)
Yan's avatar
Yan committed
258
    main_window.setAcceptDrops(True)
Yan's avatar
Yan committed
259

Yan's avatar
Yan committed
260
    if len(sys.argv) == 2:
261
        load_file(main_window, chromatogram, spectrum, ds, ms,
3Yan's avatar
3Yan committed
262
                  filename, chrom, update, config, filename=sys.argv[1])
Yan's avatar
Yan committed
263
264
265
266
267
268
    else:
        gt.pop_plot(spectrum, ms)
        gt.pop_plot(chromatogram, chrom)

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

270

Yan's avatar
Yan committed
271
272
if __name__ == "__main__":
    main()