drltools.py 31.6 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
3Yan's avatar
3Yan committed
8
from copy import copy
Yan's avatar
Yan committed
9
10
import matplotlib
import numpy as np
Yan's avatar
Yan committed
11
12
import prasopes.datatools as dt
import prasopes.graphtools as gt
Yan's avatar
Yan committed
13
import prasopes.filetools as ft
3Yan's avatar
3Yan committed
14
import prasopes.config as cf
Yan's avatar
Yan committed
15
import os.path
Yan's avatar
Yan committed
16
import logging
Yan's avatar
Yan committed
17
18
matplotlib.use("Qt5Agg")

Yan's avatar
Yan committed
19

Yan's avatar
Yan committed
20
21
22
logger = logging.getLogger('drlLogger')


Yan's avatar
Yan committed
23
24
class StretchWidget(QtWidgets.QWidget):
    """horizontal stretch class"""
Yan's avatar
Yan committed
25
    def __init__(self):
Yan's avatar
Yan committed
26
        super(StretchWidget, self).__init__()
Yan's avatar
Yan committed
27
        self._main = QtWidgets.QWidget()
Yan's avatar
Yan committed
28
29
        self.setSizePolicy(QtWidgets.QSizePolicy.Expanding
                          ,QtWidgets.QSizePolicy.Preferred)
Yan's avatar
Yan committed
30
31


Yan's avatar
Yan committed
32
def floatize(table, row, column, nonneg=True):
33
34
    """grabs the tableWidgetItem and transforms its text safely to
    float, if the text is not acceptable as float, returns zero"""
Yan's avatar
Yan committed
35
    imptext = table.item(row, column).text().replace(",",".")
36
    validator = QtGui.QDoubleValidator()
Yan's avatar
Yan committed
37
38
    if nonneg == True:
        validator.setBottom(0)
39
40
41
42
43
44
45
46
    status = validator.validate(imptext, 0)[0]
    if status == QtGui.QValidator.Acceptable:
        outfloat = float(imptext)
    else:
        outfloat = 0
    return outfloat


Yan's avatar
Yan committed
47
def get_massargs(pt, row, subset):
48
49
    startm = floatize(pt, row, 1) - (floatize(pt, row, 2) / 2)
    endm = floatize(pt, row, 1) + (floatize(pt, row, 2) / 2)
Yan's avatar
Yan committed
50
    massargs = dt.argsubselect(subset['masses'], startm, endm)
51
52
53
    return massargs


54
def update_profile(pt, row, dataset):
Yan's avatar
Yan committed
55
    """parent table profile spectrum updating procedure"""
Yan's avatar
Yan committed
56
    logger.debug("updating parent table row {} profile".format(row))
Yan's avatar
Yan committed
57
58
    # Dont do anything to graph when the spectrum is not populated
    if len(dataset) == 0:
59
        return
60
    spectrum = pt.cellWidget(row, 3).figure.get_axes()[0]
Yan's avatar
Yan committed
61
    spectrum.clear()
Yan's avatar
Yan committed
62
63
64
65
66
67
68
69
70
71
72
73
74
    limits = []
    for i,subset in enumerate(dataset):
        masses = subset['masses']
        massargs = get_massargs(pt, row, subset)
        yshape = np.mean(subset['matrix'], axis=0)
        spectrum.plot(masses, yshape, ':', color='gray')
        spectrum.plot(masses[massargs], yshape[massargs], color=
                gt.colors[i % len(gt.colors)]/255)
        limits.append((masses[massargs[[0,-1]]],max(yshape[massargs])))
    widest = np.argmax([abs(lim[0][1]-lim[0][0]) for lim in limits])
    xmin, xmax = limits[widest][0]
    xex = max((xmax-xmin)*0.25,0.20)
    spectrum.set_xlim(xmin-xex, xmax+xex)
Yan's avatar
Yan committed
75
    ymax = max(*[lim[1] for lim in limits],1)
76
77
78
    spectrum.set_ylim(ymax*-0.1, ymax*1.2)
    spectrum.figure.canvas.draw()

Yan's avatar
Yan committed
79

3Yan's avatar
3Yan committed
80
def get_intensity(row, ds, drls):
Yan's avatar
Yan committed
81
    #prevent division by 0
Yan's avatar
Yan committed
82
83
84
85
    intensity = np.concatenate([np.divide(np.sum(subset['matrix'].T[
        get_massargs(drls['pt'],row,subset)].T, axis=1),
        np.clip(subset['chrom_dat'][1], np.finfo(np.float32).eps, None))
        for subset in ds])
Yan's avatar
Yan committed
86
87
88
    return intensity


3Yan's avatar
3Yan committed
89
def get_daughterset(ds, drls):
Yan's avatar
Yan committed
90
91
    """Fuction to acquire the curves of the daugher ions"""
    logger.info("getting set of the daughter ions")
Yan's avatar
Yan committed
92
    names = []
Yan's avatar
Yan committed
93
    times = np.concatenate([sub['chrom_dat'][0, :] - drls['tshift'].value() for sub in ds])
Yan's avatar
Yan committed
94
    intensities = []
3Yan's avatar
3Yan committed
95
96
97
    for row in range(drls['dt'].rowCount()):
        if drls['dt'].cellWidget(row, 0).checkState() == 2:
            intensity = get_intensity(row, ds, drls)
3Yan's avatar
3Yan committed
98
            corlist = []
Yan's avatar
Yan committed
99
            for i in range(drls['cors'].value()):
3Yan's avatar
3Yan committed
100
101
                cor = drls['dt'].cellWidget(row, 1+i*2).currentIndex() - 1
                if cor not in (-2, -1):
