Compare commits

..

14 Commits

Author SHA1 Message Date
38099d6d7b ctrl_panel: Fix editing fields with unit "°C"
A faulty regular expression within PyQtGraph causes any Parameter with
a suffix that doesn't begin with an alphanumeric character (as matched
with \w) to act abnormally. For instance, entering "100 °C" into the
input boxes gets interpreted as 10 °C.

Use a custom regular expression for Parameters with this unit, which
simply matches for any character in the suffix group.
2024-07-31 16:24:29 +08:00
9a00c2b8f2 ctrl_panel: More appropriate steps and fixes 2024-07-31 16:18:09 +08:00
99d095ebb9 ctrl_panel: Put plotted values into readings group
For more intuitiveness to first-time users
2024-07-31 16:18:09 +08:00
54db579825 ctrl_panel: Fix max_v to only have unit "V"
As most users do not need to limit TEC voltage with accuracy of less
than 1mV.
2024-07-31 16:18:09 +08:00
3144ea2c9d ctrl_panel: Keep i_set visible when PID engaged
Since i_set is also plotted, we would want to see its precise value too.
2024-07-31 16:18:09 +08:00
8b68ff7652 ctrl_panel: Remove MutexParameter
Use the standard ListParamenter instead, and hook up UI changes and
sent commands elsewhere.
2024-07-31 16:18:09 +08:00
fb977982f8 ctrl_panel: Limits fixes
* PID Autotune test current should be positive

* Maximum absolute voltage should be 4 V not 5 V
2024-07-31 16:18:09 +08:00
e54e161e4e ctrl_panel: Code cleanup
* Remove unnecessary duplication of `THERMOSTAT_PARAMETERS`

* i -> ch

* Separate ParameterTree and Parameter initiation

* Remove extra "channel" option to root parameters, as the "value"
option is already the channel number
2024-07-31 16:18:09 +08:00
39bc3179cd ctrl_panel: PID Auto Tune -> PID Autotune 2024-07-31 16:18:09 +08:00
ada95ec243 ctrl_panel: Stop crushing spinboxes
It might not be the case on some themes, but on the default Qt theme the
spinbox are a bit too short for the containing numbers. See
https://github.com/pyqtgraph/pyqtgraph/issues/701.
2024-07-31 16:18:09 +08:00
7b899eca2a ctrl_panel: Pin down units for editable fields
User input always has the same order of magnitude, so allowing multiple
siPrefixes would be unwanted complexity. Don't allow them to be changed.

The Parameter option "noUnitEditing" is added to do so by the following
measures:

1. Don't validate for changed siPrefix and suffix, which avoids their
removal.

2. Avoid getting the cursor embedded within the unit.
2024-07-31 16:17:03 +08:00
c4ced31d18 ctrl_panel: Remove need for "mA" hack
Remove all instances of mA scaling scattered all around the code and
specify it in the parameter tree with a single source of truth.

Done by adding the option "pinSiPrefix" for all Parameters of type `int`
or `float`, and using it for current Parameters with unit "mA".
2024-07-31 16:12:55 +08:00
0d9e8a3bf2 ctrl_panel: Appropriate units for measured current
Allow the readonly display of current to vary its SI prefix in the unit,
since as a display entry it won't have the unit adjustment problem.
2024-07-31 14:45:12 +08:00
05c1a8547d ctrl_panel: Improve postfilter description 2024-07-31 14:44:51 +08:00
4 changed files with 288 additions and 73 deletions

View File

