diff --git a/docs/terminal_plots.md b/docs/terminal_plots.md index d20e33a..7734377 100644 --- a/docs/terminal_plots.md +++ b/docs/terminal_plots.md @@ -15,7 +15,12 @@ Checked against uniplot 0.23.2 (2026-10), and sufficient for now: - Log axes (`x_as_log`, `y_as_log`), units (`x_unit`, `y_unit`), gridlines, fixed ranges (`x_min` ... `y_max`). - Character sets `BLOCK` (2x2 quadrants, the default, renders cleanly in every font), `BRAILLE` (2x4, finer, but gaps in some fonts) and `ASCII`. -Plan: wrap uniplot behind a small eco module (proposed name `eco.utilities.termplot`) shaped around eco's own plots: stacked panels, strip charts, counters, archiver traces, the tweak recorder. Callers depend on that module, not on uniplot. If the gaps below start to hurt, replace the renderer with an own copy (MIT allows it; keep the copyright notice) without touching the callers. +uniplot sits behind `eco.utilities.termplot`, an eco-shaped layer that callers use instead of uniplot directly: + +- `panel_stack()` stacks plots over a shared x range, with x tick labels only under the last one. +- `LiveRegion` / `LivePlotter` keep a plot just above the current terminal line and redraw it in place. Other code can keep rewriting a status line with `\r` meanwhile, as the terminal tweaks do. While active, `LiveRegion` replaces `sys.stdout` with a proxy so it can tell whether anything else printed a newline. If so, it prints a fresh copy and restores the status line under it. + +First user: the terminal tweak's detector plot when there is no display (`ECO_NO_X=1` or plain ssh, see `eco.widgets.tweak_recorder.terminal_plot_text`). Strip charts, counters and archiver traces are meant to follow. If the gaps below start to hurt, replace the renderer with an own copy (MIT allows it; keep the copyright notice) without touching the callers. ## Shortcomings to address in an own copy diff --git a/eco/utilities/termplot.py b/eco/utilities/termplot.py new file mode 100644 index 0000000..067eff0 --- /dev/null +++ b/eco/utilities/termplot.py @@ -0,0 +1,201 @@ +""" +Text plots in the terminal, for where no Qt window can be shown (plain ssh, +ECO_NO_X=1). A thin eco-shaped layer over uniplot -- callers use this module, +not uniplot, so the renderer can be replaced later. See docs/terminal_plots.md +for the decision and the list of uniplot's shortcomings. + +- panel_stack(): several plots stacked vertically over a shared x range +- LiveRegion: keeps a block of text (a plot) just above the current terminal + line and redraws it in place, without disturbing a status line that other + code keeps rewriting with '\\r' (as the terminal tweaks do). +""" + +import shutil +import sys +import threading + +import numpy as np + + +def available(): + try: + import uniplot # noqa: F401 + + return True + except Exception: + return False + + +def terminal_size(): + return shutil.get_terminal_size((100, 40)) + + +def panel_stack(panels, width=None, height=4, x_range=None): + """Render panels stacked over a shared x range; x tick labels only under + the last one. + + panels: list of dicts with "title", "xs", "ys" and optionally + "highlight_last" (draw the last point as a separate marker series). + Returns the text, lines joined with '\\n'.""" + from uniplot import plot_to_string + + if width is None: + width = max(20, terminal_size().columns - 14) + finite_x = [ + np.asarray(p["xs"], dtype=float)[np.isfinite(np.asarray(p["xs"], dtype=float))] + for p in panels + ] + if x_range is None: + allx = np.concatenate(finite_x) if finite_x else np.array([]) + x_range = (allx.min(), allx.max()) if allx.size else (0.0, 1.0) + x_min, x_max = x_range + if x_max <= x_min: + x_min, x_max = x_min - 0.5, x_max + 0.5 + + blocks = [] + for k, p in enumerate(panels): + xs = np.asarray(p["xs"], dtype=float) + ys = np.asarray(p["ys"], dtype=float) + ok = np.isfinite(xs) & np.isfinite(ys) + xs, ys = xs[ok], ys[ok] + if xs.size == 0: # nothing to show yet: an empty frame of the same size + xs, ys = np.array([np.nan]), np.array([np.nan]) + series_x, series_y, lines = [xs], [ys], [True] + if p.get("highlight_last") and np.isfinite(xs[-1]): + series_x.append(xs[-1:]) + series_y.append(ys[-1:]) + lines.append(False) + kwargs = dict( + width=width, + height=height, + title=p["title"], + lines=lines, + x_min=x_min, + x_max=x_max, + x_labels=(k == len(panels) - 1), + color=len(series_y) > 1, + ) + try: + text = plot_to_string(series_y if len(series_y) > 1 else series_y[0], + series_x if len(series_x) > 1 else series_x[0], + **kwargs) + except Exception: + kwargs["color"] = False + text = plot_to_string([0.0], [x_min], **dict(kwargs, lines=[False])) + blocks.append(text.rstrip("\n")) + return "\n".join(blocks) + + +class LiveRegion: + """Proxy for sys.stdout that keeps a text block just above the line the + cursor is on, redrawing it in place. + + While installed, all output goes through it (so it knows whether lines + were added since the block was drawn, and what the current line shows): + - nothing printed a newline since the last draw -> the block is redrawn + in place (cursor up, rewrite, back down), the current line untouched + - otherwise (help text, prompts, other output scrolled in between) -> + a fresh copy is printed, and the current line (e.g. a status line + written with '\\r') is restored under it.""" + + def __init__(self, stream=None): + self._stream = stream if stream is not None else sys.stdout + self._lock = threading.RLock() + self._newlines = 0 + self._tail = "" + self._height = 0 + self._installed = False + + # --- stdout proxy --- + def write(self, s): + with self._lock: + n = self._stream.write(s) + if "\n" in s: + self._newlines += s.count("\n") + self._tail = s.rsplit("\n", 1)[1] + else: + self._tail += s + segments = [seg for seg in self._tail.split("\r") if seg] + self._tail = segments[-1] if segments else "" + return n + + def flush(self): + self._stream.flush() + + def __getattr__(self, name): + return getattr(self._stream, name) + + def install(self): + if not self._installed: + sys.stdout = self + self._installed = True + return self + + def uninstall(self): + if self._installed and sys.stdout is self: + sys.stdout = self._stream + self._installed = False + + # --- drawing --- + def show(self, text): + lines = text.split("\n") + with self._lock: + if self._height and self._height == len(lines) and self._newlines == 0: + seq = f"\r\x1b[{len(lines)}A" + "".join( + "\x1b[2K" + line + "\n" for line in lines + ) + else: + seq = ( + "\r\x1b[2K" + + "".join("\x1b[2K" + line + "\n" for line in lines) + + self._tail + + "\r" + ) + self._stream.write(seq) + self._stream.flush() + self._height = len(lines) + self._newlines = 0 + + +class LivePlotter: + """Redraws `render()` into a LiveRegion whenever `version()` changes.""" + + def __init__(self, render, version, interval=0.3, stream=None): + self._render = render + self._version = version + self._interval = interval + self.region = LiveRegion(stream) + self._stop_event = threading.Event() + self._drawn = None + self._thread = None + + def start(self): + self.region.install() + self._thread = threading.Thread(target=self._run, daemon=True) + self._thread.start() + return self + + def refresh(self): + version = self._version() + if version == self._drawn: + return + self._drawn = version + self.region.show(self._render()) + + def _run(self): + while not self._stop_event.is_set(): + try: + self.refresh() + except Exception: + pass + self._stop_event.wait(self._interval) + + def stop(self): + self._stop_event.set() + if self._thread is not None: + self._thread.join(timeout=2) + try: + self.refresh() # final state + except Exception: + pass + self.region.uninstall() diff --git a/eco/widgets/tweak_recorder.py b/eco/widgets/tweak_recorder.py index 764ab18..b6a3b75 100644 --- a/eco/widgets/tweak_recorder.py +++ b/eco/widgets/tweak_recorder.py @@ -234,6 +234,43 @@ def draw_tweak_plot(fig, recorder): fig.tight_layout() +def terminal_plot_text(recorder, width=None, reserve_rows=12): + """The recorder's plot as text (eco.utilities.termplot): the same layout + as draw_tweak_plot, sized to the terminal, leaving `reserve_rows` for + the tweak's help and status lines.""" + from eco.utilities import termplot + + steps, pos, val = recorder.arrays() + if len(recorder.axes) == 1: + x = pos[:, 0] if len(steps) else [] + panels = [ + { + "title": f"{name} vs {recorder.axis_names[0]}", + "xs": x, + "ys": val[:, i] if len(steps) else [], + "highlight_last": True, + } + for i, name in enumerate(recorder.detector_names) + ] + else: + series = [(n, val[:, i]) for i, n in enumerate(recorder.detector_names)] + series += [(n, pos[:, i]) for i, n in enumerate(recorder.axis_names)] + panels = [ + { + "title": name, + "xs": steps, + "ys": y if len(steps) else [], + "highlight_last": True, + } + for name, y in series + ] + panels[-1]["title"] += " (x: step)" + # per panel: title + 2 frame lines + height; x labels once at the bottom + rows = termplot.terminal_size().lines - reserve_rows + height = max(2, min(8, (rows - 1) // max(1, len(panels)) - 3)) + return termplot.panel_stack(panels, width=width, height=height) + + def figure_size(recorder): return (5.0, max(2.8, 1.7 * plot_rows(recorder))) @@ -262,6 +299,24 @@ def display_available(): return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")) +def _start_text_plot(recorder): + """Live text plot above the terminal tweak's status line, or None (with + a message) where that isn't possible.""" + import sys + + from eco.utilities import termplot + + if not termplot.available(): + print("tweak: no display and no uniplot for a text plot; still recording") + return None + if not getattr(sys.stdout, "isatty", lambda: False)(): + print("tweak: output is not a terminal, no text plot; still recording") + return None + return termplot.LivePlotter( + lambda: terminal_plot_text(recorder), lambda: recorder.version + ).start() + + @contextlib.contextmanager def terminal_recording(axes, detectors, owner=None, label=None): """Record (and, where a display is available, live-plot in a Qt window) @@ -278,6 +333,7 @@ def terminal_recording(axes, detectors, owner=None, label=None): owner._tweak_recorder = recorder except Exception: pass + text_plotter = None if display_available(): try: from eco.widgets.tweak_panel_qt import show_tweak_plot_qt @@ -286,11 +342,13 @@ def terminal_recording(axes, detectors, owner=None, label=None): except Exception as exc: print(f"tweak: no live plot ({exc}); still recording") else: - print("tweak: no display for a live plot; still recording") + text_plotter = _start_text_plot(recorder) try: yield recorder finally: recorder.stop() + if text_plotter is not None: + text_plotter.stop() print( f"\ntweak recorded {len(recorder.points)} points " f"({label or 'recorder'}.to_dataframe() for the data)" diff --git a/tests/test_termplot.py b/tests/test_termplot.py new file mode 100644 index 0000000..6575572 --- /dev/null +++ b/tests/test_termplot.py @@ -0,0 +1,73 @@ +"""eco.utilities.termplot: stacked text plots and the in-place live region.""" + +import io + +import pytest + +from eco.utilities import termplot + + +def test_live_region_redraws_in_place_when_nothing_scrolled(): + out = io.StringIO() + region = termplot.LiveRegion(out) + region.write("help\n") + region.write("\x1b[2Kstatus 1\r") + region.show("a\nb") + first = out.getvalue() + # first draw: fresh copy, then the status line restored under it + assert first.endswith("\x1b[2Ka\n\x1b[2Kb\n\x1b[2Kstatus 1\r") + region.write("\x1b[2Kstatus 2\r") # status updates with \r only + region.show("c\nd") + # nothing scrolled: cursor up 2 lines, rewrite, status line untouched + assert out.getvalue()[len(first):] == ( + "\x1b[2Kstatus 2\r" + "\r\x1b[2A\x1b[2Kc\n\x1b[2Kd\n" + ) + + +def test_live_region_prints_a_fresh_copy_after_other_output(): + out = io.StringIO() + region = termplot.LiveRegion(out) + region.show("a\nb") + region.write("enter absolute position\n") + region.write("\x1b[2Kstatus\r") + region.show("c\nd") + assert out.getvalue().endswith("\r\x1b[2K\x1b[2Kc\n\x1b[2Kd\n\x1b[2Kstatus\r") + region.show("e") # height changed: fresh copy as well + assert out.getvalue().endswith("\x1b[2Ke\n\x1b[2Kstatus\r") + + +def test_live_region_installs_as_stdout(monkeypatch): + import sys + + out = io.StringIO() + monkeypatch.setattr(sys, "stdout", out) + region = termplot.LiveRegion().install() + assert sys.stdout is region + print("x") + region.uninstall() + assert sys.stdout is out and out.getvalue() == "x\n" + + +def test_panel_stack_shares_x_and_labels_only_the_bottom(): + pytest.importorskip("uniplot") + text = termplot.panel_stack( + [ + {"title": "det", "xs": [0, 1, 2], "ys": [1, 3, 2], "highlight_last": True}, + {"title": "mot", "xs": [0, 1, 2], "ys": [0, 0.5, 1]}, + {"title": "empty", "xs": [], "ys": []}, + ], + width=40, + height=3, + ) + lines = text.split("\n") + assert [l.strip() for l in lines if l.strip() in ("det", "mot", "empty")] == [ + "det", + "mot", + "empty", + ] + frame_ends = [i for i, l in enumerate(lines) if l.startswith("└")] + assert len(frame_ends) == 3 + # x tick labels once, under the last panel only + assert frame_ends[-1] == len(lines) - 2 and lines[-1].strip().startswith("0") + assert all(lines[i + 1].strip() in ("mot", "empty") for i in frame_ends[:-1]) + assert len(lines) == 3 * (1 + 2 + 3) + 1 diff --git a/tests/test_tweak_recorder.py b/tests/test_tweak_recorder.py index 0dc6dc6..3ea9e13 100644 --- a/tests/test_tweak_recorder.py +++ b/tests/test_tweak_recorder.py @@ -238,3 +238,24 @@ def test_ipy_panel_renders_the_plot_as_png(): assert bytes(panel.plot.value[:4]) == b"\x89PNG" finally: panel.close() + + +def test_terminal_plot_text_has_the_panel_layout(monkeypatch): + pytest.importorskip("uniplot") + import os + + from eco.utilities import termplot + from eco.widgets.tweak_recorder import terminal_plot_text + + monkeypatch.setattr(termplot, "terminal_size", lambda: os.terminal_size((80, 40))) + x = Axis("mirror") + rec = TweakRecorder([x], [Det("diode", range(9)), Det("cam", range(9))], settle_samples=1) + rec.sample() + text = terminal_plot_text(rec) + assert "diode vs mirror" in text and "cam vs mirror" in text + rec2 = TweakRecorder([Axis("x"), Axis("y")], Det("d", range(9)), settle_samples=1) + rec2.sample() + text = terminal_plot_text(rec2) + titles = [l.strip() for l in text.split("\n") if l.strip() in ("d", "x", "y (x: step)")] + assert titles == ["d", "x", "y (x: step)"] + assert len(text.split("\n")) <= 40 - 12