Commit 7865a269 authored by 3Yan's avatar 3Yan
Browse files

PEP8, reactivity hidable legend, debloated

* PEP8 code-cleanup
* the legend of reactivitytools can be hidden
* code has been rewritten to reduce line-count
parent 924443d3
...@@ -13,7 +13,7 @@ from . import zcetools_help ...@@ -13,7 +13,7 @@ from . import zcetools_help
from . import reactivitytools from . import reactivitytools
__version__ = "0.0.28" __version__ = "0.0.29"
__all__ = ['config', 'datatools', 'docks', 'drltools', 'drltoos_gui', 'filetools', __all__ = ['config', 'datatools', 'docks', 'drltools', 'drltoos_gui', 'filetools',
......
...@@ -278,10 +278,12 @@ def main(): ...@@ -278,10 +278,12 @@ def main():
p_logger = logging.getLogger('parseLogger') p_logger = logging.getLogger('parseLogger')
params_logger = logging.getLogger('acqLogLogger') params_logger = logging.getLogger('acqLogLogger')
drl_logger = logging.getLogger('drlLogger') drl_logger = logging.getLogger('drlLogger')
zce_logger = logging.getLogger('zceLogger') zce_logger = logging.getLogger('zcelogger')
rxn_logger = logging.getLogger('reactivityLogger')
logging.basicConfig() logging.basicConfig()
# p_logger.setLevel("WARN") # p_logger.setLevel("WARN")
p_logger.setLevel("DEBUG") p_logger.setLevel("DEBUG")
rxn_logger.setLevel("DEBUG")
# drl_logger.setLevel("INFO") # drl_logger.setLevel("INFO")
drl_logger.setLevel("DEBUG") drl_logger.setLevel("DEBUG")
zce_logger.setLevel("DEBUG") zce_logger.setLevel("DEBUG")
......
...@@ -5,7 +5,6 @@ from matplotlib.figure import Figure ...@@ -5,7 +5,6 @@ from matplotlib.figure import Figure
from PyQt5 import QtCore from PyQt5 import QtCore
from PyQt5 import QtWidgets from PyQt5 import QtWidgets
from PyQt5 import QtGui from PyQt5 import QtGui
from PyQt5 import QtPrintSupport
from io import BytesIO from io import BytesIO
import matplotlib import matplotlib
import numpy as np import numpy as np
...@@ -20,13 +19,26 @@ matplotlib.use("Qt5Agg") ...@@ -20,13 +19,26 @@ matplotlib.use("Qt5Agg")
logger = logging.getLogger('reactivityLogger') logger = logging.getLogger('reactivityLogger')
settings = cf.settings()
class reactivityParam(QtWidgets.QHBoxLayout): class reactivityParam(QtWidgets.QHBoxLayout):
def __init__(self, parselect, type, valname, vallabel, min=None, max=None, decimals=4): """Layout with annotated text/spin box connected to settings"""
def __init__(self, parselect, type, valname, vallabel,
min=None, max=None, decimals=4):
super().__init__() super().__init__()
self.valname = valname self.valname = valname
self.addWidget(QtWidgets.QLabel(vallabel, alignment=130)) self.addWidget(QtWidgets.QLabel(vallabel, alignment=130))
def getconfval(name=self.valname, parselect=parselect):
par = "reactivity/{}_par{}".format(name, parselect.currentIndex())
logger.debug("Getting "+par)
return settings.value(par, type=type)
def setconfval(x, name=self.valname, parselect=parselect):
par = "reactivity/{}_par{}".format(name, parselect.currentIndex())
logger.debug("Setting "+par)
settings.setValue(par, x)
if type in (int, float): if type in (int, float):
if type == float: if type == float:
self.dial = QtWidgets.QDoubleSpinBox( self.dial = QtWidgets.QDoubleSpinBox(
...@@ -35,29 +47,18 @@ class reactivityParam(QtWidgets.QHBoxLayout): ...@@ -35,29 +47,18 @@ class reactivityParam(QtWidgets.QHBoxLayout):
elif type == int: elif type == int:
self.dial = QtWidgets.QSpinBox( self.dial = QtWidgets.QSpinBox(
minimum=(min or 0), maximum=(max or 255)) minimum=(min or 0), maximum=(max or 255))
self.dial.setValue(cf.settings().value( self.dial.setValue(getconfval())
"reactivity/{}_par{}".format( self.dial.valueChanged.connect(setconfval)
self.valname, parselect.currentIndex()), type=type)) parselect.currentIndexChanged.connect(
self.dial.valueChanged.connect(lambda x, y=parselect: lambda _: self.dial.setValue(getconfval()))
cf.settings().setValue("reactivity/{}_par{}".format(
self.valname, y.currentIndex()), x))
parselect.currentIndexChanged.connect(lambda x:
self.dial.setValue(cf.settings().value(
"reactivity/{}_par{}".format(
self.valname, x), type=type)))
elif type == str: elif type == str:
self.dial = QtWidgets.QLineEdit() self.dial = QtWidgets.QLineEdit()
self.dial.setText(cf.settings().value( self.dial.setText(getconfval())
"reactivity/{}_par{}".format( self.dial.textChanged.connect(setconfval)
self.valname, parselect.currentIndex()), type=type)) parselect.currentIndexChanged.connect(
self.dial.textChanged.connect(lambda x, y=parselect: lambda _: self.dial.setText(getconfval()))
cf.settings().setValue("reactivity/{}_par{}".format(
self.valname, y.currentIndex()), x))
parselect.currentIndexChanged.connect(lambda x:
self.dial.setText(cf.settings().value(
"reactivity/{}_par{}".format(self.valname, x), type=type)))
else: else:
raise ValueError("excepted 'float', 'str', 'int' as type") raise ValueError("excepted 'float', 'str' or 'int' as type")
self.addWidget(self.dial, stretch=1) self.addWidget(self.dial, stretch=1)
...@@ -66,6 +67,7 @@ def key_pressed(event, augCanvas, drls, grph, labels, parselect): ...@@ -66,6 +67,7 @@ def key_pressed(event, augCanvas, drls, grph, labels, parselect):
if event.modifiers().__int__() == QtCore.Qt.ControlModifier: if event.modifiers().__int__() == QtCore.Qt.ControlModifier:
clip_spect_img(augCanvas, drls, grph, labels, parselect) clip_spect_img(augCanvas, drls, grph, labels, parselect)
def export_dial(augCanvas, drls, grph, labels, parselect): def export_dial(augCanvas, drls, grph, labels, parselect):
"""exports the reactivity into the .dat file format""" """exports the reactivity into the .dat file format"""
if not augCanvas.filename: if not augCanvas.filename:
...@@ -78,17 +80,20 @@ def export_dial(augCanvas, drls, grph, labels, parselect): ...@@ -78,17 +80,20 @@ def export_dial(augCanvas, drls, grph, labels, parselect):
if exp_f_name != '': if exp_f_name != '':
names = ["pressure", "rel._intensity"] names = ["pressure", "rel._intensity"]
units = ["mTorr", ""] units = ["mTorr", ""]
description=os.path.basename(augCanvas.filename) description = os.path.basename(augCanvas.filename)
expf = open(exp_f_name, 'w') expf = open(exp_f_name, 'w')
expf.write(dt.specttostr(grph, " ", names, units, description)) expf.write(dt.specttostr(grph, " ", names, units, description))
expf.close expf.close
def update_parselect(augCanvas, parselect): def update_parselect(augCanvas, parselect):
# Do not do anything when data set is not populated
if len(augCanvas.ds) == 0:
return
index = parselect.currentIndex() index = parselect.currentIndex()
if index == -1: if index == -1:
index = cf.settings().value("reactivity/index", type=int) index = settings.value("reactivity/index", type=int)
parlist = [ ": ".join([str(i), j]) for i,j in parlist = [": ".join([str(i), j]) for i, j in
enumerate(augCanvas.ms['params'][0])] enumerate(augCanvas.ms['params'][0])]
parselect.clear() parselect.clear()
parselect.addItems(parlist) parselect.addItems(parlist)
...@@ -97,7 +102,7 @@ def update_parselect(augCanvas, parselect): ...@@ -97,7 +102,7 @@ def update_parselect(augCanvas, parselect):
def paint_image(augCanvas, drls, grph, labels, parselect): def paint_image(augCanvas, drls, grph, labels, parselect):
paintfig = Figure(figsize=(3.5,2), dpi=300, constrained_layout=True) paintfig = Figure(figsize=(3.5, 2), dpi=300, constrained_layout=True)
FigureCanvas(paintfig) FigureCanvas(paintfig)
printplot = paintfig.add_subplot(111) printplot = paintfig.add_subplot(111)
pop_dial(augCanvas, drls, printplot, labels, parselect) pop_dial(augCanvas, drls, printplot, labels, parselect)
...@@ -112,35 +117,48 @@ def paint_image(augCanvas, drls, grph, labels, parselect): ...@@ -112,35 +117,48 @@ def paint_image(augCanvas, drls, grph, labels, parselect):
def clip_spect_img(augCanvas, drls, grph, labels, parselect): def clip_spect_img(augCanvas, drls, grph, labels, parselect):
image=paint_image(augCanvas, drls, grph, labels, parselect) image = paint_image(augCanvas, drls, grph, labels, parselect)
QtWidgets.QApplication.clipboard().clear() QtWidgets.QApplication.clipboard().clear()
[QtWidgets.QApplication.clipboard().setImage(image, i) for i in range(2)] [QtWidgets.QApplication.clipboard().setImage(image, i) for i in range(2)]
def pop_dial(augCanvas, drls, graph, labels, parselect): def pop_dial(augCanvas, drls, graph, labels, parselect):
logger.debug("populating reactivity dialog") logger.debug("populating reactivity dialog")
# Do not do anything when data set is not populated # Do not do anything when data set is not populated
if len(augCanvas.ds) == 0: if len(augCanvas.ds) == 0:
return return
parint = parselect.currentIndex() parint = parselect.currentIndex()
coef1 = cf.settings().value("reactivity/coef1_par{}".format(parint), type=float) coef1 = settings.value(
coef2 = cf.settings().value("reactivity/coef2_par{}".format(parint), type=float) "reactivity/coef_a_par{}".format(parint), type=float)
markersize = cf.settings().value("reactivity/markersize", type=float) coef2 = settings.value(
"reactivity/coef_b_par{}".format(parint), type=float)
markersize = settings.value(
"reactivity/markersize_par{}".format(parint), type=float)
showlabel = settings.value(
"reactivity/showlabel_par{}".format(parint), type=int)
graph.clear() graph.clear()
gt.pop_plot([0], [0], graph, labels) gt.pop_plot([0], [0], graph, labels)
names, times, intensities = drl.get_daughterset(augCanvas.ds, drls) names, times, intensities = drl.get_daughterset(augCanvas.ds, drls)
colorargs = [row for row in range(drls['dt'].rowCount()) colorargs = [row for row in range(drls['dt'].rowCount())
if drls['dt'].cellWidget(row, 0).checkState() == 2] if drls['dt'].cellWidget(row, 0).checkState() == 2]
if len(names) < 2:
return
params = augCanvas.ms['params'][1] params = augCanvas.ms['params'][1]
parlen = len(params) parlen = len(params)
if len(names) < 2:
return
try:
float(params[0][parselect.currentIndex()])
except ValueError:
QtWidgets.QMessageBox.warning(
None, "Unsupported parameter",
"This parameter is not supported for mathematical evaluation\n"
"or no parameters were loaded. Please change the parameter")
return
pressures = [] pressures = []
lastpos = 0 lastpos = 0
for time in times: for time in times:
toavg = [] toavg = []
for i in range(lastpos,parlen): for i in range(lastpos, parlen):
if float(params[i][0]) == time: if float(params[i][0]) == time:
toavg.append((float( toavg.append((float(
params[i][parselect.currentIndex()])-coef1)*coef2) params[i][parselect.currentIndex()])-coef1)*coef2)
...@@ -152,27 +170,30 @@ def pop_dial(augCanvas, drls, graph, labels, parselect): ...@@ -152,27 +170,30 @@ def pop_dial(augCanvas, drls, graph, labels, parselect):
if len(toavg) != 0: if len(toavg) != 0:
pressures.append([time, np.average(toavg)]) pressures.append([time, np.average(toavg)])
if len(pressures) == 0: if len(pressures) == 0:
QtWidgets.QMessageBox.critical(None, "No times loaded", QtWidgets.QMessageBox.critical(
"Did not located any valid parameters.\n" None, "No times loaded",
"It is either start of the acquisition,\n" "Did not located any valid parameters.\n"
"or the timestamps has been corrupted.") "It is either start of the acquisition,\n"
"or the timestamps has been corrupted.")
return return
nptpressures = np.asarray(pressures).T[0] nptpressures = np.asarray(pressures).T[0]
goodtimes = np.where([t in nptpressures for t in times]) goodtimes = np.where([t in nptpressures for t in times])
alpha = cf.settings().value("reactivity/transparency_par{}".format(parint), type=int) alpha = settings.value("reactivity/transparency_par{}".format(
parint), type=int)
transcolors = [np.append(i, alpha) for i in gt.colors] transcolors = [np.append(i, alpha) for i in gt.colors]
for i in range(1,len(intensities)): for i in range(1, len(intensities)):
label = drls['pt'].item(colorargs[i], 0).text() label = drls['pt'].item(colorargs[i], 0).text()
relint = np.divide(intensities[i], np.clip(np.sum( relint = np.divide(intensities[i], np.clip(np.sum(
intensities, 0), np.finfo(np.float32).eps, None), intensities, 0), np.finfo(np.float32).eps, None),
dtype=np.float64) dtype=np.float64)
graph.plot(np.asarray(pressures).T[1], relint[goodtimes], graph.plot(np.asarray(pressures).T[1], relint[goodtimes],
label=label, color=(transcolors[ label=label, color=(transcolors[
colorargs[i] % len(transcolors)] / 255), marker=".", colorargs[i] % len(transcolors)] / 255), marker=".",
markersize=markersize, linestyle="None") markersize=markersize, linestyle="None")
legend = graph.legend( if showlabel:
loc=cf.settings().value("reactivity/labelloc", type=float)) legend = graph.legend(loc=settings.value(
[lh._legmarker.set_alpha(1) for lh in legend.legendHandles] "reactivity/labelloc_par{}".format(parint), type=float))
[lh._legmarker.set_alpha(1) for lh in legend.legendHandles]
graph.autoscale(True) graph.autoscale(True)
graph.figure.canvas.draw() graph.figure.canvas.draw()
...@@ -181,6 +202,7 @@ def pop_dial(augCanvas, drls, graph, labels, parselect): ...@@ -181,6 +202,7 @@ def pop_dial(augCanvas, drls, graph, labels, parselect):
def main_window(parent, augCanvas, update_signal, drls): def main_window(parent, augCanvas, update_signal, drls):
"""constructs a dialog window""" """constructs a dialog window"""
reactlabels = dict(name="", xlabel="pressure (mT)", ylabel="rel intensity") reactlabels = dict(name="", xlabel="pressure (mT)", ylabel="rel intensity")
def onclose(widget, event, update_fnc): def onclose(widget, event, update_fnc):
logger.debug("ZCE window custom close routine called") logger.debug("ZCE window custom close routine called")
update_signal.signal.disconnect(update_fnc) update_signal.signal.disconnect(update_fnc)
...@@ -206,13 +228,13 @@ def main_window(parent, augCanvas, update_signal, drls): ...@@ -206,13 +228,13 @@ def main_window(parent, augCanvas, update_signal, drls):
parlabel = QtWidgets.QLabel("Parameter: ") parlabel = QtWidgets.QLabel("Parameter: ")
parselect = QtWidgets.QComboBox() parselect = QtWidgets.QComboBox()
parint = parselect.currentIndex()
update_parselect(augCanvas, parselect) update_parselect(augCanvas, parselect)
parselect.currentIndexChanged.connect(lambda x: parselect.currentIndexChanged.connect(lambda x: settings.setValue(
cf.settings().setValue("reactivity/index", x)) "reactivity/index", x))
formula = QtWidgets.QLabel( formula = QtWidgets.QLabel(
"Formula for the x-axis: (Parameter - a) * b") "Formula for the x-axis: (Parameter - a) * b")
xannlayout = reactivityParam(parselect, str, "xlabel", "x axis label:") xannlayout = reactivityParam(parselect, str, "xlabel", "x axis label:")
def changevalue(x): def changevalue(x):
reactlabels['xlabel'] = x reactlabels['xlabel'] = x
dialspect.set_xlabel(x) dialspect.set_xlabel(x)
...@@ -225,6 +247,8 @@ def main_window(parent, augCanvas, update_signal, drls): ...@@ -225,6 +247,8 @@ def main_window(parent, augCanvas, update_signal, drls):
labelloclayout = reactivityParam( labelloclayout = reactivityParam(
parselect, int, "labelloc", "Label location (0-10): ", 0, 10) parselect, int, "labelloc", "Label location (0-10): ", 0, 10)
layouts = [xannlayout, translayout, labelloclayout] layouts = [xannlayout, translayout, labelloclayout]
layouts.append(reactivityParam(
parselect, int, "showlabel", "Show Label? (0-1): ", 0, 1))
layouts.append(reactivityParam( layouts.append(reactivityParam(
parselect, float, "markersize", "dot size: ", 0)) parselect, float, "markersize", "dot size: ", 0))
layouts.append(reactivityParam(parselect, float, "coef_a", "a: ")) layouts.append(reactivityParam(parselect, float, "coef_a", "a: "))
......
Markdown is supported
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