Commit c200e6fe authored by Yan's avatar Yan
Browse files

code cleanup

maybe some bugs has been introduced in process
parent e4b5c834
......@@ -15,17 +15,17 @@ import logging
matplotlib.use("Qt5Agg")
def zoom_factory(ax, base_scale, plot=None, an=None):
def zoom_factory(axis, base_scale, plot_data=dict()):
"""returns zooming functionality to axis"""
def zoom_fun(event, chart, ann):
def zoom_fun(event, pd, ax, scale):
"""zoom when scrolling"""
if event.inaxes == ax:
if event.inaxes == axis:
if event.button == 'up':
#zoom in
scale_factor = 1/base_scale
scale_factor = 1/scale
elif event.button == 'down':
#zoom out
scale_factor = base_scale
scale_factor = scale
else:
#should not happen
scale_factor = 1
......@@ -33,28 +33,29 @@ def zoom_factory(ax, base_scale, plot=None, an=None):
if event.key == 'shift':
data = event.ydata
new_top = data + (ax.get_ylim()[1] - data)*scale_factor
ax.set_ylim([new_top*-0.01,new_top])
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 ann is not None:
if type(chart['x']) != type(None):
ann_spec(event.inaxes, chart['x'], chart['y'], ann)
ax.set_xlim([data - x_left * scale_factor,
data + x_right * scale_factor])
if "annotation" in pd:
ann_spec(event.inaxes, pd)
ax.figure.canvas.draw()
fig = ax.get_figure() # get the figure of interest
fig = axis.get_figure() # get the figure of interest
# attach the call back
fig.canvas.mpl_connect('scroll_event',
lambda event: zoom_fun(event, plot, an))
lambda event: zoom_fun(
event, plot_data, axis, base_scale))
return zoom_fun
def pan_factory(axis, plot=None, annotations=None):
def pan_factory(axis, plot=dict()):
"""pan spectrum when you press a button"""
def pan_fun(event, ax):
#rescale to origin if doubleclicked
......@@ -62,8 +63,8 @@ def pan_factory(axis, plot=None, annotations=None):
ax.get_figure()
ax.autoscale(True)
ax.set_ylim(ax.get_ylim()[1]*-0.01,ax.get_ylim()[1]*1.1)
if annotations is not None:
ann_spec(ax, plot['x'], plot['y'], annotations)
if "annotation" in plot:
ann_spec(ax, plot)
ax.figure.canvas.draw()
#otherwise pan
elif event.button == 1 and event.inaxes == ax:
......@@ -74,41 +75,39 @@ def pan_factory(axis, plot=None, annotations=None):
id_release = fig.canvas.mpl_connect(
'button_release_event',
lambda action: drag_end(
action, id_drag, id_release, plot, annotations, ax))
action, id_drag, id_release, plot, ax))
def drag_fun(event, ax):
ax.drag_pan(1, 'x', event.x, event.y)
ax.figure.canvas.draw()
def drag_end(event, id_drag, id_release, chart, ann, ax):
def drag_end(event, id_drag, id_release, chart, ax):
if event.button == 1:
fig.canvas.mpl_disconnect(id_drag)
fig.canvas.mpl_disconnect(id_release)
if ann is not None:
if type(chart['x']) != type(None):
ann_spec(ax, chart['x'], chart['y'], ann)
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, ax, annotations, plot):
def pick_masses(x_min, x_max, mpl_spectrum, mass_spect):
"""zoom the spectrum in x axis by mass range"""
ax.set_xlim(x_min, x_max)
ann_spec(spectrum, plot['x'], plot['y'], annotations)
ax.figure.canvas.draw()
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,
annotations, mass_spect, t):
mass_spect, chrom_spect):
"""plot averaged spectrum of subselected part of the chromatogram"""
t['start'] = x_min
t['end'] = x_max
chrom_spect['t_start'] = x_min
chrom_spect['t_end'] = x_max
start_scan = None
end_scan = None
for i, times in enumerate(data_set['chrom_dat'][0, :]):
if times > x_min and start_scan is None:
for i, time in enumerate(data_set['chrom_dat'][0, :]):
if time > x_min and start_scan is None:
start_scan = i
if times > x_max and end_scan is None:
if time > x_max and end_scan is None:
end_scan = i
if start_scan == end_scan:
if start_scan == 0:
......@@ -129,28 +128,29 @@ def pick_times(x_min, x_max, mpl_spectrum, data_set, mpl_chromatogram,
end_scan = start_scan + 2
slims = [mpl_spectrum.get_xlim(),mpl_spectrum.get_ylim()]
mpl_spectrum.clear()
annotations.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)
spectrum_plot(mpl_spectrum, mass_spect['x'], mass_spect['y'], annotations)
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()
chrom_plot(mpl_chromatogram, data_set['chrom_dat'][0, :],
data_set['chrom_dat'][1, :])
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.')
def populate(mpl_chromatogram, mpl_spectrum, data_set, time_sel, an,
mass_spect, t):
def populate(mpl_chromatogram, mpl_spectrum, data_set, time_sel,
mass_spect, chrom_spect):
"""populate the GUI plots with desired dataset"""
an.clear()
def update_span_selector(chrom, spec, d_set, ms_spec):
mass_spect['annotation'].clear()
def update_span_selector(chrom_plot, spec, d_set, ms_spect, chrom_dat):
time_selector = SpanSelector(
chrom, lambda x_min, x_max: pick_times(
x_min, x_max,spec, d_set, chrom, an, ms_spec, t),
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)
......@@ -159,17 +159,19 @@ def populate(mpl_chromatogram, mpl_spectrum, data_set, time_sel, an,
mpl_chromatogram.clear()
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, :])
t['start'] = data_set['chrom_dat'][0,0]
t['end'] = data_set['chrom_dat'][0,-1]
time_sel[0] = update_span_selector(mpl_chromatogram, mpl_spectrum,
data_set, mass_spect)
pop_plot(mpl_spectrum, mass_spect)
chrom_spect['x']=data_set['chrom_dat'][0, :]
chrom_spect['y']=data_set['chrom_dat'][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, mass, intensities, annotations, ann_limit=0.01):
def ann_spec(ms_spec, msdata, ann_limit=0.01):
"""annotate spectrum
First define borders where the annotation should occur. Then the
......@@ -201,55 +203,45 @@ def ann_spec(ms_spec, mass, intensities, annotations, ann_limit=0.01):
return subtracted_peaks
borders=ms_spec.get_xlim()
start = np.argmax(mass>borders[0])
end = np.argmax(mass>borders[1])
start = np.argmax(msdata['x']>borders[0])
end = np.argmax(msdata['x']>borders[1])
if end == 0:
end = np.argmax(mass)
end = np.argmax(msdata['x'])
peaks = []
l = ms_spec.get_ylim()[1] * ann_limit
for i,intensity in enumerate(intensities[start:end], start=start):
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 > intensities[i-1] and intensity > intensities[i+1]:
if intensity > l and intensity > msdata['y'][i-1] and intensity > msdata['y'][i+1]:
peaks.append(i)
s_peaks = sub_peaks(peaks, mass, intensities,
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
for intensity in annotations:
for intensity in msdata['annotation']:
intensity.remove()
#remove them from tracking
annotations.clear()
msdata['annotation'].clear()
for i in s_peaks:
annotations.append(ms_spec.annotate(
'{0:.2f}'.format(mass[i]), xy=(mass[i], intensities[i]),
msdata['annotation'].append(ms_spec.annotate(
'{0:.2f}'.format(msdata['x'][i]), xy=(msdata['x'][i], msdata['y'][i]),
textcoords='data'))
def pop_plot(plot, x_val, y_val, labels, annotation=False):
def pop_plot(plot, plot_data):
"""Define and populate plot"""
line = plot.plot(x_val, y_val)
plot.set_title(labels['name'], loc ="right")
plot.set_xlabel(labels['x'])
plot.set_ylabel(labels['y'])
plot_data['line'] = plot.plot(plot_data['x'], plot_data['y'])
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.ticklabel_format(scilimits=(0, 0), axis='y')
if annotation is not False:
ann_spec(plot, x_val, y_val, annotation)
if "annotation" in plot_data:
ann_spec(plot, plot_data)
def spectrum_plot(spc, mass, intensity, an):
"""Define and populate spectrum"""
pop_plot(spc, mass, intensity, dict(
name="Spectrum",x="m/z",y="ion count"), an)
def chrom_plot(chrom, times, tic):
"""Define and populate chromatogram"""
pop_plot(chrom, times, tic, dict(
name="Chromatogram",x="time(min)",y="total ion count"))
def open_file(chrom, spc, d_set, time_sel, an, ms_s, t, fn):
def open_file(chrom_plot, spc, d_set, time_sel, ms_s, fn, chrom_s):
"""Returns chromatogram, masses and ion intensities"""
fn[0]=QtWidgets.QFileDialog.getOpenFileName(
caption = "Open spectrum",
......@@ -258,9 +250,9 @@ def open_file(chrom, spc, d_set, time_sel, an, ms_s, t, fn):
return
d_set['chrom_dat'], d_set['masses'], d_set['matrix'] \
= load_raw(fn[0])
populate(chrom, spc, d_set, time_sel, an, ms_s, t)
populate(chrom_plot, spc, d_set, time_sel, ms_s, chrom_s)
def export(mass_spec, t, fn):
def export(mass_spec, chrom_spec, fn):
"""exports the chromatogram into the .dat file format"""
if fn[0] is None:
QtWidgets.QMessageBox.warning(
......@@ -289,7 +281,7 @@ def export(mass_spec, t, fn):
"m/z\n"
"{}_{:.4}-{:.4}_minutes_of_the_aquisition\n".format(
os.path.basename(fn[0]),
t['start'], t['end']))
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]))
......@@ -300,8 +292,10 @@ if __name__=="__main__":
#ds for data_set
ds = dict(chrom_dat=None,masses=None,matrix=None)
#mass spectrometry set
ms = dict(x=None,y=None)
times = dict(start=None,end=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")
filename = [None]
p_logger = logging.getLogger('parseLogger')
......@@ -321,15 +315,14 @@ if __name__=="__main__":
mpl_canvas.setFocusPolicy( QtCore.Qt.ClickFocus )
timeSelector=[None]
annotation=[]
pan_factory(chromatogram)
zoom_factory(chromatogram, 1.15)
pan_factory(spectrum, ms, annotation)
zoom_factory(spectrum, 1.15, ms, annotation)
pan_factory(spectrum, ms)
zoom_factory(spectrum, 1.15, ms)
mass_selector = SpanSelector(
spectrum, lambda x_min, x_max: pick_masses(
x_min, x_max, spectrum, annotation, ms),
x_min, x_max, spectrum, ms),
'horizontal', useblit=True, rectprops=dict(alpha=0.15,
facecolor='purple'),
button=3)
......@@ -341,14 +334,13 @@ if __name__=="__main__":
main_window.menuBar().addMenu(file_menu)
file_menu.addAction('&Open..',
lambda: open_file(chromatogram, spectrum, ds, timeSelector,
annotation, ms, times, filename),
ms, filename, chrom),
QtCore.Qt.CTRL + QtCore.Qt.Key_O)
file_menu.addAction('&Export..', lambda: export(ms, times, filename),
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)
main_widget = QtWidgets.QWidget(main_window)
main_window.setCentralWidget(main_widget)
......@@ -356,16 +348,14 @@ if __name__=="__main__":
layout.addWidget(mpl_canvas)
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, annotation,
ms, times)
populate(chromatogram, spectrum, ds, timeSelector, ms, chrom)
else:
spectrum_plot(spectrum, [0], [0], annotation)
chrom_plot(chromatogram, [0], [0])
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