zcetools.py 7.33 KB
Newer Older
1
2
from matplotlib.backends.backend_qt5agg import\
        FigureCanvasQTAgg as FigureCanvas
Yan's avatar
Yan committed
3
4
from matplotlib.figure import Figure
from PyQt5 import QtCore
3Yan's avatar
3Yan committed
5
from PyQt5 import QtGui
Yan's avatar
Yan committed
6
from PyQt5 import QtWidgets
Yan's avatar
Yan committed
7
from PyQt5 import QtPrintSupport
3Yan's avatar
3Yan committed
8
from prasopes.zcetools_help import helpstr
3Yan's avatar
3Yan committed
9
from io import BytesIO
Yan's avatar
Yan committed
10
11
12
import numpy as np
import prasopes.graphtools as gt
import prasopes.filetools as ft
13
import prasopes.imagetools as imgt
Yan's avatar
Yan committed
14
import os.path
15
16
17
18
import logging


logger = logging.getLogger('zceLogger')
Yan's avatar
Yan committed
19
20


Yan's avatar
Yan committed
21
def pop_dial(zcespec, gradspect, data_set, coff_d, grad_d,
Yan's avatar
Yan committed
22
             textfield, parent):
23
    logger.debug("populating ZCE dialog")
Yan's avatar
Yan committed
24
    if data_set is None:
Yan's avatar
Yan committed
25
26
        QtWidgets.QMessageBox.warning(
            parent, "ZCE calculation",
Yan's avatar
Yan committed
27
            "No spectrum opened, nothing to display")
Yan's avatar
Yan committed
28
29
30
31
        return
    zcespec.clear()
    gradspect.clear()

Yan's avatar
Yan committed
32
33
    masses, coff_y = data_set.get_spectra()[0]
    coff_x = masses - 196
3Yan's avatar
3Yan committed
34
35
36
    grad_x = coff_x
    halfl = int(len(grad_x)/2)
    grad_y = -np.gradient(coff_y)\
37
38
        if np.sum(coff_y[:halfl]) > np.sum(coff_y[halfl:])\
        else np.gradient(coff_y)
Yan's avatar
Yan committed
39
40
    gradspect.axhline(0, color="#FF000088", linestyle=":")
    zcespec.axhline(0, color="#0000FF88", linestyle=":")
3Yan's avatar
3Yan committed
41
42
    gt.pop_plot(coff_x, coff_y, zcespec, coff_d)
    gt.pop_plot(grad_x, grad_y, gradspect, grad_d)
Yan's avatar
Yan committed
43
    gradspect.lines[-1].set_color("red")
Yan's avatar
Yan committed
44
45
46
    gradspect.set_ylim(bottom=gradspect.get_ylim()[1] * -0.1)
    zcespec.set_title("COFF", loc="center")

3Yan's avatar
3Yan committed
47
48
49
50
    maxarg = np.argmax(grad_y)
    grad_d['gmax'] = coff_x[maxarg]
    halfmax = np.max(grad_y) / 2
    peakargs = np.where(grad_y > halfmax)[0]
Yan's avatar
Yan committed
51
52
    start = [peakargs[0]-1, peakargs[0]]
    end = [peakargs[-1]+1, peakargs[-1]]
Yan's avatar
Yan committed
53
54
    grad_d['fwhm_y'] = [halfmax, halfmax]
    grad_d['fwhm_x'] = [
3Yan's avatar
3Yan committed
55
56
        np.interp(halfmax, grad_y[start], grad_x[start]),
        np.interp(halfmax, grad_y[end], grad_x[end])]
Yan's avatar
Yan committed
57
58
59
60
61
62
63
64
65
66
    grad_d['fwhm'] = grad_d['fwhm_x'][1] - grad_d['fwhm_x'][0]

    gradspect.plot(grad_d['fwhm_x'], grad_d['fwhm_y'], "#880088")
    textfield.setText(
        "ZCE = {:.2f}\nFWHM = {:.2f}\nCenter(HM) = {:.2f}".format(
            grad_d['gmax'], grad_d['fwhm'],
            np.mean(grad_d['fwhm_x'])))
    gradspect.annotate(' FWHM = {:.2f}'.format(grad_d['fwhm']),
                       xy=(grad_d['fwhm_x'][1], grad_d['fwhm_y'][1]))
    gradspect.annotate('{:.2f}'.format(grad_d['gmax']),
3Yan's avatar
3Yan committed
67
                       xy=(grad_x[maxarg], grad_y[maxarg]))
