drltools.py 17 KB
Newer Older
Yan's avatar
Yan committed
1
2
3
4
5
6
#!/usr/bin/env python3
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.widgets import SpanSelector
from PyQt5 import QtCore
from PyQt5 import QtWidgets
7
from PyQt5 import QtGui
Yan's avatar
Yan committed
8
from PyQt5 import QtPrintSupport
Yan's avatar
Yan committed
9
10
11
import sys
import matplotlib
import numpy as np
Yan's avatar
Yan committed
12
13
import prasopes.datatools as dt
import prasopes.graphtools as gt
Yan's avatar
Yan committed
14
import prasopes.filetools as ft
Yan's avatar
Yan committed
15
16
17
matplotlib.use("Qt5Agg")

class HBar(QtWidgets.QFrame):
18
    """horizontal bar class"""
Yan's avatar
Yan committed
19
20
21
22
23
24
    def __init__(self):
        super(HBar, self).__init__()
        self._main = QtWidgets.QWidget()
        self.setFrameShape(QtWidgets.QFrame.HLine)


Yan's avatar
Yan committed
25
def update_profile(start, end, spectrum, dataset):
26
27
    """spectrum updating procedure"""
    #Dont do anything to graph when the spectrum is not populated
Yan's avatar
Yan committed
28
    if (type(dataset['masses'])) == type(None):
29
30
        return

Yan's avatar
Yan committed
31
32
    masses = dataset['masses']
    massargs = dt.argsubselect(masses, start, end)
33
    yshape = np.mean(dataset['matrix'], axis=0)
Yan's avatar
Yan committed
34
35
    spectrum.clear()
    dots_x = masses
36
    dots_y = yshape
Yan's avatar
Yan committed
37
38
    full_x = masses[massargs]
    full_y = yshape[massargs]
39
40
    spectrum.plot(dots_x, dots_y, ':', color='gray')
    spectrum.plot(full_x, full_y, 'r')
Yan's avatar
Yan committed
41
42
43
44
    xex = (masses[massargs[-1]]-masses[massargs[0]])*0.25
    spectrum.set_xlim(masses[massargs[0]]-xex,
                      masses[massargs[-1]]+xex)
    ymax = max(yshape[massargs])
45
46
47
    spectrum.set_ylim(ymax*-0.1, ymax*1.2)
    spectrum.figure.canvas.draw()

Yan's avatar
Yan committed
48

Yan's avatar
Yan committed
49
50
51
52
53
54
def get_daughterset(ptable, dtable, ds):
    names = []
    times = ds['chrom_dat'][0,:]
    intensities = []
    #TODO: resolve intensities trouble
    for row in range(dtable.rowCount()):
Yan's avatar
Yan committed
55
        if dtable.cellWidget(row, 0).checkState() == 2:
Yan's avatar
Yan committed
56
57
58
59
60
            startm = dt.floatize(ptable.cellWidget(row,1).text())
            endm = dt.floatize(ptable.cellWidget(row,2).text())
            massargs = dt.argsubselect(ds['masses'], startm, endm)
            intensity = (np.sum(
                ds['matrix'].T[massargs].T, axis=1)) / ds['chrom_dat'][1]
Yan's avatar
Yan committed
61
            cor = dtable.cellWidget(row, 1).currentIndex()-1
Yan's avatar
Yan committed
62
            if cor != -1:
Yan's avatar
Yan committed
63
                factor = dt.floatize(dtable.cellWidget(row,2).text())
Yan's avatar
Yan committed
64
65
66
                startm = dt.floatize(ptable.cellWidget(cor,1).text())
                endm = dt.floatize(ptable.cellWidget(cor,2).text())
                massargs = dt.argsubselect(ds['masses'], startm, endm)
Yan's avatar
Yan committed
67
                correction = ((np.sum(
Yan's avatar
Yan committed
68
                    ds['matrix'].T[massargs].T, axis=1))\
Yan's avatar
Yan committed
69
70
                              / ds['chrom_dat'][1]) * factor
                intensity = intensity - correction
Yan's avatar
Yan committed
71
            intensities.append(intensity)
Yan's avatar
Yan committed
72
            names.append(dtable.item(row,0).text())
