Commit af41f521 authored by Yan's avatar Yan
Browse files

Pep8 clean-up

parent 97a0a913
......@@ -5,7 +5,7 @@ from matplotlib.figure import Figure
from matplotlib.widgets import SpanSelector
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from rawFin import load_raw
from rawFin2 import load_raw
from scipy.signal import find_peaks
import sys
import matplotlib
......@@ -15,7 +15,7 @@ matplotlib.use("Qt5Agg")
def zoom_factory(ax, base_scale, plot=None, an=None):
def zoom_fun(event, plot, an):
def zoom_fun(event, chart, ann):
if event.inaxes == ax:
if event.button == 'up':
#zoom in
......@@ -30,17 +30,17 @@ def zoom_factory(ax, base_scale, plot=None, an=None):
if event.key == 'shift':
data = event.ydata
newtop = data + (ax.get_ylim()[1] - data)*scale_factor
ax.set_ylim([newtop*-0.01,newtop])
new_top = data + (ax.get_ylim()[1] - data)*scale_factor
ax.set_ylim([new_top*-0.01,new_top])
else:
data = event.xdata
xleft = data - ax.get_xlim()[0]
xright = ax.get_xlim()[1] - data
ax.set_xlim([data - xleft*scale_factor,
data + xright*scale_factor])
if an != None:
if type(plot['x']) != type(None):
annSpectr(event.inaxes,plot['x'], plot['y'], an)
x_left = data - ax.get_xlim()[0]
x_right = ax.get_xlim()[1] - data
ax.set_xlim([data - x_left*scale_factor,
data + x_right*scale_factor])
if ann is not None:
if type(chart['x']) != type(None):
ann_spec(event.inaxes, chart['x'], chart['y'], ann)
ax.figure.canvas.draw()
fig = ax.get_figure() # get the figure of interest
......@@ -51,13 +51,13 @@ def zoom_factory(ax, base_scale, plot=None, an=None):
return zoom_fun
def pan_factory(ax, plot=None, an=None):
def pan_factory(axis, plot=None, an=None):
def pan_fun(event, ax):
if event.dblclick and event.inaxes == ax:
ax.get_figure()
ax.autoscale(True)
ax.set_ylim(ax.get_ylim()[1]*-0.01,ax.get_ylim()[1]*1.1)
annSpectr(spectrum, plot['x'], plot['y'], an)
ann_spec(spectrum, plot['x'], plot['y'], an)
ax.figure.canvas.draw()
elif event.button == 1 and event.inaxes == ax:
ax.start_pan(event.x, event.y, event.button)
......@@ -69,118 +69,118 @@ def pan_factory(ax, plot=None, an=None):
ax.drag_pan(1, 'x', event.x, event.y)
ax.figure.canvas.draw()
def drag_end(event, id_drag, id_release, plot, an, ax):
def drag_end(event, id_drag, id_release, chart, ann, ax):
if event.button == 1:
fig.canvas.mpl_disconnect(id_drag)
fig.canvas.mpl_disconnect(id_release)
if an != None:
if type(plot['x']) != type(None):
annSpectr(ax,plot['x'], plot['y'], an)
if ann is not None:
if type(chart['x']) != type(None):
ann_spec(ax, chart['x'], chart['y'], ann)
ax.figure.canvas.draw()
fig = ax.get_figure()
fig.canvas.mpl_connect('button_press_event', lambda action: pan_fun(action, ax))
fig = axis.get_figure()
fig.canvas.mpl_connect('button_press_event', lambda action: pan_fun(action, axis))
def pick_masses(xmin, xmax, ax, an, plot):
ax.set_xlim(xmin,xmax)
annSpectr(spectrum, plot['x'], plot['y'], an)
def pick_masses(x_min, x_max, ax, an, plot):
ax.set_xlim(x_min, x_max)
ann_spec(spectrum, plot['x'], plot['y'], an)
ax.figure.canvas.draw()
def picktimes(xmin, xmax, mplspectrum, dataset, mplchromatogram, an, ms_s):
def pick_times(x_min, x_max, mpl_spectrum, data_set, mpl_chromatogram, an, ms_s):
start_scan = None
end_scan = None
for i, j in enumerate(dataset['chromdat'][0, :]):
if j > xmin and start_scan == None:
for i, j in enumerate(data_set['chrom_dat'][0, :]):
if j > x_min and start_scan is None:
start_scan = i
if j > xmax and end_scan == None:
if j > x_max and end_scan is None:
end_scan = i
mplspectrum.clear()
mpl_spectrum.clear()
an.clear()
ms_s['x'] = dataset['masses']
ms_s['y'] = np.mean(dataset['matrix'][start_scan:end_scan], axis=0)
spectrPlot(spectrum, ms['x'], ms['y'], 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, ms_s):
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)
mpl_chromatogram.clear()
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):
an.clear()
def updateSpanSelector(chromatogram, spectrum, dataset, ms_s):
timeselec = SpanSelector(chromatogram, lambda xmin, xmax: picktimes(xmin, xmax, spectrum, dataset, chromatogram, an, ms_s), 'horizontal', useblit=True, rectprops=dict(alpha=0.15, facecolor='purple'),button=3)
return timeselec
mplspectrum.clear()
mplchromatogram.clear()
ms_s['x'] = dataset['masses']
ms_s['y'] = np.mean(dataset['matrix'], axis=0)
spectrPlot(mplspectrum,ms_s['x'], ms_s['y'], an)
chromPlot(mplchromatogram, dataset['chromdat'][0,:],dataset['chromdat'][1,:])
timeSel[0] = updateSpanSelector(mplchromatogram, mplspectrum, ds, ms_s)
mplchromatogram.figure.canvas.draw()
mplspectrum.figure.canvas.draw()
def annSpectr(spectrum,mass,intensity,an):
def sub_peaks(peakz,mass,intensity,x,y):
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)
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)
mpl_chromatogram.figure.canvas.draw()
mpl_spectrum.figure.canvas.draw()
def ann_spec(ms_spec, mass, intensity, an):
def sub_peaks(peakz, x_value, y_value, 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 ):
for g in peakz:
if gp == [] or (abs(max(y_value[gp]) - y_value[g]) * 10 < y and abs(x_value[gp[np.argmax(y_value[gp])]] - x_value[g]) * 20 < x):
gp.append(g)
else:
sp.append(gp[np.argmax(intensity[gp])])
sp.append(gp[np.argmax(y_value[gp])])
gp = [g]
if g == peakz[-1]:#[0][-1]:
sp.append(gp[np.argmax(intensity[gp])])
if g == peakz[-1]:
sp.append(gp[np.argmax(y_value[gp])])
return sp
borders=spectrum.get_xlim()
borders=ms_spec.get_xlim()
start = np.argmax(mass>borders[0])
end = np.argmax(mass>borders[1])
if end == 0:
end = np.argmax(mass)
peaks = find_peaks(intensity[start:end], height=spectrum.get_ylim()[1]/100)
peaks = find_peaks(intensity[start:end], height=ms_spec.get_ylim()[1] / 100)
peaks = peaks[0] + start
sp = sub_peaks(peaks,mass,intensity,spectrum.get_xlim()[1]-spectrum.get_xlim()[0],spectrum.get_ylim()[1]-spectrum.get_ylim()[0])
s_peaks = sub_peaks(peaks, mass, intensity, ms_spec.get_xlim()[1] - ms_spec.get_xlim()[0], ms_spec.get_ylim()[1] - ms_spec.get_ylim()[0])
for j in an:
j.remove()
an.clear()
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.set_ylim(spectrum.get_ylim()[1]*-0.01,)
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(chromatogram.get_ylim()[1]*-0.011,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, ms_s):
for i in s_peaks:
an.append(ms_spec.annotate('{0:.2f}'.format(mass[i]), xy=(mass[i], intensity[i]), textcoords='data'))
def spectrum_plot(spc, mass, intensity, an):
spc.plot(mass, intensity)
spc.set_title("Spectrum:", loc ="right")
spc.set_xlabel("m/z")
spc.set_ylabel("ion count")
spc.set_ylim(spc.get_ylim()[1] * -0.01, )
spc.ticklabel_format(scilimits=(0, 0), axis='y')
ann_spec(spc, mass, intensity, an)
def chrom_plot(chrom, times, tic):
chrom.plot(times, tic)
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):
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, ms_s)
d_set['chrom_dat'], d_set['masses'], d_set['matrix'] = load_raw(filename)
populate(chrom, spc, d_set, time_sel, an, ms_s)
if __name__=="__main__":
#ds for data_set
ds = dict(chromdat=None,masses=None,matrix=None)
ds = dict(chrom_dat=None,masses=None,matrix=None)
#mass spectrometry set
ms = dict(x=None,y=None)
nlogger = logging.getLogger('parseLogger')
p_logger = logging.getLogger('parseLogger')
logging.basicConfig()
nlogger.setLevel("WARN")
p_logger.setLevel("WARN")
graph = Figure(figsize=(5,4),dpi=100)
graph.patch.set_facecolor("None")
......@@ -201,14 +201,14 @@ if __name__=="__main__":
zoom_factory(chromatogram, 1.15)
pan_factory(spectrum, ms, annotation)
zoom_factory(spectrum, 1.15, ms, annotation)
mass_selector = SpanSelector(spectrum, lambda xmin, xmax: pick_masses(xmin, xmax, spectrum, annotation, ms), 'horizontal', useblit=True, rectprops=dict(alpha=0.15, facecolor='purple'),button=3)
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'), button=3)
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, ms), QtCore.Qt.CTRL + QtCore.Qt.Key_O)
file_menu.addAction('&Open..', 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)
main_widget = QtWidgets.QWidget(main_window)
......@@ -218,13 +218,14 @@ if __name__=="__main__":
layout.addWidget(mpl_canvas)
mpl_canvas.setFocus()
try:
rawfile=sys.argv[1]
ds['chromdat'],ds['masses'],ds['matrix'] = load_raw(rawfile)
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)
except:
spectrPlot(spectrum, [0], [0], annotation)
chromPlot(chromatogram, [0], [0])
else:
spectrum_plot(spectrum, [0], [0], annotation)
chrom_plot(chromatogram, [0], [0])
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