Yan's avatar
Yan committed
102
                    factor = floatize(drls['dt'], row, 2+i*2, False)
3Yan's avatar
3Yan committed
103
104
105
106
107
108
                    correction = get_intensity(cor, ds, drls) * factor
                    intensity = intensity - correction
                    corlist.append("{} * {}".format(
                        drls['dt'].item(row,2+i*2).text(),
                        drls['dt'].cellWidget(row,1+i*2).currentText()))
            cortext = " + ".join(corlist)
Yan's avatar
Yan committed
109
            intensities.append(intensity)
3Yan's avatar
3Yan committed
110
            names.append("{} - ({})".format(
Yan's avatar
Yan committed
111
                drls['dt'].item(row, 0).text(), cortext))
Yan's avatar
Yan committed
112
113
114
    return names, times, intensities


3Yan's avatar
3Yan committed
115
def get_parentset(ds, drls):
116
    names = []
Yan's avatar
Yan committed
117
    times = np.concatenate([sub['chrom_dat'][0, :] for sub in ds])
118
119
    intensities = []
    rowlist = []
3Yan's avatar
3Yan committed
120
121
    for row in range(drls['dt'].rowCount()):
        if drls['dt'].cellWidget(row, 0).checkState() == 2:
122
            rowlist.append(row)
3Yan's avatar
3Yan committed
123
124
125
126
127
128
            for corcol in range(drls['cors'].value()):
                if drls['dt'].cellWidget(
                        row, corcol*2 + 1).currentIndex() > 0\
                        and floatize(drls['dt'], row, 2) != 0:
                    rowlist.append(
                        drls['dt'].cellWidget(row, 1).currentIndex()-1)
129
    for row in set(rowlist):
3Yan's avatar
3Yan committed
130
            intensity = get_intensity(row, ds, drls)
131
            intensities.append(intensity)
3Yan's avatar
3Yan committed
132
            names.append(drls['dt'].item(row, 0).text())
133
134
135
    return names, times, intensities


3Yan's avatar
3Yan committed
136
def update_drlspectrum(ds, drls, drlspectrum):
Yan's avatar
Yan committed
137
138
    """Generic DRL spectrum updating procedure"""
    logger.info("updating DRL spectrum")
Yan's avatar
Yan committed
139
    # Do not do anything when the data set is not populated.
Yan's avatar
Yan committed
140
    if len(ds) == 0:
Yan's avatar
Yan committed
141
142
        return

3Yan's avatar
3Yan committed
143
    names, times, intensities = get_daughterset(ds, drls)
3Yan's avatar
3Yan committed
144
    drlspectrum.clear()
Yan's avatar
Yan committed
145
    gt.pop_plot(0, 0, drlspectrum, drls['graphlabels'])
3Yan's avatar
3Yan committed
146
    drlspectrum.axvline(0, 0, 0.9, color="#FF000088", linestyle=":")
3Yan's avatar
3Yan committed
147

3Yan's avatar
3Yan committed
148
149
150
151
    if drls['cutoff'].value() != 0:
        drlspectrum.axvline(drls['cutoff'].value(), 0, 0.9,
                            color="#0000FF88", linestyle=":")

152
    i = 0
3Yan's avatar
3Yan committed
153
154
155
156
    for row in range(drls['dt'].rowCount()):
        if drls['dt'].cellWidget(row, 0).checkState() == 2:
            drls['dt'].blockSignals(True)
            drls['dt'].item(row, 0).setBackground(QtGui.QBrush(
3Yan's avatar
3Yan committed
157
                QtGui.QColor(*gt.colors[row % len(gt.colors)], alpha=50)))
3Yan's avatar
3Yan committed
158
159
            drls['dt'].blockSignals(False)
            label = " {}".format(drls['pt'].item(row, 0).text())
3Yan's avatar
3Yan committed
160
161
            intensity = intensities[i]
            if drls['rel'].checkState() == 2:
Yan's avatar
Yan committed
162
163
                #Do not divide by 0
                intensity = np.divide(intensity, np.clip(np.sum(
Yan's avatar
Yan committed
164
165
                    intensities, 0), np.finfo(np.float32).eps, None),
                    dtype=np.float64)
3Yan's avatar
3Yan committed
166
            drlspectrum.plot(times, intensity, label=label,
3Yan's avatar
3Yan committed
167
                             color=(gt.colors[row % len(gt.colors)] / 255))
168
            i += 1
169
        else:
3Yan's avatar
3Yan committed
170
            drls['dt'].item(row, 0).setBackground(QtGui.QBrush())
171

172
    if len(names) != 0:
3Yan's avatar
3Yan committed
173
174
175
176
        gmax = np.amax(intensities)
        if drls['rel'].checkState() == 2:
            gmax = 1
        drlspectrum.set_ylim(top=gmax*1.1, bottom=gmax*-0.01)
177
        drlspectrum.legend(loc=2)
178
179
    drlspectrum.figure.canvas.draw()

Yan's avatar
Yan committed
180

Yan's avatar
Yan committed
181
def gettableitemlist(ptable):
182
    ion_list = []
Yan's avatar
Yan committed
183
184
185
    for row in range(ptable.rowCount()):
        text = []
        for i in range(3):
186
187
            if not isinstance(ptable.item(row, i), type(None)):
                frg = ptable.item(row, i).text()
Yan's avatar
Yan committed
188
189
190
            else:
                frg = ""
            text.append(frg)
191
        line = "{} ({}; fw={})".format(*text)
Yan's avatar
Yan committed
192
        ion_list.append(line)
193
194
195
    return ion_list


3Yan's avatar
3Yan committed
196
def update_corrfors(drls):
197
    """update corrections selection layout of the daughter table"""