Yan's avatar
Yan committed
73
74
75
76
77
78
79
    return names, times, intensities


def update_drlspectrum(ptable, dtable, ds, drlspectrum):
    #Dont do when the dataset is not populated
    if (type(ds['masses'])) == type(None):
        return
80
    colors = np.array([[255,0,0],[0,255,0],[0,0,255],[0,200,255],[255,0,255],[255,200,0]])
Yan's avatar
Yan committed
81
82
83
84

    names, times, intensities = get_daughterset(ptable, dtable, ds)
    for i in range(len(drlspectrum.lines)):
        drlspectrum.lines[0].remove()
85
86
87
    for i,j in enumerate(intensities):
        drlspectrum.plot(times, j, label=names[i],
                color=(colors[i%len(colors)] / 255))
Yan's avatar
Yan committed
88
89
90
    if len(names) != 0:
        drlspectrum.set_ylim(top=np.amax(intensities)*1.1,
                bottom=np.amax(intensities)*-0.01)
91
    drlspectrum.legend()
Yan's avatar
Yan committed
92
    drlspectrum.figure.canvas.draw()
93

94
95
    count = 0
    for row in range(dtable.rowCount()):
Yan's avatar
Yan committed
96
        if dtable.cellWidget(row, 0).checkState() ==2:
97
98
99
100
101
102
            dtable.item(row,0).setBackground(QtGui.QBrush(
                QtGui.QColor(*colors[count%len(colors)], alpha=50)))
            count += 1
        else:
            dtable.item(row,0).setBackground(QtGui.QBrush())

Yan's avatar
Yan committed
103

104
def getTableItemList(ptable):
105
    ion_list = []
Yan's avatar
Yan committed
106
107
108
109
110
111
112
113
114
115
    for row in range(ptable.rowCount()):
        text = []
        for i in range(3):
            if type(ptable.cellWidget(row, i)) is not type(None):
                frg = ptable.cellWidget(row, i).text()
            else:
                frg = ""
            text.append(frg)
        line = "{} ({}-{})".format(*text)
        ion_list.append(line)
116
117
118
119
    return ion_list


def update_drl(start_mz, end_mz, spectrum, dataset, pname, dname,
Yan's avatar
Yan committed
120
        ptable, dtable, drlspectrum):
Yan's avatar
Yan committed
121
122
    """cares that masses are in order and valid, then refresh tables"""
    for line in start_mz, end_mz:
Yan's avatar
Yan committed
123
124
125
        status = QtGui.QDoubleValidator().validate(line.text(), 0)[0]
        if status != QtGui.QValidator.Acceptable:
            line.setText("0")
Yan's avatar
Yan committed
126

Yan's avatar
Yan committed
127
128
    start = dt.floatize(start_mz.text())
    end = dt.floatize(end_mz.text())
129
130
131

    if start > end:
        start, end = end, start
132
133
134

    if float(0) not in (start, end) and pname.text() is "":
        pname.setText(str(int((start+end)/2)))
135

Yan's avatar
Yan committed
136
137
    ptnames = getTableItemList(ptable)
    for row in range(dtable.rowCount()):
Yan's avatar
Yan committed
138
139
140
141
142
143
        dtable.item(row,0).setText(ptnames[row])
        index = dtable.cellWidget(row,1).currentIndex()
        dtable.cellWidget(row,1).clear()
        dtable.cellWidget(row,1).addItem("")
        dtable.cellWidget(row,1).addItems(getTableItemList(ptable))
        dtable.cellWidget(row,1).setCurrentIndex(index)
Yan's avatar
Yan committed
144

Yan's avatar
Yan committed
145
146
    update_profile(start, end, spectrum, dataset)
    update_drlspectrum(ptable, dtable, dataset, drlspectrum)
147
148
149


def remove_rows(ptable, dtable):
Yan's avatar
Yan committed
150
    # TODO: maybe nicer selection in future, but this works for now
151
152
153
154
155
156
    rows = reversed(list(set(
        map(lambda index: index.row(), ptable.selectedIndexes()))))
    for row in rows:
        dtable.removeRow(row)
        ptable.removeRow(row)
        for i in range(dtable.rowCount()):