Yan's avatar
Yan committed
68
69
70
    zcespec.figure.canvas.draw()


Yan's avatar
Yan committed
71
def exp_zce(zce_spec, zcegrad_spec, data_set, parent):
Yan's avatar
Yan committed
72
    """export the ZCE graph into the .dat file format"""
Yan's avatar
Yan committed
73
    if data_set is None:
Yan's avatar
Yan committed
74
75
76
77
        QtWidgets.QMessageBox.warning(
            parent, "Export ZCE spectrum",
            "Nothing to export, cancelling request")
        return
Yan's avatar
Yan committed
78
79
    exp_f_name = ft.get_save_filename(
        "Export ZCE spectrum", "dat table (*.dat)", "dat", parent)
80
    if exp_f_name != '':
Yan's avatar
Yan committed
81
82
83
84
        expf = open(exp_f_name, 'w')
        expf.write("mass ion_count ion_count_gradient fwhm_x fwhm_y\n"
                   "m/z\n"
                   "{} zce={} fwhm={} hmcenter={}\n".format(
Yan's avatar
Yan committed
85
86
                       os.path.basename(data_set.filename),
                       zcegrad_spec['gmax'], zcegrad_spec['fwhm'],
Yan's avatar
Yan committed
87
88
89
90
91
92
93
94
95
96
97
98
                       np.mean(zcegrad_spec['fwhm_x'])))
        for i in range(len(zce_spec['x'])):
            fwhm = ["", ""]
            if i <= 1:
                fwhm = [zcegrad_spec['fwhm_x'][i],
                        zcegrad_spec['fwhm_y'][i]]
            expf.write("{} {} {} {} {}\n".format(
                zce_spec['x'][i], zce_spec['y'][i], zcegrad_spec['y'][i],
                fwhm[0], fwhm[1]))
        expf.close()


99
def help_msg(pw):
3Yan's avatar
3Yan committed
100
101
    QtWidgets.QMessageBox.information(
            pw, "TSQ zce tool help", "{}".format(helpstr))
102
103


Yan's avatar
Yan committed
104
def paint_override(self, ds, coff, coffgrad):
Yan's avatar
Yan committed
105
    overlay = self.plot.twinx()
Yan's avatar
Yan committed
106
    textfield = QtWidgets.QLabel()
Yan's avatar
Yan committed
107
    pop_dial(self.plot, overlay, ds, coff, coffgrad, textfield, None)
3Yan's avatar
3Yan committed
108
109


Yan's avatar
Yan committed
110
def print_graph(ds, coff, coffgrad):
3Yan's avatar
3Yan committed
111
112
113
    def printimage(printdevice, img):
        printer.setResolution(600)
        painter = QtGui.QPainter(printdevice)
114
        painter.drawImage(0, 0, img)
3Yan's avatar
3Yan committed
115
        painter.end()
116
    # TODO: substitute the QPrintPreviewDialog with QPrintPreviewWidget
3Yan's avatar
3Yan committed
117
118
119
120
    printPreview = QtPrintSupport.QPrintPreviewDialog()
    printer = printPreview.printer()
    printer.setPageSize(printer.A5)
    printer.setDuplex(printer.DuplexNone)
Yan's avatar
Yan committed
121
    imggen = imgt.ImagePainter("msspec", printer)
Yan's avatar
Yan committed
122
    imggen.popfig = lambda: paint_override(imggen, ds, coff, coffgrad)
Yan's avatar
Yan committed
123
124
    image = imggen.paint()
    printPreview.paintRequested.connect(lambda: printimage(printer, image))
3Yan's avatar
3Yan committed
125
126
127
    printPreview.exec()


Yan's avatar
Yan committed
128
def key_pressed(event, ds, coff, coffgrad):
3Yan's avatar
3Yan committed
129
130
131
    print("trigged")
    if event.key() == QtCore.Qt.Key_C:
        if event.modifiers().__int__() == QtCore.Qt.ControlModifier:
Yan's avatar
Yan committed
132
            painter = imgt.ImagePainter("zcespec")