3Yan's avatar
3Yan committed
198
199
    ionlist = gettableitemlist(drls['pt'])
    for row in range(drls['dt'].rowCount()):
Yan's avatar
Yan committed
200
        for i in range(drls['cors'].value()):
3Yan's avatar
3Yan committed
201
202
203
204
205
206
207
208
            corfor = drls['dt'].cellWidget(row, 1+i*2)
            index = corfor.currentIndex()
            corfor.blockSignals(True)
            corfor.clear()
            corfor.addItem("")
            corfor.addItems(ionlist)
            corfor.setCurrentIndex(index)
            corfor.blockSignals(False)
Yan's avatar
Yan committed
209

210

3Yan's avatar
3Yan committed
211
def ptable_changed(row, column, ds, drls, drlspectrum):
212
    """routine called by change of the ptable spectra"""
Yan's avatar
Yan committed
213
    logger.debug("ptable changed routine called")
3Yan's avatar
3Yan committed
214
215
    update_corrfors(drls)
    drls['dt'].item(row, 0).setText(gettableitemlist(drls['pt'])[row])
216
    if column in (1, 2):
3Yan's avatar
3Yan committed
217
        update_profile(drls['pt'], row, ds)
218

219

3Yan's avatar
3Yan committed
220
def dtable_changed(row, column, ds, drls, drlspectrum):
221
    """routine called by change of the dtable spectra"""
Yan's avatar
Yan committed
222
    logger.info("Change in the daughter ion table detected")
3Yan's avatar
3Yan committed
223
    if drls['dt'].cellWidget(row, 0).checkState() == 2:
Yan's avatar
Yan committed
224
225
226
        if (column == 0) or (column % 2 == 0 and drls['dt'].cellWidget(
            row, column-1).currentIndex() != 0):
            update_drlspectrum(ds, drls, drlspectrum)
227

Yan's avatar
Yan committed
228

3Yan's avatar
3Yan committed
229
def corr_changed(correction, ds, drls, drlspectrum):
230
    """routine called by change of correction for ion"""
Yan's avatar
Yan committed
231
    logger.info('''Change of the "correct to" detected''')
3Yan's avatar
3Yan committed
232
233
234
235
    for i in range(drls['dt'].rowCount()):
        for j in range(drls['dt'].columnCount()):
            if correction == drls['dt'].cellWidget(i, 1+j*2):
                row, column = i, 1 + j*2
Yan's avatar
Yan committed
236
237
238
                logger.debug('''Change of the "correct to" on '''
                             '''row {}, column {}'''.format(
                                 row + 1, column + 1))
3Yan's avatar
3Yan committed
239
    if (drls['dt'].cellWidget(row, 0).checkState() == 2
3Yan's avatar
3Yan committed
240
       and floatize(drls['dt'], row, column+1, False) != 0):
3Yan's avatar
3Yan committed
241
        update_drlspectrum(ds, drls, drlspectrum)
242
243


Yan's avatar
Yan committed
244
245
246
def corcount_changed(ds, drls, drlspectrum):
    """routine called by change of the correction factors count"""
    logger.info('''change in the correction count detected''')
3Yan's avatar
3Yan committed
247
248
    diff = int(drls['cors'].value() -
                  ((drls['dt'].columnCount() - 1) / 2))
Yan's avatar
Yan committed
249
250
251
    if diff == 0:
        return
    elif diff > 0:
3Yan's avatar
3Yan committed
252
        drls['dt'].blockSignals(True)
Yan's avatar
Yan committed
253
254
255
256
257
258
259
260
        drls['dt'].setColumnCount(1 + (drls['cors'].value() * 2))
        newcors = []
        for col in range(drls['dt'].columnCount() - (diff * 2),
                       drls['dt'].columnCount(), 2):
            for row in range(drls['dt'].rowCount()):
                    drls['dt'].setCellWidget(
                        row, col, QtWidgets.QComboBox())
                    drls['dt'].cellWidget(row, col).setFrame(False)
3Yan's avatar
3Yan committed
261
262
                    drls['dt'].cellWidget(row, col).setFocusPolicy(
                            QtCore.Qt.NoFocus)
Yan's avatar
Yan committed
263
264
265
266
267
268
269
270
271
272
273
                    drls['dt'].setItem(
                        row, col+1, QtWidgets.QTableWidgetItem())
                    newcors.append(drls['dt'].cellWidget(row, col))
        list(map(lambda x: x.currentIndexChanged.connect(lambda:
            corr_changed(x, ds, drls, drlspectrum)), newcors))
        update_corrfors(drls)
        dcolums = ["Name"]
        for i in range(drls['cors'].value()):
            dcolums.append("corrected for ({})".format(i+1))
            dcolums.append("factor ({})".format(i+1))
        drls['dt'].setHorizontalHeaderLabels(dcolums)
3Yan's avatar
3Yan committed
274
        drls['dt'].blockSignals(False)
Yan's avatar
Yan committed
275
    else:
3Yan's avatar
3Yan committed
276
        drls['dt'].blockSignals(True)
Yan's avatar
Yan committed
277
        drls['dt'].setColumnCount(1 + (drls['cors'].value() * 2))
3Yan's avatar
3Yan committed
278
        drls['dt'].blockSignals(False)
Yan's avatar
Yan committed
279
280
281
        update_drlspectrum(ds, drls, drlspectrum)


3Yan's avatar
3Yan committed
282
def remove_rows(ds, drls, drlspectrum, rows=None):
3Yan's avatar
3Yan committed
283
    logger.info("remowing rows")
284
285
    if rows == None:
        rows = reversed(list(set(
3Yan's avatar
3Yan committed
286
            map(lambda x: x.row(), drls['pt'].selectedIndexes()))))
287
    cors = []