Yan's avatar
Yan committed
157
158
159
160
            index = dtable.cellWidget(i,1).currentIndex()
            dtable.cellWidget(i,1).clear()
            dtable.cellWidget(i,1).addItem("")
            dtable.cellWidget(i,1).addItems(getTableItemList(ptable))
161
            if index == row+1:
Yan's avatar
Yan committed
162
                dtable.cellWidget(i,1).setCurrentIndex(0)
163
            elif index > row+1:
Yan's avatar
Yan committed
164
                dtable.cellWidget(i,1).setCurrentIndex(index-1)
165
166


Yan's avatar
Yan committed
167
def setDoubleCell(table, row, column):
168
169
170
171
172
173
174
175
176
177
178
179
    """populate table cell with float-validated posititve text"""
    table.setCellWidget(row,column,QtWidgets.QLineEdit())
    validator = QtGui.QDoubleValidator()
    validator.setBottom(0)
    table.cellWidget(row,column).setValidator(validator)
    table.cellWidget(row,column).setFrame(False)
    table.cellWidget(row,column).setText("0")
    table.horizontalHeader().setSectionResizeMode(
            column, QtWidgets.QHeaderView.ResizeToContents)
    return table.cellWidget(row,column)


Yan's avatar
Yan committed
180
def add_line(parent_widget, ds, parenttable,
Yan's avatar
Yan committed
181
        daughtertable, drlspectrum):
182
183
184
185
186
187
188
189
190
    """add parent ion to the table"""
    ion_graph = Figure(figsize=(3, 1.5), dpi=100, facecolor="None")
    ionspect = ion_graph.add_subplot(111, facecolor=(1, 1, 1, 0.8),
            position=(-0.01,-0.01,1.02,1.02))
    graph_canvas = FigureCanvas(ion_graph)
    graph_canvas.setStyleSheet("background-color:transparent;")
    graph_canvas.setAutoFillBackground(False)

    newrow = parenttable.rowCount()
191

192
193
194
195
196
197
198
    parenttable.setRowCount(newrow + 1)
    pname = QtWidgets.QLineEdit()
    pname.setFrame(False)
    parenttable.setCellWidget(newrow, 0, pname)
    start_mz = setDoubleCell(parenttable, newrow, 1)
    end_mz = setDoubleCell(parenttable, newrow, 2)
    parenttable.setCellWidget(newrow, 3, graph_canvas)
199
200
201
202
203
    if newrow is not 0:
        for i in range(3):
            parenttable.cellWidget(newrow, i).setText(
                str(dt.floatize(
                    parenttable.cellWidget(newrow-1, i).text())+1))
204

205
    daughtertable.setRowCount(newrow + 1)
Yan's avatar
Yan committed
206
207

    #TODO: decide which box will be used in the final version
Yan's avatar
Yan committed
208
    checkbox = QtWidgets.QCheckBox()
209
210
    dname = QtWidgets.QTableWidgetItem()
    dname.setFlags(dname.flags() & ~QtCore.Qt.ItemIsEditable)
Yan's avatar
Yan committed
211
    dname.setTextAlignment(QtCore.Qt.AlignRight)
Yan's avatar
Yan committed
212
213
    daughtertable.setItem(newrow, 0, dname)
    daughtertable.setCellWidget(newrow, 0, checkbox)
214

215
216
217
218
    corto = QtWidgets.QComboBox()
    corto.setFrame(False)
    corto.addItem("")
    corto.addItems(getTableItemList(parenttable))
Yan's avatar
Yan committed
219
    daughtertable.setCellWidget(newrow, 1, corto)
220

Yan's avatar
Yan committed
221
    corfact = setDoubleCell(daughtertable, newrow, 2)
222

223
    update_drl(start_mz, end_mz, ionspect, ds, pname, dname, 
Yan's avatar
Yan committed
224
            parenttable, daughtertable, drlspectrum)
225

Yan's avatar
Yan committed
226
227
    pname.editingFinished.connect(lambda: update_drl(
        start_mz, end_mz, ionspect, ds, pname, dname, parenttable,
Yan's avatar
Yan committed
228
        daughtertable, drlspectrum))