@ -4,6 +4,7 @@ from pyqtgraph.parametertree import (
Parameter, Parameter,
registerParameterType, registerParameterType,
) )
import pytec.gui.view.unitful
def set_tree_label_tips(tree): def set_tree_label_tips(tree):
@ -109,10 +110,10 @@ class CtrlPanel(QObject):
) )
self.params[channel].child( self.params[channel].child(
"pid", "pid_output_clamping", "output_min" "pid", "pid_output_clamping", "output_min"
).setValue(settings["parameters"]["output_min"] * 1000) ).setValue(settings["parameters"]["output_min"])
self.params[channel].child( self.params[channel].child(
"pid", "pid_output_clamping", "output_max" "pid", "pid_output_clamping", "output_max"
).setValue(settings["parameters"]["output_max"] * 1000) ).setValue(settings["parameters"]["output_max"])
self.params[channel].child( self.params[channel].child(
"output", "control_method", "target" "output", "control_method", "target"
).setValue(settings["target"]) ).setValue(settings["target"])
@ -127,13 +128,13 @@ class CtrlPanel(QObject):
) )
self.params[channel].child( self.params[channel].child(
"output", "control_method", "i_set" "output", "control_method", "i_set"
).setValue(settings["i_set"] * 1000) ).setValue(settings["i_set"])
if settings["temperature"] is not None: if settings["temperature"] is not None:
self.params[channel].child("temperature").setValue( self.params[channel].child("readings", "temperature").setValue(
settings["temperature"] settings["temperature"]
) )
if settings["tec_i"] is not None: if settings["tec_i"] is not None:
self.params[channel].child("tec_i").setValue( self.params[channel].child("readings", "tec_i").setValue(
settings["tec_i"] settings["tec_i"]
) )
@ -163,10 +164,10 @@ class CtrlPanel(QObject):
pwm_params["max_v"]["value"] pwm_params["max_v"]["value"]
) )
self.params[channel].child("output", "limits", "max_i_pos").setValue( self.params[channel].child("output", "limits", "max_i_pos").setValue(
pwm_params["max_i_pos"]["value"] * 1000 pwm_params["max_i_pos"]["value"]
) )
self.params[channel].child("output", "limits", "max_i_neg").setValue( self.params[channel].child("output", "limits", "max_i_neg").setValue(
pwm_params["max_i_neg"]["value"] * 1000 pwm_params["max_i_neg"]["value"]
) )
for limit in "max_i_pos", "max_i_neg", "max_v": for limit in "max_i_pos", "max_i_neg", "max_v":

View File

