drltools.py 19.8 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 PyQt5 import QtCore
from PyQt5 import QtWidgets
6
from PyQt5 import QtGui
Yan's avatar
Yan committed
7
from PyQt5 import QtPrintSupport
Yan's avatar
Yan committed
8
9
import matplotlib
import numpy as np
Yan's avatar
Yan committed
10
11
import prasopes.datatools as dt
import prasopes.graphtools as gt
Yan's avatar
Yan committed
12
import prasopes.filetools as ft
Yan's avatar
Yan committed
13
import os.path
Yan's avatar
Yan committed
14
15
matplotlib.use("Qt5Agg")

Yan's avatar
Yan committed
16

Yan's avatar
Yan committed
17
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)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def floatize(table, row, column):
    """grabs the tableWidgetItem and transforms its text safely to
    float, if the text is not acceptable as float, returns zero"""
    imptext = table.item(row, column).text()
    validator = QtGui.QDoubleValidator()
    validator.setBottom(0)
    status = validator.validate(imptext, 0)[0]
    if status == QtGui.QValidator.Acceptable:
        outfloat = float(imptext)
    else:
        outfloat = 0
    return outfloat


def update_profile(pt, row, dataset):
40
    """spectrum updating procedure"""
Yan's avatar
Yan committed
41
42
    # Dont do anything to graph when the spectrum is not populated
    if isinstance(dataset['masses'], type(None)):
43
44
        return

45
    spectrum = pt.cellWidget(row, 3).figure.get_axes()[0]
Yan's avatar
Yan committed
46
    masses = dataset['masses']
47
48
    massargs = dt.argsubselect(
        masses, floatize(pt, row, 1), floatize(pt, row, 2))
49
    yshape = np.mean(dataset['matrix'], axis=0)
Yan's avatar
Yan committed
50
    spectrum.clear()
51
52
53
    spectrum.plot(masses, yshape, ':', color='gray')
    spectrum.plot(masses[massargs], yshape[massargs], 'r')
    xex = max((masses[massargs[-1]]-masses[massargs[0]])*0.25, 0.20)
Yan's avatar
Yan committed
54
55
56
    spectrum.set_xlim(masses[massargs[0]]-xex,
                      masses[massargs[-1]]+xex)
    ymax = max(yshape[massargs])
57
58
59
    spectrum.set_ylim(ymax*-0.1, ymax*1.2)
    spectrum.figure.canvas.draw()

Yan's avatar
Yan committed
60

Yan's avatar
Yan committed
61
62
63
64
65
66
67
68
69
def get_intensity(row, ptable, dtable, ds):
    startm = floatize(ptable, row, 1)
    endm = floatize(ptable, row, 2)
    massargs = dt.argsubselect(ds['masses'], startm, endm)
    intensity = (np.sum(
        ds['matrix'].T[massargs].T, axis=1)) / ds['chrom_dat'][1]
    return intensity


Yan's avatar
Yan committed
70
def get_daughterset(ptable, dtable, ds):
Yan's avatar
Yan committed
71
    # TODO: write a less resources demanding function - probably "per-line"
Yan's avatar
Yan committed
72
    names = []
Yan's avatar
Yan committed
73
    times = ds['chrom_dat'][0, :]
Yan's avatar
Yan committed
74
    intensities = []
Yan's avatar
Yan committed
75
    # TODO: resolve intensities trouble
Yan's avatar
Yan committed
76
    for row in range(dtable.rowCount()):
Yan's avatar
Yan committed
77
        if dtable.cellWidget(row, 0).checkState() == 2:
Yan's avatar
Yan committed
78
            intensity = get_intensity(row, ptable, dtable, ds)
79
80
            cor = dtable.cellWidget(row, 1).currentIndex() - 1
            # TODO: check if cor still produce the mess or it started to behave
81
            # testing in this alpha stage
82
            if cor not in (-2, -1):
83
                factor = floatize(dtable, row, 2)
