plothero 0.3.0b1__cp39-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
plothero/__init__.py ADDED
@@ -0,0 +1,56 @@
1
+ """plothero — Plotly-compatible plotting for heavy signals, powered by Rust.
2
+
3
+ Use it like ``plotly.graph_objects``::
4
+
5
+ import numpy as np
6
+ import plothero as ph
7
+
8
+ t = np.linspace(0, 60, 5_000_000)
9
+ y = np.sin(2 * np.pi * 1.2 * t)
10
+
11
+ fig = ph.Figure()
12
+ fig.add_trace(ph.Scatter(x=t, y=y, mode="lines", name="signal"))
13
+ fig.update_layout(title="Signal", xaxis_title="Time (s)", yaxis_title="Amplitude")
14
+ fig.show()
15
+
16
+ Traces with more points than ``downsample_threshold`` (default 5 000) are
17
+ automatically decimated with a Rust-accelerated LTTB, Min/Max, or M4
18
+ algorithm before being handed to Plotly.js, so multi-million-point signals
19
+ stay interactive (pan/zoom) in the browser. A pure-Python fallback is used
20
+ automatically if the Rust extension has not been compiled — same results,
21
+ just slower. Build it with ``maturin develop --release``.
22
+ """
23
+
24
+ from importlib.metadata import version as _pkg_version
25
+
26
+ from plothero import graph_objects, subplots
27
+ from plothero.graph_objects import Bar, Figure, Heatmap, Layout, Scatter
28
+ from plothero.subplots import make_subplots
29
+ from plothero.downsample import (
30
+ DEFAULT_THRESHOLD,
31
+ DownsampleMethod,
32
+ lttb_downsample,
33
+ m4_downsample,
34
+ minmax_downsample,
35
+ rust_available,
36
+ )
37
+
38
+ __version__ = _pkg_version("plothero")
39
+
40
+ __all__ = [
41
+ "__version__",
42
+ "graph_objects",
43
+ "subplots",
44
+ "Figure",
45
+ "Scatter",
46
+ "Bar",
47
+ "Heatmap",
48
+ "Layout",
49
+ "make_subplots",
50
+ "DownsampleMethod",
51
+ "DEFAULT_THRESHOLD",
52
+ "lttb_downsample",
53
+ "m4_downsample",
54
+ "minmax_downsample",
55
+ "rust_available",
56
+ ]
plothero/_core.pyd ADDED
Binary file
plothero/_viewer.py ADDED
@@ -0,0 +1,326 @@
1
+ """Detached viewer process behind ``Figure.show()``.
2
+
3
+ ``show()`` (parent side, :func:`launch`) renders the figure page, saves
4
+ each decimated trace's full-resolution data next to it in a temp
5
+ directory, and starts ``python -m plothero._viewer <dir>`` in a new session
6
+ (POSIX) or as a detached process (Windows). The child (:func:`main`) loads
7
+ everything back into memory, deletes the temp directory, binds an
8
+ ephemeral port, and reports its URL on stdout. The parent reads that one
9
+ line, opens the browser, and returns, so the calling script can finish
10
+ while the figure keeps serving ``/downsample`` requests.
11
+
12
+ The child exits on its own (see :class:`PageTracker`):
13
+
14
+ - once every page that loaded the figure has sent a ``pagehide`` beacon
15
+ (or stopped sending heartbeats) and nothing new connects within a short
16
+ grace period, which also covers reloads;
17
+ - if no page ever starts sending heartbeats within ``connect_timeout`` of
18
+ the last request (or of reporting its URL, if nothing connects at all).
19
+
20
+ Trace data travels as a plain ``.npz`` file (loaded with
21
+ ``allow_pickle=False``) plus a JSON manifest, so no user objects are
22
+ pickled.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ import shutil
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+ import threading
34
+ import time
35
+ from pathlib import Path
36
+ from typing import Callable, NamedTuple, Optional
37
+
38
+ import numpy as np
39
+
40
+ # Defaults for the viewer's lifecycle, in seconds. Module-level so tests
41
+ # (and a script that knows what it's doing) can shorten them before show().
42
+ HEARTBEAT_INTERVAL = 5.0
43
+ # Generous on purpose: browsers throttle timers in background tabs (Chrome
44
+ # down to once per minute), and a closed tab is normally detected right
45
+ # away through its pagehide beacon, not through this timeout.
46
+ IDLE_TIMEOUT = 120.0
47
+ CLOSE_GRACE = 10.0
48
+ CONNECT_TIMEOUT = 120.0
49
+ STARTUP_TIMEOUT = 60.0
50
+ POLL_INTERVAL = 0.25
51
+
52
+ _URL_PREFIX = "PLOTHERO_VIEWER_URL "
53
+ _MANIFEST = "manifest.json"
54
+ _PAGE = "figure.html"
55
+ _DATA = "traces.npz"
56
+
57
+ # Popen handles of launched viewers, kept so they aren't garbage-collected
58
+ # (with a ResourceWarning) while still running, and reaped once they exit.
59
+ _children: list = []
60
+
61
+
62
+ class ViewerHandle(NamedTuple):
63
+ """A launched viewer process: its ``url`` and ``process``."""
64
+
65
+ url: str
66
+ process: subprocess.Popen
67
+
68
+
69
+ class PageTracker:
70
+ """Decides when the viewer process should exit, from the requests it receives.
71
+
72
+ Thread-safe: the HTTP handler threads call :meth:`activity`,
73
+ :meth:`heartbeat` and :meth:`closed`, and the main loop polls
74
+ :meth:`should_exit`.
75
+
76
+ Args:
77
+ idle_timeout: A page that hasn't sent a heartbeat for this long
78
+ is considered gone (tab crashed, browser killed, ...).
79
+ close_grace: Once no page is left, exit after this long without
80
+ any new request. Covers a reload, whose ``pagehide`` beacon
81
+ arrives just before the new page registers.
82
+ connect_timeout: Until a first heartbeat arrives, exit after this
83
+ long without any request (counted from the latest
84
+ :meth:`activity`, which the viewer also calls once it has
85
+ reported its URL).
86
+ clock: Monotonic time source, injectable for tests.
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ idle_timeout: float,
92
+ close_grace: float,
93
+ connect_timeout: float,
94
+ clock: Callable[[], float] = time.monotonic,
95
+ ):
96
+ self.idle_timeout = idle_timeout
97
+ self.close_grace = close_grace
98
+ self.connect_timeout = connect_timeout
99
+ self._clock = clock
100
+ self._lock = threading.Lock()
101
+ self._pages: dict[str, float] = {}
102
+ self._ever_heartbeat = False
103
+ self._last_request = clock()
104
+
105
+ def activity(self) -> None:
106
+ with self._lock:
107
+ self._last_request = self._clock()
108
+
109
+ def heartbeat(self, page_id: str) -> None:
110
+ with self._lock:
111
+ now = self._clock()
112
+ self._pages[page_id] = now
113
+ self._last_request = now
114
+ self._ever_heartbeat = True
115
+
116
+ def closed(self, page_id: str) -> None:
117
+ with self._lock:
118
+ self._pages.pop(page_id, None)
119
+ self._last_request = self._clock()
120
+
121
+ def should_exit(self) -> bool:
122
+ with self._lock:
123
+ now = self._clock()
124
+ idle = now - self._last_request
125
+ if not self._ever_heartbeat:
126
+ return idle > self.connect_timeout
127
+ self._pages = {p: t for p, t in self._pages.items() if now - t <= self.idle_timeout}
128
+ return not self._pages and idle > self.close_grace
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Parent side
133
+ # ---------------------------------------------------------------------------
134
+
135
+ def _write_payload(figure, directory: Path, heartbeat_interval: float, tracker_settings: dict) -> None:
136
+ html = figure.to_html(
137
+ full_html=True,
138
+ include_plotlyjs="cdn",
139
+ _dynamic_resample=True,
140
+ _heartbeat_ms=max(1, int(heartbeat_interval * 1000)),
141
+ )
142
+ (directory / _PAGE).write_text(html, encoding="utf-8")
143
+
144
+ from plothero.downsample import DownsampleMethod
145
+
146
+ arrays = {}
147
+ traces = {}
148
+ for i, trace in enumerate(figure.traces):
149
+ if not trace.was_downsampled():
150
+ continue # the page never calls /downsample for it
151
+ arrays[f"x{i}"] = trace.x_numeric
152
+ arrays[f"y{i}"] = trace.y
153
+ traces[str(i)] = {
154
+ "x_is_datetime": bool(trace.x_is_datetime),
155
+ "downsample_method": DownsampleMethod(trace.downsample_method).value,
156
+ "downsample_threshold": int(trace.downsample_threshold),
157
+ }
158
+ np.savez(directory / _DATA, **arrays)
159
+
160
+ manifest = {"n_traces": len(figure.traces), "traces": traces, **tracker_settings}
161
+ (directory / _MANIFEST).write_text(json.dumps(manifest), encoding="utf-8")
162
+
163
+
164
+ def _detach_kwargs() -> dict:
165
+ if os.name == "nt":
166
+ return {"creationflags": subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP}
167
+ return {"start_new_session": True}
168
+
169
+
170
+ def _child_env() -> dict:
171
+ # Make the child import this very copy of plothero, even if the parent
172
+ # found it through a sys.path tweak rather than an installed package.
173
+ env = os.environ.copy()
174
+ package_root = str(Path(__file__).resolve().parent.parent)
175
+ existing = env.get("PYTHONPATH")
176
+ env["PYTHONPATH"] = package_root + (os.pathsep + existing if existing else "")
177
+ return env
178
+
179
+
180
+ def _read_url(process: subprocess.Popen, timeout: float) -> tuple[Optional[str], str]:
181
+ """Read the child's stdout until its URL line; returns ``(url or None, other output)``."""
182
+ found: list = []
183
+ output: list = []
184
+
185
+ def reader() -> None:
186
+ for raw in process.stdout:
187
+ line = raw.decode("utf-8", errors="replace").rstrip("\r\n")
188
+ if line.startswith(_URL_PREFIX):
189
+ found.append(line[len(_URL_PREFIX):])
190
+ return
191
+ output.append(line)
192
+
193
+ thread = threading.Thread(target=reader, daemon=True)
194
+ thread.start()
195
+ thread.join(timeout)
196
+ return (found[0] if found else None), "\n".join(output)
197
+
198
+
199
+ def launch(
200
+ figure,
201
+ *,
202
+ heartbeat_interval: Optional[float] = None,
203
+ idle_timeout: Optional[float] = None,
204
+ close_grace: Optional[float] = None,
205
+ connect_timeout: Optional[float] = None,
206
+ startup_timeout: Optional[float] = None,
207
+ ) -> ViewerHandle:
208
+ """Start a detached viewer process serving ``figure`` and wait until it is reachable.
209
+
210
+ Timeouts default to the module-level constants. Raises ``OSError`` if
211
+ the process can't be started, ``RuntimeError`` if it doesn't report a
212
+ URL within ``startup_timeout`` (its output is included in the message).
213
+ """
214
+ global _children
215
+ _children = [p for p in _children if p.poll() is None]
216
+
217
+ settings = {
218
+ "idle_timeout": IDLE_TIMEOUT if idle_timeout is None else idle_timeout,
219
+ "close_grace": CLOSE_GRACE if close_grace is None else close_grace,
220
+ "connect_timeout": CONNECT_TIMEOUT if connect_timeout is None else connect_timeout,
221
+ }
222
+ directory = Path(tempfile.mkdtemp(prefix="plothero-viewer-"))
223
+ try:
224
+ _write_payload(
225
+ figure,
226
+ directory,
227
+ HEARTBEAT_INTERVAL if heartbeat_interval is None else heartbeat_interval,
228
+ settings,
229
+ )
230
+ process = subprocess.Popen(
231
+ [sys.executable, "-m", "plothero._viewer", str(directory)],
232
+ stdin=subprocess.DEVNULL,
233
+ stdout=subprocess.PIPE,
234
+ stderr=subprocess.STDOUT,
235
+ cwd=tempfile.gettempdir(),
236
+ env=_child_env(),
237
+ close_fds=True,
238
+ **_detach_kwargs(),
239
+ )
240
+ except BaseException:
241
+ shutil.rmtree(directory, ignore_errors=True)
242
+ raise
243
+
244
+ url, output = _read_url(process, STARTUP_TIMEOUT if startup_timeout is None else startup_timeout)
245
+ if url is None:
246
+ process.kill()
247
+ process.wait()
248
+ process.stdout.close()
249
+ shutil.rmtree(directory, ignore_errors=True)
250
+ detail = f":\n{output}" if output.strip() else ""
251
+ raise RuntimeError(f"viewer process did not report a URL (exit code {process.returncode}){detail}")
252
+ process.stdout.close()
253
+ _children.append(process)
254
+ return ViewerHandle(url, process)
255
+
256
+
257
+ # ---------------------------------------------------------------------------
258
+ # Child side
259
+ # ---------------------------------------------------------------------------
260
+
261
+ def _load_payload(directory: Path) -> tuple[bytes, list, dict]:
262
+ from plothero.downsample import DownsampleMethod
263
+ from plothero.graph_objects import Scatter
264
+
265
+ manifest = json.loads((directory / _MANIFEST).read_text(encoding="utf-8"))
266
+ body = (directory / _PAGE).read_bytes()
267
+ traces: list = [None] * manifest["n_traces"]
268
+ with np.load(directory / _DATA, allow_pickle=False) as data:
269
+ for key, spec in manifest["traces"].items():
270
+ i = int(key)
271
+ trace = Scatter(
272
+ x=data[f"x{i}"],
273
+ y=data[f"y{i}"],
274
+ downsample_threshold=spec["downsample_threshold"],
275
+ downsample_method=DownsampleMethod(spec["downsample_method"]),
276
+ )
277
+ # x was saved already converted to float64 seconds.
278
+ trace.x_is_datetime = spec["x_is_datetime"]
279
+ traces[i] = trace
280
+ return body, traces, manifest
281
+
282
+
283
+ def _detach_stdio() -> None:
284
+ # Release the parent's pipe (so its reader sees EOF) and the terminal.
285
+ devnull = os.open(os.devnull, os.O_RDWR)
286
+ for fd in (0, 1, 2):
287
+ os.dup2(devnull, fd)
288
+ os.close(devnull)
289
+
290
+
291
+ def main(argv: Optional[list] = None) -> int:
292
+ from plothero.graph_objects import _make_request_handler, _start_server
293
+
294
+ args = sys.argv[1:] if argv is None else argv
295
+ if len(args) != 1:
296
+ print("usage: python -m plothero._viewer <payload-dir>", file=sys.stderr)
297
+ return 2
298
+ directory = Path(args[0])
299
+ try:
300
+ body, traces, manifest = _load_payload(directory)
301
+ finally:
302
+ # Everything is in memory now; nothing is left behind on disk even
303
+ # if this process is later killed.
304
+ shutil.rmtree(directory, ignore_errors=True)
305
+
306
+ tracker = PageTracker(manifest["idle_timeout"], manifest["close_grace"], manifest["connect_timeout"])
307
+ url, server = _start_server(_make_request_handler(body, traces, tracker), daemon=True)
308
+
309
+ sys.stdout.write(f"{_URL_PREFIX}{url}\n")
310
+ sys.stdout.flush()
311
+ _detach_stdio()
312
+ # The connect window starts once the URL is out, so a slow startup
313
+ # can't use it up before the parent has even read the URL.
314
+ tracker.activity()
315
+
316
+ try:
317
+ while not tracker.should_exit():
318
+ time.sleep(POLL_INTERVAL)
319
+ finally:
320
+ server.shutdown()
321
+ server.server_close()
322
+ return 0
323
+
324
+
325
+ if __name__ == "__main__":
326
+ sys.exit(main())
plothero/downsample.py ADDED
@@ -0,0 +1,190 @@
1
+ """Downsampling backends.
2
+
3
+ Uses the compiled Rust extension (``plothero._core``) when available, and
4
+ falls back to a pure-Python implementation otherwise so the package still
5
+ works (just slower) without a Rust toolchain.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import enum
11
+
12
+ import numpy as np
13
+
14
+ try:
15
+ from plothero._core import lttb_downsample as _lttb_rs
16
+ from plothero._core import m4_downsample as _m4_rs
17
+ from plothero._core import minmax_downsample as _minmax_rs
18
+ RUST_AVAILABLE = True
19
+ except ImportError:
20
+ RUST_AVAILABLE = False
21
+
22
+ DEFAULT_THRESHOLD = 5_000 # points above this trigger automatic downsampling
23
+
24
+
25
+ class DownsampleMethod(enum.Enum):
26
+ """Downsampling algorithm to use when rendering large traces."""
27
+ LTTB = "lttb" # Best visual fidelity for smooth signals
28
+ MINMAX = "minmax" # Preserves peaks/troughs — preferred for biomedical signals
29
+ M4 = "m4" # Preserves peaks/troughs *and* bucket boundaries — twice MinMax's point cost
30
+ NONE = "none" # No downsampling (renders all points — use with care)
31
+
32
+
33
+ def _lttb_py(x: np.ndarray, y: np.ndarray, threshold: int):
34
+ """LTTB downsampling — pure Python fallback."""
35
+ n = len(x)
36
+ if threshold == 0 or threshold >= n:
37
+ return x, y
38
+ if threshold < 3:
39
+ return np.array([x[0], x[-1]]), np.array([y[0], y[-1]])
40
+
41
+ out_x = [x[0]]
42
+ out_y = [y[0]]
43
+ bucket_size = (n - 2) / (threshold - 2)
44
+ last_idx = 0
45
+
46
+ for i in range(threshold - 2):
47
+ curr_start = max(int(i * bucket_size + 1), 1)
48
+ curr_end = min(int((i + 1) * bucket_size + 1), n - 1)
49
+
50
+ next_start = int((i + 1) * bucket_size + 1)
51
+ next_end = min(int((i + 2) * bucket_size + 1), n)
52
+ next_start = min(next_start, n - 1)
53
+
54
+ avg_x = float(np.mean(x[next_start:next_end]))
55
+ avg_y = float(np.mean(y[next_start:next_end]))
56
+
57
+ ax, ay = float(x[last_idx]), float(y[last_idx])
58
+ max_area = -1.0
59
+ max_idx = curr_start
60
+
61
+ for j in range(curr_start, curr_end + 1):
62
+ area = abs((ax - avg_x) * (float(y[j]) - ay) - (ax - float(x[j])) * (avg_y - ay))
63
+ if area > max_area:
64
+ max_area = area
65
+ max_idx = j
66
+
67
+ out_x.append(x[max_idx])
68
+ out_y.append(y[max_idx])
69
+ last_idx = max_idx
70
+
71
+ out_x.append(x[-1])
72
+ out_y.append(y[-1])
73
+ return np.array(out_x, dtype=np.float64), np.array(out_y, dtype=np.float64)
74
+
75
+
76
+ def _minmax_py(x: np.ndarray, y: np.ndarray, n_out: int):
77
+ """MinMax downsampling — pure Python fallback."""
78
+ n = len(x)
79
+ if n_out == 0 or n_out >= n:
80
+ return x, y
81
+
82
+ n_buckets = max(n_out // 2, 1)
83
+ bucket_size = n / n_buckets
84
+
85
+ out_x: list = []
86
+ out_y: list = []
87
+
88
+ for i in range(n_buckets):
89
+ start = int(i * bucket_size)
90
+ end = min(int((i + 1) * bucket_size), n)
91
+ if start >= end:
92
+ continue
93
+
94
+ bucket_y = y[start:end]
95
+ min_idx = start + int(np.argmin(bucket_y))
96
+ max_idx = start + int(np.argmax(bucket_y))
97
+
98
+ if min_idx == max_idx:
99
+ out_x.append(x[min_idx])
100
+ out_y.append(y[min_idx])
101
+ elif min_idx < max_idx:
102
+ out_x.extend([x[min_idx], x[max_idx]])
103
+ out_y.extend([y[min_idx], y[max_idx]])
104
+ else:
105
+ out_x.extend([x[max_idx], x[min_idx]])
106
+ out_y.extend([y[max_idx], y[min_idx]])
107
+
108
+ return np.array(out_x, dtype=np.float64), np.array(out_y, dtype=np.float64)
109
+
110
+
111
+ def _m4_py(x: np.ndarray, y: np.ndarray, n_out: int):
112
+ """M4 downsampling — pure Python fallback."""
113
+ n = len(x)
114
+ if n_out == 0 or n_out >= n:
115
+ return x, y
116
+
117
+ n_buckets = max(n_out // 4, 1)
118
+ bucket_size = n / n_buckets
119
+
120
+ out_x: list = []
121
+ out_y: list = []
122
+
123
+ for i in range(n_buckets):
124
+ start = int(i * bucket_size)
125
+ end = min(int((i + 1) * bucket_size), n)
126
+ if start >= end:
127
+ continue
128
+
129
+ bucket_y = y[start:end]
130
+ first_idx = start
131
+ last_idx = end - 1
132
+ min_idx = start + int(np.argmin(bucket_y))
133
+ max_idx = start + int(np.argmax(bucket_y))
134
+
135
+ # Chronological order, deduplicated (a bucket with < 4 distinct
136
+ # samples would otherwise repeat a point, e.g. first == min).
137
+ for idx in sorted({first_idx, min_idx, max_idx, last_idx}):
138
+ out_x.append(x[idx])
139
+ out_y.append(y[idx])
140
+
141
+ return np.array(out_x, dtype=np.float64), np.array(out_y, dtype=np.float64)
142
+
143
+
144
+ def lttb_downsample(x: np.ndarray, y: np.ndarray, threshold: int):
145
+ """Downsample ``(x, y)`` to ``threshold`` points using LTTB.
146
+
147
+ Returns ``(x_out, y_out)`` as float64 numpy arrays. Uses the compiled
148
+ Rust extension when available, otherwise a pure-Python fallback.
149
+ """
150
+ x = np.ascontiguousarray(x, dtype=np.float64)
151
+ y = np.ascontiguousarray(y, dtype=np.float64)
152
+ if RUST_AVAILABLE:
153
+ return _lttb_rs(x, y, threshold)
154
+ return _lttb_py(x, y, threshold)
155
+
156
+
157
+ def minmax_downsample(x: np.ndarray, y: np.ndarray, n_out: int):
158
+ """Downsample ``(x, y)`` to ~``n_out`` points using Min/Max decimation.
159
+
160
+ Returns ``(x_out, y_out)`` as float64 numpy arrays. Uses the compiled
161
+ Rust extension when available, otherwise a pure-Python fallback.
162
+ """
163
+ x = np.ascontiguousarray(x, dtype=np.float64)
164
+ y = np.ascontiguousarray(y, dtype=np.float64)
165
+ if RUST_AVAILABLE:
166
+ return _minmax_rs(x, y, n_out)
167
+ return _minmax_py(x, y, n_out)
168
+
169
+
170
+ def m4_downsample(x: np.ndarray, y: np.ndarray, n_out: int):
171
+ """Downsample ``(x, y)`` to ~``n_out`` points using M4 decimation.
172
+
173
+ Keeps the first, last, minimum, and maximum sample of each bucket
174
+ (deduplicated, in chronological order) — like Min/Max, but also
175
+ preserving each bucket's boundary samples at up to twice the point
176
+ cost per bucket.
177
+
178
+ Returns ``(x_out, y_out)`` as float64 numpy arrays. Uses the compiled
179
+ Rust extension when available, otherwise a pure-Python fallback.
180
+ """
181
+ x = np.ascontiguousarray(x, dtype=np.float64)
182
+ y = np.ascontiguousarray(y, dtype=np.float64)
183
+ if RUST_AVAILABLE:
184
+ return _m4_rs(x, y, n_out)
185
+ return _m4_py(x, y, n_out)
186
+
187
+
188
+ def rust_available() -> bool:
189
+ """Return ``True`` if the compiled Rust extension is loaded."""
190
+ return RUST_AVAILABLE