Commit 2b8cfd90 authored by Yan's avatar Yan
Browse files

PEP8 style clean-up

parent 088b2627
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"""
......@@ -13,6 +14,7 @@ def floatize(imptext):
outfloat = 0
return outfloat
def argsubselect(array, minimum, maximum):
"""finds arguments which fits into boundary conditions,
if there is no fit, return nearest argument"""
......
#!/usr/bin/env python3
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.widgets import SpanSelector
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtPrintSupport
import sys
import matplotlib
import numpy as np
import prasopes.datatools as dt
......@@ -14,6 +12,7 @@ import prasopes.graphtools as gt
import prasopes.filetools as ft
matplotlib.use("Qt5Agg")
class HBar(QtWidgets.QFrame):
"""horizontal bar class"""
def __init__(self):
......@@ -24,8 +23,8 @@ class HBar(QtWidgets.QFrame):
def update_profile(start, end, spectrum, dataset):
"""spectrum updating procedure"""
#Dont do anything to graph when the spectrum is not populated
if (type(dataset['masses'])) == type(None):
# Dont do anything to graph when the spectrum is not populated
if isinstance(dataset['masses'], type(None)):
return
masses = dataset['masses']
......@@ -48,65 +47,66 @@ def update_profile(start, end, spectrum, dataset):
def get_daughterset(ptable, dtable, ds):
names = []
times = ds['chrom_dat'][0,:]
times = ds['chrom_dat'][0, :]
intensities = []
#TODO: resolve intensities trouble
# TODO: resolve intensities trouble
for row in range(dtable.rowCount()):
if dtable.cellWidget(row, 0).checkState() == 2:
startm = dt.floatize(ptable.cellWidget(row,1).text())
endm = dt.floatize(ptable.cellWidget(row,2).text())
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, 1).currentIndex()-1
if cor != -1:
factor = dt.floatize(dtable.cellWidget(row,2).text())
startm = dt.floatize(ptable.cellWidget(cor,1).text())
endm = dt.floatize(ptable.cellWidget(cor,2).text())
factor = dt.floatize(dtable.cellWidget(row, 2).text())
startm = dt.floatize(ptable.cellWidget(cor, 1).text())
endm = dt.floatize(ptable.cellWidget(cor, 2).text())
massargs = dt.argsubselect(ds['masses'], startm, endm)
correction = ((np.sum(
ds['matrix'].T[massargs].T, axis=1))\
ds['matrix'].T[massargs].T, axis=1))
/ ds['chrom_dat'][1]) * factor
intensity = intensity - correction
intensities.append(intensity)
names.append(dtable.item(row,0).text())
names.append(dtable.item(row, 0).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):
# Dont do when the dataset is not populated
if isinstance(ds['masses'], type(None)):
return
colors = np.array([[255,0,0],[0,255,0],[0,0,255],[0,200,255],[255,0,255],[255,200,0]])
colors = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255],
[0, 200, 255], [255, 0, 255], [255, 200, 0]])
names, times, intensities = get_daughterset(ptable, dtable, ds)
for i in range(len(drlspectrum.lines)):
drlspectrum.lines[0].remove()
for i,j in enumerate(intensities):
for i, j in enumerate(intensities):
drlspectrum.plot(times, j, label=names[i],
color=(colors[i%len(colors)] / 255))
color=(colors[i % len(colors)] / 255))
if len(names) != 0:
drlspectrum.set_ylim(top=np.amax(intensities)*1.1,
bottom=np.amax(intensities)*-0.01)
bottom=np.amax(intensities)*-0.01)
drlspectrum.legend()
drlspectrum.figure.canvas.draw()
count = 0
for row in range(dtable.rowCount()):
if dtable.cellWidget(row, 0).checkState() ==2:
dtable.item(row,0).setBackground(QtGui.QBrush(
QtGui.QColor(*colors[count%len(colors)], alpha=50)))
if dtable.cellWidget(row, 0).checkState() == 2:
dtable.item(row, 0).setBackground(QtGui.QBrush(
QtGui.QColor(*colors[count % len(colors)], alpha=50)))
count += 1
else:
dtable.item(row,0).setBackground(QtGui.QBrush())
dtable.item(row, 0).setBackground(QtGui.QBrush())
def getTableItemList(ptable):
def gettableitemlist(ptable):
ion_list = []
for row in range(ptable.rowCount()):
text = []
for i in range(3):
if type(ptable.cellWidget(row, i)) is not type(None):
if not isinstance(ptable.cellWidget(row, i), type(None)):
frg = ptable.cellWidget(row, i).text()
else:
frg = ""
......@@ -116,8 +116,8 @@ def getTableItemList(ptable):
return ion_list
def update_drl(start_mz, end_mz, spectrum, dataset, pname, dname,
ptable, dtable, drlspectrum):
def update_drl(start_mz, end_mz, spectrum, dataset, pname,
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]
......@@ -133,14 +133,14 @@ def update_drl(start_mz, end_mz, spectrum, dataset, pname, dname,
if float(0) not in (start, end) and pname.text() is "":
pname.setText(str(int((start+end)/2)))
ptnames = getTableItemList(ptable)
ptnames = gettableitemlist(ptable)
for row in range(dtable.rowCount()):
dtable.item(row,0).setText(ptnames[row])
index = dtable.cellWidget(row,1).currentIndex()
dtable.cellWidget(row,1).clear()
dtable.cellWidget(row,1).addItem("")
dtable.cellWidget(row,1).addItems(getTableItemList(ptable))
dtable.cellWidget(row,1).setCurrentIndex(index)
dtable.item(row, 0).setText(ptnames[row])
index = dtable.cellWidget(row, 1).currentIndex()
dtable.cellWidget(row, 1).clear()
dtable.cellWidget(row, 1).addItem("")
dtable.cellWidget(row, 1).addItems(gettableitemlist(ptable))
dtable.cellWidget(row, 1).setCurrentIndex(index)
update_profile(start, end, spectrum, dataset)
update_drlspectrum(ptable, dtable, dataset, drlspectrum)
......@@ -149,40 +149,39 @@ def update_drl(start_mz, end_mz, spectrum, dataset, pname, dname,
def remove_rows(ptable, dtable):
# TODO: maybe nicer selection in future, but this works for now
rows = reversed(list(set(
map(lambda index: index.row(), ptable.selectedIndexes()))))
map(lambda x: x.row(), ptable.selectedIndexes()))))
for row in rows:
dtable.removeRow(row)
ptable.removeRow(row)
for i in range(dtable.rowCount()):
index = dtable.cellWidget(i,1).currentIndex()
dtable.cellWidget(i,1).clear()
dtable.cellWidget(i,1).addItem("")
dtable.cellWidget(i,1).addItems(getTableItemList(ptable))
index = dtable.cellWidget(i, 1).currentIndex()
dtable.cellWidget(i, 1).clear()
dtable.cellWidget(i, 1).addItem("")
dtable.cellWidget(i, 1).addItems(gettableitemlist(ptable))
if index == row+1:
dtable.cellWidget(i,1).setCurrentIndex(0)
dtable.cellWidget(i, 1).setCurrentIndex(0)
elif index > row+1:
dtable.cellWidget(i,1).setCurrentIndex(index-1)
dtable.cellWidget(i, 1).setCurrentIndex(index-1)
def setDoubleCell(table, row, column):
def setdoublecell(table, row, column):
"""populate table cell with float-validated posititve text"""
table.setCellWidget(row,column,QtWidgets.QLineEdit())
table.setCellWidget(row, column, QtWidgets.QLineEdit())
validator = QtGui.QDoubleValidator()
validator.setBottom(0)
table.cellWidget(row,column).setValidator(validator)
table.cellWidget(row,column).setFrame(False)
table.cellWidget(row,column).setText("0")
table.cellWidget(row, column).setValidator(validator)
table.cellWidget(row, column).setFrame(False)
table.cellWidget(row, column).setText("0")
table.horizontalHeader().setSectionResizeMode(
column, QtWidgets.QHeaderView.ResizeToContents)
return table.cellWidget(row,column)
return table.cellWidget(row, column)
def add_line(parent_widget, ds, parenttable,
daughtertable, drlspectrum):
def add_line(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),
position=(-0.01,-0.01,1.02,1.02))
ionspect = ion_graph.add_subplot(
111, facecolor=(1, 1, 1, 0.8), position=(-0.01, -0.01, 1.02, 1.02))
graph_canvas = FigureCanvas(ion_graph)
graph_canvas.setStyleSheet("background-color:transparent;")
graph_canvas.setAutoFillBackground(False)
......@@ -193,8 +192,8 @@ def add_line(parent_widget, ds, parenttable,
pname = QtWidgets.QLineEdit()
pname.setFrame(False)
parenttable.setCellWidget(newrow, 0, pname)
start_mz = setDoubleCell(parenttable, newrow, 1)
end_mz = setDoubleCell(parenttable, newrow, 2)
start_mz = setdoublecell(parenttable, newrow, 1)
end_mz = setdoublecell(parenttable, newrow, 2)
parenttable.setCellWidget(newrow, 3, graph_canvas)
if newrow is not 0:
for i in range(3):
......@@ -204,7 +203,7 @@ def add_line(parent_widget, ds, parenttable,
daughtertable.setRowCount(newrow + 1)
#TODO: decide which box will be used in the final version
# TODO: decide which box will be used in the final version
checkbox = QtWidgets.QCheckBox()
dname = QtWidgets.QTableWidgetItem()
dname.setFlags(dname.flags() & ~QtCore.Qt.ItemIsEditable)
......@@ -215,28 +214,28 @@ def add_line(parent_widget, ds, parenttable,
corto = QtWidgets.QComboBox()
corto.setFrame(False)
corto.addItem("")
corto.addItems(getTableItemList(parenttable))
corto.addItems(gettableitemlist(parenttable))
daughtertable.setCellWidget(newrow, 1, corto)
corfact = setDoubleCell(daughtertable, newrow, 2)
setdoublecell(daughtertable, newrow, 2)
update_drl(start_mz, end_mz, ionspect, ds, pname, dname,
parenttable, daughtertable, drlspectrum)
update_drl(start_mz, end_mz, ionspect, ds, pname,
parenttable, daughtertable, drlspectrum)
pname.editingFinished.connect(lambda: update_drl(
start_mz, end_mz, ionspect, ds, pname, dname, parenttable,
start_mz, end_mz, ionspect, ds, pname, parenttable,
daughtertable, drlspectrum))
start_mz.editingFinished.connect(lambda: update_drl(
start_mz, end_mz, ionspect, ds, pname, dname, parenttable,
start_mz, end_mz, ionspect, ds, pname, parenttable,
daughtertable, drlspectrum))
end_mz.editingFinished.connect(lambda: update_drl(
start_mz, end_mz, ionspect, ds, pname, dname, parenttable,
start_mz, end_mz, ionspect, ds, pname, parenttable,
daughtertable, drlspectrum))
checkbox.stateChanged.connect(lambda: update_drlspectrum(
parenttable, daughtertable, ds, drlspectrum))
def iontable(labels, exp_col):
def iontable(labels):
"""creates a table for ions"""
table = QtWidgets.QTableWidget(columnCount=len(labels))
table.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
......@@ -247,7 +246,7 @@ def iontable(labels, exp_col):
for n in range(table.columnCount()):
table.horizontalHeader().setSectionResizeMode(
n, QtWidgets.QHeaderView.Stretch)
table.setMinimumSize(600,0)
table.setMinimumSize(600, 0)
return table
......@@ -266,8 +265,8 @@ def load_drltables(parent, ptable, dtable, dataset, drlspectrum):
with open(filename, 'r') as cfile:
rawdata = cfile.read().splitlines()
for i in range(1,len(rawdata)):
rawline=rawdata[i].split(",")
for i in range(1, len(rawdata)):
rawline = rawdata[i].split(",")
if len(rawline) != 6 or int(rawline[3]) not in range(3) \
or int(rawline[4]) not in range(len(rawdata)):
QtWidgets.QMessageBox.warning(
......@@ -276,19 +275,19 @@ def load_drltables(parent, ptable, dtable, dataset, drlspectrum):
" cancelling request".format(i+1))
return
for j, k in enumerate((names, start_masses, end_masses,
states, corrected_to, corr_factors)):
states, corrected_to, corr_factors)):
k.append(rawline[j])
for row in reversed(range(ptable.rowCount())):
dtable.removeRow(row)
ptable.removeRow(row)
#first populate only parent table
# first populate only parent table
for i in range(len(names)):
add_line(parent, dataset, ptable, dtable, drlspectrum)
add_line(dataset, ptable, dtable, drlspectrum)
print(names[i])
ptable.cellWidget(i, 0).setText(names[i])
ptable.cellWidget(i, 1).setText(start_masses[i])
ptable.cellWidget(i, 2).setText(end_masses[i])
#and after that daughter table
# and after that daughter table
for i in range(len(names)):
dtable.cellWidget(i, 1).setCurrentIndex(
int(corrected_to[i]))
......@@ -308,11 +307,10 @@ def save_drlconfig(ptable, dtable, parent):
for row in range(ptable.rowCount()):
vals = []
for i in range(3):
vals.append(ptable.cellWidget(row,i).text())
vals.append(dtable.cellWidget(row,0).checkState())
vals.append(dtable.cellWidget(row,1).currentIndex())
vals.append(dtable.cellWidget(row,2).text())
#vals = ",".join(map(str, vals))
vals.append(ptable.cellWidget(row, i).text())
vals.append(dtable.cellWidget(row, 0).checkState())
vals.append(dtable.cellWidget(row, 1).currentIndex())
vals.append(dtable.cellWidget(row, 2).text())
expf.write("{}\n".format((",".join(map(str, vals)))))
expf.close()
......@@ -330,7 +328,7 @@ def export_drlspectrum(parent, fn, ptable, dtable, ds):
expf = open(exp_f_name, 'w')
expf.write("times, {}\n".format((",".join(names))))
for i in range(len(times)):
dataset = []
dataset = list()
dataset.append(times[i])
for intensity in intensities:
dataset.append(intensity[i])
......@@ -339,39 +337,35 @@ def export_drlspectrum(parent, fn, ptable, dtable, ds):
def print_graph(labels, ptable, dtable, ds):
printfig = Figure(figsize=(5,2), dpi=100)
printfig = Figure(figsize=(5, 2), dpi=100)
printplot = printfig.add_subplot(111)
printcanvas = FigureCanvas(printfig)
gt.pop_plot(printplot, labels)
update_drlspectrum(ptable, dtable, ds, printplot)
widget = QtWidgets.QDialog(None,
windowTitle='Print preview')
widget = QtWidgets.QDialog(None, windowTitle='Print preview')
layout = QtWidgets.QVBoxLayout(widget)
layout.addWidget(printcanvas)
widget.resize(600,400)
widget.resize(600, 400)
widget.show()
dialog = QtPrintSupport.QPrintDialog()
if dialog.exec_() == QtWidgets.QDialog.Accepted:
#dialog.printer().setFullPage(False)
#printcanvas.render(dialog.printer())
#graph.canvas.render(dialog.printer())
printcanvas.render(dialog.printer())
widget.close()
def main_window(parent, ds, filename, cache):
"""constructs a dialog window"""
def saveonclose(window, event, cache,pt,dt,canvas):
cache[0], cache[1], cache[2] = pt, dt, canvas
QtWidgets.QMainWindow.closeEvent(window, event)
def saveonclose(widget, event, buffer, ptable, dtable, canvas):
buffer[0], buffer[1], buffer[2] = ptable, dtable, canvas
QtWidgets.QMainWindow.closeEvent(widget, event)
main_window = QtWidgets.QMainWindow(
window = QtWidgets.QMainWindow(
parent, windowTitle='Delayed reactant labelling')
dial_widget = QtWidgets.QWidget(main_window)
main_window.setCentralWidget(dial_widget)
main_widget = QtWidgets.QWidget(window)
window.setCentralWidget(main_widget)
main_window.closeEvent = lambda event: saveonclose(
main_window, event, cache, pt, dt, graph_canvas)
window.closeEvent = lambda event: saveonclose(
window, event, cache, pt, dt, graph_canvas)
dial_graph = Figure(figsize=(5, 2), dpi=100, facecolor="None")
chromplot = dial_graph.add_subplot(111, facecolor=(1, 1, 1, 0.8))
......@@ -379,18 +373,18 @@ def main_window(parent, ds, filename, cache):
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")
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")
drl_export = QtWidgets.QPushButton("&Export")
drl_print = QtWidgets.QPushButton("&Print")
close = QtWidgets.QPushButton("&Close")
close.clicked.connect(main_window.close)
close.clicked.connect(window.close)
btn_add = QtWidgets.QPushButton("&Add")
btn_rem = QtWidgets.QPushButton("Remove")
......@@ -398,33 +392,32 @@ def main_window(parent, ds, filename, cache):
# pt = parenttable
# dt = daughtertable
if cache == [None, None, None]:
dt = iontable(["","Name", "corrected to", "factor"], 2)
dt = iontable(["", "Name", "corrected to", "factor"])
dt.horizontalHeader().setSectionResizeMode(
0, QtWidgets.QHeaderView.ResizeToContents)
dt.horizontalHeader().setSectionResizeMode(
3, QtWidgets.QHeaderView.Fixed)
pt = iontable(["Name", "start (m/z)", "end (m/z)", "profile"], 2)
add_line(dial_widget, ds, pt, dt, chromplot)
pt = iontable(["Name", "start (m/z)", "end (m/z)", "profile"])
add_line(ds, pt, dt, chromplot)
else:
pt = cache[0]
dt = cache[1]
graph_canvas = cache[2]
btn_add.clicked.connect(lambda: add_line(
dial_widget, ds, pt, dt, chromplot))
ds, pt, dt, chromplot))
btn_rem.clicked.connect(lambda: remove_rows(pt,dt))
drl_load.clicked.connect(lambda: load_drltables(
dial_widget, pt, dt, ds, chromplot))
main_widget, pt, dt, ds, chromplot))
drl_save.clicked.connect(lambda: save_drlconfig(
pt, dt, dial_widget))
pt, dt, main_widget))
drl_print.clicked.connect(lambda: print_graph(
graphlabels, pt, dt, ds))
drl_export.clicked.connect(lambda: export_drlspectrum(
dial_widget, filename, pt, dt, ds))
main_widget, filename, pt, dt, ds))
main_layout = QtWidgets.QVBoxLayout(dial_widget)
main_layout = QtWidgets.QVBoxLayout(main_widget)
sub_layout = QtWidgets.QHBoxLayout()
tablelayout = QtWidgets.QVBoxLayout()
pt_butlayout = QtWidgets.QHBoxLayout()
......@@ -454,4 +447,4 @@ def main_window(parent, ds, filename, cache):
tablelayout.addWidget(QtWidgets.QLabel("Corrected ions table:"))
tablelayout.addWidget(dt)
main_window.show()
window.show()
......@@ -21,7 +21,7 @@ def get_save_filename(caption, fnfilter, suffix, parent):
and thus also cant check for file with the selected suffix"""
filename = QtWidgets.QFileDialog.getSaveFileName(
caption=caption, filter=fnfilter,
options = QtWidgets.QFileDialog.DontConfirmOverwrite)[0]
options=QtWidgets.QFileDialog.DontConfirmOverwrite)[0]
if suffix[0] is not ".":
suffix = ".{}".format(suffix)
if filename[-len(suffix):] != suffix:
......
......@@ -190,7 +190,6 @@ def pop_plot(plot, plot_data):
plot.tick_params(axis='y', which='minor', left=False)
def populate(mpl_chromatogram, mpl_spectrum, data_set,
mass_spect, chrom_spect):
"""populate the GUI plots with desired dataset"""
......
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