Yan's avatar
Yan committed
84
85
                correction = get_intensity(cor, ptable, dtable, ds)\
                    * factor
Yan's avatar
Yan committed
86
                intensity = intensity - correction
Yan's avatar
Yan committed
87
            intensities.append(intensity)
Yan's avatar
Yan committed
88
89
90
91
            names.append("{} - {} * {}".format(
                dtable.item(row, 0).text(),
                dtable.item(row,2).text(),
                dtable.cellWidget(row,1).currentText()))
Yan's avatar
Yan committed
92
93
94
    return names, times, intensities


95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def get_parentset(ptable, dtable, ds):
    names = []
    times = ds['chrom_dat'][0, :]
    intensities = []
    # TODO: resolve intensities trouble
    rowlist = []
    for row in range(dtable.rowCount()):
        if dtable.cellWidget(row, 0).checkState() == 2:
            rowlist.append(row)
            if dtable.cellWidget(row, 1).currentIndex() > 0\
                    and floatize(dtable, row, 2) != 0:
                rowlist.append(
                    dtable.cellWidget(row, 1).currentIndex()-1)
    for row in set(rowlist):
            intensity = get_intensity(row, ptable, dtable, ds)
            intensities.append(intensity)
            names.append(dtable.item(row, 0).text())
    return names, times, intensities


Yan's avatar
Yan committed
115
def update_drlspectrum(ptable, dtable, ds, drlspectrum):
116
    # Dont do anything when the dataset is not populated
Yan's avatar
Yan committed
117
    if isinstance(ds['masses'], type(None)):
Yan's avatar
Yan committed
118
        return
119
    colors = np.array([[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255],
120
121
122
                       [0, 200, 255], [255, 200, 0], [255, 100, 0],
                       [200, 50, 0], [255, 0, 200], [0, 100, 0],
                       [0, 100, 255], [100, 100, 100]])
Yan's avatar
Yan committed
123

124
    # TODO: write a less resources demanding function
Yan's avatar
Yan committed
125
126
127
    names, times, intensities = get_daughterset(ptable, dtable, ds)
    for i in range(len(drlspectrum.lines)):
        drlspectrum.lines[0].remove()
128

129
    i = 0
130
    for row in range(dtable.rowCount()):
Yan's avatar
Yan committed
131
        if dtable.cellWidget(row, 0).checkState() == 2:
132
            dtable.blockSignals(True)
Yan's avatar
Yan committed
133
            dtable.item(row, 0).setBackground(QtGui.QBrush(
134
                QtGui.QColor(*colors[row % len(colors)], alpha=50)))
135
136
            dtable.blockSignals(False)
            label = " {}".format(ptable.item(row, 0).text())
137
138
139
            drlspectrum.plot(times, intensities[i], label=label,
                             color=(colors[row % len(colors)] / 255))
            i += 1
140
        else:
Yan's avatar
Yan committed
141
            dtable.item(row, 0).setBackground(QtGui.QBrush())
142

143
144
145
146
    if len(names) != 0:
        drlspectrum.set_ylim(top=np.amax(intensities)*1.1,
                             bottom=np.amax(intensities)*-0.01)
        drlspectrum.legend(loc=2)
147
148
    drlspectrum.figure.canvas.draw()

Yan's avatar
Yan committed
149

Yan's avatar
Yan committed
150
def gettableitemlist(ptable):
151
    ion_list = []
Yan's avatar
Yan committed
152
153
154
    for row in range(ptable.rowCount()):
        text = []
        for i in range(3):
155
156
            if not isinstance(ptable.item(row, i), type(None)):
                frg = ptable.item(row, i).text()
Yan's avatar
Yan committed
157
158
159
160
161
            else:
                frg = ""
            text.append(frg)
        line = "{} ({}-{})".format(*text)
        ion_list.append(line)
162
163
164
    return ion_list


