prasopes.py 7.52 KB
Newer Older
Yan's avatar
Yan committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env python3

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.widgets import SpanSelector
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from rawFin import load_raw
from scipy.signal import find_peaks
import sys
import matplotlib
import numpy as np
import logging
matplotlib.use("Qt5Agg")


def zoom_factory(ax, base_scale, das=None):
    def zoom_fun(event, das):
        if event.inaxes == ax:
            # get the current x and y limits
            cur_xlim = ax.get_xlim()
            # cur_ylim = ax.get_ylim()
            # set the range
            # cur_xrange = (cur_xlim[1] - cur_xlim[0])*.5
            # cur_yrange = (cur_ylim[1] - cur_ylim[0])*.5
            xdata = event.xdata  # get event x location
            # ydata = event.ydata  # get event y location
            #  generate better understanding of our position
            x_left = xdata - cur_xlim[0]
            x_right = cur_xlim[1] - xdata
            # y_top = ydata - cur_ylim[0]
            # y_bottom = cur_ylim[1] - ydata
            if event.button == 'up':
                # deal with zoom in
                scale_factor = 1/base_scale
            elif event.button == 'down':
                # deal with zoom out
                scale_factor = base_scale
            else:
                # deal with something that should never happen
                scale_factor = 1
                print(event.button)
            # set new limits
            ax.set_xlim([xdata - x_left*scale_factor,
                        xdata + x_right*scale_factor])
            # ax.set_ylim([ydata - y_top*scale_factor,
            #             ydata + y_bottom*scale_factor])
            ax.figure.canvas.draw()  # force re-draw
            if das != None:
                print("TODO_NOT READY YET")

    fig = ax.get_figure()  # get the figure of interest
    # attach the call back
    fig.canvas.mpl_connect('scroll_event', lambda event: zoom_fun(event, das))

    # return the function
    return zoom_fun


def pan_factory(ax,ds):
    def pan_fun(event):
        if event.button == 1 and event.inaxes == ax:
            ax.start_pan(event.x, event.y, event.button)
            id_drag = fig.canvas.mpl_connect('motion_notify_event', drag_fun)
            id_release = fig.canvas.mpl_connect('button_release_event',
                                                lambda action: drag_end(action, id_drag, id_release))

    def drag_fun(event):
        ax.drag_pan(1, 'x', event.x, event.y)
        ax.figure.canvas.draw()

    def drag_end(event, id_drag, id_release):
        if event.button == 1:
            fig.canvas.mpl_disconnect(id_drag)
            fig.canvas.mpl_disconnect(id_release)
    fig = ax.get_figure()
    fig.canvas.mpl_connect('button_press_event', pan_fun)


def picktimes(xmin, xmax, mplspectrum, dataset, mplchromatogram, an):
    start_scan = 0
    end_scan = -1
    for i, j in enumerate(dataset['chromdat'][0, :]):
        if j > xmin and start_scan == 0:
            start_scan = i
        if j > xmax and end_scan == -1:
            end_scan = i
    mplspectrum.clear()
    spectrPlot(spectrum, dataset['masses'], np.mean(dataset['matrix'][start_scan:end_scan], axis=0), an)
    mplchromatogram.clear()
    chromPlot(mplchromatogram, dataset['chromdat'][0, :], dataset['chromdat'][1, :])
    mplchromatogram.plot(dataset['chromdat'][0, start_scan:end_scan], dataset['chromdat'][1, start_scan:end_scan], 'b.')

def populate(mplchromatogram, mplspectrum, dataset, timeSel,an):
    def updateSpanSelector(chromatogram, spectrum, dataset):
        timeselec = SpanSelector(chromatogram, lambda xmin, xmax: picktimes(xmin, xmax, spectrum, dataset, chromatogram, an), 'horizontal', useblit=True, rectprops=dict(alpha=0.15, facecolor='purple'),button=3)
        return timeselec
    mplspectrum.clear()
    mplchromatogram.clear()
    spectrPlot(mplspectrum,dataset['masses'], np.mean(dataset['matrix'], axis=0),an)
    chromPlot(mplchromatogram, dataset['chromdat'][0,:],dataset['chromdat'][1,:])
    timeSel[0] = updateSpanSelector(mplchromatogram, mplspectrum, ds)
    mplchromatogram.figure.canvas.draw()
    mplspectrum.figure.canvas.draw()

