Commit bf7df136 authored by Yan's avatar Yan
Browse files

Unite spectrum variables and objects into one class

parent 14dcd27b
...@@ -49,16 +49,44 @@ class QStatusBarLogger(logging.Handler): ...@@ -49,16 +49,44 @@ class QStatusBarLogger(logging.Handler):
self.trigger.signal.emit() self.trigger.signal.emit()
def load_file(parent, chrom_plot, spc, d_set, ms_s, fn, chrom_s, class AugFigureCanvas(FigureCanvas):
update, settings, loadthread, filename=None): #TODO: move the widget into graphtools when I'm done
def __init__(self):
self.figure = Figure(figsize=(5, 4), dpi=100, facecolor="None",
constrained_layout=True)
super().__init__(self.figure)
self.ds = []
self.ms = dict(annotation=[], name="Spectrum", xlabel="m/z",
ylabel="ion count", xtics=20, predict=None,
params=[], headers=[], texts=[])
self.chrom = dict(x=[0], y=[0], t_start=None, t_end=None, machtype=None,
name="Chromatogram", xlabel="time(min)",
ylabel="total ion count", timesarg=[])
self.filename = None
self.drlcache = [None, None]
grid = self.figure.add_gridspec(2, 1)
self.chromplot = self.figure.add_subplot(grid[0,0], facecolor=(1, 1, 1, 0.8))
self.spectplot = self.figure.add_subplot(grid[1,0], facecolor=(1, 1, 1, 0.8))
self.setStyleSheet("background-color:transparent;")
self.setAutoFillBackground(False)
self.paramstable = dt.table(["","name","value"], 100)
gt.pan_factory(self.chromplot)
gt.zoom_factory(self.chromplot, 1.15)
gt.pan_factory(self.spectplot, self.ms)
gt.zoom_factory(self.spectplot, 1.15, self.ms)
gt.textedit_factory(self.spectplot, self.ms)
self.mass_selector = gt.AugSpanSelector(self.spectplot, self.ms)
#TODO: rewrite timeSelector to better shape when I'm done
self.time_selector = SpanSelector(self.chromplot, lambda x_min, x_max:
gt.pick_times(x_min, x_max, self.spectplot, self.ds, self.chromplot, self.ms, self.chrom, self.paramstable), 'horizontal', useblit=True, rectprops=dict(
alpha=0.15, facecolor='purple'), button=3)
def load_file(parent, augCanvas, update, settings, loadthread, filename=None):
"""populates dataset and plots it""" """populates dataset and plots it"""
directory=settings.value("open_folder") directory = augCanvas.filename or settings.value("open_folder")
if fn[0] is not None: filename = filename or QtWidgets.QFileDialog.getOpenFileName(
directory=fn[0] caption="Open spectrum", directory=directory,
if filename == None:
filename = QtWidgets.QFileDialog.getOpenFileName(
caption="Open spectrum",
directory=directory,
filter="Finnigan RAW files (*.raw, *.RAW)")[0] filter="Finnigan RAW files (*.raw, *.RAW)")[0]
if filename is not '' and os.path.isfile(filename)\ if filename is not '' and os.path.isfile(filename)\
and not os.path.isdir(filename): and not os.path.isdir(filename):
...@@ -67,8 +95,10 @@ def load_file(parent, chrom_plot, spc, d_set, ms_s, fn, chrom_s, ...@@ -67,8 +95,10 @@ def load_file(parent, chrom_plot, spc, d_set, ms_s, fn, chrom_s,
def runfnc(): def runfnc():
try: try:
[i.clear() for i in ( [i.clear() for i in (
d_set, chrom_s['timesarg'], ms_s['params'],ms_s['headers'])] augCanvas.ds, augCanvas.chrom['timesarg'],
[d_set.append(dict(chrom_dat=i[0], masses=i[1], matrix=i[2])) augCanvas.ms['params'],augCanvas.ms['headers'])]
[augCanvas.ds.append(dict(
chrom_dat=i[0], masses=i[1], matrix=i[2]))
for i in load_raw(filename, settings.value("tmp_location"))] for i in load_raw(filename, settings.value("tmp_location"))]
except rawprasslib.ParsingException as pex: except rawprasslib.ParsingException as pex:
errormsg.append("Opening of the file has failed!") errormsg.append("Opening of the file has failed!")
...@@ -80,18 +110,23 @@ def load_file(parent, chrom_plot, spc, d_set, ms_s, fn, chrom_s, ...@@ -80,18 +110,23 @@ def load_file(parent, chrom_plot, spc, d_set, ms_s, fn, chrom_s,
return return
if autoparams == True: if autoparams == True:
try: try:
ms_s['params'], rawheaders, chrom_s['machtype'] = load_params(filename) (augCanvas.ms['params'], rawheaders
segments = [len(subset['chrom_dat'][0]) for subset in d_set] , augCanvas.chrom['machtype']) = load_params(filename)
indicies = [sum(segments[:i+1]) for i in range(len(segments))] segments = [len(subset['chrom_dat'][0])
ms_s['headers'] = np.split(rawheaders, indicies)[:-1] for subset in augCanvas.ds]
indicies = [sum(segments[:i+1])
for i in range(len(segments))]
augCanvas.ms['headers'] = np.split(
rawheaders, indicies)[:-1]
except Exception as pex: except Exception as pex:
errormsg.append("File is incompatible with the rawautoparams,") errormsg.append(
"File is incompatible with the rawautoparams,")
errormsg.append( errormsg.append(
"no parameters loaded!\n\n" "no parameters loaded!\n\n"
"Error message:\n{}".format(pex.args[0])) "Error message:\n{}".format(pex.args[0]))
error.signal.emit() error.signal.emit()
gt.populate(chrom_plot, spc, d_set, ms_s, chrom_s) gt.populate(augCanvas)
fn[0] = filename augCanvas.filename = filename
parent.setWindowTitle("Prasopes - {}".format( parent.setWindowTitle("Prasopes - {}".format(
os.path.basename(filename))) os.path.basename(filename)))
update.signal.emit() update.signal.emit()
...@@ -175,17 +210,17 @@ def oddeven_changed(chromatogram, spectrum, ds, ms, filename, chrom, config, ...@@ -175,17 +210,17 @@ def oddeven_changed(chromatogram, spectrum, ds, ms, filename, chrom, config,
update_spectrum(chromatogram, spectrum, ds, ms, filename, chrom, config) update_spectrum(chromatogram, spectrum, ds, ms, filename, chrom, config)
def key_pressed(event, chrom, spect, ds, ms_ds, fn, chrom_ds, config): def key_pressed(event, augCanvas, config):
if event.key() == QtCore.Qt.Key_F5: if event.key() == QtCore.Qt.Key_F5:
update_spectrum(chrom, spect, ds, ms_ds, fn, chrom_ds, config) update_spectrum(augCanvas, config)
if event.key() == QtCore.Qt.Key_C: if event.key() == QtCore.Qt.Key_C:
if event.modifiers().__int__() == QtCore.Qt.ControlModifier: if event.modifiers().__int__() == QtCore.Qt.ControlModifier:
imgt.clip_spect_img(ms_ds, spect) imgt.clip_spect_img(augCanvas)
if event.modifiers().__int__() == QtCore.Qt.ControlModifier+\ if event.modifiers().__int__() == QtCore.Qt.ControlModifier+\
QtCore.Qt.ShiftModifier: QtCore.Qt.ShiftModifier:
dt.clip_spectstr(spect, chrom_ds, fn) dt.clip_spectstr(augCanvas)
if event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right): if event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right):
gt.shift_times(event, spect, chrom, ds, ms_ds, chrom_ds) gt.shift_times(event, augCanvas)
def about(parent): def about(parent):
...@@ -200,15 +235,7 @@ def main(): ...@@ -200,15 +235,7 @@ def main():
app = QtWidgets.QApplication(sys.argv) app = QtWidgets.QApplication(sys.argv)
loadthread = QtCore.QThread() loadthread = QtCore.QThread()
ds = [] augCanvas = AugFigureCanvas()
ms = dict(annotation=[], name="Spectrum", xlabel="m/z",
ylabel="ion count", xtics=20, predict=None,
params=[], headers=[], texts=[])
chrom = dict(x=[0], y=[0], t_start=None, t_end=None, machtype=None,
name="Chromatogram", xlabel="time(min)",
ylabel="total ion count", timesarg=[])
filename = [None]
drlcache = [None, None]
update = update_signal() update = update_signal()
config = cf.settings() config = cf.settings()
...@@ -235,60 +262,35 @@ def main(): ...@@ -235,60 +262,35 @@ def main():
params_logger.addHandler(barHandler) params_logger.addHandler(barHandler)
barHandler.setLevel("DEBUG") barHandler.setLevel("DEBUG")
paramstable = dt.table(["","name","value"], 100)
paramstable.horizontalHeader().setSectionResizeMode(
0, QtWidgets.QHeaderView.ResizeToContents)
graph = Figure(figsize=(5, 4), dpi=100, facecolor="None", constrained_layout=True)
grid = graph.add_gridspec(2, 1)
chromatogram = graph.add_subplot(grid[0,0], facecolor=(1, 1, 1, 0.8))
spectrum = graph.add_subplot(grid[1,0], facecolor=(1, 1, 1, 0.8))
mpl_canvas = FigureCanvas(graph)
mpl_canvas.setStyleSheet("background-color:transparent;")
mpl_canvas.setAutoFillBackground(False)
gt.pan_factory(chromatogram)
gt.zoom_factory(chromatogram, 1.15)
gt.pan_factory(spectrum, ms)
gt.zoom_factory(spectrum, 1.15, ms)
gt.textedit_factory(spectrum, ms)
mass_selector = gt.AugSpanSelector(spectrum, ms)
time_selector = SpanSelector(chromatogram, lambda x_min, x_max:
gt.pick_times( x_min, x_max, spectrum, ds, chromatogram, ms, chrom,
paramstable), 'horizontal', useblit=True, rectprops=dict(
alpha=0.15, facecolor='purple'), button=3)
main_window = QtWidgets.QMainWindow(windowTitle="Prasopes") main_window = QtWidgets.QMainWindow(windowTitle="Prasopes")
if QtGui.QIcon.themeName() is "": if QtGui.QIcon.themeName() is "":
QtGui.QIcon.setThemeName("TangoMFK") QtGui.QIcon.setThemeName("TangoMFK")
lfvars = (main_window, chromatogram, spectrum, ds, ms, filename, chrom,
update, config, loadthread)
consoledock = docks.consoleDockWidget( consoledock = docks.consoleDockWidget(
locals(), "&Console", "view/consolevisible") locals(), "&Console", "view/consolevisible")
treedock = docks.treeDockWidget( treedock = docks.treeDockWidget(
update, "&File browser", "view/filebrowservisible", load_file, lfvars) "&File browser", "view/filebrowservisible", update, load_file, main_window,
augCanvas, config, loadthread)
paramsdock = docks.augDock("Acquisition parameters", "&Acq parameters", paramsdock = docks.augDock("Acquisition parameters", "&Acq parameters",
"view/acqparvisible") "view/acqparvisible")
update.signal.connect(lambda: gt.update_paramstable(paramstable, ms, chrom)) update.signal.connect(lambda: gt.update_paramstable(augCanvas))
paramsdock.setWidget(paramstable) paramsdock.setWidget(augCanvas.paramstable)
openact = QtWidgets.QAction(QtGui.QIcon.fromTheme( openact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
"document-open"), "&Open...", None) "document-open"), "&Open...", None)
openact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_O) openact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_O)
openact.triggered.connect(lambda: load_file( openact.triggered.connect(lambda: load_file(
main_window, chromatogram, spectrum, ds, ms, filename, chrom, main_window, augCanvas, update, config, loadthread))
update, config, loadthread))
exportact = QtWidgets.QAction(QtGui.QIcon.fromTheme( exportact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
"document-save-as"), "&Export...", None) "document-save-as"), "&Export...", None)
exportact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_E) exportact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_E)
exportact.triggered.connect(lambda: ft.export_dial( exportact.triggered.connect(lambda: ft.export_dial(
spectrum, chrom, filename, main_window)) augCanvas, main_window))
printact = QtWidgets.QAction(QtGui.QIcon.fromTheme( printact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
"document-print"), "&Print", None) "document-print"), "&Print", None)
printact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_P) printact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_P)
printact.triggered.connect(lambda: print_graph( printact.triggered.connect(lambda: print_graph(augCanvas))
ds, ms, chrom, spectrum, filename, paramstable))
settingsact = QtWidgets.QAction(QtGui.QIcon.fromTheme( settingsact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
"preferences-system"), "&Settings...", None) "preferences-system"), "&Settings...", None)
settingsact.triggered.connect(lambda: cf.dial(main_window)) settingsact.triggered.connect(lambda: cf.dial(main_window))
...@@ -300,12 +302,12 @@ def main(): ...@@ -300,12 +302,12 @@ def main():
"applications-utilities"), "&TSQ zce...", None) "applications-utilities"), "&TSQ zce...", None)
zceact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_T) zceact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_T)
zceact.triggered.connect(lambda: zce.dialog( zceact.triggered.connect(lambda: zce.dialog(
main_window, ds, filename, update)) main_window, augCanvas, update))
drlact = QtWidgets.QAction(QtGui.QIcon.fromTheme( drlact = QtWidgets.QAction(QtGui.QIcon.fromTheme(
"applications-utilities"), "&DRL...", None) "applications-utilities"), "&DRL...", None)
drlact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_D) drlact.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_D)
drlact.triggered.connect(lambda: drl.main_window( drlact.triggered.connect(lambda: drl.main_window(
main_window, ds, filename, drlcache, update)) main_window, augCanvas, update))
aboutact = QtWidgets.QAction("&About Prasopes", None) aboutact = QtWidgets.QAction("&About Prasopes", None)
aboutact.triggered.connect(lambda: about(main_window)) aboutact.triggered.connect(lambda: about(main_window))
autozoomy = QtWidgets.QAction(QtGui.QIcon.fromTheme( autozoomy = QtWidgets.QAction(QtGui.QIcon.fromTheme(
...@@ -313,23 +315,22 @@ def main(): ...@@ -313,23 +315,22 @@ def main():
checked=config.value("view/autozoomy", type=bool)) checked=config.value("view/autozoomy", type=bool))
autozoomy.triggered.connect(lambda: config.setValue( autozoomy.triggered.connect(lambda: config.setValue(
"view/autozoomy", autozoomy.isChecked())) "view/autozoomy", autozoomy.isChecked()))
autozoomy.triggered.connect(lambda: gt.autozoomy(spectrum)) autozoomy.triggered.connect(lambda: gt.autozoomy(augCanvas.spectrum))
intensitiesact = QtWidgets.QAction("&Show intensities", None, intensitiesact = QtWidgets.QAction("&Show intensities", None,
checkable=True, checked=config.value("view/intensities", checkable=True, checked=config.value("view/intensities",
type=bool)) type=bool))
intensitiesact.triggered.connect(lambda: config.setValue( intensitiesact.triggered.connect(lambda: config.setValue(
"view/intensities", intensitiesact.isChecked())) "view/intensities", intensitiesact.isChecked()))
intensitiesact.triggered.connect(lambda: gt.ann_spec(spectrum, ms)) intensitiesact.triggered.connect(lambda: gt.ann_spec(augCanvas))
intensitiesact.triggered.connect(lambda: spectrum.figure.canvas.draw()) intensitiesact.triggered.connect(lambda: augCanvas.draw())
oddevenact = QtWidgets.QAction("&Odd / even", None, checkable=True, oddevenact = QtWidgets.QAction("&Odd / even", None, checkable=True,
checked=config.value("view/oddeven", type=bool)) checked=config.value("view/oddeven", type=bool))
oddevenact.triggered.connect(lambda: oddevenact.triggered.connect(lambda:
oddeven_changed(chromatogram, spectrum, ds, ms, filename, chrom, oddeven_changed(augCanvas, config, oddevenact))
config, oddevenact))
predictform = QtWidgets.QLineEdit(maximumWidth=150) predictform = QtWidgets.QLineEdit(maximumWidth=150)
predictform.editingFinished.connect(lambda: predictmz( predictform.editingFinished.connect(lambda: predictmz(
predictform, chromatogram, spectrum, ds, ms, chrom)) predictform, augCanvas))
file_menu = QtWidgets.QMenu('&File', main_window) file_menu = QtWidgets.QMenu('&File', main_window)
main_window.menuBar().addMenu(file_menu) main_window.menuBar().addMenu(file_menu)
...@@ -356,8 +357,7 @@ def main(): ...@@ -356,8 +357,7 @@ def main():
main_window.menuBar().addMenu(help_menu) main_window.menuBar().addMenu(help_menu)
help_menu.addAction(aboutact) help_menu.addAction(aboutact)
main_window.setCentralWidget(mpl_canvas) main_window.setCentralWidget(augCanvas)
toolBar = QtWidgets.QToolBar(main_window) toolBar = QtWidgets.QToolBar(main_window)
toolBar.setAllowedAreas(QtCore.Qt.TopToolBarArea) toolBar.setAllowedAreas(QtCore.Qt.TopToolBarArea)
...@@ -378,11 +378,10 @@ def main(): ...@@ -378,11 +378,10 @@ def main():
main_window.dragEnterEvent = lambda event: drag_entered(event) main_window.dragEnterEvent = lambda event: drag_entered(event)
main_window.dropEvent = lambda event: dropped( main_window.dropEvent = lambda event: dropped(
event, main_window, chromatogram, spectrum, ds, ms, filename, event, main_window, augCanvas, update, config)
chrom, update, config)
main_window.setAcceptDrops(True) main_window.setAcceptDrops(True)
main_window.keyPressEvent = lambda event: key_pressed(event, chromatogram, main_window.keyPressEvent = lambda event: key_pressed(
spectrum, ds, ms, filename, chrom, config) event, augCanvas, config)
main_window.addToolBar(QtCore.Qt.TopToolBarArea, toolBar) main_window.addToolBar(QtCore.Qt.TopToolBarArea, toolBar)
main_window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, treedock) main_window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, treedock)
...@@ -393,12 +392,11 @@ def main(): ...@@ -393,12 +392,11 @@ def main():
main_window.setFocus() main_window.setFocus()
if len(sys.argv) == 2: if len(sys.argv) == 2:
load_file(main_window, chromatogram, spectrum, ds, ms, load_file(main_window, augCanvas, update, config, loadthread,
filename, chrom, update, config, loadthread,
filename=sys.argv[1]) filename=sys.argv[1])
else: else:
gt.pop_plot(0, 0, spectrum, ms) gt.pop_plot(0, 0, augCanvas.spectplot, augCanvas.ms)
gt.pop_plot(0, 0, chromatogram, chrom) gt.pop_plot(0, 0, augCanvas.chromplot, augCanvas.chrom)
main_window.show() main_window.show()
sys.exit(app.exec_()) sys.exit(app.exec_())
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
from PyQt5 import QtWidgets from PyQt5 import QtWidgets
from code import InteractiveConsole from code import InteractiveConsole
from io import StringIO from io import StringIO
import os from os import path
import contextlib import contextlib
import numpy as np import numpy as np
import prasopes.config as cf import prasopes.config as cf
...@@ -57,7 +57,8 @@ def consoleDockWidget(localvars, actionname, cfval): ...@@ -57,7 +57,8 @@ def consoleDockWidget(localvars, actionname, cfval):
return dock return dock
def treeDockWidget(update, actionname, cfval, load_file, lfvars): def treeDockWidget(actionname, cfval, update, loadfnc, parent,
augCanvas, config, loadthread):
config = cf.settings() config = cf.settings()
fileModel = QtWidgets.QFileSystemModel() fileModel = QtWidgets.QFileSystemModel()
fileModel.setRootPath('') fileModel.setRootPath('')
...@@ -70,18 +71,18 @@ def treeDockWidget(update, actionname, cfval, load_file, lfvars): ...@@ -70,18 +71,18 @@ def treeDockWidget(update, actionname, cfval, load_file, lfvars):
dirview.setModel(fileModel) dirview.setModel(fileModel)
dock = augDock("Folder View", actionname, cfval) dock = augDock("Folder View", actionname, cfval)
[dock.layout.addWidget(i) for i in (treeview, dirview)] [dock.layout.addWidget(i) for i in (treeview, dirview)]
filename = lfvars[5]
def scrolltoonce(): def scrolltoonce():
fileModel.layoutChanged.disconnect(scrolltoonce) fileModel.layoutChanged.disconnect(scrolltoonce)
treeview.scrollTo(fileModel.index(config.value("open_folder")), 1) treeview.scrollTo(fileModel.index(config.value("open_folder")), 1)
fileModel.directoryLoaded.connect( fileModel.directoryLoaded.connect(
lambda: treeview.resizeColumnToContents(0)) lambda: treeview.resizeColumnToContents(0))
update.signal.connect(lambda: treeview.setCurrentIndex(fileModel.index( update.signal.connect(lambda: treeview.setCurrentIndex(fileModel.index(
filename[0]))) augCanvas.filename)))
update.signal.connect(lambda: dirview.setRootIndex(fileModel.index( update.signal.connect(lambda: dirview.setRootIndex(fileModel.index(
os.path.dirname(os.path.realpath(filename[0]))))) path.dirname(path.realpath(augCanvas.filename)))))
fileModel.layoutChanged.connect(scrolltoonce) fileModel.layoutChanged.connect(scrolltoonce)
clickload = lambda index: load_file(*lfvars, filename=fileModel.filePath(index)) clickload = lambda index: loadfnc(parent, augCanvas, update, config,
loadthread, filename=fileModel.filePath(index))
for i in [treeview.doubleClicked, dirview.doubleClicked, dirview.clicked]: for i in [treeview.doubleClicked, dirview.doubleClicked, dirview.clicked]:
i.connect(clickload) i.connect(clickload)
return dock return dock
...@@ -620,8 +620,11 @@ def select_all_btn_up(ds, drls, drlspectrum, state=None): ...@@ -620,8 +620,11 @@ def select_all_btn_up(ds, drls, drlspectrum, state=None):
drls['checkAll'].blockSignals(False) drls['checkAll'].blockSignals(False)
def main_window(parent, ds, filename, cache, update_signal): def main_window(parent, augCanvas, update_signal):
"""constructs a dialog window""" """constructs a dialog window"""
ds = augCanvas.ds
filename = augCanvas.filename
cache = augCanvas.drlcache
def onclose(widget, event, buffer, drls, canvas, update_fnc, update_ptrows): def onclose(widget, event, buffer, drls, canvas, update_fnc, update_ptrows):
buffer[0], buffer[1] = drls, canvas buffer[0], buffer[1] = drls, canvas
update_signal.signal.disconnect(update_fnc) update_signal.signal.disconnect(update_fnc)
......
...@@ -20,7 +20,7 @@ ann_bbox = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.5) ...@@ -20,7 +20,7 @@ ann_bbox = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.5)
class AugSpanSelector(SpanSelector): class AugSpanSelector(SpanSelector):
def __init__(self, ax, data): def __init__(self, ax, data):
SpanSelector.__init__(self, ax, onselect=lambda x,y: None, super().__init__(ax, onselect=lambda x,y: None,
direction='horizontal', minspan=0.01, useblit=True, direction='horizontal', minspan=0.01, useblit=True,
rectprops=dict(alpha=0.15, facecolor='purple'), rectprops=dict(alpha=0.15, facecolor='purple'),
onmove_callback=None, span_stays=False, button=3) onmove_callback=None, span_stays=False, button=3)
...@@ -36,14 +36,14 @@ class AugSpanSelector(SpanSelector): ...@@ -36,14 +36,14 @@ class AugSpanSelector(SpanSelector):
self.direction = 'horizontal' self.direction = 'horizontal'
self.onselect = self.pick_masses self.onselect = self.pick_masses
self.new_axes(self.ax) self.new_axes(self.ax)
SpanSelector._press(self, event) super()._press(event)
def _release(self, event): def _release(self, event):
"""on button release event""" """on button release event"""
if self.pressv is None: if self.pressv is None:
return return
elif self.direction == 'horizontal': elif self.direction == 'horizontal':
SpanSelector._release(self, event) super()._release(event)
else: else:
self.rect.set_visible(False) self.rect.set_visible(False)
self.canvas.draw_idle() self.canvas.draw_idle()
...@@ -58,7 +58,7 @@ class AugSpanSelector(SpanSelector): ...@@ -58,7 +58,7 @@ class AugSpanSelector(SpanSelector):
def _set_span_xy(self, event): def _set_span_xy(self, event):
"""Setting the span coordinates override""" """Setting the span coordinates override"""
if self.direction == 'horizontal': if self.direction == 'horizontal':
SpanSelector._set_span_xy(self, event) super()._set_span_xy(event)
else: else:
x,y = self._get_data(event) x,y = self._get_data(event)
if y is None: if y is None:
...@@ -399,32 +399,30 @@ def legendize(rawlegend, chrom_data): ...@@ -399,32 +399,30 @@ def legendize(rawlegend, chrom_data):
return strtext return strtext
def populate(mpl_chromatogram, mpl_spectrum, data_set, def populate(augCanvas):
ms_data, chrom_data):
"""populate the GUI plots with desired dataset""" """populate the GUI plots with desired dataset"""
if np.array_equal(data_set, []): if np.array_equal(augCanvas.ds, []):
return return
ms_data['annotation'].clear() [i.clear() for i in (augCanvas.ms['annotation'],
mpl_spectrum.clear() augCanvas.chromplot, augCanvas.spectplot)]
mpl_chromatogram.clear()
if ms_data['predict'] != None: if augCanvas.ms['predict'] != None:
maxm = np.argmax(ms_data['predict'][1]) + ms_data['predict'][0] predict = augCanvas.ms['predict']
maxm = np.argmax(predict[1]) + predict[0]
maxseek = dt.argsubselect(linex, maxm-.5, maxm+.5) maxseek = dt.argsubselect(linex, maxm-.5, maxm+.5)
maxpos = maxseek[np.argmax(liney[maxseek])] maxpos = maxseek[np.argmax(liney[maxseek])]
crudeints = ms_data['predict'][1] * ms_data['y'][maxpos] crudeints = predict[1] * ms_data['y'][maxpos]
crudemasses = (np.arange(len(ms_data['predict'][1])) + crudemasses = (np.arange(len(predict[1])) + linex[maxpos])
linex[maxpos])
pmasses, pints = [], [] pmasses, pints = [], []
[pmasses.extend([np.nan,i,i]) for i in crudemasses] [pmasses.extend([np.nan,i,i]) for i in crudemasses]
[pints.extend([np.nan,0,i]) for i in crudeints] [pints.extend([np.nan,0,i]) for i in crudeints]
mpl_spectrum.plot(pmasses,pints, linewidth=1) augCanvas.spectplot.plot(pmasses, pints, linewidth=1)
chrom_data['t_start'] = data_set[0]['chrom_dat'][0, 0] augCanvas.chrom['t_start'] = augCanvas.ds[0]['chrom_dat'][0, 0]
chrom_data['t_end'] = data_set[-1]['chrom_dat'][0, -1] augCanvas.chrom['t_end'] = augCanvas.ds[-1]['chrom_dat'][0, -1]
for i,subset in enumerate(data_set): for i,subset in enumerate(augCanvas.ds):
if len(ms_data['headers']) == len(data_set): if len(augCanvas.ms['headers']) == len(augCanvas.ds):
legend = legendize(ms_data['headers'][i], chrom_data) legend = legendize(augCanvas.ms['headers'][i], augCanvas.chrom)
else: else:
legend = None legend = None
if cf.settings().value("view/oddeven", type=bool): if cf.settings().value("view/oddeven", type=bool):
...@@ -433,17 +431,20 @@ def populate(mpl_chromatogram, mpl_spectrum, data_set, ...@@ -433,17 +431,20 @@ def populate(mpl_chromatogram, mpl_spectrum, data_set,
msy = np.mean(subset['matrix'][j::2], axis=0) msy = np.mean(subset['matrix'][j::2], axis=0)
chromx = subset['chrom_dat'][0, :][j::2] chromx = subset['chrom_dat'][0, :][j::2]
chromy = subset['chrom_dat'][1, :][j::2] chromy = subset['chrom_dat'][1, :][j::2]
pop_plot(msx, msy, mpl_spectrum, ms_data, i*2+j, legend) pop_plot(msx, msy, augCanvas.spectplot, augCanvas.ms,