165
166
167
168
169
170
171
172
173
174
175
176
def update_corrfors(ptable, dtable):
    """update corrections selection layout of the daughter table"""
    ionlist = gettableitemlist(ptable)
    for row in range(dtable.rowCount()):
        corfor = dtable.cellWidget(row, 1)
        index = corfor.currentIndex()
        corfor.blockSignals(True)
        corfor.clear()
        corfor.addItem("")
        corfor.addItems(ionlist)
        corfor.setCurrentIndex(index)
        corfor.blockSignals(False)
Yan's avatar
Yan committed
177

178

3Yan's avatar
3Yan committed
179
def ptable_changed(row, column, ptable, dtable, ds, drlspectrum):
180
181
182
183
184
    """routine called by change of the ptable spectra"""
    update_corrfors(ptable, dtable)
    dtable.item(row, 0).setText(gettableitemlist(ptable)[row])
    if column in (1, 2):
        update_profile(ptable, row, ds)
185

186
187
188
189
190
191
192
def dtable_changed(row, column, ptable, dtable, ds, drlspectrum):
    """routine called by change of the dtable spectra"""
    if dtable.cellWidget(row, 0).checkState() == 2:
        if (column == 0)\
           or (column == 2
               and dtable.cellWidget(row, 1).currentIndex() != 0):
                update_drlspectrum(ptable, dtable, ds, drlspectrum)
193

Yan's avatar
Yan committed
194

195
196
197
198
199
def corr_changed(row, ptable, dtable, ds, drlspectrum):
    """routine called by change of correction for ion"""
    if (dtable.cellWidget(row, 0).checkState() == 2
       and floatize(dtable, row, 2) != 0):
        update_drlspectrum(ptable, dtable, ds, drlspectrum)
200
201


202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def delete_row(row, ptable, dtable, ds, drlspectrum):
    dtable.cellWidget(row,0).setCheckState(0)
    dtable.removeRow(row)
    ptable.removeRow(row)
    for i in range(dtable.rowCount()):
        corfor = dtable.cellWidget(i, 1)
        corfor.disconnect()
        index = corfor.currentIndex()
        corfor.clear()
        corfor.addItem("")
        corfor.addItems(gettableitemlist(ptable))
        if index == row+1:
            corfor.setCurrentIndex(0)
            corr_changed(i, ptable, dtable, ds, drlspectrum)
        elif index > row+1:
            corfor.setCurrentIndex(index-1)
        else:
            corfor.setCurrentIndex(index)
        corfor.currentIndexChanged.connect(lambda: corr_changed(
            i, ptable, dtable, ds, drlspectrum))


224
def remove_rows(ptable, dtable, ds, drlspectrum):
Yan's avatar
Yan committed
225
    # TODO: maybe nicer selection in future, but this works for now
226
    rows = reversed(list(set(
Yan's avatar
Yan committed
227
        map(lambda x: x.row(), ptable.selectedIndexes()))))
228
    for row in rows:
229
        delete_row(row, ptable, dtable, ds, drlspectrum)
230
231


Yan's avatar
Yan committed
232
def add_line(ds, parenttable, daughtertable, drlspectrum):
233
    """add parent ion to the table"""
234
235
236
237
238
239
240
241
242
243
244
245
    newrow = parenttable.rowCount()

    parenttable.blockSignals(True)
    daughtertable.blockSignals(True)

    parenttable.setRowCount(newrow + 1)
    for i in range(3):
        parenttable.setItem(newrow, i, QtWidgets.QTableWidgetItem())
        if newrow is not 0:
            parenttable.item(newrow, i).setText(str(floatize(
                    parenttable, newrow-1, i)+1))

246
    ion_graph = Figure(figsize=(3, 1.5), dpi=100, facecolor="None")
247
248
    ion_graph.add_subplot(111, facecolor=(1, 1, 1, 0.8),
                          position=(-0.01, -0.01, 1.02, 1.02))