288
    for row in rows:
3Yan's avatar
3Yan committed
289
290
291
292
        drls['dt'].cellWidget(row,0).setCheckState(0)
        drls['dt'].removeRow(row)
        drls['pt'].removeRow(row)
        for i in range(drls['dt'].rowCount()):
Yan's avatar
Yan committed
293
            for cornum in range(drls['cors'].value()):
3Yan's avatar
3Yan committed
294
                corfor = drls['dt'].cellWidget(i, 1+cornum*2)
3Yan's avatar
3Yan committed
295
                cors.append(corfor)
3Yan's avatar
3Yan committed
296
297
298
299
300
301
302
                corfor.disconnect()
                index = corfor.currentIndex()
                corfor.clear()
                corfor.addItem("")
                corfor.addItems(gettableitemlist(drls['pt']))
                if index == row+1:
                    corfor.setCurrentIndex(0)
3Yan's avatar
3Yan committed
303
                    corr_changed(corfor, ds, drls, drlspectrum)
3Yan's avatar
3Yan committed
304
305
306
307
                elif index > row+1:
                    corfor.setCurrentIndex(index-1)
                else:
                    corfor.setCurrentIndex(index)
Yan's avatar
Yan committed
308
309
        list(map(lambda x: x.currentIndexChanged.connect(lambda:
            corr_changed(x, ds, drls, drlspectrum)), cors))
310
311


3Yan's avatar
3Yan committed
312
def add_line(ds, drls, drlspectrum):
313
    """add parent ion to the table"""
Yan's avatar
Yan committed
314
    logger.debug("adding line")
3Yan's avatar
3Yan committed
315
    newrow = drls['pt'].rowCount()
316

3Yan's avatar
3Yan committed
317
318
    drls['pt'].blockSignals(True)
    drls['dt'].blockSignals(True)
319

3Yan's avatar
3Yan committed
320
    drls['pt'].setRowCount(newrow + 1)
321
    for i in range(3):
3Yan's avatar
3Yan committed
322
        drls['pt'].setItem(newrow, i, QtWidgets.QTableWidgetItem())
323
        if newrow is not 0:
3Yan's avatar
3Yan committed
324
325
326
327
            val = floatize(drls['pt'], newrow-1, i)
            if i != 2:
                val = val+1
            drls['pt'].item(newrow, i).setText(str(val))
328

329
    ion_graph = Figure(figsize=(3, 1.5), dpi=100, facecolor="None")
330
331
    ion_graph.add_subplot(111, facecolor=(1, 1, 1, 0.8),
                          position=(-0.01, -0.01, 1.02, 1.02))
332
333
334
    graph_canvas = FigureCanvas(ion_graph)
    graph_canvas.setStyleSheet("background-color:transparent;")
    graph_canvas.setAutoFillBackground(False)
3Yan's avatar
3Yan committed
335
    drls['pt'].setCellWidget(newrow, 3, graph_canvas)
336

3Yan's avatar
3Yan committed
337
    drls['dt'].setRowCount(newrow + 1)
Yan's avatar
Yan committed
338
    checkbox = QtWidgets.QCheckBox()
3Yan's avatar
3Yan committed
339
    checkbox.setFocusProxy(drls['dt'])
340
341
    dname = QtWidgets.QTableWidgetItem()
    dname.setFlags(dname.flags() & ~QtCore.Qt.ItemIsEditable)
Yan's avatar
Yan committed
342
    dname.setTextAlignment(QtCore.Qt.AlignRight)
3Yan's avatar
3Yan committed
343
344
    drls['dt'].setItem(newrow, 0, dname)
    drls['dt'].setCellWidget(newrow, 0, checkbox)
3Yan's avatar
3Yan committed
345

Yan's avatar
Yan committed
346
    for i in range(drls['cors'].value()):
3Yan's avatar
3Yan committed
347
348
        col = copy(1+i*2)
        drls['dt'].setCellWidget(newrow, col, QtWidgets.QComboBox())
3Yan's avatar
3Yan committed
349
        drls['dt'].cellWidget(newrow, col).setFocusPolicy(QtCore.Qt.NoFocus)
3Yan's avatar
3Yan committed
350
351
        drls['dt'].cellWidget(newrow, col).setFrame(False)
        drls['dt'].setItem(newrow, col+1, QtWidgets.QTableWidgetItem())
352

3Yan's avatar
3Yan committed
353
354
    drls['pt'].blockSignals(False)
    drls['dt'].blockSignals(False)
355

3Yan's avatar
3Yan committed
356
    cors = list(map(lambda x: drls['dt'].cellWidget(newrow, 1+x*2),
Yan's avatar
Yan committed
357
                    range(drls['cors'].value())))
3Yan's avatar
3Yan committed
358
359
360
    list(map(lambda x: x.currentIndexChanged.connect(lambda:
        corr_changed(x, ds, drls, drlspectrum)), cors))

3Yan's avatar
3Yan committed
361
    ptable_changed(newrow, 1, ds, drls, drlspectrum)
362
    select_all_btn_up(ds, drls, drlspectrum)
363

Yan's avatar
Yan committed
364
    checkbox.stateChanged.connect(lambda: update_drlspectrum(
3Yan's avatar
3Yan committed
365
        ds, drls, drlspectrum))
366
367
    checkbox.stateChanged.connect(lambda: select_all_btn_up(
        ds, drls, drlspectrum))
368
369


Yan's avatar
Yan committed
370
def iontable(labels):
371
372
    """creates a table for ions"""
    table = QtWidgets.QTableWidget(columnCount=len(labels))
373
    table.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
374
375
                        QtWidgets.QSizePolicy.Expanding)
    table.setHorizontalHeaderLabels(labels)