Yan's avatar
Yan committed
133
            painter.popfig = lambda: paint_override(painter, ds, coff, coffgrad)
Yan's avatar
Yan committed
134
            painter.clip()
Yan's avatar
Yan committed
135
136


137
def dialog(parent, augCanvas, update_signal):
3Yan's avatar
3Yan committed
138
139
140
141
    coff = dict(name="", xlabel="Voltage (V)", ylabel="ion count")
    coffgrad = dict(c_ymin=-0.1, name="", xlabel="",
                    ylabel="ion count gradient", gmax=None, fwhm_x=None,
                    fwhm_y=None, fwhm=None)
Yan's avatar
Yan committed
142

143
144
145
146
147
148
    def onclose(widget, event, update_fnc):
        logger.debug("ZCE window custom close routine called")
        update_signal.signal.disconnect(update_fnc)
        QtWidgets.QDialog.closeEvent(widget, event)

    def update_fnc():
149
        pop_dial(coffspect, coffspect_grad, augCanvas.ds, coff, coffgrad,
Yan's avatar
Yan committed
150
                 textfield, parent)
151

Yan's avatar
Yan committed
152
153
    dial_widget = QtWidgets.QDialog(
            parent, windowTitle='TSQ zero collision energy calculator')
154
155
156
    dial_widget.closeEvent = lambda event: onclose(
        dial_widget, event, update_fnc)
    update_signal.signal.connect(update_fnc)
Yan's avatar
Yan committed
157

Yan's avatar
Yan committed
158
    dial_graph = Figure(figsize=(5, 2), dpi=100, facecolor="None")
Yan's avatar
Yan committed
159
160
161
162
163
164
165
166
167
168
169
    coffspect = dial_graph.add_subplot(111, facecolor=(1, 1, 1, 0.8))
    coffspect_grad = coffspect.twinx()
    graph_canvas = FigureCanvas(dial_graph)
    graph_canvas.setStyleSheet("background-color:transparent;")
    graph_canvas.setAutoFillBackground(False)

    gt.zoom_factory(coffspect_grad, 1.15, coffgrad)
    gt.pan_factory(coffspect_grad, coffgrad)

    zce_export = QtWidgets.QPushButton("Export ZCE")
    zce_export.clicked.connect(lambda: exp_zce(
Yan's avatar
Yan committed
170
        coff, coffgrad, augCanvas.ds, parent))
Yan's avatar
Yan committed
171
172
    zce_print = QtWidgets.QPushButton("Print ZCE")
    zce_print.clicked.connect(lambda: print_graph(
Yan's avatar
Yan committed
173
        augCanvas.ds, coff, coffgrad))
Yan's avatar
Yan committed
174
    zce_help = QtWidgets.QPushButton("Help")
175
    zce_help.clicked.connect(lambda: help_msg(parent))
Yan's avatar
Yan committed
176
177
178
    close_button = QtWidgets.QPushButton("Close")
    close_button.clicked.connect(dial_widget.close)

3Yan's avatar
3Yan committed
179
    dial_widget.keyPressEvent = lambda event: key_pressed(
Yan's avatar
Yan committed
180
            event, augCanvas.ds, coff, coffgrad)
3Yan's avatar
3Yan committed
181

Yan's avatar
Yan committed
182
183
184
185
186
187
    butt_layout = QtWidgets.QHBoxLayout()
    butt_layout.addWidget(zce_help)
    butt_layout.addStretch(1)
    textfield = QtWidgets.QLabel(coffgrad['gmax'])
    butt_layout.addWidget(textfield)
    butt_layout.addStretch(1)
Yan's avatar
Yan committed
188
    butt_layout.addWidget(zce_print)
Yan's avatar
Yan committed
189
190
191
192
193
194
    butt_layout.addWidget(zce_export)
    butt_layout.addWidget(close_button)

    dial_layout = QtWidgets.QVBoxLayout(dial_widget)
    dial_layout.addWidget(graph_canvas)
    dial_layout.addLayout(butt_layout)
3Yan's avatar
3Yan committed
195
    dial_widget.setFocus()
Yan's avatar
Yan committed
196
    dial_widget.show()
197
    pop_dial(coffspect, coffspect_grad, augCanvas.ds, coff, coffgrad,
Yan's avatar
Yan committed
198
             textfield, parent)