Commit 171f0ff3 authored by Yan's avatar Yan
Browse files

Got plotting working in DRL

parent 44ccbedb
......@@ -33,7 +33,7 @@ def main():
name="Chromatogram", xlabel="time(min)",
ylabel="total ion count")
filename = [None]
drlcache = [None, None]
drlcache = [None, None, None]
p_logger = logging.getLogger('parseLogger')
logging.basicConfig()
......
from PyQt5 import QtGui
import numpy as np
def floatize(imptext):
"""grabs the text and transforms it safely to folat,
if the text is not acceptable as float, returns zero"""
validator = QtGui.QDoubleValidator()
validator.setBottom(0)
status = validator.validate(imptext, 0)[0]
if status == QtGui.QValidator.Acceptable:
outfloat = float(imptext)
else:
outfloat = 0
return outfloat
def argsubselect(array, minimum, maximum):
"""finds arguments which fits into boundary conditions,
if there is no fit, return nearest argument"""
args = np.where((array >= minimum) & (array <= maximum))[0]
if len(args) == 0:
aver = (minimum+maximum)/2
args = [(np.abs(array - aver)).argmin()]
return args
......@@ -9,6 +9,8 @@ from PyQt5 import QtGui
import sys
import matplotlib
import numpy as np
import prasopes.datatools as dt
import prasopes.graphtools as gt
matplotlib.use("Qt5Agg")
class HBar(QtWidgets.QFrame):
......@@ -19,70 +21,95 @@ class HBar(QtWidgets.QFrame):
self.setFrameShape(QtWidgets.QFrame.HLine)
def update_spectrum(start, end, spectrum, dataset):
def update_profile(start, end, spectrum, dataset):
"""spectrum updating procedure"""
#Dont do anything to graph when the spectrum is not populated
if (start == 0 and start == end) or type(dataset['masses']) == type(None):
if (type(dataset['masses'])) == type(None):
return
#TODO: make the function more economical both in CPU load and in linecount
mlen = len(dataset['masses'])
start_mass = None
end_mass = None
for i, mass in enumerate(dataset['masses'][0:]):
if mass > start and start_mass is None:
start_mass = i
if mass > end and end_mass is None:
end_mass = i
if end_mass is None:
end_mass = mlen
if start_mass is None:
start_mass = mlen-1
if start_mass == end_mass:
if start_mass == 0:
end_mass = 1
else:
start_mass -= 1
end_mass = start_mass + 2
spectrum.clear()
masses = dataset['masses']
massargs = dt.argsubselect(masses, start, end)
yshape = np.mean(dataset['matrix'], axis=0)
dots_x = dataset['masses']
spectrum.clear()
dots_x = masses
dots_y = yshape
full_x = dataset['masses'][start_mass:end_mass]
full_y = yshape[start_mass:end_mass]
full_x = masses[massargs]
full_y = yshape[massargs]
spectrum.plot(dots_x, dots_y, ':', color='gray')
spectrum.plot(full_x, full_y, 'r')
xex = (dataset['masses'][end_mass-1]-dataset['masses'][start_mass])*0.25
spectrum.set_xlim(dataset['masses'][start_mass]-xex,dataset['masses'][end_mass-1]+xex)
ymax = max(yshape[start_mass:end_mass])
xex = (masses[massargs[-1]]-masses[massargs[0]])*0.25
spectrum.set_xlim(masses[massargs[0]]-xex,
masses[massargs[-1]]+xex)
ymax = max(yshape[massargs])
spectrum.set_ylim(ymax*-0.1, ymax*1.2)
spectrum.figure.canvas.draw()
def get_daughterset(ptable, dtable, ds):
names = []
times = ds['chrom_dat'][0,:]
intensities = []
#TODO: resolve intensities trouble
for row in range(dtable.rowCount()):
if dtable.cellWidget(row, 1).checkState() == 2:
startm = dt.floatize(ptable.cellWidget(row,1).text())
endm = dt.floatize(ptable.cellWidget(row,2).text())
massargs = dt.argsubselect(ds['masses'], startm, endm)
intensity = (np.sum(
ds['matrix'].T[massargs].T, axis=1)) / ds['chrom_dat'][1]
cor = dtable.cellWidget(row, 2).currentIndex()-1
if cor != -1:
factor = dt.floatize(dtable.cellWidget(row,3).text())
startm = dt.floatize(ptable.cellWidget(cor,1).text())
endm = dt.floatize(ptable.cellWidget(cor,2).text())
massargs = dt.argsubselect(ds['masses'], startm, endm)
corrections = ((np.sum(
ds['matrix'].T[massargs].T, axis=1))\
/ ds['chrom_dat'][1]) * factor
itensity = intensities - corrections
intensities.append(intensity)
names.append(dtable.item(row,1).text())
return names, times, intensities
def update_drlspectrum(ptable, dtable, ds, drlspectrum):
#Dont do when the dataset is not populated
if (type(ds['masses'])) == type(None):
return
names, times, intensities = get_daughterset(ptable, dtable, ds)
for i in range(len(drlspectrum.lines)):
drlspectrum.lines[0].remove()
for i in intensities:
drlspectrum.plot(times, i)
if len(names) != 0:
drlspectrum.set_ylim(top=np.amax(intensities)*1.1,
bottom=np.amax(intensities)*-0.01)
drlspectrum.figure.canvas.draw()
def getTableItemList(ptable):
ion_list = []
for i in range(ptable.rowCount()):
if type(ptable.cellWidget(i,0)) is not type(None):
name = ptable.cellWidget(i,0).text()
if type(ptable.cellWidget(i, 0)) is not type(None):
name = ptable.cellWidget(i, 0).text()
else:
name = ""
text = "{} ({}-{})".format(
name, (ptable.cellWidget(i,1).text()),
(ptable.cellWidget(i,2).text()))
name, (ptable.cellWidget(i, 1).text()),
(ptable.cellWidget(i, 2).text()))
ion_list.append(text)
return ion_list
def update_drl(start_mz, end_mz, spectrum, dataset, pname, dname,
ptable, dtable):
ptable, dtable, drlspectrum):
"""cares that masses are in order and valid, then refresh tables"""
for line in start_mz, end_mz:
status = QtGui.QDoubleValidator().validate(line.text(),0)[0]
if status in (0, 1):
line.setText("0.00")
status = QtGui.QDoubleValidator().validate(line.text(), 0)[0]
if status != QtGui.QValidator.Acceptable:
line.setText("0")
start = float(start_mz.text())
end = float(end_mz.text())
start = dt.floatize(start_mz.text())
end = dt.floatize(end_mz.text())
if start > end:
start, end = end, start
......@@ -90,7 +117,7 @@ def update_drl(start_mz, end_mz, spectrum, dataset, pname, dname,
end_mz.setText(str(end))
dname.setText("{} ({:.2f}-{:.2f})".format(
pname.text(),float(start_mz.text()),float(end_mz.text())))
pname.text(), start, end))
for i in (range(dtable.rowCount())):
index = dtable.cellWidget(i,2).currentIndex()
......@@ -99,7 +126,8 @@ def update_drl(start_mz, end_mz, spectrum, dataset, pname, dname,
dtable.cellWidget(i,2).addItems(getTableItemList(ptable))
dtable.cellWidget(i,2).setCurrentIndex(index)
update_spectrum(start, end, spectrum, dataset)
update_profile(start, end, spectrum, dataset)
update_drlspectrum(ptable, dtable, dataset, drlspectrum)
def remove_rows(ptable, dtable):
......@@ -133,7 +161,8 @@ def setDoubleCell(table,row,column):
return table.cellWidget(row,column)
def add_line(parent_widget, mass_selector, spectrum, ds, parenttable, daughtertable):
def add_line(parent_widget, mass_selector, spectrum, ds, parenttable,
daughtertable, drlspectrum):
"""add parent ion to the table"""
ion_graph = Figure(figsize=(3, 1.5), dpi=100, facecolor="None")
ionspect = ion_graph.add_subplot(111, facecolor=(1, 1, 1, 0.8),
......@@ -155,6 +184,7 @@ def add_line(parent_widget, mass_selector, spectrum, ds, parenttable, daughterta
daughtertable.setRowCount(newrow + 1)
#TODO: decide which box will be used in the final version
checkbox = QtWidgets.QCheckBox()
daughtertable.setItem(newrow,0, QtWidgets.QTableWidgetItem())
daughtertable.item(newrow,0).setFlags(daughtertable.item(newrow,0).flags()
& ~QtCore.Qt.ItemIsSelectable)
......@@ -164,7 +194,7 @@ def add_line(parent_widget, mass_selector, spectrum, ds, parenttable, daughterta
dname.setFlags(dname.flags() & ~QtCore.Qt.ItemIsEditable)
dname.setTextAlignment(QtCore.Qt.AlignRight)
daughtertable.setItem(newrow, 1, dname)
daughtertable.setCellWidget(newrow, 1, QtWidgets.QCheckBox())
daughtertable.setCellWidget(newrow, 1, checkbox)
corto = QtWidgets.QComboBox()
corto.setFrame(False)
......@@ -175,17 +205,19 @@ def add_line(parent_widget, mass_selector, spectrum, ds, parenttable, daughterta
corfact = setDoubleCell(daughtertable, newrow, 3)
update_drl(start_mz, end_mz, ionspect, ds, pname, dname,
parenttable, daughtertable)
parenttable, daughtertable, drlspectrum)
pname.editingFinished.connect(lambda: update_drl(
start_mz, end_mz, ionspect, ds, pname, dname, parenttable,
daughtertable))
daughtertable, drlspectrum))
start_mz.editingFinished.connect(lambda: update_drl(
start_mz, end_mz, ionspect, ds, pname, dname, parenttable,
daughtertable))
daughtertable, drlspectrum))
end_mz.editingFinished.connect(lambda: update_drl(
start_mz, end_mz, ionspect, ds, pname, dname, parenttable,
daughtertable))
daughtertable, drlspectrum))
checkbox.stateChanged.connect(lambda: update_drlspectrum(
parenttable, daughtertable, ds, drlspectrum))
def iontable(labels, exp_col):
......@@ -207,8 +239,8 @@ def iontable(labels, exp_col):
def dialog(parent, ds, filename, mass_selector, spectrum, cache):
"""constructs a dialog window"""
def savecache(cache,pt,dt):
cache[0], cache[1] = pt, dt
def savecache(cache,pt,dt,canvas):
cache[0], cache[1], cache[2] = pt, dt, canvas
dial_widget = QtWidgets.QDialog(
parent, windowTitle='Delayed reactant labelling')
......@@ -218,6 +250,12 @@ def dialog(parent, ds, filename, mass_selector, spectrum, cache):
graph_canvas = FigureCanvas(dial_graph)
graph_canvas.setStyleSheet("background-color:transparent;")
graph_canvas.setAutoFillBackground(False)
graphlabels = dict(x=[0], y=[0], line=None, name="",
xlabel="time(min)", ylabel="relative intensity")
gt.pan_factory(chromplot)
gt.zoom_factory(chromplot, 1.15)
gt.pop_plot(chromplot, graphlabels)
drl_load = QtWidgets.QPushButton("&Load")
drl_save = QtWidgets.QPushButton("&Save")
......@@ -230,7 +268,7 @@ def dialog(parent, ds, filename, mass_selector, spectrum, cache):
# pt = parenttable
# dt = daughtertable
if cache == [None, None]:
if cache == [None, None, None]:
dt = iontable(["","Name", "corrected to", "factor"], 2)
dt.horizontalHeader().setSectionResizeMode(
0, QtWidgets.QHeaderView.ResizeToContents)
......@@ -239,16 +277,17 @@ def dialog(parent, ds, filename, mass_selector, spectrum, cache):
pt = iontable(["Name", "start (m/z)", "end (m/z)", "profile"], 2)
for i in range(5):
add_line(dial_widget, mass_selector, spectrum, ds, pt, dt)
add_line(dial_widget, mass_selector, spectrum, ds, pt, dt,
chromplot)
else:
pt = cache[0]
dt = cache[1]
graph_canvas = cache[2]
btn_add.clicked.connect(lambda: add_line(
dial_widget, mass_selector, spectrum, ds, pt, dt))
dial_widget, mass_selector, spectrum, ds, pt, dt, chromplot))
btn_rem.clicked.connect(lambda: remove_rows(pt,dt))
dial_widget.finished.connect(lambda: savecache(cache, pt, dt))
dial_widget.finished.connect(lambda: savecache(cache, pt, dt, graph_canvas))
main_layout = QtWidgets.QVBoxLayout(dial_widget)
sub_layout = QtWidgets.QHBoxLayout()
......
import numpy as np
import prasopes.datatools as dt
def zoom_factory(axis, base_scale, plot_data=None):
......@@ -95,10 +96,7 @@ def pick_times(x_min, x_max, mpl_spectrum, data_set, mpl_chromatogram,
chrom_spect['t_start'] = x_min
chrom_spect['t_end'] = x_max
times = data_set['chrom_dat'][0, :]
timesarg = np.where((times >= x_min) & (times <= x_max))[0]
if len(timesarg) == 0:
aver = (x_min+x_max)/2
timesarg = [(np.abs(times - aver)).argmin()]
timesarg = dt.argsubselect(times, x_min, x_max)
slims = [mpl_spectrum.get_xlim(), mpl_spectrum.get_ylim()]
mpl_spectrum.clear()
mass_spect['annotation'].clear()
......
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