376
377
378
379
380
    table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)

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

383
    return table
384
385


3Yan's avatar
3Yan committed
386
def load_drltables(parent, dataset, drls, drlspectrum):
Yan's avatar
Yan committed
387
388
    filename = QtWidgets.QFileDialog.getOpenFileName(
            caption="Load DRL config tables",
3Yan's avatar
3Yan committed
389
390
            filter="comma-separated values (*.csv)",
            directory=cf.settings().value("open_folder"))[0]
Yan's avatar
Yan committed
391
392
    if filename is not '':
        names = []
393
394
        masses = []
        peak_widths = []
Yan's avatar
Yan committed
395
        states = []
3Yan's avatar
3Yan committed
396
        corrections = []
Yan's avatar
Yan committed
397

3Yan's avatar
3Yan committed
398

Yan's avatar
Yan committed
399
400
        with open(filename, 'r') as cfile:
            rawdata = cfile.read().splitlines()
3Yan's avatar
3Yan committed
401
402
        for i in range(len(rawdata[0].split(","))-4):
            corrections.append([])
Yan's avatar
Yan committed
403
404
        for i in range(1, len(rawdata)):
            rawline = rawdata[i].split(",")
Yan's avatar
Yan committed
405
            n = len(rawline)
3Yan's avatar
3Yan committed
406
            if n < 4 or not n % 2 == 0 or (rawline[3] not in map(
3Yan's avatar
3Yan committed
407
                str,range(3))) or not (set(map(int, rawline[4:n:2]))
3Yan's avatar
3Yan committed
408
                & set(range(-1, n)) or (n == 4)):
Yan's avatar
Yan committed
409
410
                QtWidgets.QMessageBox.warning(
                    parent, "Load DRL config tables",
3Yan's avatar
3Yan committed
411
412
413
                    "Wrong or corrupted config file.\n"
                    "Error encountered on line {}.\n"
                    "Cancelling request.".format(i+1))
Yan's avatar
Yan committed
414
                return
415
            for j, k in enumerate((names, masses, peak_widths,
3Yan's avatar
3Yan committed
416
                                   states, *corrections)):
3Yan's avatar
3Yan committed
417
418
                if len(rawline) > j:
                    k.append(rawline[j])
3Yan's avatar
3Yan committed
419
420
421
        for row in reversed(range(drls['pt'].rowCount())):
            drls['dt'].removeRow(row)
            drls['pt'].removeRow(row)
422
        # first populate only the parent table
Yan's avatar
Yan committed
423
        for i in range(len(names)):
3Yan's avatar
3Yan committed
424
425
            add_line(dataset, drls, drlspectrum)
            drls['pt'].item(i, 0).setText(names[i])
426
427
            drls['pt'].item(i, 1).setText(masses[i])
            drls['pt'].item(i, 2).setText(peak_widths[i])
428
        # and after that the daughter table
3Yan's avatar
3Yan committed
429
        drls['cors'].setValue(int((len(corrections) / 2)))
Yan's avatar
Yan committed
430
        for i in range(len(names)):
3Yan's avatar
3Yan committed
431
            for j in range(int((len(rawline)-4)/2)):
3Yan's avatar
3Yan committed
432
                drls['dt'].cellWidget(i, 1+j*2).setCurrentIndex(
3Yan's avatar
3Yan committed
433
434
                    int(corrections[0+j*2][i]))
                drls['dt'].item(i, 2+j*2).setText(corrections[1+j*2][i])
3Yan's avatar
3Yan committed
435
            drls['dt'].cellWidget(i, 0).setCheckState(int(states[i]))
Yan's avatar
Yan committed
436
437


3Yan's avatar
3Yan committed
438
def save_drlconfig(drls, parent, exp_f_name=None):
Yan's avatar
Yan committed
439
    """safe DRL table layout so it can be summoned when needed"""
440
441
442
443
    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
444
    if exp_f_name is not '':
3Yan's avatar
3Yan committed
445
        corlist = []
Yan's avatar
Yan committed
446
        for i in range(drls['cors'].value()):
3Yan's avatar
3Yan committed
447
448
449
            corlist.append("corrected_to_{}, factor_{} ".format(
                i+1, i+1))
        cortext = ", ".join(corlist)
Yan's avatar
Yan committed
450
        expf = open(exp_f_name, 'w')
451
        expf.write("#ion_name, m/z, peak_width, visible,"
3Yan's avatar
3Yan committed
452
                   "{}\n".format(cortext))
3Yan's avatar
3Yan committed
453
        for row in range(drls['pt'].rowCount()):
Yan's avatar
Yan committed
454
455
            vals = []
            for i in range(3):
3Yan's avatar
3Yan committed
456
457
                vals.append(drls['pt'].item(row, i).text())
            vals.append(drls['dt'].cellWidget(row, 0).checkState())
Yan's avatar
Yan committed
458
            for i in range(drls['cors'].value()):
3Yan's avatar
3Yan committed
459
460
                vals.append(drls['dt'].cellWidget(row, 1+i*2).currentIndex())
                vals.append(drls['dt'].item(row, 2+i*2).text())
Yan's avatar
Yan committed
461
462
463
            expf.write("{}\n".format((",".join(map(str, vals)))))
        expf.close()

Yan's avatar
Yan committed
464

3Yan's avatar
3Yan committed
465
def export_drlspectrum(parent, fn, ds, drls):
Yan's avatar
Yan committed
466
467
    if fn[0] is None:
        QtWidgets.QMessageBox.warning(
Yan's avatar
Yan committed
468
469
            None, "Export DRL dat aset",
            "No file opened. Nothing to export, canceling request")
Yan's avatar
Yan committed
470
        return