229
230
    start_mz.editingFinished.connect(lambda: update_drl(
        start_mz, end_mz, ionspect, ds, pname, dname, parenttable,
Yan's avatar
Yan committed
231
        daughtertable, drlspectrum))
232
233
    end_mz.editingFinished.connect(lambda: update_drl(
        start_mz, end_mz, ionspect, ds, pname, dname, parenttable,
Yan's avatar
Yan committed
234
235
236
        daughtertable, drlspectrum))
    checkbox.stateChanged.connect(lambda: update_drlspectrum(
        parenttable, daughtertable, ds, drlspectrum))
237
238


239
240
241
def iontable(labels, exp_col):
    """creates a table for ions"""
    table = QtWidgets.QTableWidget(columnCount=len(labels))
242
    table.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
243
244
                        QtWidgets.QSizePolicy.Expanding)
    table.setHorizontalHeaderLabels(labels)
245
246
247
248
249
250
251
    table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)

    for n in range(table.columnCount()):
        table.horizontalHeader().setSectionResizeMode(
            n, QtWidgets.QHeaderView.Stretch)
    table.setMinimumSize(600,0)

252
    return table
253
254


Yan's avatar
Yan committed
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
def load_drltables(parent, ptable, dtable, dataset, drlspectrum):
    filename = QtWidgets.QFileDialog.getOpenFileName(
            caption="Load DRL config tables",
            filter="comma-separated values (*.csv)")[0]
    if filename is not '':
        names = []
        start_masses = []
        end_masses = []
        states = []
        corrected_to = []
        corr_factors = []

        with open(filename, 'r') as cfile:
            rawdata = cfile.read().splitlines()
        for i in range(1,len(rawdata)):
            rawline=rawdata[i].split(",")
            if len(rawline) != 6 or int(rawline[3]) not in range(3) \
                    or int(rawline[4]) not in range(len(rawdata)):
                QtWidgets.QMessageBox.warning(
                    parent, "Load DRL config tables",
                    "Config file corrupted on line {},"
                    " cancelling request".format(i+1))
                return
            for j, k in enumerate((names, start_masses, end_masses,
                               states, corrected_to, corr_factors)):
                k.append(rawline[j])
Yan's avatar
Yan committed
281
282
283
        for row in reversed(range(ptable.rowCount())):
            dtable.removeRow(row)
            ptable.removeRow(row)
Yan's avatar
Yan committed
284
285
286
287
288
289
290
291
292
        #first populate only parent table
        for i in range(len(names)):
            add_line(parent, dataset, ptable, dtable, drlspectrum)
            print(names[i])
            ptable.cellWidget(i, 0).setText(names[i])
            ptable.cellWidget(i, 1).setText(start_masses[i])
            ptable.cellWidget(i, 2).setText(end_masses[i])
        #and after that daughter table
        for i in range(len(names)):
Yan's avatar
Yan committed
293
            dtable.cellWidget(i, 1).setCurrentIndex(
Yan's avatar
Yan committed
294
                int(corrected_to[i]))
Yan's avatar
Yan committed
295
296
            dtable.cellWidget(i, 2).setText(corr_factors[i])
            dtable.cellWidget(i, 0).setCheckState(int(states[i]))
Yan's avatar
Yan committed
297
298


Yan's avatar
Yan committed
299
300
301
302
303
304
305
306
307
308
309
310
311
def save_drlconfig(ptable, dtable, parent):
    """safe DRL table layout so it can be summoned when needed"""
    exp_f_name = ft.get_save_filename(
        "Save DRL table layout", "comma-separated values (*.csv)",
        "csv", parent)
    if exp_f_name is not '':
        expf = open(exp_f_name, 'w')
        expf.write("#ion_name, start m/z, end m/z, visible,"
                   "corrected_to, factor\n")
        for row in range(ptable.rowCount()):
            vals = []
            for i in range(3):
                vals.append(ptable.cellWidget(row,i).text())
Yan's avatar
Yan committed
312
313
314
            vals.append(dtable.cellWidget(row,0).checkState())
            vals.append(dtable.cellWidget(row,1).currentIndex())
            vals.append(dtable.cellWidget(row,2).text())
