Commit 8be8fa29 authored by Yan's avatar Yan
Browse files

reduced line lenght, added docstrings

parent 6fcfb05e
......@@ -7,7 +7,6 @@ from PyQt5 import QtCore
from PyQt5 import QtWidgets
#from rawFin2 import load_raw
from rawParse import load_raw
#from scipy.signal import find_peaks
import sys
import matplotlib
import numpy as np
......@@ -16,7 +15,9 @@ matplotlib.use("Qt5Agg")
def zoom_factory(ax, base_scale, plot=None, an=None):
"""returns zooming functionality to axis"""
def zoom_fun(event, chart, ann):
"""zoom when scrolling"""
if event.inaxes == ax:
if event.button == 'up':
#zoom in
......@@ -46,14 +47,16 @@ def zoom_factory(ax, base_scale, plot=None, an=None):
fig = ax.get_figure() # get the figure of interest
# attach the call back
fig.canvas.mpl_connect('scroll_event', lambda event: zoom_fun(event, plot, an))
fig.canvas.mpl_connect('scroll_event',
lambda event: zoom_fun(event, plot, an))
# return the function
return zoom_fun
def pan_factory(axis, plot=None, annotations=None):
"""pan spectrum when you press a button"""
def pan_fun(event, ax):
#rescale to origin if doubleclicked
if event.dblclick and event.inaxes == ax:
ax.get_figure()
ax.autoscale(True)
......@@ -61,12 +64,16 @@ def pan_factory(axis, plot=None, annotations=None):
if annotations is not None:
ann_spec(ax, plot['x'], plot['y'], annotations)
ax.figure.canvas.draw()
#otherwise pan
elif 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', lambda action: drag_fun(action, ax))
id_drag = fig.canvas.mpl_connect(
'motion_notify_event',
lambda action: drag_fun(action, ax))
id_release = fig.canvas.mpl_connect(
'button_release_event', lambda action: drag_end(
action, id_drag, id_release, plot, annotations, ax))
'button_release_event',
lambda action: drag_end(
action, id_drag, id_release, plot, annotations, ax))
def drag_fun(event, ax):
ax.drag_pan(1, 'x', event.x, event.y)
......@@ -81,100 +88,120 @@ def pan_factory(axis, plot=None, annotations=None):
ann_spec(ax, chart['x'], chart['y'], ann)
ax.figure.canvas.draw()
fig = axis.get_figure()
fig.canvas.mpl_connect('button_press_event', lambda action: pan_fun(action, axis))
fig.canvas.mpl_connect('button_press_event',
lambda action: pan_fun(action, axis))
def pick_masses(x_min, x_max, ax, an, plot):
def pick_masses(x_min, x_max, ax, annotations, plot):
"""zoom the spectrum in x axis by mass range"""
ax.set_xlim(x_min, x_max)
ann_spec(spectrum, plot['x'], plot['y'], an)
ann_spec(spectrum, plot['x'], plot['y'], annotations)
ax.figure.canvas.draw()
def pick_times(x_min, x_max, mpl_spectrum, data_set, mpl_chromatogram, an, ms_s):
def pick_times(x_min, x_max, mpl_spectrum, data_set, mpl_chromatogram,
annotations, mass_spect):
"""plot averaged spectrum of subselected part of the chromatogram"""
start_scan = None
end_scan = None
for i, j in enumerate(data_set['chrom_dat'][0, :]):
if j > x_min and start_scan is None:
for i, times in enumerate(data_set['chrom_dat'][0, :]):
if times > x_min and start_scan is None:
start_scan = i
if j > x_max and end_scan is None:
if times > x_max and end_scan is None:
end_scan = i
mpl_spectrum.clear()
an.clear()
ms_s['x'] = data_set['masses']
ms_s['y'] = np.mean(data_set['matrix'][start_scan:end_scan], axis=0)
spectrum_plot(spectrum, ms['x'], ms['y'], an)
annotations.clear()
mass_spect['x'] = data_set['masses']
mass_spect['y'] = np.mean(data_set['matrix'][start_scan:end_scan]
, axis=0)
spectrum_plot(spectrum, mass_spect['x'], mass_spect['y'], annotations)
mpl_chromatogram.clear()
chrom_plot(mpl_chromatogram, data_set['chrom_dat'][0, :], data_set['chrom_dat'][1, :])
chrom_plot(mpl_chromatogram, data_set['chrom_dat'][0, :],
data_set['chrom_dat'][1, :])
mpl_chromatogram.plot(data_set['chrom_dat'][0, start_scan:end_scan],
data_set['chrom_dat'][1, start_scan:end_scan],
'b.')
def populate(mpl_chromatogram, mpl_spectrum, data_set, time_sel, an, ms_s):
def populate(mpl_chromatogram, mpl_spectrum, data_set, time_sel, an,
mass_spect):
"""populate the GUI plots with desired dataset"""
an.clear()
def update_span_selector(chrom, spec, d_set, ms_spec):
time_selector = SpanSelector(chrom,
lambda x_min, x_max: pick_times(
x_min, x_max,spec, d_set, chrom, an, ms_spec),
'horizontal',
useblit=True,
rectprops=dict(alpha=0.15, facecolor='purple'),
button=3)
time_selector = SpanSelector(
chrom, lambda x_min, x_max: pick_times(
x_min, x_max,spec, d_set, chrom, an, ms_spec),
'horizontal',
useblit=True,
rectprops=dict(alpha=0.15, facecolor='purple'), button=3)
return time_selector
mpl_spectrum.clear()
mpl_chromatogram.clear()
ms_s['x'] = data_set['masses']
ms_s['y'] = np.mean(data_set['matrix'], axis=0)
spectrum_plot(mpl_spectrum, ms_s['x'], ms_s['y'], an)
chrom_plot(mpl_chromatogram, data_set['chrom_dat'][0, :], data_set['chrom_dat'][1, :])
time_sel[0] = update_span_selector(mpl_chromatogram, mpl_spectrum, data_set, ms_s)
mass_spect['x'] = data_set['masses']
mass_spect['y'] = np.mean(data_set['matrix'], axis=0)
spectrum_plot(mpl_spectrum, mass_spect['x'], mass_spect['y'], an)
chrom_plot(mpl_chromatogram, data_set['chrom_dat'][0, :],
data_set['chrom_dat'][1, :])
time_sel[0] = update_span_selector(mpl_chromatogram, mpl_spectrum,
data_set, mass_spect)
mpl_chromatogram.figure.canvas.draw()
mpl_spectrum.figure.canvas.draw()
def ann_spec(ms_spec, mass, intensity, annotations, ann_limit=0.01):
def sub_peaks(peakz, x_value, y_value, x, y, coef_x=10, coef_y=10):
sp = sorted(peakz,
def ann_spec(ms_spec, mass, intensities, annotations, ann_limit=0.01):
"""annotate spectrum
First define borders where the annotation should occur. Then the
function finds local maxima of the data set by forcycling through
the dataset and then substracts found local minimas so it contains
only subset of the most intense one which are in reasonable distance
from each other. Then the function remove old annotation and
annotate the spectrum by abovementioned subsection of local maximas.
"""
def sub_peaks(peakz, x_value, y_value, xrange, yrange, coef_x=10,
coef_y=10):
"""Returns reasonable subselection of local maximas"""
sort_peaks = sorted(peakz,
key=lambda h: y_value[h],
reverse=True)
sub=[]
rx = x/coef_x
ry = y/coef_y
for g in sp:
subtracted_peaks=[]
red_x = xrange / coef_x
red_y = yrange / coef_y
for peak in sort_peaks:
add = True
yv = y_value[g]
xv = x_value[g]
for u in sub:
if abs(yv - y_value[u]) < ry and abs(xv - x_value[u]) < rx:
yv = y_value[peak]
xv = x_value[peak]
for u in subtracted_peaks:
if abs(yv - y_value[u]) < red_y \
and abs(xv - x_value[u]) < red_x:
add = False
if add:
sub.append(g)
return sub
subtracted_peaks.append(peak)
return subtracted_peaks
borders=ms_spec.get_xlim()
wstart = np.argmax(mass>borders[0])
wend = np.argmax(mass>borders[1])
if wend == 0:
wend = np.argmax(mass)
#peaks = find_peaks(intensity[wstart:wend], height=ms_spec.get_ylim()[1] / 100)
start = np.argmax(mass>borders[0])
end = np.argmax(mass>borders[1])
if end == 0:
end = np.argmax(mass)
peaks = []
l = ms_spec.get_ylim()[1] * ann_limit
q = intensity
for i,j in enumerate(q[wstart:wend], start=wstart):
#wend selects the first element which not to include.
for i,intensity in enumerate(intensities[start:end], start=start):
#end selects the first element which not to include.
#Thus q[i+1] always exists as it points to that last element.
if j > l and j > q[i-1] and j > q[i+1]:
if intensity > l and intensity > q[i-1] and intensity > q[i+1]:
peaks.append(i)
s_peaks = sub_peaks(peaks, mass, intensity,
s_peaks = sub_peaks(peaks, mass, intensities,
ms_spec.get_xlim()[1] - ms_spec.get_xlim()[0],
ms_spec.get_ylim()[1] - ms_spec.get_ylim()[0])
for j in annotations:
j.remove()
for intensity in annotations:
intensity.remove()
annotations.clear()
for i in s_peaks:
annotations.append(ms_spec.annotate('{0:.2f}'.format(mass[i]),
xy=(mass[i], intensity[i]),
textcoords='data'))
annotations.append(ms_spec.annotate(
'{0:.2f}'.format(mass[i]), xy=(mass[i], intensities[i]),
textcoords='data'))
def spectrum_plot(spc, mass, intensity, an):
def spectrum_plot(spc, mass, intensity,an):
"""Define and populate spectrum"""
spc.plot(mass, intensity)
spc.set_title("Spectrum:", loc ="right")
spc.set_xlabel("m/z")
......@@ -184,20 +211,24 @@ def spectrum_plot(spc, mass, intensity, an):
ann_spec(spc, mass, intensity, an)
def chrom_plot(chrom, times, tic):
"""Define and populate chromatogram"""
chrom.plot(times, tic)
chrom.set_ylim(chrom.get_ylim()[1] * -0.011, chrom.get_ylim()[1] * 1.1)
chrom.set_ylim(chrom.get_ylim()[1] * -0.011,
chrom.get_ylim()[1] * 1.1)
chrom.set_title("Chromatogram:", loc ="right")
chrom.set_xlabel("time (min)")
chrom.set_ylabel("total ion count")
chrom.ticklabel_format(scilimits=(0, 0), axis='y')
def open_file(chrom, spc, d_set, time_sel, an, ms_s):
"""Returns chromatogram, masses and ion intensities"""
filename=QtWidgets.QFileDialog.getOpenFileName(
caption = "Open spectrum",
filter="Finnigan RAW files (*.raw, *.RAW)")[0]
if filename is '':
return
d_set['chrom_dat'], d_set['masses'], d_set['matrix'] = load_raw(filename)
d_set['chrom_dat'], d_set['masses'], d_set['matrix'] \
= load_raw(filename)
populate(chrom, spc, d_set, time_sel, an, ms_s)
......@@ -231,19 +262,23 @@ if __name__=="__main__":
pan_factory(spectrum, ms, annotation)
zoom_factory(spectrum, 1.15, ms, annotation)
mass_selector = SpanSelector(
spectrum, lambda x_min, x_max: pick_masses(x_min, x_max, spectrum, annotation, ms),
'horizontal', useblit=True, rectprops=dict(alpha=0.15, facecolor='purple'),
spectrum, lambda x_min, x_max: pick_masses(
x_min, x_max, spectrum, annotation, ms),
'horizontal', useblit=True, rectprops=dict(alpha=0.15,
facecolor='purple'),
button=3)
app = QtWidgets.QApplication(sys.argv)
main_window = QtWidgets.QMainWindow()
file_menu = QtWidgets.QMenu('&File',main_window)
file_menu = QtWidgets.QMenu('&File', main_window)
main_window.menuBar().addMenu(file_menu)
file_menu.addAction('&Open..',
lambda: open_file(chromatogram, spectrum, ds, timeSelector, annotation, ms),
lambda: open_file(chromatogram, spectrum, ds, timeSelector,
annotation, ms),
QtCore.Qt.CTRL + QtCore.Qt.Key_O)
file_menu.addAction('&Quit', main_window.close, QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
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)
......@@ -256,7 +291,8 @@ if __name__=="__main__":
if len(sys.argv) == 2:
raw_file=sys.argv[1]
ds['chrom_dat'],ds['masses'],ds['matrix'] = load_raw(raw_file)
populate(chromatogram, spectrum, ds, timeSelector,annotation, ms)
populate(chromatogram, spectrum, ds, timeSelector, annotation,
ms)
else:
spectrum_plot(spectrum, [0], [0], annotation)
chrom_plot(chromatogram, [0], [0])
......
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