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