3Yan's avatar
3Yan committed
471
    names, times, intensities = get_daughterset(ds, drls)
3Yan's avatar
3Yan committed
472
473
474
475
    if drls['cutoff'].value() == 0:
        subset = np.where(times > 0)[0]
    else:
        subset = np.where((times > 0) & (times < drls['cutoff'].value()))[0]
3Yan's avatar
3Yan committed
476
    times = times[subset]
Yan's avatar
Yan committed
477
    intensities = list(map(lambda x: x[subset], intensities))
3Yan's avatar
3Yan committed
478
479

    pnames, ptimes, pintensities = get_parentset(ds, drls)
480
481
    if names == []:
        QtWidgets.QMessageBox.warning(
Yan's avatar
Yan committed
482
483
484
            None, "Export DRL data set",
            "No rows in the Corrected ions table selected. "
            "Nothing to export, canceling request")
485
486
487
488
        return
    fname = QtWidgets.QFileDialog.getSaveFileName(
            None,"Export DRL data",
        options=(QtWidgets.QFileDialog.DontConfirmOverwrite |
Yan's avatar
Yan committed
489
        QtWidgets.QFileDialog.HideNameFilterDetails),
3Yan's avatar
3Yan committed
490
        directory=fn[0][:-4])[0]
491
492
493
494
495
    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
496
497
498
499
500
501
502
503
504
505
    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
506
507
508
509
510
    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')
Yan's avatar
Yan committed
511
        expf.write("times,{}\n".format((",".join(table[0]))))
3Yan's avatar
3Yan committed
512
513
        expf.write("timeshift = {}, cutoff = {}\n".format(
            drls['tshift'].value(), drls['cutoff'].value()))
514
        for j in range(len(times)):
Yan's avatar
Yan committed
515
            dataset = list()
516
517
518
            dataset.append(times[j])
            for intensity in table[1]:
                dataset.append(intensity[j])
Yan's avatar
Yan committed
519
520
            expf.write("{}\n".format((",".join(map(str, dataset)))))
        expf.close()
3Yan's avatar
3Yan committed
521
    save_drlconfig(drls, parent, exp_f_name[2])
Yan's avatar
Yan committed
522

Yan's avatar
Yan committed
523

Yan's avatar
Yan committed
524
def print_graph(ds, drls):
Yan's avatar
Yan committed
525
    printfig = Figure(figsize=(5, 2), dpi=100)
Yan's avatar
Yan committed
526
527
    printplot = printfig.add_subplot(111)
    printcanvas = FigureCanvas(printfig)
Yan's avatar
Yan committed
528
    gt.pop_plot(0, 0, printplot, drls['graphlabels'])
3Yan's avatar
3Yan committed
529
    update_drlspectrum(ds, drls, printplot)
Yan's avatar
Yan committed
530
    widget = QtWidgets.QDialog(None, windowTitle='Print preview')
Yan's avatar
Yan committed
531
532
    layout = QtWidgets.QVBoxLayout(widget)
    layout.addWidget(printcanvas)
Yan's avatar
Yan committed
533
    widget.resize(600, 400)
Yan's avatar
Yan committed
534
535
536
537
538
539
540
    widget.show()
    dialog = QtPrintSupport.QPrintDialog()
    if dialog.exec_() == QtWidgets.QDialog.Accepted:
        printcanvas.render(dialog.printer())
    widget.close()


3Yan's avatar
3Yan committed
541
def clip_range(drls):
3Yan's avatar
3Yan committed
542
543
    """copy selected part of the table"""
    logger.debug("copying selected table cells to clipboard")
544
    activeObject = QtWidgets.QApplication.focusWidget()
3Yan's avatar
3Yan committed
545
    if activeObject in (drls['pt'], drls['dt']):
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
        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))


3Yan's avatar
3Yan committed
571
def paste_clip(ds, drls, drlspectrum):
3Yan's avatar
3Yan committed
572
    logger.debug("pasting data from clipboard")
573
    activeObject = QtWidgets.QApplication.focusWidget()
3Yan's avatar
3Yan committed
574
    if activeObject in (drls['pt'], drls['dt'])\
575
576
577
578
579
580
581
        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")
3Yan's avatar
3Yan committed
582
            return
583
584
585
586
587
588
589
        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):
3Yan's avatar
3Yan committed
590
                if table == drls['pt'] and j < 3:
591
                    if i >= (table.rowCount()):
3Yan's avatar
3Yan committed
592
                        add_line(ds, drls, drlspectrum)
593
                    table.item(i, j).setText(col)
594
                if table == drls['dt'] and j != 0 and j % 2 == 0\
595
596
597
598
                     and i < table.rowCount():
                     table.item(i,j).setText(col)


3Yan's avatar
3Yan committed
599
def key_pressed(event, ds, drls, drlspectrum):
600
    if event.key() == QtCore.Qt.Key_Delete:
601
        rows = reversed(list(map(lambda x: x.row(),
3Yan's avatar
3Yan committed
602
603
            drls['pt'].selectionModel().selectedRows())))
        remove_rows(ds, drls, drlspectrum, rows)
Yan's avatar
Yan committed
604
    if event.key() == QtCore.Qt.Key_F5:
3Yan's avatar
3Yan committed
605
606
607
        update_drlspectrum(ds, drls, drlspectrum)
        for row in range(drls['pt'].rowCount()):
            update_profile(drls['pt'], row, ds)
608
609
    if event.key() == QtCore.Qt.Key_C\
        and event.modifiers().__int__() == QtCore.Qt.ControlModifier:
3Yan's avatar
3Yan committed
610
        clip_range(drls)
611
612
    if event.key() == QtCore.Qt.Key_V\
        and event.modifiers().__int__() == QtCore.Qt.ControlModifier:
