fix(smargon): stop only the moving axes on Ctrl-C and scan abort
smargopolo has no stop endpoint; an axis is halted by setting its target to its readback. Stopping a motor retargeted its axis even when idle, and the coordinator's on_stop retargeted all SCS axes on every scan abort, so readback noise and kinematics round-off accumulated in the targets of idle axes. The controller now tracks the absolute moves commanded by BEC until they finish. stop_moving() retargets only those axes whose readback is not yet within tolerance of the target, in one request; all other targets stay untouched and nothing is sent if no axis moves. The O-vector is still never retargeted (STOP_EXCLUDED_AXES); a stop only ends BEC's wait for it. Motor stop() and the coordinator's on_stop use stop_moving(); an axis halted via the coordinator now ends its move status immediately instead of timing out. stop_all() still retargets every non-O axis as an explicit command. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01M8zoDzRrboFFDabqB9bLNZ
This commit was merged in pull request #361.
This commit is contained in:
1 parent
887de5582f
commit
5ea5bd864f
5 files changed
+192
-7
No files matched your search
@@ -116,6 +116,18 @@ pytest tests/tests_devices/test_smargon_transport.py tests/tests_devices/test_sm
|
||||
|
||||
All run against `FakeTransport` — no hardware or server needed.
|
||||
|
||||
## Stop (Ctrl-C, scan abort)
|
||||
|
||||
smargopolo has no stop endpoint; an axis is halted by setting its target to its
|
||||
readback. A stop only does this for axes that are actually moving: the controller
|
||||
remembers the targets of the absolute moves BEC commanded (`move`, `umv`, `move_scs`)
|
||||
until they finish, and `stop()` of a motor or of the `smargon` coordinator retargets only
|
||||
those axes whose readback is not yet within tolerance of the target, in one request.
|
||||
Idle axes keep their target, so repeated aborts do not accumulate readback noise or
|
||||
kinematics round-off in the targets. Not stopped: relative moves, nudges and moves made
|
||||
outside BEC. The O-vector is never retargeted (see below); `dev.smargon.stop_all()`
|
||||
still retargets every other axis (explicit command only).
|
||||
|
||||
## Open items / to confirm with the smargopolo maintainer (Wayne Glettig)
|
||||
|
||||
- **Stop semantics**: no explicit stop endpoint; we retarget axes to their readback
|
||||
|
||||
@@ -22,7 +22,7 @@ import time
|
||||
|
||||
from ophyd import OphydObject
|
||||
|
||||
from .transport.base import Axis, BeamlineAxis, Mode, SmargopoloTransport
|
||||
from .transport.base import STOP_EXCLUDED_AXES, Axis, BeamlineAxis, Mode, SmargopoloTransport
|
||||
from .transport.errors import SmargopoloModeError
|
||||
from .transport.fake import FakeTransport
|
||||
from .transport.rest import RestTransport
|
||||
@@ -103,6 +103,9 @@ class SmargopoloController(OphydObject):
|
||||
else:
|
||||
self.transport = RestTransport(host=host, port=port, timeout=timeout)
|
||||
self._axes: dict[Axis, object] = {} # scs_axis -> SmargopoloMotor (registered by motors)
|
||||
# raw targets of absolute moves commanded by BEC that have not finished yet;
|
||||
# stop_moving() only halts these axes, the others are never retargeted
|
||||
self._active_moves: dict[Axis, float] = {}
|
||||
self._connected = False
|
||||
# readback monitor: follows moves made outside BEC (smargopolo web interface)
|
||||
self.monitor_interval = DEFAULT_MONITOR_INTERVAL
|
||||
@@ -207,8 +210,64 @@ class SmargopoloController(OphydObject):
|
||||
return self.transport.get_positions()
|
||||
|
||||
def move_absolute(self, targets: dict) -> None:
|
||||
parsed = {Axis(a): float(v) for a, v in targets.items()}
|
||||
with self._lock:
|
||||
self.transport.move_absolute({Axis(a): float(v) for a, v in targets.items()})
|
||||
self.transport.move_absolute(parsed)
|
||||
self._active_moves.update(parsed)
|
||||
|
||||
def finish_move(self, axis: Axis, target: float | None = None) -> None:
|
||||
"""Forget the active move of *axis* (only if it still has *target*, when given)."""
|
||||
axis = Axis(axis)
|
||||
with self._lock:
|
||||
if target is None or self._active_moves.get(axis) == target:
|
||||
self._active_moves.pop(axis, None)
|
||||
|
||||
def active_moves(self) -> dict:
|
||||
"""Raw targets of the BEC moves that are still active, ``{Axis: target}``."""
|
||||
with self._lock:
|
||||
return dict(self._active_moves)
|
||||
|
||||
def stop_moving(self, axes: list | None = None) -> list:
|
||||
"""Halt only the axes that are actually moving (used by Ctrl-C / scan abort).
|
||||
|
||||
Candidates are the axes with an active BEC move (of *axes*, or all). An axis
|
||||
whose readback is already within its motor's tolerance of the target has
|
||||
finished and is left alone. Only the remaining axes are retargeted to their
|
||||
readback, in one request; all other axes keep their target untouched, so a stop
|
||||
does not write readback (encoder noise, kinematics round-off) into the targets
|
||||
of idle axes. O-vector axes (STOP_EXCLUDED_AXES) are never retargeted: a stop
|
||||
only ends BEC's wait for them. Returns the axes that were halted.
|
||||
"""
|
||||
wanted = None if axes is None else {Axis(a) for a in axes}
|
||||
with self._lock:
|
||||
candidates = {
|
||||
a: t for a, t in self._active_moves.items() if wanted is None or a in wanted
|
||||
}
|
||||
if not candidates:
|
||||
return []
|
||||
for axis in candidates:
|
||||
self._active_moves.pop(axis, None)
|
||||
positions = self.transport.get_positions()
|
||||
moving = []
|
||||
for axis, target in candidates.items():
|
||||
pos = positions.get(axis)
|
||||
if pos is None:
|
||||
continue
|
||||
motor = self._axes.get(axis)
|
||||
tol = getattr(motor, "_tolerance", 1e-3)
|
||||
dist = motor._distance(pos, target) if motor is not None else abs(pos - target)
|
||||
if dist > tol:
|
||||
moving.append(axis)
|
||||
halted = [a for a in moving if a not in STOP_EXCLUDED_AXES]
|
||||
if halted:
|
||||
self.transport.stop(halted)
|
||||
for axis in moving:
|
||||
motor = self._axes.get(axis)
|
||||
if motor is not None:
|
||||
motor._stopped = True # ends its move poll ("interrupted by stop()")
|
||||
if halted:
|
||||
logger.info(f"{self.name}: stopped {', '.join(a.value for a in halted)}")
|
||||
return halted
|
||||
|
||||
def move_relative(self, deltas: dict) -> None:
|
||||
with self._lock:
|
||||
@@ -307,6 +366,7 @@ class SmargopoloController(OphydObject):
|
||||
if wait:
|
||||
for ax, val in parsed.items():
|
||||
self._wait_axis(ax, val)
|
||||
self.finish_move(ax, val)
|
||||
|
||||
def _wait_axis(self, axis: Axis, target: float, timeout: float | None = None) -> None:
|
||||
motor = self._axes.get(axis)
|
||||
@@ -333,7 +393,12 @@ class SmargopoloController(OphydObject):
|
||||
self.transport.nudge_beamline(parsed, modify_offset=modify_offset)
|
||||
|
||||
def stop_all(self) -> None:
|
||||
"""Halt all SCS axes."""
|
||||
"""Retarget ALL SCS axes to their readback (explicit operator command only).
|
||||
|
||||
Ctrl-C / scan aborts use :meth:`stop_moving`, which leaves idle axes untouched.
|
||||
"""
|
||||
with self._lock:
|
||||
self._active_moves.clear()
|
||||
self.stop(None)
|
||||
|
||||
def motor_positions(self) -> dict:
|
||||
|
||||
@@ -228,10 +228,12 @@ class SmargopoloMotor(Device, PositionerBase):
|
||||
time.sleep(self._poll_interval)
|
||||
self._update_readback(self.controller.get_position(self.scs_axis))
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
self.controller.finish_move(self.scs_axis, target)
|
||||
self.motor_is_moving.put(0)
|
||||
if not status.done:
|
||||
status.set_exception(exc)
|
||||
return
|
||||
self.controller.finish_move(self.scs_axis, target)
|
||||
self.motor_is_moving.put(0)
|
||||
if self._stopped:
|
||||
if not status.done:
|
||||
@@ -276,10 +278,15 @@ class SmargopoloMotor(Device, PositionerBase):
|
||||
return self.move(position, wait=False, **kwargs)
|
||||
|
||||
def stop(self, *, success: bool = False) -> None:
|
||||
"""Halt this axis immediately (best-effort: never raises during teardown)."""
|
||||
"""Halt this axis if it is moving (best-effort: never raises during teardown).
|
||||
|
||||
Only an active move of this axis is stopped (its target is set to the
|
||||
readback); an idle axis is not touched, so stopping does not write readback
|
||||
noise into its target.
|
||||
"""
|
||||
self._stopped = True
|
||||
try:
|
||||
self.controller.stop([self.scs_axis])
|
||||
self.controller.stop_moving([self.scs_axis])
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
self.log.warning("%s: transport stop failed: %s", self.name, exc)
|
||||
finally:
|
||||
|
||||
@@ -147,8 +147,8 @@ class SmarGon(PSIDeviceBase):
|
||||
super().wait_for_connection(all_signals=all_signals, timeout=timeout)
|
||||
|
||||
def on_stop(self) -> None:
|
||||
"""Halt all SCS axes."""
|
||||
self.controller.stop_all()
|
||||
"""Halt the SCS axes that are moving; idle axes keep their targets untouched."""
|
||||
self.controller.stop_moving()
|
||||
|
||||
# -- delegated whole-goniometer operations -----------------------------
|
||||
|
||||
|
||||
@@ -419,3 +419,104 @@ def test_stop_all_and_o_motor_stop_leave_o_vector_untouched():
|
||||
sgox.stop()
|
||||
assert transport._targets[Axis.OX] == pytest.approx(2.0)
|
||||
assert sgox.motor_is_moving.get() == 0
|
||||
|
||||
|
||||
# -- stop: only the moving axes are retargeted ---------------------------------
|
||||
|
||||
|
||||
def _spy_stop(controller):
|
||||
"""Record the axes passed to transport.stop()."""
|
||||
calls = []
|
||||
original = controller.transport.stop
|
||||
|
||||
def spy(axes=None):
|
||||
calls.append(None if axes is None else sorted(a.value for a in axes))
|
||||
return original(axes)
|
||||
|
||||
controller.transport.stop = spy
|
||||
return calls
|
||||
|
||||
|
||||
def test_stop_of_idle_axes_does_not_touch_the_targets():
|
||||
coord = _coordinator()
|
||||
sgx = _motor("sgx", "SHX")
|
||||
sgchi = _motor("sgchi", "CHI")
|
||||
coord.reference()
|
||||
sgx.move(0.5, wait=True)
|
||||
calls = _spy_stop(coord.controller)
|
||||
sgx.stop()
|
||||
sgchi.stop()
|
||||
coord.stop() # scan abort: the coordinator is in the stop list
|
||||
assert calls == []
|
||||
assert coord.controller.active_moves() == {}
|
||||
|
||||
|
||||
def test_coordinator_stop_halts_only_the_moving_axis():
|
||||
from csaxs_bec.devices.smargon.transport.base import Axis
|
||||
|
||||
coord = _coordinator(gradual_motion=True)
|
||||
sgx = _motor("sgx", "SHX", gradual_motion=True)
|
||||
_motor("sgchi", "CHI", gradual_motion=True)
|
||||
coord.reference()
|
||||
targets_before = dict(coord.controller.transport._targets)
|
||||
calls = _spy_stop(coord.controller)
|
||||
st = sgx.set(1e6) # far target: stays in flight
|
||||
coord.stop()
|
||||
assert calls == [["SHX"]]
|
||||
with pytest.raises(RuntimeError, match="interrupted by stop"):
|
||||
st.wait(timeout=5)
|
||||
targets = coord.controller.transport._targets
|
||||
assert targets[Axis.SHX] != 1e6
|
||||
assert {a: v for a, v in targets.items() if a is not Axis.SHX} == {
|
||||
a: v for a, v in targets_before.items() if a is not Axis.SHX
|
||||
}
|
||||
assert sgx.motor_is_moving.get() == 0
|
||||
|
||||
|
||||
def test_motor_stop_halts_its_own_move_only():
|
||||
coord = _coordinator(gradual_motion=True)
|
||||
sgx = _motor("sgx", "SHX", gradual_motion=True)
|
||||
sgy = _motor("sgy", "SHY", gradual_motion=True)
|
||||
coord.reference()
|
||||
calls = _spy_stop(coord.controller)
|
||||
st_x = sgx.set(1e6)
|
||||
st_y = sgy.set(1e6)
|
||||
sgx.stop()
|
||||
assert calls == [["SHX"]]
|
||||
with pytest.raises(RuntimeError):
|
||||
st_x.wait(timeout=5)
|
||||
assert not st_y.done
|
||||
sgy.stop()
|
||||
assert calls == [["SHX"], ["SHY"]]
|
||||
|
||||
|
||||
def test_finished_move_scs_without_wait_is_not_retargeted():
|
||||
coord = _coordinator()
|
||||
_motor("sgx", "SHX")
|
||||
coord.reference()
|
||||
coord.move_scs(SHX=0.3, wait=False) # instant in the non-gradual fake
|
||||
calls = _spy_stop(coord.controller)
|
||||
coord.stop()
|
||||
assert calls == []
|
||||
assert coord.controller.active_moves() == {}
|
||||
|
||||
|
||||
def test_stop_all_still_retargets_every_axis():
|
||||
coord = _coordinator()
|
||||
coord.reference()
|
||||
calls = _spy_stop(coord.controller)
|
||||
coord.stop_all()
|
||||
assert calls == [None]
|
||||
|
||||
|
||||
def test_stop_of_a_moving_o_motor_ends_the_wait_without_retargeting():
|
||||
coord = _coordinator(gradual_motion=True)
|
||||
sgox = _motor("sgox", "OX", gradual_motion=True)
|
||||
coord.reference()
|
||||
calls = _spy_stop(coord.controller)
|
||||
st = sgox.set(1e6)
|
||||
assert coord.controller.stop_moving() == []
|
||||
assert calls == []
|
||||
with pytest.raises(RuntimeError, match="interrupted by stop"):
|
||||
st.wait(timeout=5)
|
||||
assert sgox.motor_is_moving.get() == 0
|
||||
Reference in new issue
Block a user