Yan's avatar
Yan committed
315
316
317
318
            #vals = ",".join(map(str, vals))
            expf.write("{}\n".format((",".join(map(str, vals)))))
        expf.close()

Yan's avatar
Yan committed
319

Yan's avatar
Yan committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def export_drlspectrum(parent, fn, ptable, dtable, ds):
    if fn[0] is None:
        QtWidgets.QMessageBox.warning(
            main_window, "Export DRL dataset",
            "Nothing to export, cancelling request")
        return
    names, times, intensities = get_daughterset(ptable, dtable, ds)
    exp_f_name = ft.get_save_filename(
        "Export DRL data", "comma-separated values (*.csv)", "csv", parent)
    if exp_f_name is not '':
        expf = open(exp_f_name, 'w')
        expf.write("times, {}\n".format((",".join(names))))
        for i in range(len(times)):
            dataset = []
            dataset.append(times[i])
            for intensity in intensities:
                dataset.append(intensity[i])
            expf.write("{}\n".format((",".join(map(str, dataset)))))
        expf.close()

Yan's avatar
Yan committed
340

Yan's avatar
Yan committed
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
def print_graph(labels, ptable, dtable, ds):
    printfig = Figure(figsize=(5,2), dpi=100)
    printplot = printfig.add_subplot(111)
    printcanvas = FigureCanvas(printfig)
    gt.pop_plot(printplot, labels)
    update_drlspectrum(ptable, dtable, ds, printplot)
    widget = QtWidgets.QDialog(None,
            windowTitle='Print preview')
    layout = QtWidgets.QVBoxLayout(widget)
    layout.addWidget(printcanvas)
    widget.resize(600,400)
    widget.show()
    dialog = QtPrintSupport.QPrintDialog()
    if dialog.exec_() == QtWidgets.QDialog.Accepted:
        #dialog.printer().setFullPage(False)
        #printcanvas.render(dialog.printer())
        #graph.canvas.render(dialog.printer())
        printcanvas.render(dialog.printer())
    widget.close()


Yan's avatar
Yan committed
362
def main_window(parent, ds, filename, cache):
363
    """constructs a dialog window"""
Yan's avatar
Yan committed
364
    def saveonclose(window, event, cache,pt,dt,canvas):
Yan's avatar
Yan committed
365
        cache[0], cache[1], cache[2] = pt, dt, canvas
Yan's avatar
Yan committed
366
        QtWidgets.QMainWindow.closeEvent(window, event)
Yan's avatar
Yan committed
367

Yan's avatar
Yan committed
368
    main_window = QtWidgets.QMainWindow(
Yan's avatar
Yan committed
369
        parent, windowTitle='Delayed reactant labelling')
Yan's avatar
Yan committed
370
371
372
373
374
    dial_widget = QtWidgets.QWidget(main_window)
    main_window.setCentralWidget(dial_widget)

    main_window.closeEvent = lambda event: saveonclose(
        main_window, event, cache, pt, dt, graph_canvas)
Yan's avatar
Yan committed
375

Yan's avatar
Yan committed
376
377
    dial_graph = Figure(figsize=(5, 2), dpi=100, facecolor="None")
    chromplot = dial_graph.add_subplot(111, facecolor=(1, 1, 1, 0.8))
Yan's avatar
Yan committed
378
379
380
    graph_canvas = FigureCanvas(dial_graph)
    graph_canvas.setStyleSheet("background-color:transparent;")
    graph_canvas.setAutoFillBackground(False)
Yan's avatar
Yan committed
381
382
383
384
385
386
    graphlabels = dict(x=[0], y=[0], line=None, name="",
                xlabel="time(min)", ylabel="relative intensity")
    gt.pan_factory(chromplot)
    gt.zoom_factory(chromplot, 1.15)
    gt.pop_plot(chromplot, graphlabels)

Yan's avatar
Yan committed
387

388
389
390
    drl_load = QtWidgets.QPushButton("&Load")
    drl_save = QtWidgets.QPushButton("&Save")
    drl_export = QtWidgets.QPushButton("&Export")
