drltools.py 22.5 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
def get_intensity(row, ptable, dtable, ds):
    startm = floatize(ptable, row, 1)
    endm = floatize(ptable, row, 2)
    massargs = dt.argsubselect(ds['masses'], startm, endm)
65
    nonzero_tic = list(map(lambda x: max(x, 1), ds['chrom_dat'][1]))
Yan's avatar
Yan committed
66
    intensity = (np.sum(
67
        ds['matrix'].T[massargs].T, axis=1)) / nonzero_tic
Yan's avatar
Yan committed
68
69
70
    return intensity


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


94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
114
def update_drlspectrum(ptable, dtable, ds, drlspectrum):
115
    # Dont do anything when the dataset is not populated
Yan's avatar
Yan committed
116
    if isinstance(ds['masses'], type(None)):
Yan's avatar
Yan committed
117
        return
118
    colors = np.array([[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255],
119
120
121
                       [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
122

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

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

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

Yan's avatar
Yan committed
148

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


164
165
166
167
168
169
170
171
172
173
174
175
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
176

177

3Yan's avatar
3Yan committed
178
def ptable_changed(row, column, ptable, dtable, ds, drlspectrum):
179
180
181
182
183
    """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)
184

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
def remove_rows(ptable, dtable, ds, drlspectrum, rows=None):
Yan's avatar
Yan committed
203
    # TODO: maybe nicer selection in future, but this works for now
204
205
206
    if rows == None:
        rows = reversed(list(set(
            map(lambda x: x.row(), ptable.selectedIndexes()))))
207
    for row in rows:
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
        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))
227
228


Yan's avatar
Yan committed
229
def add_line(ds, parenttable, daughtertable, drlspectrum):
230
    """add parent ion to the table"""
231
232
233
234
235
236
237
238
239
240
241
242
    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))

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

251
    daughtertable.setRowCount(newrow + 1)
Yan's avatar
Yan committed
252
    checkbox = QtWidgets.QCheckBox()
253
    checkbox.setFocusProxy(daughtertable)
254
255
    dname = QtWidgets.QTableWidgetItem()
    dname.setFlags(dname.flags() & ~QtCore.Qt.ItemIsEditable)
Yan's avatar
Yan committed
256
    dname.setTextAlignment(QtCore.Qt.AlignRight)
Yan's avatar
Yan committed
257
258
    daughtertable.setItem(newrow, 0, dname)
    daughtertable.setCellWidget(newrow, 0, checkbox)
259
    corfor = QtWidgets.QComboBox()
260
    corfor.setFocusProxy(daughtertable)
261
262
263
264
265
266
267
    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
268
    ptable_changed(newrow, 1, parenttable, daughtertable, ds,
3Yan's avatar
3Yan committed
269
                   drlspectrum)
270

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


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

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

290
    return table
291
292


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


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

Yan's avatar
Yan committed
357

Yan's avatar
Yan committed
358
359
360
def export_drlspectrum(parent, fn, ptable, dtable, ds):
    if fn[0] is None:
        QtWidgets.QMessageBox.warning(
361
            None, "Export DRL dataset",
Yan's avatar
Yan committed
362
363
364
            "Nothing to export, cancelling request")
        return
    names, times, intensities = get_daughterset(ptable, dtable, ds)
365
    pnames, ptimes, pintensities = get_parentset(ptable, dtable, ds)
366
367
368
369
370
371
372
373
374
375
376
377
378
379
    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
380
381
382
383
384
385
386
387
388
389
    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
390
391
392
393
394
395
396
    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
397
            dataset = list()
398
399
400
            dataset.append(times[j])
            for intensity in table[1]:
                dataset.append(intensity[j])
Yan's avatar
Yan committed
401
402
            expf.write("{}\n".format((",".join(map(str, dataset)))))
        expf.close()
403
    save_drlconfig(ptable, dtable, parent, exp_f_name[2])
Yan's avatar
Yan committed
404

Yan's avatar
Yan committed
405

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


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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
def clip_range(ptable, dtable):
    activeObject = QtWidgets.QApplication.focusWidget()
    if activeObject in (ptable, dtable):
        table = activeObject
        if len(table.selectedRanges()) == 0:
            return
        if len(table.selectedRanges()) > 1:
            QtWidgets.QMessageBox.warning(
                None, "Operation not supported",
                "Operation not supported for multiple ranges,\n"
                "cancelling request")
            return
        sr = table.selectedRanges()[0]
        rows = []
        for row in range(sr.topRow(), sr.bottomRow() + 1):
            line = []
            for col in range(sr.leftColumn(), sr.rightColumn() + 1):
                if isinstance(table.cellWidget(row, col),
                            QtWidgets.QComboBox):
                    line.append(
                        table.cellWidget(row, col).currentText())
                elif isinstance(table.item(row, col),
                              QtWidgets.QTableWidgetItem):
                    line.append(table.item(row, col).text())
            rows.append(("\t").join(line))
        QtWidgets.QApplication.clipboard().setText(("\n").join(rows))


def paste_clip(ptable, dtable, ds, drlspectrum):
    activeObject = QtWidgets.QApplication.focusWidget()
    if activeObject in (ptable, dtable)\
        and activeObject.selectedRanges() != []:
        table = activeObject
        if len(table.selectedRanges()) > 1:
            QtWidgets.QMessageBox.warning(
                None, "Operation not supported",
                "Operation not supported for multiple ranges,\n"
                "cancelling request")
        cliptext = QtWidgets.QApplication.clipboard().text()
        rows = cliptext.split("\n")
        startrow = table.selectedRanges()[0].topRow()
        startcol = table.selectedRanges()[0].leftColumn()
        for i, row in enumerate(rows, start=startrow):
            cols = row.split("\t")
            for j, col in enumerate(cols, start=startcol):
                if table == ptable and j < 3:
                    if i >= (table.rowCount()):
                        add_line(ds, ptable, dtable, drlspectrum)
                    table.item(i, j).setText(col)
                if table == dtable and j == 2\
                     and i < table.rowCount():
                     table.item(i,j).setText(col)


477
478
def key_pressed(event, ptable, dtable, ds, drlspectrum):
    if event.key() == QtCore.Qt.Key_Delete:
479
480
481
        rows = reversed(list(map(lambda x: x.row(),
            ptable.selectionModel().selectedRows())))
        remove_rows(ptable, dtable, ds, drlspectrum, rows)
Yan's avatar
Yan committed
482
483
484
485
    if event.key() == QtCore.Qt.Key_F5:
        update_drlspectrum(ptable, dtable, ds, drlspectrum)
        for row in range(ptable.rowCount()):
            update_profile(ptable, row, ds)
486
487
488
489
490
491
    if event.key() == QtCore.Qt.Key_C\
        and event.modifiers().__int__() == QtCore.Qt.ControlModifier:
        clip_range(ptable, dtable)
    if event.key() == QtCore.Qt.Key_V\
        and event.modifiers().__int__() == QtCore.Qt.ControlModifier:
        paste_clip(ptable, dtable, ds, drlspectrum)
492
493


Yan's avatar
Yan committed
494
def main_window(parent, ds, filename, cache):
495
    """constructs a dialog window"""
Yan's avatar
Yan committed
496
497
    def saveonclose(widget, event, buffer, ptable, dautable, canvas):
        buffer[0], buffer[1], buffer[2] = ptable, dautable, canvas
Yan's avatar
Yan committed
498
        QtWidgets.QMainWindow.closeEvent(widget, event)
Yan's avatar
Yan committed
499

Yan's avatar
Yan committed
500
    window = QtWidgets.QMainWindow(
Yan's avatar
Yan committed
501
        parent, windowTitle='Delayed reactant labelling')
Yan's avatar
Yan committed
502
503
    main_widget = QtWidgets.QWidget(window)
    window.setCentralWidget(main_widget)
Yan's avatar
Yan committed
504

Yan's avatar
Yan committed
505
    window.closeEvent = lambda event: saveonclose(
Yan's avatar
Yan committed
506
        window, event, cache, pt, dtable, graph_canvas)
Yan's avatar
Yan committed
507

Yan's avatar
Yan committed
508
509
    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
510
511
512
    graph_canvas = FigureCanvas(dial_graph)
    graph_canvas.setStyleSheet("background-color:transparent;")
    graph_canvas.setAutoFillBackground(False)
Yan's avatar
Yan committed
513
    graphlabels = dict(x=[0], y=[0], line=None, name="",
Yan's avatar
Yan committed
514
515
                       xlabel="time(min)",
                       ylabel="relative intensity")
Yan's avatar
Yan committed
516
517
518
519
    gt.pan_factory(chromplot)
    gt.zoom_factory(chromplot, 1.15)
    gt.pop_plot(chromplot, graphlabels)

520
521
522
    drl_load = QtWidgets.QPushButton("&Load")
    drl_save = QtWidgets.QPushButton("&Save")
    drl_export = QtWidgets.QPushButton("&Export")
Yan's avatar
Yan committed
523
    drl_print = QtWidgets.QPushButton("&Print")
524
    close = QtWidgets.QPushButton("&Close")
Yan's avatar
Yan committed
525
    close.clicked.connect(window.close)
526

Yan's avatar
Yan committed
527
528
529
    btn_add = QtWidgets.QPushButton("&Add")
    btn_rem = QtWidgets.QPushButton("Remove")

530
531
    # pt = parenttable
    # dt = daughtertable
Yan's avatar
Yan committed
532
    if cache == [None, None, None]:
Yan's avatar
Yan committed
533
        dtable = iontable(["Name", "corrected for", "factor"])
534

Yan's avatar
Yan committed
535
        pt = iontable(["Name", "start (m/z)", "end (m/z)", "profile"])
Yan's avatar
Yan committed
536
        add_line(ds, pt, dtable, chromplot)
Yan's avatar
Yan committed
537
538
    else:
        pt = cache[0]
Yan's avatar
Yan committed
539
        dtable = cache[1]
Yan's avatar
Yan committed
540
        graph_canvas = cache[2]
541

542
543
544
    window.keyPressEvent = lambda event: key_pressed(
        event, pt, dtable, ds, chromplot)

545
    btn_add.clicked.connect(lambda: add_line(
Yan's avatar
Yan committed
546
        ds, pt, dtable, chromplot))
547
548
    btn_rem.clicked.connect(lambda: remove_rows(
        pt, dtable, ds, chromplot))
Yan's avatar
Yan committed
549
    drl_load.clicked.connect(lambda: load_drltables(
Yan's avatar
Yan committed
550
        main_widget, pt, dtable, ds, chromplot))
Yan's avatar
Yan committed
551
    drl_save.clicked.connect(lambda: save_drlconfig(
Yan's avatar
Yan committed
552
        pt, dtable, main_widget))
Yan's avatar
Yan committed
553
    drl_print.clicked.connect(lambda: print_graph(
Yan's avatar
Yan committed
554
        graphlabels, pt, dtable, ds))
Yan's avatar
Yan committed
555
    drl_export.clicked.connect(lambda: export_drlspectrum(
Yan's avatar
Yan committed
556
        main_widget, filename, pt, dtable, ds))
557

558
    pt.itemChanged.connect(lambda item: ptable_changed(
Yan's avatar
Yan committed
559
        item.row(), item.column(), pt, dtable, ds, chromplot))
560
561
562
563

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

Yan's avatar
Yan committed
564
    main_layout = QtWidgets.QVBoxLayout(main_widget)
Yan's avatar
Yan committed
565
566
    sub_layout = QtWidgets.QHBoxLayout()
    tablelayout = QtWidgets.QVBoxLayout()
Yan's avatar
Yan committed
567
    pt_butlayout = QtWidgets.QHBoxLayout()
Yan's avatar
Yan committed
568
    main_butlayout = QtWidgets.QHBoxLayout()
Yan's avatar
Yan committed
569

Yan's avatar
Yan committed
570
571
572
573
    pt_butlayout.addWidget(btn_add)
    pt_butlayout.addWidget(btn_rem)
    pt_butlayout.addStretch(0)

574
575
    main_layout.addLayout(sub_layout)
    main_layout.addWidget(HBar())
Yan's avatar
Yan committed
576
    main_layout.addLayout(main_butlayout)
577

Yan's avatar
Yan committed
578
579
    main_butlayout.addWidget(drl_load)
    main_butlayout.addWidget(drl_save)
Yan's avatar
Yan committed
580
    main_butlayout.addWidget(drl_print)
Yan's avatar
Yan committed
581
582
    main_butlayout.addStretch(1)
    main_butlayout.addWidget(drl_export)
583
    main_butlayout.addWidget(close)
Yan's avatar
Yan committed
584

585
    sub_layout.addWidget(graph_canvas, stretch=1)
Yan's avatar
Yan committed
586
    sub_layout.addLayout(tablelayout)
587

Yan's avatar
Yan committed
588
589
590
591
    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
592
    tablelayout.addWidget(dtable)
593

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