Commit 40f00d32 authored by Yan's avatar Yan
Browse files

PEP8 clean-up, minor style fixes

parent c200e6fe
......@@ -5,7 +5,6 @@ from matplotlib.figure import Figure
from matplotlib.widgets import SpanSelector
from PyQt5 import QtCore
from PyQt5 import QtWidgets
#from rawFin2 import load_raw
from rawParse import load_raw
import os.path
import sys
......@@ -21,52 +20,49 @@ def zoom_factory(axis, base_scale, plot_data=dict()):
"""zoom when scrolling"""
if event.inaxes == axis:
if event.button == 'up':
#zoom in
# zoom in
scale_factor = 1/scale
elif event.button == 'down':
#zoom out
# zoom out
scale_factor = scale
else:
#should not happen
# should not happen
scale_factor = 1
print(event.button)
if event.key == 'shift':
data = event.ydata
new_top = data + (ax.get_ylim()[1] - data)\
* scale_factor
new_top = data + (ax.get_ylim()[1] - data) \
* scale_factor
axis.set_ylim([new_top * -0.01, new_top])
else:
data = event.xdata
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 "annotation" in pd:
data + x_right * scale_factor])
if "annotation" in pd:
ann_spec(event.inaxes, pd)
ax.figure.canvas.draw()
fig = axis.get_figure() # get the figure of interest
# attach the call back
fig = axis.get_figure()
fig.canvas.mpl_connect('scroll_event',
lambda event: zoom_fun(
event, plot_data, axis, base_scale))
return zoom_fun
def pan_factory(axis, plot=dict()):
"""pan spectrum when you press a button"""
def pan_fun(event, ax):
#rescale to origin if doubleclicked
# rescale to origin if doubleclicked
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)
ax.set_ylim(ax.get_ylim()[1]*-0.01, ax.get_ylim()[1]*1.1)
if "annotation" in plot:
ann_spec(ax, plot)
ax.figure.canvas.draw()
#otherwise pan
# 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(
......@@ -88,15 +84,18 @@ def pan_factory(axis, plot=dict()):
if "annotation" in chart:
ann_spec(ax, chart)
ax.figure.canvas.draw()
fig = axis.get_figure()
fig.canvas.mpl_connect('button_press_event',
lambda action: pan_fun(action, axis))
def pick_masses(x_min, x_max, mpl_spectrum, mass_spect):
"""zoom the spectrum in x axis by mass range"""
mpl_spectrum.set_xlim(x_min, x_max)
ann_spec(mpl_spectrum, mass_spect)
def pick_times(x_min, x_max, mpl_spectrum, data_set, mpl_chromatogram,
mass_spect, chrom_spect):
"""plot averaged spectrum of subselected part of the chromatogram"""
......@@ -111,65 +110,57 @@ def pick_times(x_min, x_max, mpl_spectrum, data_set, mpl_chromatogram,
end_scan = i
if start_scan == end_scan:
if start_scan == 0:
end_scan=1
end_scan = 1
elif start_scan is None:
end_scan=len(data_set['chrom_dat'][0, :])
start_scan=end_scan-1
end_scan = len(data_set['chrom_dat'][0, :])
start_scan = end_scan - 1
else:
time=(x_min+x_max)/2
d1 = time - data_set['chrom_dat'][0,start_scan-1]
d2 = data_set['chrom_dat'][0,start_scan] - time
time = (x_min+x_max)/2
d1 = time - data_set['chrom_dat'][0, start_scan-1]
d2 = data_set['chrom_dat'][0, start_scan] - time
if d1 < d2:
start_scan -=1
start_scan -= 1
elif d1 > d2:
end_scan +=1
end_scan += 1
else:
start_scan -=1
start_scan -= 1
end_scan = start_scan + 2
slims = [mpl_spectrum.get_xlim(),mpl_spectrum.get_ylim()]
slims = [mpl_spectrum.get_xlim(), mpl_spectrum.get_ylim()]
mpl_spectrum.clear()
mass_spect['annotation'].clear()
mass_spect['x'] = data_set['masses']
mass_spect['y'] = np.mean(data_set['matrix'][start_scan:end_scan]
, axis=0)
mass_spect['y'] = np.mean(
data_set['matrix'][start_scan:end_scan], axis=0)
pop_plot(mpl_spectrum, mass_spect)
mpl_spectrum.set_xlim(slims[0])
mpl_spectrum.set_ylim(slims[1])
ann_spec(mpl_spectrum, mass_spect)
mpl_chromatogram.clear()
pop_plot(mpl_chromatogram, chrom_spect)
mpl_chromatogram.plot(data_set['chrom_dat'][0, start_scan:end_scan],
data_set['chrom_dat'][1, start_scan:end_scan],
'b.')
dots_x = data_set['chrom_dat'][0, start_scan:end_scan]
dots_y = data_set['chrom_dat'][1, start_scan:end_scan]
mpl_chromatogram.plot(dots_x, dots_y, 'b.')
def populate(mpl_chromatogram, mpl_spectrum, data_set, time_sel,
def populate(mpl_chromatogram, mpl_spectrum, data_set,
mass_spect, chrom_spect):
"""populate the GUI plots with desired dataset"""
mass_spect['annotation'].clear()
def update_span_selector(chrom_plot, spec, d_set, ms_spect, chrom_dat):
time_selector = SpanSelector(
chrom_plot, lambda x_min, x_max: pick_times(
x_min, x_max,spec, d_set, chrom_plot, ms_spect,
chrom_dat),
'horizontal',
useblit=True,
rectprops=dict(alpha=0.15, facecolor='purple'), button=3)
return time_selector
mpl_spectrum.clear()
mpl_chromatogram.clear()
mass_spect['x'] = data_set['masses']
mass_spect['y'] = np.mean(data_set['matrix'], axis=0)
pop_plot(mpl_spectrum, mass_spect)
chrom_spect['x']=data_set['chrom_dat'][0, :]
chrom_spect['y']=data_set['chrom_dat'][1, :]
mpl_spectrum.figure.canvas.draw()
chrom_spect['x'] = data_set['chrom_dat'][0, :]
chrom_spect['y'] = data_set['chrom_dat'][1, :]
chrom_spect['t_start'] = data_set['chrom_dat'][0, 0]
chrom_spect['t_end'] = data_set['chrom_dat'][0, -1]
pop_plot(mpl_chromatogram, chrom_spect)
chrom_spect['t_start'] = data_set['chrom_dat'][0,0]
chrom_spect['t_end'] = data_set['chrom_dat'][0,-1]
time_sel[0] = update_span_selector(
mpl_chromatogram, mpl_spectrum, data_set,
mass_spect, chrom_spect)
mpl_chromatogram.figure.canvas.draw()
mpl_spectrum.figure.canvas.draw()
def ann_spec(ms_spec, msdata, ann_limit=0.01):
"""annotate spectrum
......@@ -184,10 +175,9 @@ def ann_spec(ms_spec, msdata, ann_limit=0.01):
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)
subtracted_peaks=[]
sort_peaks = sorted(
peakz, key=lambda h: y_value[h], reverse=True)
subtracted_peaks = []
red_x = xrange / coef_x
red_y = yrange / coef_y
for peak in sort_peaks:
......@@ -202,26 +192,27 @@ def ann_spec(ms_spec, msdata, ann_limit=0.01):
subtracted_peaks.append(peak)
return subtracted_peaks
borders=ms_spec.get_xlim()
start = np.argmax(msdata['x']>borders[0])
end = np.argmax(msdata['x']>borders[1])
borders = ms_spec.get_xlim()
start = np.argmax(msdata['x'] > borders[0])
end = np.argmax(msdata['x'] > borders[1])
if end == 0:
end = np.argmax(msdata['x'])
peaks = []
l = ms_spec.get_ylim()[1] * ann_limit
for i,intensity in enumerate(msdata['y'][start:end], start=start):
#end selects the first element which not to include.
#Thus intensity[i+1] always exists as it points to that last element.
if intensity > l and intensity > msdata['y'][i-1] and intensity > msdata['y'][i+1]:
lim = ms_spec.get_ylim()[1] * ann_limit
for i, intensity in enumerate(msdata['y'][start:end], start=start):
# end selects the first element which not to include.
# Thus intensity[i+1] always exists.
if intensity > lim and intensity > msdata['y'][i-1] \
and intensity > msdata['y'][i+1]:
peaks.append(i)
s_peaks = sub_peaks(peaks, msdata['x'], msdata['y'],
ms_spec.get_xlim()[1] - ms_spec.get_xlim()[0],
ms_spec.get_ylim()[1] - ms_spec.get_ylim()[0])
#delete objects from the spectra
# delete objects from the spectra
for intensity in msdata['annotation']:
intensity.remove()
#remove them from tracking
# remove them from tracking
msdata['annotation'].clear()
for i in s_peaks:
......@@ -229,28 +220,30 @@ def ann_spec(ms_spec, msdata, ann_limit=0.01):
'{0:.2f}'.format(msdata['x'][i]), xy=(msdata['x'][i], msdata['y'][i]),
textcoords='data'))
def pop_plot(plot, plot_data):
"""Define and populate plot"""
plot_data['line'] = plot.plot(plot_data['x'], plot_data['y'])
plot.set_title(plot_data['name'], loc ="right")
plot.set_title(plot_data['name'], loc="right")
plot.set_xlabel(plot_data['xlabel'])
plot.set_ylabel(plot_data['ylabel'])
plot.set_ylim(plot.get_ylim()[1] * -0.01,
plot.get_ylim()[1] * 1.1)
plot.get_ylim()[1] * 1.1)
plot.ticklabel_format(scilimits=(0, 0), axis='y')
if "annotation" in plot_data:
ann_spec(plot, plot_data)
def open_file(chrom_plot, spc, d_set, time_sel, ms_s, fn, chrom_s):
def open_file(chrom_plot, spc, d_set, ms_s, fn, chrom_s):
"""Returns chromatogram, masses and ion intensities"""
fn[0]=QtWidgets.QFileDialog.getOpenFileName(
caption = "Open spectrum",
fn[0] = QtWidgets.QFileDialog.getOpenFileName(
caption="Open spectrum",
filter="Finnigan RAW files (*.raw, *.RAW)")[0]
if fn[0] is '':
return
d_set['chrom_dat'], d_set['masses'], d_set['matrix'] \
= load_raw(fn[0])
populate(chrom_plot, spc, d_set, time_sel, ms_s, chrom_s)
if fn[0] is not'':
d_set['chrom_dat'], d_set['masses'], d_set['matrix'] \
= load_raw(fn[0])
populate(chrom_plot, spc, d_set, ms_s, chrom_s)
def export(mass_spec, chrom_spec, fn):
"""exports the chromatogram into the .dat file format"""
......@@ -259,24 +252,22 @@ def export(mass_spec, chrom_spec, fn):
main_window, "Export spectrum",
"Nothing to export, cancelling request")
return
exp_f_name=QtWidgets.QFileDialog.getSaveFileName(
caption = "Export spectrum",
exp_f_name = QtWidgets.QFileDialog.getSaveFileName(
caption="Export spectrum",
filter="dat table format (*.dat)")[0]
if exp_f_name is '':
return
else:
#fix for Qt5 "Feature"
if exp_f_name is not '':
# fix for Qt5 "Feature"
if exp_f_name[-4:] != '.dat':
exp_f_name = exp_f_name + ".dat"
if os.path.isfile(exp_f_name):
quest = QtWidgets.QMessageBox.warning(
main_window , "Export spectrum",
"{} already exists.\n Do you want to replace it?".\
format(os.path.basename(exp_f_name)),
main_window, "Export spectrum",
"{} already exists.\n Do you want to replace it?"
.format(os.path.basename(exp_f_name)),
QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
if(hex(quest)) == "0x10000":
return
expf=open(exp_f_name,'w')
expf = open(exp_f_name, 'w')
expf.write("mass ion_count\n"
"m/z\n"
"{}_{:.4}-{:.4}_minutes_of_the_aquisition\n".format(
......@@ -284,38 +275,36 @@ def export(mass_spec, chrom_spec, fn):
chrom_spec['t_start'], chrom_spec['t_end']))
for i in range(len(mass_spec['x'])):
expf.write("{} {}\n".format(
mass_spec['x'][i],mass_spec['y'][i]))
mass_spec['x'][i], mass_spec['y'][i]))
expf.close()
if __name__=="__main__":
#ds for data_set
ds = dict(chrom_dat=None,masses=None,matrix=None)
#mass spectrometry set
if __name__ == "__main__":
# ds for data_set, ms for mass_spec_dataset, chrom for chrom_dataset
ds = dict(chrom_dat=None, masses=None, matrix=None)
ms = dict(x=[0], y=[0], line=None, annotation=[],
name="Spectrum",xlabel="m/z",ylabel="ion count")
chrom = dict(x=[0], y=[0], line=[0], t_start=None, t_end=None,
name="Chromatogram", xlabel="time(min)", ylabel="total ion count")
name="Spectrum", xlabel="m/z", ylabel="ion count")
chrom = dict(x=[0], y=[0], line=None, t_start=None, t_end=None,
name="Chromatogram", xlabel="time(min)",
ylabel="total ion count")
filename = [None]
p_logger = logging.getLogger('parseLogger')
logging.basicConfig()
p_logger.setLevel("WARN")
graph = Figure(figsize=(5,4),dpi=100)
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))
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)
mpl_canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
mpl_canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
timeSelector=[None]
pan_factory(chromatogram)
zoom_factory(chromatogram, 1.15)
pan_factory(spectrum, ms)
......@@ -323,21 +312,24 @@ if __name__=="__main__":
mass_selector = SpanSelector(
spectrum, lambda x_min, x_max: pick_masses(
x_min, x_max, spectrum, ms),
'horizontal', useblit=True, rectprops=dict(alpha=0.15,
facecolor='purple'),
button=3)
'horizontal', useblit=True, rectprops=dict(
alpha=0.15, facecolor='purple'), button=3)
time_selector = SpanSelector(
chromatogram, lambda x_min, x_max: pick_times(
x_min, x_max, spectrum, ds, chromatogram, ms, chrom),
'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: open_file(chromatogram, spectrum, ds, timeSelector,
ms, filename, chrom),
file_menu.addAction('&Open..', lambda: open_file(
chromatogram, spectrum, ds, ms, filename, chrom),
QtCore.Qt.CTRL + QtCore.Qt.Key_O)
file_menu.addAction('&Export..', lambda: export(ms, chrom, filename),
QtCore.Qt.CTRL + QtCore.Qt.Key_E)
file_menu.addAction('&Export..', lambda: export(
ms, chrom, filename), QtCore.Qt.CTRL + QtCore.Qt.Key_E)
file_menu.addAction('&Quit', main_window.close,
QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
......@@ -349,14 +341,13 @@ if __name__=="__main__":
mpl_canvas.setFocus()
if len(sys.argv) == 2:
raw_file=sys.argv[1]
filename[0]=raw_file
ds['chrom_dat'],ds['masses'],ds['matrix'] = load_raw(raw_file)
populate(chromatogram, spectrum, ds, timeSelector, ms, chrom)
raw_file = sys.argv[1]
filename[0] = raw_file
ds['chrom_dat'], ds['masses'], ds['matrix'] = load_raw(raw_file)
populate(chromatogram, spectrum, ds, ms, chrom)
else:
pop_plot(spectrum, ms)
pop_plot(chromatogram, chrom)
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