Commit 45a507cd authored by Yan's avatar Yan
Browse files

initial commit

parents
## Prasopes
Prasopes is a free and open source Thermo/Finnigan .RAW spectra viewer. It is an implementation example of rawFin library. Its limitation of the supported format range is limited by the current developemnt state of this library.
## Usage
If running from cmdline, the first argument is taken as a spectrum file. Otherwise use File -> Open or Ctrl+O to open a spectrum.
#!/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_())
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment