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.
@@ -0,0 +1,1124 @@
1
+ """Plotly-compatible graph objects: ``Figure``, ``Scatter``, ``Bar``, ``Heatmap``, ``Layout``.
2
+
3
+ Mirrors the ``plotly.graph_objects`` API surface closely enough that most
4
+ code written for it works unchanged after swapping the import to
5
+ ``import plothero.graph_objects as go``. ``Figure``, ``Scatter``, ``Bar``,
6
+ ``Heatmap``, and ``Layout`` are also exported by the top-level package, which
7
+ is the recommended style::
8
+
9
+ import plothero as ph
10
+
11
+ fig = ph.Figure()
12
+ fig.add_trace(ph.Scatter(x=t, y=y, mode="lines", name="signal",
13
+ line=dict(color="#e41a1c", width=1)))
14
+ fig.update_layout(title="Signal", xaxis_title="Time (s)")
15
+ fig.show()
16
+
17
+ Any keyword not explicitly modeled here (``line``, ``marker``, ``opacity``,
18
+ ``hovertemplate``, ``fill``, ...) is passed straight through to the Plotly.js
19
+ JSON spec, including Plotly's "magic underscore" shorthand
20
+ (``marker_color="red"`` -> ``marker={"color": "red"}``). Traces larger than
21
+ ``downsample_threshold`` points are transparently decimated (Rust-accelerated
22
+ LTTB/Min-Max) before being handed to Plotly.js — this is the one addition
23
+ Plotly itself does not have, exposed as optional extra kwargs.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import copy
29
+ import enum
30
+ import json
31
+ import re
32
+ import socketserver
33
+ import threading
34
+ import warnings
35
+ import webbrowser
36
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
37
+ from pathlib import Path
38
+ from typing import Any, Optional, Union
39
+ from urllib.parse import parse_qs, urlparse
40
+
41
+ import numpy as np
42
+
43
+ from plothero.downsample import (
44
+ DEFAULT_THRESHOLD,
45
+ DownsampleMethod,
46
+ lttb_downsample,
47
+ m4_downsample,
48
+ minmax_downsample,
49
+ )
50
+
51
+ PLOTLYJS_CDN = "https://cdn.plot.ly/plotly-2.35.2.min.js"
52
+ DEFAULT_HTML_WIDTH = "100%"
53
+ DEFAULT_HTML_HEIGHT = "600px"
54
+
55
+ # Point budget for a single zoomed-in /downsample fetch. Deliberately much
56
+ # higher than a trace's static downsample_threshold (which sizes the
57
+ # initial full-range view): a zoomed-in fetch only covers a slice of the
58
+ # timeline, so it can afford far more points, and the extra density is
59
+ # what makes noisy signals read as a filled band instead of a jagged
60
+ # comb. resample_range() already returns the exact raw slice untouched
61
+ # when it has fewer than this many points, so tight zooms show real data.
62
+ DYNAMIC_RESAMPLE_POINTS = 20_000
63
+
64
+ # Keys under which Plotly's "magic underscore" notation nests remaining
65
+ # segments, e.g. xaxis_title -> {"xaxis": {"title": ...}}.
66
+ NESTED_PREFIXES = (
67
+ "xaxis", "yaxis", "title", "legend", "margin", "font", "line", "marker",
68
+ "hoverlabel", "colorbar", "textfont", "scene",
69
+ )
70
+
71
+ # Real top-level Layout keys that happen to contain an underscore but must
72
+ # NOT be split by the magic-underscore expander.
73
+ FLAT_KEYS = {
74
+ "plot_bgcolor", "paper_bgcolor", "showlegend", "hovermode",
75
+ "hoverdistance", "dragmode", "clickmode", "barmode", "bargap",
76
+ "bargroupgap", "boxmode", "violinmode", "uirevision", "separators",
77
+ }
78
+
79
+
80
+ # ---------------------------------------------------------------------------
81
+ # JSON / dict helpers
82
+ # ---------------------------------------------------------------------------
83
+
84
+ def to_plotly_json(value: Any) -> Any:
85
+ """Recursively convert a value to something JSON-serialisable."""
86
+ if isinstance(value, dict):
87
+ return {k: to_plotly_json(v) for k, v in value.items()}
88
+ if isinstance(value, (list, tuple)):
89
+ return [to_plotly_json(v) for v in value]
90
+ if isinstance(value, np.ndarray):
91
+ return value.tolist()
92
+ if isinstance(value, np.generic):
93
+ return value.item()
94
+ if isinstance(value, enum.Enum):
95
+ return value.value
96
+ if hasattr(value, "to_plotly_json"):
97
+ return value.to_plotly_json()
98
+ return value
99
+
100
+
101
+ def _axis_suffix(index: int) -> str:
102
+ """Plotly axis id suffix for a 1-indexed subplot: 1 -> '', 2 -> '2', ..."""
103
+ return "" if index == 1 else str(index)
104
+
105
+
106
+ def deep_merge(base: dict, updates: dict) -> dict:
107
+ """Recursively merge ``updates`` into ``base`` (in place)."""
108
+ for key, value in updates.items():
109
+ if isinstance(value, dict) and isinstance(base.get(key), dict):
110
+ deep_merge(base[key], value)
111
+ else:
112
+ base[key] = value
113
+ return base
114
+
115
+
116
+ def expand_underscore(kwargs: dict) -> dict:
117
+ """Expand Plotly's magic-underscore kwargs into nested dicts.
118
+
119
+ ``marker_color="red"`` -> ``{"marker": {"color": "red"}}``
120
+ ``xaxis_title="Time"`` -> ``{"xaxis": {"title": "Time"}}``
121
+
122
+ Known flat keys (e.g. ``plot_bgcolor``) are left untouched.
123
+ """
124
+ result: dict = {}
125
+ for key, value in kwargs.items():
126
+ if key in FLAT_KEYS or "_" not in key:
127
+ result[key] = to_plotly_json(value)
128
+ continue
129
+ prefix, _, rest = key.partition("_")
130
+ if prefix in NESTED_PREFIXES:
131
+ nested = expand_underscore({rest: value})
132
+ container = result.setdefault(prefix, {})
133
+ deep_merge(container, nested)
134
+ else:
135
+ result[key] = to_plotly_json(value)
136
+ return result
137
+
138
+
139
+ # ---------------------------------------------------------------------------
140
+ # Datetime helpers
141
+ # ---------------------------------------------------------------------------
142
+
143
+ def to_numeric(x) -> tuple[np.ndarray, bool]:
144
+ """Return ``(x_float64, is_datetime)``.
145
+
146
+ Converts ``datetime64`` / pandas ``DatetimeIndex`` / date-like objects to
147
+ float64 seconds-since-epoch so they can be downsampled numerically.
148
+ """
149
+ arr = np.asarray(x)
150
+
151
+ if np.issubdtype(arr.dtype, np.datetime64):
152
+ ns = arr.astype("datetime64[ns]").astype(np.float64)
153
+ return np.ascontiguousarray(ns / 1e9, dtype=np.float64), True
154
+
155
+ if arr.dtype == object:
156
+ try:
157
+ import pandas as pd
158
+ parsed = pd.to_datetime(arr)
159
+ # Force ns resolution explicitly: pandas >= 2.0 may parse into
160
+ # us/ms-resolution datetime64 depending on input, and a bare
161
+ # .astype(np.int64) would then be in the wrong unit.
162
+ ns = parsed.to_numpy().astype("datetime64[ns]").astype(np.int64).astype(np.float64)
163
+ return np.ascontiguousarray(ns / 1e9, dtype=np.float64), True
164
+ except Exception:
165
+ pass
166
+
167
+ return np.ascontiguousarray(arr, dtype=np.float64), False
168
+
169
+
170
+ _PLOTLY_DATE_RE = re.compile(r"\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?)?\Z")
171
+
172
+ _NS_PER_UNIT = {
173
+ "D": 86_400 * 10**9, "h": 3_600 * 10**9, "m": 60 * 10**9,
174
+ "s": 10**9, "ms": 10**6, "us": 10**3, "ns": 1,
175
+ }
176
+ # datetime64[ns] covers about 1677 to 2262; these are its limits in us.
177
+ _NS_RANGE_US = (-(2**63) // 1000 + 1, (2**63 - 1) // 1000)
178
+
179
+
180
+ def _datetime64_to_ns(dt: np.datetime64) -> Optional[int]:
181
+ """Nanoseconds since the epoch as an exact Python ``int`` (``None`` for NaT).
182
+
183
+ Unlike ``dt.astype("datetime64[ns]")``, which wraps around silently
184
+ outside the datetime64[ns] range, this is correct for any year.
185
+ """
186
+ if np.isnat(dt):
187
+ return None
188
+ unit, count = np.datetime_data(dt.dtype)
189
+ if unit not in _NS_PER_UNIT: # Y, M, W: calendar units, exact in days
190
+ dt, unit, count = dt.astype("datetime64[D]"), "D", 1
191
+ return int(dt.astype(np.int64)) * count * _NS_PER_UNIT[unit]
192
+
193
+
194
+ def _plotly_bound_to_ns(raw: str) -> int:
195
+ """Parse a bound in the format Plotly.js reports (see ``_PLOTLY_DATE_RE``) without pandas."""
196
+ # The fraction is added as an integer: numpy would parse 7 to 9
197
+ # fractional digits straight to datetime64[ns], which wraps far-out years.
198
+ whole, _, fraction = raw.partition(".")
199
+ return _datetime64_to_ns(np.datetime64(whole)) + int(fraction.ljust(9, "0"))
200
+
201
+
202
+ def _numpy_bound_to_ns(raw: str) -> Optional[int]:
203
+ # Parse at us first: unlike ns, it covers any year. Inside the ns range,
204
+ # parse again at ns to keep sub-microsecond digits.
205
+ dt = np.datetime64(raw, "us")
206
+ if not np.isnat(dt) and _NS_RANGE_US[0] <= int(dt.astype(np.int64)) <= _NS_RANGE_US[1]:
207
+ dt = np.datetime64(raw, "ns")
208
+ return _datetime64_to_ns(dt)
209
+
210
+
211
+ def _datetime_bound_to_seconds(raw: str) -> float:
212
+ """Parse one datetime axis bound reported by Plotly.js to seconds-since-epoch.
213
+
214
+ Plotly.js trims trailing zeros, so the two bounds of a range can differ
215
+ in precision (e.g. ``2026-01-01`` vs ``2026-01-01 00:10:00.5``). Parsing
216
+ each bound on its own as ISO-8601 avoids pandas inferring one format
217
+ from the first value and rejecting the second. Raises ``ValueError``
218
+ for a bound that is not a valid ISO-8601 date.
219
+
220
+ The zero-padded, timezone-free strings Plotly.js reports after a zoom
221
+ (``YYYY-MM-DD[ HH:MM[:SS[.fff]]]``) are parsed with numpy. Any other
222
+ input goes to pandas when it is installed, since numpy is stricter
223
+ (e.g. for timezone suffixes), and to numpy otherwise.
224
+
225
+ Years outside the datetime64[ns] range (about 1677 to 2262), which
226
+ Plotly.js reports when the axis is zoomed far out, are converted
227
+ exactly too. All data lies inside that range, so such a bound simply
228
+ includes everything on its side.
229
+ """
230
+ if _PLOTLY_DATE_RE.match(raw):
231
+ # The format Plotly.js reports, on which numpy and pandas agree.
232
+ # Parsing it with numpy keeps the first zoom from importing pandas,
233
+ # which can take several seconds in a fresh environment.
234
+ return _plotly_bound_to_ns(raw) / 1e9
235
+ try:
236
+ import pandas as pd
237
+ except ImportError:
238
+ ns = _numpy_bound_to_ns(raw)
239
+ else:
240
+ try:
241
+ ts = pd.to_datetime(raw, format="ISO8601")
242
+ except (OverflowError, pd.errors.OutOfBoundsDatetime):
243
+ # Older pandas only parses into the datetime64[ns] range.
244
+ ns = _numpy_bound_to_ns(raw)
245
+ else:
246
+ # to_datetime64() keeps the Timestamp's own unit (us for far-out
247
+ # years in newer pandas), where .value would raise OverflowError.
248
+ ns = None if pd.isna(ts) else _datetime64_to_ns(ts.to_datetime64())
249
+ if ns is None:
250
+ raise ValueError(f"invalid datetime range bound: {raw!r}")
251
+ return ns / 1e9
252
+
253
+
254
+ def numeric_to_iso(x_seconds: np.ndarray) -> list[str]:
255
+ """Convert float64 seconds-since-epoch back to ISO-8601 strings."""
256
+ ns = (x_seconds * 1e9).astype("datetime64[ns]")
257
+ return [str(t) for t in ns]
258
+
259
+
260
+ # ---------------------------------------------------------------------------
261
+ # Scatter
262
+ # ---------------------------------------------------------------------------
263
+
264
+ class Scatter:
265
+ """Plotly-compatible scatter/line trace with transparent downsampling.
266
+
267
+ Accepts the same keyword arguments as ``plotly.graph_objects.Scatter``
268
+ (``x``, ``y``, ``mode``, ``name``, ``line``, ``marker``, ``opacity``,
269
+ ``text``, ``fill``, ``hovertemplate``, magic-underscore shortcuts such as
270
+ ``line_color=``/``marker_size=``, ...). Unrecognised keywords are passed
271
+ straight through to the Plotly.js trace spec.
272
+
273
+ ``x`` accepts numeric values, ``datetime64``, or a pandas
274
+ ``DatetimeIndex`` — datetime handling is automatic, exactly like real
275
+ Plotly.
276
+
277
+ Extra keywords (not present in Plotly) control downsampling for large
278
+ traces:
279
+
280
+ Args:
281
+ downsample_threshold: Automatically downsample when the trace has
282
+ more than this many points. Default 5 000.
283
+ downsample_method: :class:`~plothero.DownsampleMethod` to use.
284
+ Default ``MINMAX`` (preserves peaks/troughs).
285
+ """
286
+
287
+ type = "scatter"
288
+
289
+ def __init__(
290
+ self,
291
+ x=None,
292
+ y=None,
293
+ mode: Optional[str] = None,
294
+ name: Optional[str] = None,
295
+ downsample_threshold: int = DEFAULT_THRESHOLD,
296
+ downsample_method: DownsampleMethod = DownsampleMethod.MINMAX,
297
+ **kwargs,
298
+ ):
299
+ if y is None:
300
+ raise ValueError("Scatter requires 'y'")
301
+
302
+ self.y = np.ascontiguousarray(y, dtype=np.float64)
303
+ if x is None:
304
+ self.x_numeric = np.arange(len(self.y), dtype=np.float64)
305
+ self.x_is_datetime = False
306
+ else:
307
+ self.x_numeric, self.x_is_datetime = to_numeric(x)
308
+
309
+ self.name = name
310
+ self.mode = mode if mode is not None else self._default_mode(len(self.y))
311
+ self.downsample_threshold = downsample_threshold
312
+ self.downsample_method = downsample_method
313
+ self.extra = expand_underscore(kwargs)
314
+
315
+ @staticmethod
316
+ def _default_mode(n: int) -> str:
317
+ # Matches Plotly.js's own default heuristic.
318
+ return "lines+markers" if n <= 20 else "lines"
319
+
320
+ def downsample(self) -> tuple[np.ndarray, np.ndarray]:
321
+ """Return ``(x, y)`` after optional downsampling."""
322
+ x, y = self.x_numeric, self.y
323
+ n = len(y)
324
+
325
+ if self.downsample_method == DownsampleMethod.NONE or n <= self.downsample_threshold:
326
+ return x, y
327
+ if self.downsample_method == DownsampleMethod.LTTB:
328
+ return lttb_downsample(x, y, self.downsample_threshold)
329
+ if self.downsample_method == DownsampleMethod.M4:
330
+ return m4_downsample(x, y, self.downsample_threshold)
331
+ return minmax_downsample(x, y, self.downsample_threshold)
332
+
333
+ def was_downsampled(self) -> bool:
334
+ """Whether ``downsample()`` actually decimates this trace's full-resolution data."""
335
+ return self.downsample_method != DownsampleMethod.NONE and len(self.y) > self.downsample_threshold
336
+
337
+ def resample_range(self, x0_raw: str, x1_raw: str, n: int) -> dict:
338
+ """Re-downsample the full-resolution data to ``n`` points within ``[x0_raw, x1_raw]``.
339
+
340
+ Used by the server behind :meth:`Figure.show` (detached or
341
+ in-process) to serve higher-fidelity data for the currently
342
+ zoomed-in x-range. ``x0_raw``/``x1_raw``
343
+ are whatever Plotly.js reports as the axis range (numeric strings,
344
+ or date strings for a datetime axis).
345
+ """
346
+ x, y = self.x_numeric, self.y
347
+ if self.x_is_datetime:
348
+ bounds = np.array([_datetime_bound_to_seconds(x0_raw), _datetime_bound_to_seconds(x1_raw)])
349
+ else:
350
+ bounds = np.array([float(x0_raw), float(x1_raw)], dtype=np.float64)
351
+ lo, hi = float(bounds.min()), float(bounds.max())
352
+
353
+ # Include one sample past each edge so the line connects smoothly
354
+ # to data just outside the visible range.
355
+ i0 = max(int(np.searchsorted(x, lo, side="left")) - 1, 0)
356
+ i1 = min(int(np.searchsorted(x, hi, side="right")) + 1, len(x))
357
+ x_slice, y_slice = x[i0:i1], y[i0:i1]
358
+
359
+ if self.downsample_method == DownsampleMethod.NONE or len(x_slice) <= n:
360
+ x_out, y_out = x_slice, y_slice
361
+ elif self.downsample_method == DownsampleMethod.LTTB:
362
+ x_out, y_out = lttb_downsample(x_slice, y_slice, n)
363
+ elif self.downsample_method == DownsampleMethod.M4:
364
+ x_out, y_out = m4_downsample(x_slice, y_slice, n)
365
+ else:
366
+ x_out, y_out = minmax_downsample(x_slice, y_slice, n)
367
+
368
+ return {
369
+ "x": numeric_to_iso(x_out) if self.x_is_datetime else x_out.tolist(),
370
+ "y": y_out.tolist(),
371
+ }
372
+
373
+ def to_plotly_json(self) -> dict:
374
+ x_ds, y_ds = self.downsample()
375
+ trace: dict = copy.deepcopy(self.extra)
376
+ trace["type"] = self.type
377
+ trace["x"] = numeric_to_iso(x_ds) if self.x_is_datetime else x_ds.tolist()
378
+ trace["y"] = y_ds.tolist()
379
+ trace["mode"] = self.mode
380
+ if self.name is not None:
381
+ trace["name"] = self.name
382
+ return trace
383
+
384
+ def __repr__(self) -> str:
385
+ return f"Scatter(name={self.name!r}, mode={self.mode!r}, n={len(self.y)})"
386
+
387
+
388
+ class Bar:
389
+ """Plotly-compatible bar trace.
390
+
391
+ Accepts the same keyword arguments as ``plotly.graph_objects.Bar``
392
+ (``x``, ``y``, ``name``, ``orientation``, ``marker``, ``text``,
393
+ ``hovertemplate``, magic-underscore shortcuts such as
394
+ ``marker_color=``, ...). Unrecognised keywords are passed straight
395
+ through to the Plotly.js trace spec.
396
+
397
+ Unlike :class:`Scatter`, values are passed through as-is (no numeric /
398
+ datetime coercion or downsampling) since bar traces are typically
399
+ categorical.
400
+ """
401
+
402
+ type = "bar"
403
+
404
+ def __init__(
405
+ self,
406
+ x=None,
407
+ y=None,
408
+ name: Optional[str] = None,
409
+ orientation: Optional[str] = None,
410
+ **kwargs,
411
+ ):
412
+ if x is None and y is None:
413
+ raise ValueError("Bar requires 'x' and/or 'y'")
414
+
415
+ self.x = x
416
+ self.y = y
417
+ self.name = name
418
+ self.orientation = orientation
419
+ self.extra = expand_underscore(kwargs)
420
+
421
+ def was_downsampled(self) -> bool:
422
+ """Always ``False``: Bar traces are never downsampled."""
423
+ return False
424
+
425
+ def to_plotly_json(self) -> dict:
426
+ trace: dict = copy.deepcopy(self.extra)
427
+ trace["type"] = self.type
428
+ if self.x is not None:
429
+ trace["x"] = to_plotly_json(self.x)
430
+ if self.y is not None:
431
+ trace["y"] = to_plotly_json(self.y)
432
+ if self.name is not None:
433
+ trace["name"] = self.name
434
+ if self.orientation is not None:
435
+ trace["orientation"] = self.orientation
436
+ return trace
437
+
438
+ def __repr__(self) -> str:
439
+ return f"Bar(name={self.name!r}, orientation={self.orientation!r})"
440
+
441
+
442
+ class Heatmap:
443
+ """Plotly-compatible heatmap trace.
444
+
445
+ Accepts the same keyword arguments as ``plotly.graph_objects.Heatmap``
446
+ (``z``, ``x``, ``y``, ``name``, ``colorscale``, ``zmin``, ``zmax``,
447
+ magic-underscore shortcuts such as ``colorbar_title=``, ...).
448
+ Unrecognised keywords are passed straight through to the Plotly.js
449
+ trace spec.
450
+ """
451
+
452
+ type = "heatmap"
453
+
454
+ def __init__(
455
+ self,
456
+ z=None,
457
+ x=None,
458
+ y=None,
459
+ name: Optional[str] = None,
460
+ colorscale: Optional[Union[str, list]] = None,
461
+ **kwargs,
462
+ ):
463
+ if z is None:
464
+ raise ValueError("Heatmap requires 'z'")
465
+
466
+ self.z = z
467
+ self.x = x
468
+ self.y = y
469
+ self.name = name
470
+ self.colorscale = colorscale
471
+ self.extra = expand_underscore(kwargs)
472
+
473
+ def was_downsampled(self) -> bool:
474
+ """Always ``False``: Heatmap traces are never downsampled."""
475
+ return False
476
+
477
+ def to_plotly_json(self) -> dict:
478
+ trace: dict = copy.deepcopy(self.extra)
479
+ trace["type"] = self.type
480
+ trace["z"] = to_plotly_json(self.z)
481
+ if self.x is not None:
482
+ trace["x"] = to_plotly_json(self.x)
483
+ if self.y is not None:
484
+ trace["y"] = to_plotly_json(self.y)
485
+ if self.name is not None:
486
+ trace["name"] = self.name
487
+ if self.colorscale is not None:
488
+ trace["colorscale"] = to_plotly_json(self.colorscale)
489
+ return trace
490
+
491
+ def __repr__(self) -> str:
492
+ return f"Heatmap(name={self.name!r})"
493
+
494
+
495
+ Trace = Union[Scatter, Bar, Heatmap]
496
+
497
+ _TRACE_TYPES: dict[str, type] = {
498
+ "scatter": Scatter,
499
+ "bar": Bar,
500
+ "heatmap": Heatmap,
501
+ }
502
+
503
+
504
+ def _trace_from_dict(spec: dict) -> Trace:
505
+ spec = dict(spec)
506
+ trace_type = spec.pop("type", "scatter")
507
+ cls = _TRACE_TYPES.get(trace_type)
508
+ if cls is None:
509
+ supported = ", ".join(repr(t) for t in _TRACE_TYPES)
510
+ raise NotImplementedError(
511
+ f"Trace type {trace_type!r} is not supported yet — only {supported} are implemented."
512
+ )
513
+ return cls(**spec)
514
+
515
+
516
+ # ---------------------------------------------------------------------------
517
+ # Layout
518
+ # ---------------------------------------------------------------------------
519
+
520
+ class Layout:
521
+ """Plotly-compatible layout, supporting magic-underscore kwargs."""
522
+
523
+ def __init__(self, arg: Optional[dict] = None, **kwargs):
524
+ self.data = expand_underscore(dict(arg or {}))
525
+ deep_merge(self.data, expand_underscore(kwargs))
526
+ self._normalize_title()
527
+
528
+ def _normalize_title(self) -> None:
529
+ if isinstance(self.data.get("title"), str):
530
+ self.data["title"] = {"text": self.data["title"]}
531
+
532
+ def update(self, arg: Optional[dict] = None, **kwargs) -> "Layout":
533
+ """Merge new properties into the layout. Returns ``self`` for chaining."""
534
+ merged = dict(arg or {})
535
+ merged.update(kwargs)
536
+ deep_merge(self.data, expand_underscore(merged))
537
+ self._normalize_title()
538
+ return self
539
+
540
+ def merge_normalized(self, key: str, value: dict) -> None:
541
+ """Deep-merge an already-``expand_underscore``d ``value`` under ``key``.
542
+
543
+ Skips the ``expand_underscore``/``to_plotly_json`` pass ``update()``
544
+ would otherwise redo on every call — useful when the same normalized
545
+ value is merged under many keys (e.g. broadcasting to every subplot
546
+ axis) and only needs computing once.
547
+ """
548
+ deep_merge(self.data.setdefault(key, {}), copy.deepcopy(value))
549
+
550
+ def to_dict(self) -> dict:
551
+ return copy.deepcopy(self.data)
552
+
553
+
554
+ def _make_request_handler(body: bytes, traces: list, tracker: Any = None) -> type:
555
+ """Build the HTTP handler shared by the in-process server and the detached viewer.
556
+
557
+ Routes:
558
+
559
+ - ``GET /downsample?trace=i&x0=..&x1=..&n=..``: calls
560
+ ``traces[i].resample_range(x0, x1, n)`` and returns the result as
561
+ JSON (400 on bad parameters, or if ``traces[i]`` is ``None`` / not a
562
+ resampled trace).
563
+ - ``GET /heartbeat?page=<id>`` and ``POST /closed?page=<id>``: page
564
+ lifecycle signals, forwarded to ``tracker`` (see
565
+ :class:`plothero._viewer.PageTracker`). No-ops when ``tracker`` is
566
+ ``None``.
567
+ - Any other ``GET``: the figure page (``body``).
568
+ """
569
+
570
+ class _Handler(BaseHTTPRequestHandler):
571
+ def do_GET(self) -> None: # noqa: N802 (BaseHTTPRequestHandler naming)
572
+ parsed = urlparse(self.path)
573
+ if tracker is not None:
574
+ tracker.activity()
575
+ if parsed.path == "/downsample":
576
+ self._serve_downsample(parsed)
577
+ elif parsed.path == "/heartbeat":
578
+ if tracker is not None:
579
+ tracker.heartbeat(self._page_id(parsed))
580
+ self._send(204, b"", None)
581
+ else:
582
+ self._send(200, body, "text/html; charset=utf-8")
583
+
584
+ def do_POST(self) -> None: # noqa: N802 (BaseHTTPRequestHandler naming)
585
+ parsed = urlparse(self.path)
586
+ if tracker is not None:
587
+ tracker.activity()
588
+ if parsed.path == "/closed":
589
+ if tracker is not None:
590
+ tracker.closed(self._page_id(parsed))
591
+ self._send(204, b"", None)
592
+ else:
593
+ self._send(404, b"", None)
594
+
595
+ @staticmethod
596
+ def _page_id(parsed) -> str:
597
+ return parse_qs(parsed.query).get("page", [""])[0][:64]
598
+
599
+ def _serve_downsample(self, parsed) -> None:
600
+ params = parse_qs(parsed.query)
601
+ try:
602
+ trace = traces[int(params["trace"][0])]
603
+ n = max(2, min(int(params.get("n", ["2000"])[0]), 50_000))
604
+ result = trace.resample_range(params["x0"][0], params["x1"][0], n)
605
+ status = 200
606
+ except (KeyError, IndexError, ValueError, AttributeError, OverflowError):
607
+ result = {}
608
+ status = 400
609
+ self._send(status, json.dumps(result).encode("utf-8"), "application/json")
610
+
611
+ def _send(self, status: int, payload: bytes, content_type: Optional[str]) -> None:
612
+ self.send_response(status)
613
+ if content_type is not None:
614
+ self.send_header("Content-Type", content_type)
615
+ self.send_header("Content-Length", str(len(payload)))
616
+ self.end_headers()
617
+ self.wfile.write(payload)
618
+
619
+ def log_message(self, format: str, *args: Any) -> None:
620
+ pass # silence default request logging to stderr
621
+
622
+ return _Handler
623
+
624
+
625
+ class _LocalHTTPServer(ThreadingHTTPServer):
626
+ """``ThreadingHTTPServer`` that skips the reverse DNS lookup in ``server_bind``.
627
+
628
+ ``HTTPServer.server_bind`` calls ``socket.getfqdn`` on the bound
629
+ address only to fill ``server_name``, which nothing here uses. Where
630
+ reverse DNS is slow, that lookup alone can delay the server by tens of
631
+ seconds.
632
+ """
633
+
634
+ def server_bind(self) -> None:
635
+ socketserver.TCPServer.server_bind(self)
636
+ self.server_name, self.server_port = self.server_address[:2]
637
+
638
+
639
+ def _start_server(handler: type, daemon: bool) -> tuple[str, ThreadingHTTPServer]:
640
+ """Bind ``handler`` to an ephemeral port on 127.0.0.1 and serve it on a new thread."""
641
+ server = _LocalHTTPServer(("127.0.0.1", 0), handler)
642
+ threading.Thread(target=server.serve_forever, daemon=daemon).start()
643
+ host, port = server.server_address[:2]
644
+ return f"http://{host}:{port}/", server
645
+
646
+
647
+ def _serve_figure_locally(figure: "Figure") -> tuple[str, ThreadingHTTPServer]:
648
+ """Serve ``figure`` from a local HTTP server in this process; returns ``(url, server)``.
649
+
650
+ Used by ``Figure.show(detached=False)``. The default ``show()`` serves
651
+ the same handler from a separate process instead (see
652
+ :mod:`plothero._viewer`).
653
+
654
+ Binds an ephemeral port on 127.0.0.1 and serves the page from memory
655
+ (no file written to disk). Also serves ``/downsample``: the page's
656
+ zoom/pan listener (see ``Figure._dynamic_resample_js``) calls back into
657
+ this endpoint to re-downsample each decimated trace's full-resolution
658
+ data to the currently visible x-range, so zooming in reveals real detail
659
+ instead of an interpolation of the original fixed-size decimation.
660
+
661
+ The server's thread is deliberately *not* a daemon: Python won't exit
662
+ the process while a non-daemon thread is still running, so the server
663
+ (and the URL) stays alive for as long as anything is left to do in the
664
+ program (including a plain script's remaining statements), instead of
665
+ dying the instant the last line runs, which would otherwise silently
666
+ break zooming before anyone gets a chance to use it. Call
667
+ ``server.shutdown()`` to stop it early (e.g. in tests, to avoid leaving
668
+ a live thread past the test that started it).
669
+ """
670
+ html = figure.to_html(full_html=True, include_plotlyjs="cdn", _dynamic_resample=True)
671
+ handler = _make_request_handler(html.encode("utf-8"), list(figure.traces))
672
+ return _start_server(handler, daemon=False)
673
+
674
+
675
+ # ---------------------------------------------------------------------------
676
+ # Figure
677
+ # ---------------------------------------------------------------------------
678
+
679
+ class Figure:
680
+ """Plotly-compatible figure — renders to interactive HTML via Plotly.js.
681
+
682
+ Mirrors ``plotly.graph_objects.Figure``::
683
+
684
+ fig = ph.Figure()
685
+ fig.add_trace(ph.Scatter(x=t, y=y, name="signal"))
686
+ fig.update_layout(title="Signal", xaxis_title="Time (s)")
687
+ fig.show()
688
+ html = fig.to_html()
689
+ """
690
+
691
+ def __init__(self, data=None, layout: Optional[Union[Layout, dict]] = None, **kwargs):
692
+ self.traces: list[Trace] = []
693
+ # Set by plothero.subplots.make_subplots(): {"rows", "cols", "axis_map"},
694
+ # where axis_map maps (row, col) -> (xaxis_ref, yaxis_ref), e.g. ("x2", "y2").
695
+ self._subplot_grid: Optional[dict] = None
696
+ if data is not None:
697
+ self.add_traces(data)
698
+
699
+ if isinstance(layout, Layout):
700
+ self._layout = Layout(layout.to_dict())
701
+ if kwargs:
702
+ self._layout.update(**kwargs)
703
+ else:
704
+ self._layout = Layout(layout or {}, **kwargs)
705
+
706
+ # ------------------------------------------------------------------
707
+ # Trace management
708
+ # ------------------------------------------------------------------
709
+
710
+ @property
711
+ def data(self) -> tuple:
712
+ return tuple(self.traces)
713
+
714
+ @property
715
+ def layout(self) -> Layout:
716
+ return self._layout
717
+
718
+ def add_trace(self, trace: Union[Trace, dict], row: Optional[int] = None, col: Optional[int] = None) -> "Figure":
719
+ """Add a trace to the figure. Returns ``self`` for chaining.
720
+
721
+ If the figure was created with
722
+ :func:`~plothero.subplots.make_subplots`, pass ``row``/``col``
723
+ (1-indexed, row 1 = top) to place the trace in a specific subplot
724
+ panel instead of the default axes.
725
+ """
726
+ if isinstance(trace, dict):
727
+ trace = _trace_from_dict(trace)
728
+ if not isinstance(trace, (Scatter, Bar, Heatmap)):
729
+ raise TypeError(f"Expected a Scatter, Bar, or Heatmap trace, got {type(trace).__name__}")
730
+ if row is not None or col is not None:
731
+ trace = copy.copy(trace)
732
+ trace.extra = dict(trace.extra)
733
+ self._assign_subplot_axes(trace, row, col)
734
+ self.traces.append(trace)
735
+ return self
736
+
737
+ def _assign_subplot_axes(self, trace: Trace, row: Optional[int], col: Optional[int]) -> None:
738
+ xref, yref = self._resolve_subplot_axes(row, col)
739
+ trace.extra.setdefault("xaxis", xref)
740
+ trace.extra.setdefault("yaxis", yref)
741
+
742
+ def _resolve_subplot_axes(self, row: Optional[int], col: Optional[int]) -> tuple:
743
+ """Validate a ``row``/``col`` pair and return its ``(xref, yref)`` axis ids."""
744
+ if row is None or col is None:
745
+ raise ValueError("row and col must be given together")
746
+ if self._subplot_grid is None:
747
+ raise ValueError(
748
+ "row/col were given but this figure was not created with "
749
+ "make_subplots() — see plothero.subplots.make_subplots()."
750
+ )
751
+ grid = self._subplot_grid
752
+ try:
753
+ return grid["axis_map"][(row, col)]
754
+ except KeyError:
755
+ raise ValueError(
756
+ f"(row={row}, col={col}) is out of range for a "
757
+ f"{grid['rows']}x{grid['cols']} subplot grid"
758
+ ) from None
759
+
760
+ def add_traces(self, traces) -> "Figure":
761
+ for trace in traces:
762
+ self.add_trace(trace)
763
+ return self
764
+
765
+ def add_scatter(self, row: Optional[int] = None, col: Optional[int] = None, **kwargs) -> "Figure":
766
+ """Shortcut for ``add_trace(Scatter(**kwargs), row=row, col=col)``."""
767
+ return self.add_trace(Scatter(**kwargs), row=row, col=col)
768
+
769
+ def add_bar(self, row: Optional[int] = None, col: Optional[int] = None, **kwargs) -> "Figure":
770
+ """Shortcut for ``add_trace(Bar(**kwargs), row=row, col=col)``."""
771
+ return self.add_trace(Bar(**kwargs), row=row, col=col)
772
+
773
+ def add_heatmap(self, row: Optional[int] = None, col: Optional[int] = None, **kwargs) -> "Figure":
774
+ """Shortcut for ``add_trace(Heatmap(**kwargs), row=row, col=col)``."""
775
+ return self.add_trace(Heatmap(**kwargs), row=row, col=col)
776
+
777
+ # ------------------------------------------------------------------
778
+ # Layout
779
+ # ------------------------------------------------------------------
780
+
781
+ def update_layout(self, arg: Optional[dict] = None, **kwargs) -> "Figure":
782
+ """Update layout properties (supports magic-underscore kwargs)."""
783
+ self._layout.update(arg, **kwargs)
784
+ return self
785
+
786
+ def update_xaxes(self, row: Optional[int] = None, col: Optional[int] = None, **kwargs) -> "Figure":
787
+ """Update x-axis properties.
788
+
789
+ With no ``row``/``col``, updates every x-axis (all subplot panels,
790
+ or the single ``xaxis`` on a non-subplot figure) — matching Plotly.
791
+ Pass both ``row`` and ``col`` to target one subplot panel instead.
792
+ """
793
+ expanded = expand_underscore(kwargs)
794
+ for key in self._axis_layout_keys("x", row, col):
795
+ self._layout.merge_normalized(key, expanded)
796
+ return self
797
+
798
+ def update_yaxes(self, row: Optional[int] = None, col: Optional[int] = None, **kwargs) -> "Figure":
799
+ """Update y-axis properties.
800
+
801
+ With no ``row``/``col``, updates every y-axis (all subplot panels,
802
+ or the single ``yaxis`` on a non-subplot figure) — matching Plotly.
803
+ Pass both ``row`` and ``col`` to target one subplot panel instead.
804
+ """
805
+ expanded = expand_underscore(kwargs)
806
+ for key in self._axis_layout_keys("y", row, col):
807
+ self._layout.merge_normalized(key, expanded)
808
+ return self
809
+
810
+ def _axis_layout_keys(self, axis: str, row: Optional[int], col: Optional[int]) -> list[str]:
811
+ if row is None and col is None:
812
+ if self._subplot_grid is None:
813
+ return [f"{axis}axis"]
814
+ n_axes = self._subplot_grid["rows"] * self._subplot_grid["cols"]
815
+ return [f"{axis}axis{_axis_suffix(i)}" for i in range(1, n_axes + 1)]
816
+ xref, yref = self._resolve_subplot_axes(row, col)
817
+ ref = xref if axis == "x" else yref
818
+ suffix = ref[1:] # ref is always f"{axis}{_axis_suffix(index)}"
819
+ return [f"{axis}axis{suffix}"]
820
+
821
+ # ------------------------------------------------------------------
822
+ # Serialization
823
+ # ------------------------------------------------------------------
824
+
825
+ def to_dict(self) -> dict:
826
+ return {
827
+ "data": [t.to_plotly_json() for t in self.traces],
828
+ "layout": self._layout.to_dict(),
829
+ }
830
+
831
+ def to_plotly_json(self) -> dict:
832
+ return self.to_dict()
833
+
834
+ def to_json(self, **kwargs) -> str:
835
+ return json.dumps(self.to_dict(), allow_nan=False, **kwargs)
836
+
837
+ # ------------------------------------------------------------------
838
+ # Rendering
839
+ # ------------------------------------------------------------------
840
+
841
+ def to_html(
842
+ self,
843
+ full_html: bool = True,
844
+ include_plotlyjs: Union[str, bool] = "cdn",
845
+ *,
846
+ _dynamic_resample: bool = False,
847
+ _heartbeat_ms: Optional[int] = None,
848
+ ) -> str:
849
+ """Render the figure to an HTML string.
850
+
851
+ Args:
852
+ full_html: If ``True`` (default), return a complete
853
+ ``<!DOCTYPE html>`` document. If ``False``, return only the
854
+ ``<div>`` + ``<script>`` fragment (for embedding / Jupyter).
855
+ include_plotlyjs: ``"cdn"`` (default), ``"inline"`` (bundles the
856
+ Plotly.js from the installed ``plotly`` package, works
857
+ offline), or ``False`` (caller loads Plotly.js separately).
858
+
859
+ Returns:
860
+ HTML string.
861
+ """
862
+ spec = self.to_dict()
863
+ resampled_indices = []
864
+ if _dynamic_resample:
865
+ for i, trace in enumerate(self.traces):
866
+ if trace.was_downsampled():
867
+ spec["data"][i]["_phDownsample"] = True
868
+ resampled_indices.append(i)
869
+ spec_json = json.dumps(spec, allow_nan=False)
870
+ div_id = f"fig-{id(self):x}"
871
+
872
+ if include_plotlyjs == "cdn":
873
+ plotlyjs_tag = f'<script src="{PLOTLYJS_CDN}"></script>'
874
+ elif include_plotlyjs == "inline":
875
+ plotlyjs_tag = self._inline_plotlyjs()
876
+ else:
877
+ plotlyjs_tag = ""
878
+
879
+ width = spec["layout"].get("width")
880
+ height = spec["layout"].get("height")
881
+ div_width = f"{width}px" if width else DEFAULT_HTML_WIDTH
882
+ # A full HTML document fills the browser viewport by default, like
883
+ # real Plotly's fig.show() does; a fragment (Jupyter/_repr_html_)
884
+ # keeps a fixed-height box since it has no <head> to anchor a
885
+ # percentage-height chain to.
886
+ fill_height = full_html and height is None
887
+ div_height = f"{height}px" if height else ("100%" if full_html else DEFAULT_HTML_HEIGHT)
888
+ config_json = json.dumps({"responsive": True, "scrollZoom": True})
889
+
890
+ resample_js = self._dynamic_resample_js(div_id) if resampled_indices else ""
891
+
892
+ plot_call = (
893
+ f'<div id="{div_id}" style="width:{div_width};height:{div_height};"></div>\n'
894
+ f"<script>\n"
895
+ f"(function() {{\n"
896
+ f"var spec = {spec_json};\n"
897
+ f"Plotly.newPlot('{div_id}', spec.data, spec.layout, {config_json});\n"
898
+ f"{resample_js}"
899
+ f"}})();\n"
900
+ f"</script>"
901
+ )
902
+
903
+ if not full_html:
904
+ # Self-contained: include the Plotly.js tag here too, since there's
905
+ # no <head> for the full_html branch to put it in.
906
+ if plotlyjs_tag:
907
+ return f"{plotlyjs_tag}\n{plot_call}"
908
+ return plot_call
909
+
910
+ viewport_style = (
911
+ " <style>\n"
912
+ " html, body { margin: 0; padding: 0; height: 100%; }\n"
913
+ " </style>\n"
914
+ ) if fill_height else ""
915
+
916
+ # Before the Plotly.js tag, so a slow CDN load doesn't delay the
917
+ # page registering itself with the detached viewer.
918
+ heartbeat_tag = f" {self._heartbeat_js(_heartbeat_ms)}\n" if _heartbeat_ms else ""
919
+
920
+ return (
921
+ "<!DOCTYPE html>\n"
922
+ "<html>\n"
923
+ "<head>\n"
924
+ ' <meta charset="utf-8">\n'
925
+ f"{heartbeat_tag}"
926
+ f" {plotlyjs_tag}\n"
927
+ f"{viewport_style}"
928
+ "</head>\n"
929
+ "<body>\n"
930
+ f" {plot_call}\n"
931
+ "</body>\n"
932
+ "</html>"
933
+ )
934
+
935
+ @staticmethod
936
+ def _inline_plotlyjs() -> str:
937
+ try:
938
+ import plotly
939
+ bundle = Path(plotly.__file__).parent / "package_data" / "plotly.min.js"
940
+ if bundle.exists():
941
+ return f"<script>{bundle.read_text(encoding='utf-8')}</script>"
942
+ except ImportError:
943
+ pass
944
+ return f'<script src="{PLOTLYJS_CDN}"></script>'
945
+
946
+ @staticmethod
947
+ def _dynamic_resample_js(div_id: str) -> str:
948
+ """JS that re-fetches full-fidelity data for the zoomed-in x-range on every pan/zoom.
949
+
950
+ Calls back to ``/downsample`` on whatever server this page was
951
+ loaded from. Logs to the browser console on every attempt/failure
952
+ (visible in DevTools) rather than failing silently, since a static
953
+ HTML export opened directly (no such backend) is a legitimate case
954
+ where these calls are expected to fail.
955
+
956
+ Plotly.newPlot() does not clone trace data, so ``spec.data[i]`` and
957
+ ``gd.data[i]`` are the same object; Plotly.restyle() overwrites its
958
+ ``.x``/``.y`` in place. A copy of each downsampled trace's original
959
+ arrays is snapshotted right after the initial plot renders so that
960
+ resetting/zooming back out (reported by Plotly as
961
+ ``evt['xaxis.autorange'] === true``, not a numeric range) can
962
+ restore the original view instead of being stuck on the last
963
+ zoomed-in fetch.
964
+ """
965
+ return (
966
+ f"var gd = document.getElementById('{div_id}');\n"
967
+ f"console.info('[plothero] dynamic resample armed for div', '{div_id}');\n"
968
+ "var phOriginal = {};\n"
969
+ "spec.data.forEach(function(trace, i) {\n"
970
+ " if (trace._phDownsample) {\n"
971
+ " phOriginal[i] = {x: trace.x.slice(), y: trace.y.slice()};\n"
972
+ " }\n"
973
+ "});\n"
974
+ "var phResampleTimer = null;\n"
975
+ "gd.on('plotly_relayout', function(evt) {\n"
976
+ " console.debug('[plothero] plotly_relayout fired', evt);\n"
977
+ " clearTimeout(phResampleTimer);\n"
978
+ " phResampleTimer = setTimeout(function() {\n"
979
+ " spec.data.forEach(function(trace, i) {\n"
980
+ " if (!trace._phDownsample) return;\n"
981
+ " var axisKey = 'xaxis' + (trace.xaxis || 'x').slice(1);\n"
982
+ " var orig = phOriginal[i];\n"
983
+ " if (orig && evt[axisKey + '.autorange'] === true) {\n"
984
+ " console.debug('[plothero] axes reset -- restoring original', orig.x.length, 'points for trace', i);\n"
985
+ " Plotly.restyle(gd, {x: [orig.x], y: [orig.y]}, [i]);\n"
986
+ " return;\n"
987
+ " }\n"
988
+ " var axis = gd.layout[axisKey];\n"
989
+ " var range = axis && axis.range;\n"
990
+ " if (!range) {\n"
991
+ " console.warn('[plothero] no range on', axisKey, '-- skipping resample for trace', i);\n"
992
+ " return;\n"
993
+ " }\n"
994
+ f" var n = {DYNAMIC_RESAMPLE_POINTS};\n"
995
+ " var url = '/downsample?trace=' + i\n"
996
+ " + '&x0=' + encodeURIComponent(range[0])\n"
997
+ " + '&x1=' + encodeURIComponent(range[1])\n"
998
+ " + '&n=' + n;\n"
999
+ " console.debug('[plothero] fetching', url);\n"
1000
+ " fetch(url).then(function(r) {\n"
1001
+ " if (!r.ok) { throw new Error('HTTP ' + r.status); }\n"
1002
+ " return r.json();\n"
1003
+ " }).then(function(d) {\n"
1004
+ " if (d && d.x && d.y) {\n"
1005
+ " console.debug('[plothero] resampled trace', i, 'to', d.x.length, 'points');\n"
1006
+ " Plotly.restyle(gd, {x: [d.x], y: [d.y]}, [i]);\n"
1007
+ " } else {\n"
1008
+ " console.warn('[plothero] resample response missing x/y', d);\n"
1009
+ " }\n"
1010
+ " }).catch(function(err) {\n"
1011
+ " console.error('[plothero] dynamic resample failed for trace', i, err);\n"
1012
+ " });\n"
1013
+ " });\n"
1014
+ " }, 150);\n"
1015
+ "});\n"
1016
+ )
1017
+
1018
+ @staticmethod
1019
+ def _heartbeat_js(interval_ms: int) -> str:
1020
+ """``<script>`` that keeps the detached viewer process (:mod:`plothero._viewer`) alive.
1021
+
1022
+ Each page load picks a random id and pings ``/heartbeat`` every
1023
+ ``interval_ms``. ``pagehide`` sends a ``/closed`` beacon so the
1024
+ viewer can exit promptly once the last page is gone, instead of
1025
+ waiting for the heartbeats to time out. A page restored from the
1026
+ back/forward cache pings again right away.
1027
+ """
1028
+ return (
1029
+ "<script>\n"
1030
+ "(function() {\n"
1031
+ " var page = Math.random().toString(36).slice(2) + Date.now().toString(36);\n"
1032
+ " function beat() {\n"
1033
+ " fetch('/heartbeat?page=' + page, {cache: 'no-store'}).catch(function() {});\n"
1034
+ " }\n"
1035
+ " beat();\n"
1036
+ f" setInterval(beat, {int(interval_ms)});\n"
1037
+ " window.addEventListener('pagehide', function() {\n"
1038
+ " if (navigator.sendBeacon) { navigator.sendBeacon('/closed?page=' + page); }\n"
1039
+ " });\n"
1040
+ " window.addEventListener('pageshow', function(evt) { if (evt.persisted) { beat(); } });\n"
1041
+ "})();\n"
1042
+ "</script>"
1043
+ )
1044
+
1045
+ def write_html(self, file: Union[str, Path], **kwargs) -> None:
1046
+ """Write the figure to an HTML file (``full_html``/``include_plotlyjs`` kwargs supported)."""
1047
+ Path(file).write_text(self.to_html(**kwargs), encoding="utf-8")
1048
+
1049
+ def show(self, *, detached: bool = True) -> "Figure":
1050
+ """Render the figure and open it in the default web browser via a local HTTP server.
1051
+
1052
+ Zooming/panning into a decimated trace re-fetches real full-resolution
1053
+ data for the visible range from that server, instead of just
1054
+ interpolating the original fixed-size decimation (see
1055
+ :func:`_serve_figure_locally`).
1056
+
1057
+ Args:
1058
+ detached: If ``True`` (default), the server runs in a separate
1059
+ background process (see :mod:`plothero._viewer`), and
1060
+ ``show()`` returns as soon as it is up. Your script can
1061
+ finish while the figure stays open and zooming keeps
1062
+ working, like a MATLAB figure. That process exits on its
1063
+ own shortly after the last browser tab showing the figure
1064
+ is closed, and also if no browser ever connects. If the
1065
+ viewer process cannot be started, ``show()`` warns and
1066
+ falls back to ``detached=False``.
1067
+
1068
+ If ``False``, the server runs on a thread inside this
1069
+ process. That thread is not a daemon, so it keeps the
1070
+ process alive for as long as it runs: in a plain script the
1071
+ program won't exit at its last line while the server is up,
1072
+ so press Ctrl+C (or close the terminal) once you're done
1073
+ zooming.
1074
+
1075
+ Returns:
1076
+ The figure itself, for chaining.
1077
+ """
1078
+ downsampled = any(trace.was_downsampled() for trace in self.traces)
1079
+ if detached:
1080
+ from plothero import _viewer
1081
+
1082
+ try:
1083
+ url = _viewer.launch(self).url
1084
+ except (OSError, RuntimeError) as exc:
1085
+ warnings.warn(
1086
+ f"plothero: could not start the detached viewer process ({exc}); "
1087
+ "serving the figure from this process instead.",
1088
+ RuntimeWarning,
1089
+ stacklevel=2,
1090
+ )
1091
+ return self.show(detached=False)
1092
+ if downsampled:
1093
+ print(
1094
+ f"plothero: serving {url} from a background viewer process -- "
1095
+ "zooming/panning keeps re-fetching full-resolution data after this "
1096
+ "script exits. The viewer stops when the page is closed."
1097
+ )
1098
+ else:
1099
+ url, _server = _serve_figure_locally(self)
1100
+ if downsampled:
1101
+ print(
1102
+ f"plothero: serving {url} -- this process will keep running so "
1103
+ "zooming/panning can keep re-fetching full-resolution data. "
1104
+ "Press Ctrl+C to stop."
1105
+ )
1106
+ webbrowser.open(url)
1107
+ return self
1108
+
1109
+ def _repr_html_(self) -> str:
1110
+ """Jupyter notebook / JupyterLab inline rendering."""
1111
+ return self.to_html(full_html=False, include_plotlyjs="cdn")
1112
+
1113
+ def to_plotly_figure(self):
1114
+ """Convert to a real ``plotly.graph_objects.Figure`` (requires ``pip install plotly``)."""
1115
+ try:
1116
+ import plotly.graph_objects as go
1117
+ except ImportError as exc:
1118
+ raise ImportError(
1119
+ "Install the 'plotly' package to use to_plotly_figure(): pip install plotly"
1120
+ ) from exc
1121
+ return go.Figure(self.to_dict())
1122
+
1123
+ def __repr__(self) -> str:
1124
+ return f"Figure(traces={len(self.traces)}, title={self._layout.data.get('title')!r})"