3Yan's avatar
3Yan committed
613
        paste_clip(ds, drls, drlspectrum)
614

Yan's avatar
Yan committed
615

616
617
def select_all_btn_up(ds, drls, drlspectrum, state=None):
    logger.info('''Change of the select-all button detected''')
618
619
620
621
622
623
624
625
626
627
    if state in (0,2):
        for row in range(drls['dt'].rowCount()):
            drls['dt'].cellWidget(row, 0).blockSignals(True)
            drls['dt'].cellWidget(row, 0).setCheckState(state)
            drls['dt'].cellWidget(row, 0).blockSignals(False)
        update_drlspectrum(ds, drls, drlspectrum)
    elif state == 1:
        drls['checkAll'].setCheckState(2)
    else:
        drls['checkAll'].blockSignals(True)
3Yan's avatar
3Yan committed
628
629
        btns = [drls['dt'].cellWidget(row, 0).checkState()
                for row in range(drls['dt'].rowCount())]
630
        if all(btns):
631
            drls['checkAll'].setCheckState(2)
632
633
        elif any(btns):
            drls['checkAll'].setCheckState(1)
634
635
        else:
            drls['checkAll'].setCheckState(0)
636
        drls['checkAll'].blockSignals(False)
637

638

639
def main_window(parent, ds, filename, cache, update_signal):
640
    """constructs a dialog window"""
641
    def onclose(widget, event, buffer, drls, canvas, update_fnc, update_ptrows):
3Yan's avatar
3Yan committed
642
        buffer[0], buffer[1] = drls, canvas
643
        update_signal.signal.disconnect(update_fnc)
644
        update_signal.signal.disconnect(update_ptrows)
Yan's avatar
Yan committed
645
        QtWidgets.QMainWindow.closeEvent(widget, event)
Yan's avatar
Yan committed
646

647
648
649
    def update_fnc():
        update_drlspectrum(ds, drls, chromplot)

650
651
652
653
    def update_ptrows():
        for row in range(drls['pt'].rowCount()):
            ptable_changed(row, 1, ds, drls, chromplot)

654
655
656
657
658
659
    if cache == [None, None]:
        # pt = parenttable
        # dt = daughtertable
        drls = dict(pt=None, dt=None, tshift=None, cutoff=None, cors=None,
                rel=None, checkAll=None)
        drls['tshift'] = QtWidgets.QDoubleSpinBox(
3Yan's avatar
3Yan committed
660
            minimum=-100, maximum=1440, decimals=3)
661
        drls['cutoff'] = QtWidgets.QDoubleSpinBox(
3Yan's avatar
3Yan committed
662
            minimum=0, maximum=1440, decimals=3)
663
664
665
666
        drls['rel'] = QtWidgets.QCheckBox("Steady state approximation")
        drls['checkAll'] = QtWidgets.QCheckBox("Select all")
        drls['cors'] = QtWidgets.QSpinBox(minimum=0)
        drls['cors'].setValue(3)
Yan's avatar
Yan committed
667
        drls['graphlabels'] = dict(line=None, name="", xlabel="time(min)",
668
                                   ylabel="relative intensity")
Yan's avatar
Yan committed
669

3Yan's avatar
3Yan committed
670
671
672
673
674
675
676
        dial_graph = Figure(figsize=(5, 2), dpi=100, facecolor="None")
        chromplot = dial_graph.add_subplot(111, facecolor=(1, 1, 1, 0.8))
        graph_canvas = FigureCanvas(dial_graph)
        graph_canvas.setStyleSheet("background-color:transparent;")
        graph_canvas.setAutoFillBackground(False)
        gt.pan_factory(chromplot)
        gt.zoom_factory(chromplot, 1.15)
Yan's avatar
Yan committed
677
        gt.pop_plot(0, 0, chromplot, drls['graphlabels'])
3Yan's avatar
3Yan committed
678

3Yan's avatar
3Yan committed
679
        dcolums = ["Name"]
Yan's avatar
Yan committed
680
        for i in range(drls['cors'].value()):
3Yan's avatar
3Yan committed
681
682
683
            dcolums.append("corrected for ({})".format(i+1))
            dcolums.append("factor ({})".format(i+1))
        drls['dt'] = iontable(dcolums)
684
        drls['pt'] = iontable(["Name", "Mass (m/z)", "Peak width",
3Yan's avatar
3Yan committed
685
                               "profile"])
3Yan's avatar
3Yan committed
686
        #TODO: DIRTY, DIRTY, DIRTY !!! do it nicer when I'll know how i want it
687
688
689
        [drls['dt'].horizontalHeader().setSectionResizeMode(
             n, QtWidgets.QHeaderView.Interactive) for n in range(
                    drls['dt'].columnCount())]
3Yan's avatar
3Yan committed
690
        add_line(ds, drls, chromplot)
Yan's avatar
Yan committed
691
    else:
3Yan's avatar
3Yan committed
692
693
        drls = cache[0]
        graph_canvas = cache[1]
3Yan's avatar
3Yan committed
694
        chromplot = graph_canvas.figure.axes[0]
695

696
697
698
699
700
701
    window = QtWidgets.QMainWindow(
        parent, windowTitle='Delayed reactant labeling')
    main_widget = QtWidgets.QWidget(window)
    window.setCentralWidget(main_widget)

    window.closeEvent = lambda event: onclose(
3Yan's avatar
3Yan committed
702
        window, event, cache, drls, graph_canvas, update_fnc, update_ptrows)