Yan's avatar
Yan committed
391
    drl_print = QtWidgets.QPushButton("&Print")
392
    close = QtWidgets.QPushButton("&Close")
Yan's avatar
Yan committed
393
    close.clicked.connect(main_window.close)
394

Yan's avatar
Yan committed
395
396
397
    btn_add = QtWidgets.QPushButton("&Add")
    btn_rem = QtWidgets.QPushButton("Remove")

398
399
    # pt = parenttable
    # dt = daughtertable
Yan's avatar
Yan committed
400
    if cache == [None, None, None]:
Yan's avatar
Yan committed
401
402
        dt = iontable(["","Name", "corrected to", "factor"], 2)
        dt.horizontalHeader().setSectionResizeMode(
403
            0, QtWidgets.QHeaderView.ResizeToContents)
Yan's avatar
Yan committed
404
        dt.horizontalHeader().setSectionResizeMode(
405
406
            3, QtWidgets.QHeaderView.Fixed)

Yan's avatar
Yan committed
407
        pt = iontable(["Name", "start (m/z)", "end (m/z)", "profile"], 2)
408
        add_line(dial_widget, ds, pt, dt, chromplot)
Yan's avatar
Yan committed
409
410
411
    else:
        pt = cache[0]
        dt = cache[1]
Yan's avatar
Yan committed
412
        graph_canvas = cache[2]
413
414

    btn_add.clicked.connect(lambda: add_line(
Yan's avatar
Yan committed
415
        dial_widget, ds, pt, dt, chromplot))
416
    btn_rem.clicked.connect(lambda: remove_rows(pt,dt))
Yan's avatar
Yan committed
417
418
    drl_load.clicked.connect(lambda: load_drltables(
        dial_widget, pt, dt, ds, chromplot))
Yan's avatar
Yan committed
419
420
    drl_save.clicked.connect(lambda: save_drlconfig(
        pt, dt, dial_widget))
Yan's avatar
Yan committed
421
422
    drl_print.clicked.connect(lambda: print_graph(
        graphlabels, pt, dt, ds))
Yan's avatar
Yan committed
423
424
    drl_export.clicked.connect(lambda: export_drlspectrum(
        dial_widget, filename, pt, dt, ds))
Yan's avatar
Yan committed
425

426

Yan's avatar
Yan committed
427
428
429
    main_layout = QtWidgets.QVBoxLayout(dial_widget)
    sub_layout = QtWidgets.QHBoxLayout()
    tablelayout = QtWidgets.QVBoxLayout()
Yan's avatar
Yan committed
430
    pt_butlayout = QtWidgets.QHBoxLayout()
Yan's avatar
Yan committed
431
    main_butlayout = QtWidgets.QHBoxLayout()
Yan's avatar
Yan committed
432

Yan's avatar
Yan committed
433
434
435
436
    pt_butlayout.addWidget(btn_add)
    pt_butlayout.addWidget(btn_rem)
    pt_butlayout.addStretch(0)

437
438
    main_layout.addLayout(sub_layout)
    main_layout.addWidget(HBar())
Yan's avatar
Yan committed
439
    main_layout.addLayout(main_butlayout)
440

Yan's avatar
Yan committed
441
442
443
444
    main_butlayout.addWidget(drl_load)
    main_butlayout.addWidget(drl_save)
    main_butlayout.addStretch(1)
    main_butlayout.addWidget(drl_export)
Yan's avatar
Yan committed
445
    main_butlayout.addWidget(drl_print)
446
    main_butlayout.addWidget(close)
Yan's avatar
Yan committed
447

448
    sub_layout.addWidget(graph_canvas, stretch=1)
Yan's avatar
Yan committed
449
    sub_layout.addLayout(tablelayout)
450

Yan's avatar
Yan committed
451
452
453
454
455
    tablelayout.addWidget(QtWidgets.QLabel("Raw ions table:"))
    tablelayout.addWidget(pt)
    tablelayout.addLayout(pt_butlayout)
    tablelayout.addWidget(QtWidgets.QLabel("Corrected ions table:"))
    tablelayout.addWidget(dt)
456

Yan's avatar
Yan committed
457
    main_window.show()