249
250
251
252
    graph_canvas = FigureCanvas(ion_graph)
    graph_canvas.setStyleSheet("background-color:transparent;")
    graph_canvas.setAutoFillBackground(False)
    parenttable.setCellWidget(newrow, 3, graph_canvas)
253

254
    daughtertable.setRowCount(newrow + 1)
Yan's avatar
Yan committed
255
    checkbox = QtWidgets.QCheckBox()
256
257
    dname = QtWidgets.QTableWidgetItem()
    dname.setFlags(dname.flags() & ~QtCore.Qt.ItemIsEditable)
Yan's avatar
Yan committed
258
    dname.setTextAlignment(QtCore.Qt.AlignRight)
Yan's avatar
Yan committed
259
260
    daughtertable.setItem(newrow, 0, dname)
    daughtertable.setCellWidget(newrow, 0, checkbox)
261
262
263
264
265
266
267
268
    corfor = QtWidgets.QComboBox()
    corfor.setFrame(False)
    daughtertable.setCellWidget(newrow, 1, corfor)
    daughtertable.setItem(newrow, 2, QtWidgets.QTableWidgetItem())

    parenttable.blockSignals(False)
    daughtertable.blockSignals(False)

Yan's avatar
Yan committed
269
    ptable_changed(newrow, 1, parenttable, daughtertable, ds,
3Yan's avatar
3Yan committed
270
                   drlspectrum)
271

Yan's avatar
Yan committed
272
273
    checkbox.stateChanged.connect(lambda: update_drlspectrum(
        parenttable, daughtertable, ds, drlspectrum))
274
275
    corfor.currentIndexChanged.connect(lambda: corr_changed(
        newrow, parenttable, daughtertable, ds, drlspectrum))
276
277


Yan's avatar
Yan committed
278
def iontable(labels):
279
280
    """creates a table for ions"""
    table = QtWidgets.QTableWidget(columnCount=len(labels))
281
    table.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
282
283
                        QtWidgets.QSizePolicy.Expanding)
    table.setHorizontalHeaderLabels(labels)
284
285
286
287
288
    table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)

    for n in range(table.columnCount()):
        table.horizontalHeader().setSectionResizeMode(
            n, QtWidgets.QHeaderView.Stretch)
Yan's avatar
Yan committed
289
    table.setMinimumSize(600, 0)
290

291
    return table
292
293


Yan's avatar
Yan committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
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()
Yan's avatar
Yan committed
308
309
        for i in range(1, len(rawdata)):
            rawline = rawdata[i].split(",")
310
            # TODO: rawline[4] can be -1 - decide if accept this behaviour
Yan's avatar
Yan committed
311
            if len(rawline) != 6 or int(rawline[3]) not in range(3) \
312
                    or int(rawline[4]) not in range(-1,len(rawdata)):
Yan's avatar
Yan committed
313
314
315
316
317
318
                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,
Yan's avatar
Yan committed
319
                                   states, corrected_to, corr_factors)):
Yan's avatar
Yan committed
320
                k.append(rawline[j])
Yan's avatar
Yan committed
321
322
323
        for row in reversed(range(ptable.rowCount())):
            dtable.removeRow(row)
            ptable.removeRow(row)
324
        # first populate only the parent table
Yan's avatar
Yan committed
325
        for i in range(len(names)):
Yan's avatar
Yan committed
326
            add_line(dataset, ptable, dtable, drlspectrum)
327
328
329
            ptable.item(i, 0).setText(names[i])
            ptable.item(i, 1).setText(start_masses[i])
            ptable.item(i, 2).setText(end_masses[i])
330
        # and after that the daughter table
Yan's avatar
Yan committed
331
        for i in range(len(names)):
Yan's avatar
Yan committed
332
            dtable.cellWidget(i, 1).setCurrentIndex(
Yan's avatar
Yan committed
333
                int(corrected_to[i]))
334
            dtable.item(i, 2).setText(corr_factors[i])