703
704
705
706
707
708
709
710
711
712
713
714
715
716

    time_title = QtWidgets.QLabel("Time shift (min):")
    cutoff_title = QtWidgets.QLabel("Cut off (min):")

    drl_load = QtWidgets.QPushButton("&Load")
    drl_save = QtWidgets.QPushButton("&Save")
    drl_export = QtWidgets.QPushButton("&Export")
    drl_print = QtWidgets.QPushButton("&Print")
    close = QtWidgets.QPushButton("&Close")
    close.clicked.connect(window.close)

    btn_add = QtWidgets.QPushButton("&Add")
    btn_rem = QtWidgets.QPushButton("Remove")

717
    window.keyPressEvent = lambda event: key_pressed(
3Yan's avatar
3Yan committed
718
        event, ds, drls, chromplot)
719

720
    btn_add.clicked.connect(lambda: add_line(
3Yan's avatar
3Yan committed
721
        ds, drls, chromplot))
722
    btn_rem.clicked.connect(lambda: remove_rows(
3Yan's avatar
3Yan committed
723
        ds, drls, chromplot))
Yan's avatar
Yan committed
724
    drl_load.clicked.connect(lambda: load_drltables(
3Yan's avatar
3Yan committed
725
        main_widget, ds, drls, chromplot))
Yan's avatar
Yan committed
726
    drl_save.clicked.connect(lambda: save_drlconfig(
3Yan's avatar
3Yan committed
727
        drls, main_widget))
Yan's avatar
Yan committed
728
    drl_print.clicked.connect(lambda: print_graph(ds, drls))
Yan's avatar
Yan committed
729
    drl_export.clicked.connect(lambda: export_drlspectrum(
3Yan's avatar
3Yan committed
730
731
732
733
734
735
        main_widget, filename, ds, drls))

    drls['pt'].itemChanged.connect(lambda item: ptable_changed(
        item.row(), item.column(), ds, drls, chromplot))
    drls['dt'].itemChanged.connect(lambda item: dtable_changed(
        item.row(), item.column(), ds, drls, chromplot))
736
737
    drls['tshift'].valueChanged.connect(update_fnc)
    drls['cutoff'].valueChanged.connect(update_fnc)
Yan's avatar
Yan committed
738
739
    drls['cors'].valueChanged.connect(lambda: corcount_changed(
        ds, drls, chromplot))
740
    drls['rel'].stateChanged.connect(update_fnc)
741
742
    drls['checkAll'].stateChanged.connect(lambda state:
        select_all_btn_up(ds, drls, chromplot, state))
743
    update_signal.signal.connect(update_fnc)
744
    update_signal.signal.connect(update_ptrows)
745

746
747
748
749
750
751
752
753
754
    actionBar = QtWidgets.QToolBar(window)
    window.addToolBar(QtCore.Qt.BottomToolBarArea, actionBar)
    actionBar.setAllowedAreas(QtCore.Qt.BottomToolBarArea)
    actionBar.setFloatable(False)
    actionBar.setMovable(False)
    actionBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
    actionBar.addWidget(drl_load)
    actionBar.addWidget(drl_save)
    actionBar.addWidget(drl_print)
Yan's avatar
Yan committed
755
    actionBar.addWidget(StretchWidget())
756
757
758
759
760
761
762
    actionBar.addWidget(drl_export)
    actionBar.addWidget(close)

    dtdock = QtWidgets.QDockWidget()
    dtdock.setWidget(QtWidgets.QWidget())
    dtdock_layout = QtWidgets.QVBoxLayout(dtdock.widget())
    dtdock.setWindowTitle("Corrected ions table")
Yan's avatar
Yan committed
763
764
765
766
767
768
769
    dt_butlayout = QtWidgets.QHBoxLayout()
    dt_butlayout.addWidget(drls['checkAll'])
    dt_butlayout.addWidget(StretchWidget())
    dt_butlayout.addWidget(QtWidgets.QLabel("Number of corrections:"))
    dt_butlayout.addWidget(drls['cors'])
    dt_butlayout.addWidget(StretchWidget())
    dtdock_layout.addLayout(dt_butlayout)
770
    dtdock_layout.addWidget(drls['dt'])
Yan's avatar
Yan committed
771
    window.addDockWidget(QtCore.Qt.BottomDockWidgetArea, dtdock)
772
773
774
775
776
777

    ptdock = QtWidgets.QDockWidget()
    ptdock.setWidget(QtWidgets.QWidget())
    ptdock_layout = QtWidgets.QVBoxLayout(ptdock.widget())
    ptdock.setWindowTitle("Raw ions table")
    ptdock_layout.addWidget(drls['pt'])
Yan's avatar
Yan committed
778
779
780
781
    pt_butlayout = QtWidgets.QHBoxLayout()
    pt_butlayout.addWidget(btn_add)
    pt_butlayout.addWidget(btn_rem)
    pt_butlayout.addStretch(0)
782
783
784
785
786
787
788
    ptdock_layout.addLayout(pt_butlayout)
    window.addDockWidget(QtCore.Qt.RightDockWidgetArea, ptdock)

    main_layout = QtWidgets.QVBoxLayout(main_widget)
    graphparams_layout = QtWidgets.QHBoxLayout()
    main_layout.addWidget(graph_canvas, stretch=1)
    main_layout.addLayout(graphparams_layout)
3Yan's avatar
3Yan committed
789
790
791
    graphparams_layout.addWidget(time_title)
    graphparams_layout.addWidget(drls['tshift'])
    graphparams_layout.addStretch(1)
3Yan's avatar
3Yan committed
792
793
794
    graphparams_layout.addWidget(cutoff_title)
    graphparams_layout.addWidget(drls['cutoff'])
    graphparams_layout.addStretch(1)
3Yan's avatar
3Yan committed
795
796
    graphparams_layout.addWidget(drls['rel'])
    graphparams_layout.addStretch(1)
797
798


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