@ -1,22 +1,31 @@
{ {
"ctrl_panel": [ "ctrl_panel": [
{ {
"name": "temperature", "name": "readings",
"title": "Temperature", "title": "Readings",
"type": "float", "type": "group",
"format": "{value:.4f} °C", "tip": "Thermostat readings",
"readonly": true, "children": [
"tip": "The measured temperature at the thermistor" {
}, "name": "temperature",
{ "title": "Temperature",
"name": "tec_i", "type": "float",
"title": "Current through TEC", "format": "{value:.4f} {suffix}",
"type": "float", "suffix": "°C",
"siPrefix": true, "readonly": true,
"suffix": "A", "tip": "The measured temperature at the thermistor"
"decimals": 6, },
"readonly": true, {
"tip": "The measured current through the TEC" "name": "tec_i",
"title": "Current through TEC",
"type": "float",
"siPrefix": true,
"suffix": "A",
"decimals": 6,
"readonly": true,
"tip": "The measured current through the TEC"
}
]
}, },
{ {
"name": "output", "name": "output",
@ -45,16 +54,19 @@
"children": [ "children": [
{ {
"name": "i_set", "name": "i_set",
"title": "Set Current (mA)", "title": "Set Current",
"type": "float", "type": "float",
"value": 0, "value": 0,
"step": 100, "step": 0.1,
"limits": [ "limits": [
-2000, -2,
2000 2
], ],
"triggerOnShow": true,
"decimals": 6, "decimals": 6,
"pinSiPrefix": "m",
"suffix": "A",
"siPrefix": true,
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"pwm", "pwm",
@ -66,7 +78,7 @@
}, },
{ {
"name": "target", "name": "target",
"title": "Setpoint (°C)", "title": "Setpoint",
"type": "float", "type": "float",
"visible": false, "visible": false,
"value": 25, "value": 25,
@ -75,7 +87,10 @@
-273, -273,
300 300
], ],
"format": "{value:.4f}", "format": "{value:.4f} {suffix}",
"suffix": "°C",
"regex": "(?P<number>[+-]?((((\\d+(\\.\\d*)?)|(\\d*\\.\\d+))([eE][+-]?\\d+)?)|((?i:nan)|(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>.*))?$",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"pid", "pid",
@ -96,16 +111,20 @@
"children": [ "children": [
{ {
"name": "max_i_pos", "name": "max_i_pos",
"title": "Max Cooling Current (mA)", "title": "Max Cooling Current",
"type": "float", "type": "float",
"value": 0, "value": 0,
"step": 100, "step": 0.1,
"decimals": 6, "decimals": 6,
"compactHeight": false,
"limits": [ "limits": [
0, 0,
2000 2
], ],
"siPrefix": true,
"pinSiPrefix": "m",
"suffix": "A",
"noUnitEditing": true,
"compactHeight": false,
"param": [ "param": [
"pwm", "pwm",
"ch", "ch",
@ -116,16 +135,20 @@
}, },
{ {
"name": "max_i_neg", "name": "max_i_neg",
"title": "Max Heating Current (mA)", "title": "Max Heating Current",
"type": "float", "type": "float",
"value": 0, "value": 0,
"step": 100, "step": 0.1,
"decimals": 6, "decimals": 6,
"compactHeight": false, "siPrefix": true,
"pinSiPrefix": "m",
"suffix": "A",
"noUnitEditing": true,
"limits": [ "limits": [
0, 0,
2000 2
], ],
"compactHeight": false,
"param": [ "param": [
"pwm", "pwm",
"ch", "ch",
@ -136,15 +159,17 @@
}, },
{ {
"name": "max_v", "name": "max_v",
"title": "Max Absolute Voltage (V)", "title": "Max Absolute Voltage",
"type": "float", "type": "float",
"value": 0, "value": 0,
"step": 0.1, "step": 0.1,
"decimals": 3,
"limits": [ "limits": [
0, 0,
4 4
], ],
"siPrefix": true, "suffix": "V",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"pwm", "pwm",
@ -167,7 +192,7 @@
"children": [ "children": [
{ {
"name": "t0", "name": "t0",
"title": "T₀ (°C)", "title": "T₀",
"type": "float", "type": "float",
"value": 25, "value": 25,
"step": 0.1, "step": 0.1,
@ -175,7 +200,10 @@
-100, -100,
100 100
], ],
"format": "{value:.4f}", "format": "{value:.4f} {suffix}",
"suffix": "°C",
"regex": "(?P<number>[+-]?((((\\d+(\\.\\d*)?)|(\\d*\\.\\d+))([eE][+-]?\\d+)?)|((?i:nan)|(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>.*))?$",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"s-h", "s-h",
@ -187,11 +215,13 @@
}, },
{ {
"name": "r0", "name": "r0",
"title": "R₀ (Ω)", "title": "R₀",
"type": "float", "type": "float",
"value": 10000, "value": 10000,
"step": 1, "step": 100,
"siPrefix": true, "siPrefix": true,
"suffix": "Ω",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"s-h", "s-h",
@ -203,10 +233,12 @@
}, },
{ {
"name": "b", "name": "b",
"title": "B (K)", "title": "B",
"type": "float", "type": "float",
"value": 3950, "value": 3950,
"step": 1, "step": 10,
"suffix": "K",
"noUnitEditing": true,
"decimals": 4, "decimals": 4,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
@ -230,8 +262,8 @@
"limits": { "limits": {
"Off": null, "Off": null,
"47 dB @ 10.41 Hz": 27.0, "47 dB @ 10.41 Hz": 27.0,
"62 dB @ 9.1 Hz": 21.25, "62 dB @ 10 Hz": 21.25,
"86 dB @ 10 Hz": 20.0, "86 dB @ 9.1 Hz": 20.0,
"92 dB @ 8.4 Hz": 16.67 "92 dB @ 8.4 Hz": 16.67
}, },
"tip": "Trade off effective sampling rate and rejection of (50±1) Hz and (60±1) Hz", "tip": "Trade off effective sampling rate and rejection of (50±1) Hz and (60±1) Hz",
@ -251,7 +283,6 @@
"title": "Kp", "title": "Kp",
"type": "float", "type": "float",
"step": 0.1, "step": 0.1,
"suffix": "",
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"pid", "pid",
@ -263,9 +294,11 @@
}, },
{ {
"name": "ki", "name": "ki",
"title": "Ki (Hz)", "title": "Ki",
"type": "float", "type": "float",
"step": 0.1, "step": 0.1,
"suffix": "Hz",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"pid", "pid",
@ -277,9 +310,11 @@
}, },
{ {
"name": "kd", "name": "kd",
"title": "Kd (s)", "title": "Kd",
"type": "float", "type": "float",
"step": 0.1, "step": 0.1,
"suffix": "s",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"pid", "pid",
@ -298,14 +333,18 @@
"children": [ "children": [
{ {
"name": "output_min", "name": "output_min",
"title": "Minimum (mA)", "title": "Minimum",
"type": "float", "type": "float",
"step": 100, "step": 0.1,
"limits": [ "limits": [
-2000, -2,
2000 2
], ],
"decimals": 6, "decimals": 6,
"siPrefix": true,
"pinSiPrefix": "m",
"suffix": "A",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"pid", "pid",
@ -317,14 +356,18 @@
}, },
{ {
"name": "output_max", "name": "output_max",
"title": "Maximum (mA)", "title": "Maximum",
"type": "float", "type": "float",
"step": 100, "step": 0.1,
"limits": [ "limits": [
-2000, -2,
2000 2
], ],
"decimals": 6, "decimals": 6,
"siPrefix": true,
"pinSiPrefix": "m",
"suffix": "A",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"param": [ "param": [
"pid", "pid",
@ -345,11 +388,14 @@
"children": [ "children": [
{ {
"name": "target_temp", "name": "target_temp",
"title": "Target Temperature (°C)", "title": "Target Temperature",
"type": "float", "type": "float",
"value": 20, "value": 20,
"step": 0.1, "step": 0.1,
"format": "{value:.4f}", "format": "{value:.4f} {suffix}",
"suffix": "°C",
"regex": "(?P<number>[+-]?((((\\d+(\\.\\d*)?)|(\\d*\\.\\d+))([eE][+-]?\\d+)?)|((?i:nan)|(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>.*))?$",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"pid_autotune": [ "pid_autotune": [
"target_temp", "target_temp",
@ -359,16 +405,20 @@
}, },
{ {
"name": "test_current", "name": "test_current",
"title": "Test Current (mA)", "title": "Test Current",
"type": "float", "type": "float",
"value": 0, "value": 0,
"decimals": 6, "decimals": 6,
"compactHeight": false, "step": 0.1,
"step": 100,
"limits": [ "limits": [
0, 0,
2000 2
], ],
"siPrefix": true,
"pinSiPrefix": "m",
"suffix": "A",
"noUnitEditing": true,
"compactHeight": false,
"pid_autotune": [ "pid_autotune": [
"test_current", "test_current",
"ch" "ch"
@ -377,12 +427,14 @@
}, },
{ {
"name": "temp_swing", "name": "temp_swing",
"title": "Temperature Swing (°C)", "title": "Temperature Swing",
"type": "float", "type": "float",
"value": 1.5, "value": 1.5,
"step": 0.1, "step": 0.1,
"prefix": "±", "format": "{value:.4f} {suffix}",
"format": "{value:.4f}", "suffix": "°C",
"regex": "(?P<number>[+-]?((((\\d+(\\.\\d*)?)|(\\d*\\.\\d+))([eE][+-]?\\d+)?)|((?i:nan)|(inf))))\\s*((?P<siPrefix>[uyzafpnµm kMGTPEZY]?)(?P<suffix>.*))?$",
"noUnitEditing": true,
"compactHeight": false, "compactHeight": false,
"pid_autotune": [ "pid_autotune": [
"temp_swing", "temp_swing",
@ -392,11 +444,13 @@
}, },
{ {
"name": "lookback", "name": "lookback",
"title": "Lookback (s)", "title": "Lookback",
"type": "float", "type": "float",
"value": 3.0, "value": 3.0,
"step": 0.1, "step": 0.1,
"format": "{value:.4f}", "format": "{value:.4f} {suffix}",
"noUnitEditing": true,
"suffix": "s",
"compactHeight": false, "compactHeight": false,
"pid_autotune": [ "pid_autotune": [
"lookback", "lookback",

View File

@ -0,0 +1,159 @@
from PyQt6.QtCore import QSignalBlocker
from PyQt6.QtGui import QValidator
from pyqtgraph import SpinBox
import pyqtgraph.functions as fn
from pyqtgraph.parametertree.parameterTypes import (
SimpleParameter,
NumericParameterItem,
registerParameterItemType,
)
class UnitfulSpinBox(SpinBox):
"""
Extension of PyQtGraph's SpinBox widget.
Adds:
* The "pinSiPrefix" option, where the siPrefix could be fixed to a
particular scale instead of as determined by its value.
* The "noUnitEditing" option, where the unit portion of the
SpinBox text, including the siPrefix, is fixed and uneditable.
"""
def __init__(self, parent=None, value=0.0, **kwargs):
super().__init__(parent, value, **kwargs)
self._current_si_prefix = ""
self.lineEdit().cursorPositionChanged.connect(
self.editor_cursor_position_changed
)
def validate(self, strn, pos):
ret, strn, pos = super().validate(strn, pos)
if self.opts.get("noUnitEditing") is True:
suffix = self.opts["suffix"]
# When the unit is edited / removed
if not (
strn.endswith(suffix)
and strn.removesuffix(suffix).endswith(self._current_si_prefix)
):
# Then the input is invalid instead of incomplete, reject this change
ret = QValidator.State.Invalid
return ret, strn, pos
def editor_cursor_position_changed(self, oldpos, newpos):
"""
Modified from the original Qt C++ source,
QAbstractSpinBox::editorCursorPositionChanged
Their suffix is different than our suffix; there's no obvious
way to set that one here.
"""
if self.opts.get("noUnitEditing") is True:
edit = self.lineEdit()
if edit.hasSelectedText():
return # Allow for selecting units, for copy-and-paste
unit_len = len(self._current_si_prefix) + len(self.opts["suffix"])
text_len = len(edit.text())
pos = -1
# Cursor in unit
if text_len - unit_len < newpos < text_len:
if oldpos == text_len:
pos = text_len - unit_len
else:
pos = text_len
if pos != -1:
with QSignalBlocker(edit):
edit.setCursorPosition(pos)
def setOpts(self, **opts):
if "pinSiPrefix" in opts:
self.opts["pinSiPrefix"] = opts.pop("pinSiPrefix")
if "noUnitEditing" in opts:
self.opts["noUnitEditing"] = opts.pop("noUnitEditing")
super().setOpts(**opts)
def formatText(self, prev=None):
"""
Implement 'pinSiPrefix' mechanism for pyqtgraph.SpinBox, where
SI prefixes could be pinned down.
Code modified from the PyQtGraph source
"""
# get the number of decimal places to print
decimals = self.opts['decimals']
suffix = self.opts['suffix']
prefix = self.opts['prefix']
pin_si_prefix = self.opts.get("pinSiPrefix")
# format the string
val = self.value()
if self.opts['siPrefix'] is True:
# SI prefix was requested, so scale the value accordingly
if pin_si_prefix is not None and pin_si_prefix in fn.SI_PREFIX_EXPONENTS:
# fixed scale
s = 10**-fn.SI_PREFIX_EXPONENTS[pin_si_prefix]
p = pin_si_prefix
elif self.val == 0 and prev is not None:
# special case: if it's zero use the previous prefix
(s, p) = fn.siScale(prev)
else:
(s, p) = fn.siScale(val)
parts = {'value': val, 'suffix': suffix, 'decimals': decimals, 'siPrefix': p, 'scaledValue': s*val, 'prefix':prefix}
self._current_si_prefix = p
else:
# no SI prefix /suffix requested; scale is 1
parts = {'value': val, 'suffix': suffix, 'decimals': decimals, 'siPrefix': '', 'scaledValue': val, 'prefix':prefix}
parts['prefixGap'] = '' if parts['prefix'] == '' else ' '
parts['suffixGap'] = '' if (parts['suffix'] == '' and parts['siPrefix'] == '') else ' '
return self.opts['format'].format(**parts)
class UnitfulNumericParameterItem(NumericParameterItem):
"""
Subclasses PyQtGraph's `NumericParameterItem` and uses
UnitfulSpinBox for editing.
"""
def makeWidget(self):
opts = self.param.opts
t = opts['type']
defs = {
'value': 0, 'min': None, 'max': None,
'step': 1.0, 'dec': False,
'siPrefix': False, 'suffix': '', 'decimals': 3,
'pinSiPrefix': None, 'noUnitEditing': False,
}
if t == 'int':
defs['int'] = True
defs['minStep'] = 1.0
for k in defs:
if k in opts:
defs[k] = opts[k]
if 'limits' in opts:
defs['min'], defs['max'] = opts['limits']
w = UnitfulSpinBox()
w.setOpts(**defs)
w.sigChanged = w.sigValueChanged
w.sigChanging = w.sigValueChanging
return w
registerParameterItemType(
"float", UnitfulNumericParameterItem, SimpleParameter, override=True
)
registerParameterItemType(
"int", UnitfulNumericParameterItem, SimpleParameter, override=True
)

View File

@ -267,9 +267,6 @@ class MainWindow(QtWidgets.QMainWindow):
for inner_param, change, data in changes: for inner_param, change, data in changes:
if change == "value": if change == "value":
if inner_param.opts.get("param", None) is not None: if inner_param.opts.get("param", None) is not None:
if inner_param.opts.get("title", None).endswith(" (mA)"):
data /= 1000 # Given in mA
thermostat_param = inner_param.opts["param"] thermostat_param = inner_param.opts["param"]
if thermostat_param[1] == "ch": if thermostat_param[1] == "ch":
thermostat_param[1] = ch thermostat_param[1] = ch
@ -296,6 +293,10 @@ class MainWindow(QtWidgets.QMainWindow):
if activater[1] == "ch": if activater[1] == "ch":
activater[1] = ch activater[1] = ch
await self.client.set_param(*activater) await self.client.set_param(*activater)
else:
await self.client.set_param(
"pwm", ch, "i_set", inner_param.child("i_set").value()
)
@asyncSlot() @asyncSlot()
async def pid_autotune_request(self, ch=0): async def pid_autotune_request(self, ch=0):