Feature/spec style commands #362
No files matched your search
@@ -0,0 +1,127 @@
|
||||
"""spec-style commands for the BEC IPython shell.
|
||||
|
||||
Moves:
|
||||
umv samx 1 samy 2 -> umv(dev.samx, 1, dev.samy, 2)
|
||||
umvr samx -0.5 -> umvr(dev.samx, -0.5)
|
||||
mv / mvr likewise; "dev.samx" is accepted too, commas are optional.
|
||||
|
||||
Scans (the number is spec's *intervals*, so 10 intervals = 11 points):
|
||||
ascan samx 0 1 10 0.1 -> ascan(dev.samx, 0, 1, 10, 0.1)
|
||||
runs scans.line_scan(dev.samx, 0, 1, steps=11,
|
||||
exp_time=0.1, relative=False)
|
||||
dscan samx -1 1 10 0.1 -> same with relative=True
|
||||
ct 0.5 / ct -> ct(0.5) / ct() runs scans.acquire(exp_time=...)
|
||||
|
||||
Every command prints the real BEC command before running it, so users keep
|
||||
the connection to BEC (moves: the transformed line prints it; ascan, dscan,
|
||||
ct and wm print it themselves, also when called directly).
|
||||
|
||||
Positions:
|
||||
wm samx samy -> wm("samx", "samy") runs dev.wm(["samx", "samy"])
|
||||
wm sam* / wm sam[xy] -> wildcards, as in dev.wm
|
||||
|
||||
Only single-line input with the exact word layout above is rewritten; every
|
||||
value must be one word (no spaces). Anything else (umv(...), umv = ..., umv?,
|
||||
loops, function bodies) passes unchanged.
|
||||
"""
|
||||
|
||||
import builtins
|
||||
import re
|
||||
|
||||
_CMD = re.compile(r"^(\s*)(umvr?|mvr?|ascan|dscan|ct|wm)(?:\s+(?![(=,.?])(.*?))?\s*$")
|
||||
_NAME = re.compile(r"^(dev\.)?[A-Za-z_][A-Za-z0-9_]*$")
|
||||
_WM_NAME = re.compile(r"^(dev\.)?[A-Za-z_*?\[][A-Za-z0-9_*?\[\]]*$")
|
||||
_CT_DEFAULT = 1.0
|
||||
|
||||
|
||||
def _dev(name):
|
||||
return name if name.startswith("dev.") else f"dev.{name}"
|
||||
|
||||
|
||||
def _is_value(word):
|
||||
return not word.startswith(("=", ")"))
|
||||
|
||||
|
||||
def shell_moves(lines):
|
||||
# only single-line input: never touch function bodies, loops or strings
|
||||
if len(lines) != 1:
|
||||
return lines
|
||||
m = _CMD.match(lines[0])
|
||||
if not m:
|
||||
return lines
|
||||
indent, cmd, rest = m.groups()
|
||||
words = (rest or "").replace(",", " ").split()
|
||||
|
||||
if cmd == "ct":
|
||||
if len(words) > 1 or not all(map(_is_value, words)):
|
||||
return lines
|
||||
args = words
|
||||
elif cmd == "wm":
|
||||
if not words or not all(_WM_NAME.match(w) for w in words):
|
||||
return lines
|
||||
args = [repr(w.removeprefix("dev.")) for w in words]
|
||||
elif cmd in ("ascan", "dscan"):
|
||||
if len(words) != 5 or not _NAME.match(words[0]) or not all(map(_is_value, words)):
|
||||
return lines
|
||||
args = [_dev(words[0])] + words[1:]
|
||||
else:
|
||||
if len(words) < 2 or len(words) % 2:
|
||||
return lines
|
||||
args = []
|
||||
for name, pos in zip(words[::2], words[1::2]):
|
||||
if not _NAME.match(name) or not _is_value(pos):
|
||||
return lines
|
||||
args += [_dev(name), pos]
|
||||
# umv/umvr/mv/mvr are BEC's own commands: print the call in the
|
||||
# executed line (not here: IPython runs transformers more than once)
|
||||
call = f"{cmd}({', '.join(args)})"
|
||||
return [f"{indent}print({call!r}); {call}\n"]
|
||||
return [f"{indent}{cmd}({', '.join(args)})\n"]
|
||||
|
||||
|
||||
def _scans():
|
||||
return builtins.__dict__["bec"].scans
|
||||
|
||||
|
||||
def _line_scan(motor, start, end, intervals, exp_time, relative):
|
||||
if int(intervals) != intervals or intervals < 1:
|
||||
raise ValueError(f"intervals must be a positive integer, got {intervals!r}")
|
||||
steps = int(intervals) + 1
|
||||
print(
|
||||
f"scans.line_scan(dev.{motor.name}, {start}, {end}, steps={steps}, "
|
||||
f"exp_time={exp_time}, relative={relative})"
|
||||
)
|
||||
return _scans().line_scan(
|
||||
motor, start, end, steps=steps, exp_time=exp_time, relative=relative
|
||||
)
|
||||
|
||||
|
||||
def ascan(motor, start, end, intervals, exp_time):
|
||||
"""spec ascan: absolute line scan, intervals + 1 points."""
|
||||
return _line_scan(motor, start, end, intervals, exp_time, relative=False)
|
||||
|
||||
|
||||
def dscan(motor, start, end, intervals, exp_time):
|
||||
"""spec dscan: line scan relative to the current position, intervals + 1 points."""
|
||||
return _line_scan(motor, start, end, intervals, exp_time, relative=True)
|
||||
|
||||
|
||||
def ct(exp_time=_CT_DEFAULT):
|
||||
"""spec ct: count for exp_time seconds (default 1 s)."""
|
||||
print(f"scans.acquire(exp_time={exp_time})")
|
||||
return _scans().acquire(exp_time=exp_time)
|
||||
|
||||
|
||||
def wm(*devices):
|
||||
"""spec wm: show readback, setpoint and limits; names, devices or wildcards."""
|
||||
names = [d if isinstance(d, str) else d.name for d in devices]
|
||||
print(f"dev.wm({names!r})")
|
||||
return builtins.__dict__["dev"].wm(names)
|
||||
|
||||
|
||||
def register(ip):
|
||||
"""Install the transformer and the commands once (safe to call again)."""
|
||||
tr = ip.input_transformers_cleanup
|
||||
if not any(getattr(t, "__name__", "") == "shell_moves" for t in tr):
|
||||
tr.append(shell_moves)
|
||||
ip.user_ns.update(ascan=ascan, dscan=dscan, ct=ct, wm=wm)
|
||||
@@ -150,4 +150,11 @@ if _args.session.lower() == "lamni" or _args.session.lower() == "flomni" or _arg
|
||||
# plus the session's own states (OMNY: omny_vacuum)
|
||||
from csaxs_bec.bec_ipython_client.startup.beamline_states import set_default_beamline_states
|
||||
|
||||
set_default_beamline_states(bec, session=_args.session.lower())
|
||||
set_default_beamline_states(bec, session=_args.session.lower())
|
||||
# SPEC-STYLE COMMANDS (umv samx 1, umvr, mv, mvr, ascan, dscan, ct, wm)
|
||||
try:
|
||||
from csaxs_bec.bec_ipython_client.plugins.tool_box.spec_commands import register as _register_spec_commands
|
||||
|
||||
_register_spec_commands(bec._ip)
|
||||
except Exception:
|
||||
logger.warning("Failed to register spec-style commands.")
|
||||
@@ -0,0 +1,141 @@
|
||||
import builtins
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from csaxs_bec.bec_ipython_client.plugins.tool_box.spec_commands import (
|
||||
ascan,
|
||||
ct,
|
||||
dscan,
|
||||
register,
|
||||
shell_moves,
|
||||
wm,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"src, want",
|
||||
[
|
||||
(
|
||||
"umv samx 1 samy 2\n",
|
||||
"print('umv(dev.samx, 1, dev.samy, 2)'); umv(dev.samx, 1, dev.samy, 2)\n",
|
||||
),
|
||||
("umvr samx -0.5\n", "print('umvr(dev.samx, -0.5)'); umvr(dev.samx, -0.5)\n"),
|
||||
(
|
||||
"mv dev.samx 3, samy pos+1\n",
|
||||
"print('mv(dev.samx, 3, dev.samy, pos+1)'); mv(dev.samx, 3, dev.samy, pos+1)\n",
|
||||
),
|
||||
("mvr lsamrot 1e-3 \n", "print('mvr(dev.lsamrot, 1e-3)'); mvr(dev.lsamrot, 1e-3)\n"),
|
||||
("umv(dev.samx, 1)\n", None),
|
||||
("umv (dev.samx, 1)\n", None),
|
||||
("umv = 3\n", None),
|
||||
("umv?\n", None),
|
||||
("umv samx\n", None),
|
||||
("umv samx 1 + 2\n", None),
|
||||
("umv 1 samx\n", None),
|
||||
("mvx a b\n", None),
|
||||
("ascan samx 0 1 10 0.1\n", "ascan(dev.samx, 0, 1, 10, 0.1)\n"),
|
||||
("dscan dev.samy -1 1 20 0.5\n", "dscan(dev.samy, -1, 1, 20, 0.5)\n"),
|
||||
("ct 0.5\n", "ct(0.5)\n"),
|
||||
("ct\n", "ct()\n"),
|
||||
("ascan samx 0 1 10\n", None),
|
||||
("ascan 0 samx 1 10 0.1\n", None),
|
||||
("ascan(dev.samx, 0, 1, 10, 0.1)\n", None),
|
||||
("ct 1 2\n", None),
|
||||
("ct = 3\n", None),
|
||||
("ct?\n", None),
|
||||
("wm samx samy\n", "wm('samx', 'samy')\n"),
|
||||
("wm dev.samx, sam*\n", "wm('samx', 'sam*')\n"),
|
||||
("wm sam[xy]\n", "wm('sam[xy]')\n"),
|
||||
("wm\n", None),
|
||||
("wm samx 1\n", None),
|
||||
("wm(dev.samx)\n", None),
|
||||
("wm?\n", None),
|
||||
],
|
||||
)
|
||||
def test_shell_moves(src, want):
|
||||
assert shell_moves([src]) == [want or src]
|
||||
|
||||
|
||||
def test_shell_moves_multiline_untouched():
|
||||
lines = ["for i in range(3):\n", " umv samx i\n"]
|
||||
assert shell_moves(lines) == lines
|
||||
|
||||
|
||||
def test_register_is_idempotent():
|
||||
class _IP:
|
||||
input_transformers_cleanup = []
|
||||
user_ns = {}
|
||||
|
||||
ip = _IP()
|
||||
register(ip)
|
||||
register(ip)
|
||||
assert ip.input_transformers_cleanup == [shell_moves]
|
||||
assert ip.user_ns["ascan"] is ascan and ip.user_ns["ct"] is ct
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bec_scans():
|
||||
bec = mock.MagicMock()
|
||||
with mock.patch.dict(builtins.__dict__, {"bec": bec}):
|
||||
yield bec.scans
|
||||
|
||||
|
||||
def _motor(name):
|
||||
m = mock.MagicMock()
|
||||
m.name = name
|
||||
return m
|
||||
|
||||
|
||||
def test_ascan_runs_line_scan_with_intervals_plus_one(bec_scans, capsys):
|
||||
samx = _motor("samx")
|
||||
ascan(samx, 0, 1, 10, 0.1)
|
||||
bec_scans.line_scan.assert_called_once_with(
|
||||
samx, 0, 1, steps=11, exp_time=0.1, relative=False
|
||||
)
|
||||
assert "scans.line_scan(dev.samx, 0, 1, steps=11, exp_time=0.1, relative=False)" in (
|
||||
capsys.readouterr().out
|
||||
)
|
||||
|
||||
|
||||
def test_dscan_is_relative(bec_scans, capsys):
|
||||
samy = _motor("samy")
|
||||
dscan(samy, -1, 1, 4, 0.5)
|
||||
bec_scans.line_scan.assert_called_once_with(
|
||||
samy, -1, 1, steps=5, exp_time=0.5, relative=True
|
||||
)
|
||||
assert "relative=True" in capsys.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("intervals", [0, -3, 2.5])
|
||||
def test_scan_rejects_bad_intervals(bec_scans, intervals):
|
||||
with pytest.raises(ValueError):
|
||||
ascan(_motor("samx"), 0, 1, intervals, 0.1)
|
||||
bec_scans.line_scan.assert_not_called()
|
||||
|
||||
|
||||
def test_ct(bec_scans, capsys):
|
||||
ct(0.5)
|
||||
ct()
|
||||
assert bec_scans.acquire.call_args_list == [
|
||||
mock.call(exp_time=0.5),
|
||||
mock.call(exp_time=1.0),
|
||||
]
|
||||
out = capsys.readouterr().out
|
||||
assert "scans.acquire(exp_time=0.5)" in out and "scans.acquire(exp_time=1.0)" in out
|
||||
|
||||
|
||||
def test_wm_passes_names_to_dev_wm(capsys):
|
||||
dev = mock.MagicMock()
|
||||
with mock.patch.dict(builtins.__dict__, {"dev": dev}):
|
||||
wm("samx", _motor("samy"), "sam*")
|
||||
dev.wm.assert_called_once_with(["samx", "samy", "sam*"])
|
||||
assert "dev.wm(['samx', 'samy', 'sam*'])" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_transformed_move_prints_bec_command(capsys):
|
||||
calls = []
|
||||
ns = {"umv": lambda *a: calls.append(a), "dev": mock.MagicMock()}
|
||||
exec(shell_moves(["umv samx 1\n"])[0], ns)
|
||||
assert capsys.readouterr().out == "umv(dev.samx, 1)\n"
|
||||
assert calls == [(ns["dev"].samx, 1)]
|
||||
Reference in new issue
Block a user