Yan's avatar
Yan committed
335
            dtable.cellWidget(i, 0).setCheckState(int(states[i]))
Yan's avatar
Yan committed
336
337


338
def save_drlconfig(ptable, dtable, parent, exp_f_name=None):
Yan's avatar
Yan committed
339
    """safe DRL table layout so it can be summoned when needed"""
340
341
342
343
    if exp_f_name == None:
        exp_f_name = ft.get_save_filename(
            "Save DRL table layout", "comma-separated values (*.csv)",
            "csv", parent)
Yan's avatar
Yan committed
344
345
346
347
348
349
350
    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):
351
                vals.append(ptable.item(row, i).text())
Yan's avatar
Yan committed
352
353
            vals.append(dtable.cellWidget(row, 0).checkState())
            vals.append(dtable.cellWidget(row, 1).currentIndex())
354
            vals.append(dtable.item(row, 2).text())
Yan's avatar
Yan committed
355
356
357
            expf.write("{}\n".format((",".join(map(str, vals)))))
        expf.close()

Yan's avatar
Yan committed
358

Yan's avatar
Yan committed
359
360
361
def export_drlspectrum(parent, fn, ptable, dtable, ds):
    if fn[0] is None:
        QtWidgets.QMessageBox.warning(
362
            None, "Export DRL dataset",
Yan's avatar
Yan committed
363
364
365
            "Nothing to export, cancelling request")
        return
    names, times, intensities = get_daughterset(ptable, dtable, ds)
366
    pnames, ptimes, pintensities = get_parentset(ptable, dtable, ds)
367
368
369
370
371
372
373
374
375
376
377
378
379
380
    if names == []:
        QtWidgets.QMessageBox.warning(
            None, "Export DRL dataset",
            "Nothing to export, cancelling request")
        return
    fname = QtWidgets.QFileDialog.getSaveFileName(
            None,"Export DRL data",
        options=(QtWidgets.QFileDialog.DontConfirmOverwrite |
        QtWidgets.QFileDialog.HideNameFilterDetails))[0]
    if fname is '':
        return
    exp_f_name = list(map(lambda x: "{}/{}-{}.csv".format(
        fname, os.path.basename(fname), x),
        ["raw", "corrected", "input"]))