def annSpectr(spectrum,mass,intensity,an):
    def sub_peaks(peakz,mass,intensity,x,y):
        gp=[]
        sp=[]
        for g in peakz[0]:
            if gp == [] or (abs(max(intensity[gp]) - intensity[g])*10 < y and abs(mass[gp[np.argmax(intensity[gp])]] - mass[g])*20 < x ):
                gp.append(g)
            else:
                sp.append(gp[np.argmax(intensity[gp])])
                gp = [g]
            if g == peakz[0][-1]:
                sp.append(gp[np.argmax(intensity[gp])])
        return sp
    peaks = find_peaks(intensity, height=spectrum.get_ylim()[1]/100)
    sp = sub_peaks(peaks,mass,intensity,spectrum.get_xlim()[1]-spectrum.get_xlim()[0],spectrum.get_ylim()[1]-spectrum.get_ylim()[0])

    an = []
    for i in sp:
        an.append(spectrum.annotate('{0:.2f}'.format(mass[i]), xy=(mass[i],intensity[i]),textcoords='data'))



def spectrPlot(spetrum,mass,intensity, an):
    spectrum.plot(mass,intensity)
    spectrum.set_title("Spectrum:", loc = "right")
    spectrum.set_xlabel("m/z")
    spectrum.set_ylabel("ion count")
    spectrum.ticklabel_format(scilimits=(0,0),axis='y')
    annSpectr(spectrum, mass, intensity, an)

def chromPlot(chromatogram,times,tic):
    chromatogram.plot(times,tic)
    chromatogram.set_ylim(bottom=0,top=chromatogram.get_ylim()[1]*1.1)
    chromatogram.set_title("Chromatogram:", loc = "right")
    chromatogram.set_xlabel("time (min)")
    chromatogram.set_ylabel("total ion count")
    chromatogram.ticklabel_format(scilimits=(0,0),axis='y')

def openFile(cromatogram, spectrum, ds, timeSel,an):
    filename=QtWidgets.QFileDialog.getOpenFileName(caption = "Open spectrum", filter="Finnigan RAW files (*.raw, *.RAW)")[0]
    if filename is '':
        return
    ds['chromdat'],ds['masses'],ds['matrix'] = load_raw(filename)
    populate(chromatogram, spectrum, ds, timeSel,an)


if __name__=="__main__":
    #ds for data_set
    ds = dict(chromdat=None,masses=None,matrix=None)

    nlogger = logging.getLogger('parseLogger')
    logging.basicConfig()
    nlogger.setLevel("WARN")

    graph = Figure(figsize=(5,4),dpi=100)
    graph.patch.set_facecolor("None")

    chromatogram = graph.add_subplot(211,facecolor=(1,1,1,0.8))
    spectrum = graph.add_subplot(212,facecolor=(1,1,1,0.8))
    graph.tight_layout()

    mpl_canvas = FigureCanvas(graph)
    mpl_canvas.setStyleSheet("background-color:transparent;")
    mpl_canvas.setAutoFillBackground(False)
    
    timeSelector=[None]
    annotation=[]

    pan_factory(chromatogram,ds)
    zoom_factory(chromatogram, 1.15)
    pan_factory(spectrum,ds)
    zoom_factory(spectrum, 1.15, ds)

    app = QtWidgets.QApplication(sys.argv)
    main_window = QtWidgets.QMainWindow()

    file_menu = QtWidgets.QMenu('&File',main_window)
    main_window.menuBar().addMenu(file_menu)
    file_menu.addAction('&Open..', lambda: openFile(chromatogram,spectrum, ds, timeSelector,annotation), QtCore.Qt.CTRL + QtCore.Qt.Key_O)
    file_menu.addAction('&Quit', main_window.close, QtCore.Qt.CTRL + QtCore.Qt.Key_Q)

    main_widget = QtWidgets.QWidget(main_window)
    main_window.setCentralWidget(main_widget)

    layout = QtWidgets.QVBoxLayout(main_widget)
    layout.addWidget(mpl_canvas)

    try:
        rawfile=sys.argv[1]
        ds['chromdat'],ds['masses'],ds['matrix'] = load_raw(rawfile)
        populate(chromatogram, spectrum, ds, timeSelector,annotation)
    except:
        None

    main_window.show()
    sys.exit(app.exec_())