Yan's avatar
Yan committed
381
382
383
384
385
386
387
388
389
390
    for name in exp_f_name:
        if os.path.isfile(name):
            quest = QtWidgets.QMessageBox.warning(
                parent, "Export DRL data",
                "File {} already exists in the filesystem.\n"
                "Do you want to overwrite it?"
                .format(os.path.basename(name)),
                QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
            if quest == QtWidgets.QMessageBox.No:
                return
391
392
393
394
395
396
397
    if not os.path.exists(fname):
        os.makedirs(fname)
    for i, table in enumerate([[pnames, pintensities],
                               [names, intensities]]):
        expf = open(exp_f_name[i], 'w')
        expf.write("times, {}\n".format((",".join(table[0]))))
        for j in range(len(times)):
Yan's avatar
Yan committed
398
            dataset = list()
399
400
401
            dataset.append(times[j])
            for intensity in table[1]:
                dataset.append(intensity[j])
Yan's avatar
Yan committed
402
403
            expf.write("{}\n".format((",".join(map(str, dataset)))))
        expf.close()
404
    save_drlconfig(ptable, dtable, parent, exp_f_name[2])
Yan's avatar
Yan committed
405

Yan's avatar
Yan committed
406

Yan's avatar
Yan committed
407
def print_graph(labels, ptable, dtable, ds):
Yan's avatar
Yan committed
408
    printfig = Figure(figsize=(5, 2), dpi=100)
Yan's avatar
Yan committed
409
410
411
412
    printplot = printfig.add_subplot(111)
    printcanvas = FigureCanvas(printfig)
    gt.pop_plot(printplot, labels)
    update_drlspectrum(ptable, dtable, ds, printplot)
Yan's avatar
Yan committed
413
    widget = QtWidgets.QDialog(None, windowTitle='Print preview')
Yan's avatar
Yan committed
414
415
    layout = QtWidgets.QVBoxLayout(widget)
    layout.addWidget(printcanvas)
Yan's avatar
Yan committed
416
    widget.resize(600, 400)
Yan's avatar
Yan committed
417
418
419
420
421
422
423
    widget.show()
    dialog = QtPrintSupport.QPrintDialog()
    if dialog.exec_() == QtWidgets.QDialog.Accepted:
        printcanvas.render(dialog.printer())
    widget.close()


424
425
426
427
428
def key_pressed(event, ptable, dtable, ds, drlspectrum):
    if event.key() == QtCore.Qt.Key_Delete:
        for row in map(lambda x: x.row(),
                       ptable.selectionModel().selectedRows()):
            delete_row(row, ptable, dtable, ds, drlspectrum)
Yan's avatar
Yan committed
429
430
431
432
    if event.key() == QtCore.Qt.Key_F5:
        update_drlspectrum(ptable, dtable, ds, drlspectrum)
        for row in range(ptable.rowCount()):
            update_profile(ptable, row, ds)
433
434


Yan's avatar
Yan committed
435
def main_window(parent, ds, filename, cache):
436
    """constructs a dialog window"""
Yan's avatar
Yan committed
437
438
    def saveonclose(widget, event, buffer, ptable, dautable, canvas):
        buffer[0], buffer[1], buffer[2] = ptable, dautable, canvas
Yan's avatar
Yan committed
439
        QtWidgets.QMainWindow.closeEvent(widget, event)
Yan's avatar
Yan committed
440

Yan's avatar
Yan committed
441
    window = QtWidgets.QMainWindow(
Yan's avatar
Yan committed
442
        parent, windowTitle='Delayed reactant labelling')
Yan's avatar
Yan committed
443
444
    main_widget = QtWidgets.QWidget(window)
    window.setCentralWidget(main_widget)
Yan's avatar
Yan committed
445

Yan's avatar
Yan committed
446
    window.closeEvent = lambda event: saveonclose(
Yan's avatar
Yan committed
447
        window, event, cache, pt, dtable, graph_canvas)
Yan's avatar
Yan committed
448

Yan's avatar
Yan committed
449
450
    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
451
452
453
    graph_canvas = FigureCanvas(dial_graph)
    graph_canvas.setStyleSheet("background-color:transparent;")
    graph_canvas.setAutoFillBackground(False)
Yan's avatar
Yan committed
454
    graphlabels = dict(x=[0], y=[0], line=None, name="",
Yan's avatar
Yan committed
455
456
                       xlabel="time(min)",
                       ylabel="relative intensity")
Yan's avatar
Yan committed
457
458
459
460
    gt.pan_factory(chromplot)
    gt.zoom_factory(chromplot, 1.15)
    gt.pop_plot(chromplot, graphlabels)

461
462
463
    drl_load = QtWidgets.QPushButton("&Load")
    drl_save = QtWidgets.QPushButton("&Save")
    drl_export = QtWidgets.QPushButton("&Export")
Yan's avatar
Yan committed
464
    drl_print = QtWidgets.QPushButton("&Print")
465
    close = QtWidgets.QPushButton("&Close")
Yan's avatar
Yan committed
466
    close.clicked.connect(window.close)
467

Yan's avatar
Yan committed
468
469
470
    btn_add = QtWidgets.QPushButton("&Add")
    btn_rem = QtWidgets.QPushButton("Remove")

471
472
    # pt = parenttable
    # dt = daughtertable
Yan's avatar
Yan committed
473
    if cache == [None, None, None]:
Yan's avatar
Yan committed
474
        dtable = iontable(["Name", "corrected for", "factor"])
475

Yan's avatar
Yan committed
476
        pt = iontable(["Name", "start (m/z)", "end (m/z)", "profile"])
Yan's avatar
Yan committed
477
        add_line(ds, pt, dtable, chromplot)
Yan's avatar
Yan committed
478
479
    else:
        pt = cache[0]
Yan's avatar
Yan committed
480
        dtable = cache[1]
Yan's avatar
Yan committed
481
        graph_canvas = cache[2]
482

483
484
485
    window.keyPressEvent = lambda event: key_pressed(
        event, pt, dtable, ds, chromplot)

486
    btn_add.clicked.connect(lambda: add_line(
Yan's avatar
Yan committed
487
        ds, pt, dtable, chromplot))
488
489
    btn_rem.clicked.connect(lambda: remove_rows(
        pt, dtable, ds, chromplot))
Yan's avatar
Yan committed
490
    drl_load.clicked.connect(lambda: load_drltables(
Yan's avatar
Yan committed
491
        main_widget, pt, dtable, ds, chromplot))
Yan's avatar
Yan committed
492
    drl_save.clicked.connect(lambda: save_drlconfig(
Yan's avatar
Yan committed
493
        pt, dtable, main_widget))
Yan's avatar
Yan committed
494
    drl_print.clicked.connect(lambda: print_graph(
Yan's avatar
Yan committed
495
        graphlabels, pt, dtable, ds))
Yan's avatar
Yan committed
496
    drl_export.clicked.connect(lambda: export_drlspectrum(
Yan's avatar
Yan committed
497
        main_widget, filename, pt, dtable, ds))
498

499
    pt.itemChanged.connect(lambda item: ptable_changed(
Yan's avatar
Yan committed
500
        item.row(), item.column(), pt, dtable, ds, chromplot))
501
502
503
504

    dtable.itemChanged.connect(lambda item: dtable_changed(
        item.row(), item.column(), pt, dtable, ds, chromplot))

Yan's avatar
Yan committed
505
    main_layout = QtWidgets.QVBoxLayout(main_widget)
Yan's avatar
Yan committed
506
507
    sub_layout = QtWidgets.QHBoxLayout()
    tablelayout = QtWidgets.QVBoxLayout()
Yan's avatar
Yan committed
508
    pt_butlayout = QtWidgets.QHBoxLayout()
Yan's avatar
Yan committed
509
    main_butlayout = QtWidgets.QHBoxLayout()
Yan's avatar
Yan committed
510

Yan's avatar
Yan committed
511
512
513
514
    pt_butlayout.addWidget(btn_add)
    pt_butlayout.addWidget(btn_rem)
    pt_butlayout.addStretch(0)

515
516
    main_layout.addLayout(sub_layout)
    main_layout.addWidget(HBar())
Yan's avatar
Yan committed
517
    main_layout.addLayout(main_butlayout)
518

Yan's avatar
Yan committed
519
520
    main_butlayout.addWidget(drl_load)
    main_butlayout.addWidget(drl_save)
Yan's avatar
Yan committed
521
    main_butlayout.addWidget(drl_print)
Yan's avatar
Yan committed
522
523
    main_butlayout.addStretch(1)
    main_butlayout.addWidget(drl_export)
524
    main_butlayout.addWidget(close)
Yan's avatar
Yan committed
525

526
    sub_layout.addWidget(graph_canvas, stretch=1)
Yan's avatar
Yan committed
527
    sub_layout.addLayout(tablelayout)
528

Yan's avatar
Yan committed
529
530
531
532
    tablelayout.addWidget(QtWidgets.QLabel("Raw ions table:"))
    tablelayout.addWidget(pt)
    tablelayout.addLayout(pt_butlayout)
    tablelayout.addWidget(QtWidgets.QLabel("Corrected ions table:"))
Yan's avatar
Yan committed
533
    tablelayout.addWidget(dtable)
534

Yan's avatar
Yan committed
535
    window.show()