qeviz

qeviz — Python adapter for the qeviz visualization library.

Converts pandas DataFrames to the qeviz ModelData format and provides a chainable plot object for Jupyter display and standalone HTML export.

Quick start

::

import qeviz

# From DataFrames
p = qeviz.plot(nodes_df, edges_df, points_df, group_col="Condition")
p                                       # auto-display in Jupyter
p.group("FirstGame").points().show()    # chain + explicit display

# From a fitted pyENA model
p = qeviz.from_pyena(model, group_col="Condition")
p.edges("FirstGame", also="SecondGame")
p.edges(unit="FirstGame::alice")

# Introspect available groups / units
p.groups()   # ["FirstGame", "SecondGame"]
p.units()    # ["FirstGame::alice", ...]

# Export to file
p.export_html("output.html")

Chain API

All chain methods return a new QEPlot — the original is unchanged.

plot_obj.group(*names, intervals=True) Which group means (and CI boxes) to show. Omit names → all groups.

plot_obj.edges(group, *, unit, compare, also, show) Which edge network to draw. Omit → no network rendered.

plot_obj.points(show=True) Show or hide individual unit scatter dots.

plot_obj.trajectories(units=None, smooth="none", ...) Show supplied ordered unit trajectories.

plot_obj.labels(nodes, means, points) Label visibility: "on" | "off" | "click" | "auto".

Dependencies

Required : pandas Optional : IPython (Jupyter inline display) pyENA (for from_pyena())

   1"""
   2qeviz — Python adapter for the qeviz visualization library.
   3
   4Converts pandas DataFrames to the qeviz ModelData format and provides
   5a chainable plot object for Jupyter display and standalone HTML export.
   6
   7Quick start
   8-----------
   9::
  10
  11    import qeviz
  12
  13    # From DataFrames
  14    p = qeviz.plot(nodes_df, edges_df, points_df, group_col="Condition")
  15    p                                       # auto-display in Jupyter
  16    p.group("FirstGame").points().show()    # chain + explicit display
  17
  18    # From a fitted pyENA model
  19    p = qeviz.from_pyena(model, group_col="Condition")
  20    p.edges("FirstGame", also="SecondGame")
  21    p.edges(unit="FirstGame::alice")
  22
  23    # Introspect available groups / units
  24    p.groups()   # ["FirstGame", "SecondGame"]
  25    p.units()    # ["FirstGame::alice", ...]
  26
  27    # Export to file
  28    p.export_html("output.html")
  29
  30Chain API
  31---------
  32All chain methods return a *new* ``QEPlot`` — the original is unchanged.
  33
  34``plot_obj.group(*names, intervals=True)``
  35    Which group means (and CI boxes) to show.  Omit names → all groups.
  36
  37``plot_obj.edges(group, *, unit, compare, also, show)``
  38    Which edge network to draw.  Omit → no network rendered.
  39
  40``plot_obj.points(show=True)``
  41    Show or hide individual unit scatter dots.
  42
  43``plot_obj.trajectories(units=None, smooth="none", ...)``
  44    Show supplied ordered unit trajectories.
  45
  46``plot_obj.labels(nodes, means, points)``
  47    Label visibility: ``"on" | "off" | "click" | "auto"``.
  48
  49Dependencies
  50------------
  51Required : pandas
  52Optional : IPython (Jupyter inline display)
  53           pyENA  (for :func:`from_pyena`)
  54"""
  55
  56from __future__ import annotations
  57
  58import copy
  59import json
  60import math
  61import os
  62import re
  63import time
  64from typing import Any, Optional, Sequence, Union
  65
  66import numpy as np
  67import pandas as pd
  68
  69
  70# The chain methods below follow the R package (R/R/render.R) line for line:
  71# the same option names, the same validation and the same <qe-graph> markup,
  72# so a plot built in Python matches one built in R (tests/golden/).
  73
  74_UNSET: Any = object()   # "argument not supplied" (qe_labels() semantics)
  75
  76#: Paul Tol's "bright" scheme, the renderer's default palette.
  77_PALETTE = ["#4477AA", "#EE6677", "#228833", "#CCBB44",
  78            "#66CCEE", "#AA3377", "#BBBBBB", "#000000"]
  79
  80
  81def palette() -> list:
  82    """The default qeviz colour palette (Paul Tol "bright"), as in R's ``qe_palette()``."""
  83    return list(_PALETTE)
  84
  85
  86# ── Internal helpers ───────────────────────────────────────────────────────────
  87
  88def _is_na(v: Any) -> bool:
  89    return v is None or (isinstance(v, float) and (math.isnan(v) or math.isinf(v)))
  90
  91
  92def _native(v: Any) -> Any:
  93    """numpy scalar → Python native; NaN / inf → None."""
  94    if hasattr(v, "item") and not isinstance(v, (list, dict, str)):
  95        v = v.item()
  96    return None if _is_na(v) else v
  97
  98
  99def _value_type(values: list) -> str:
 100    """R's qe_frame() column type, inferred from the non-missing values."""
 101    vals = [v for v in values if not _is_na(v)]
 102    if not vals:
 103        return "logical"            # an all-NA column, as R types it
 104    if all(isinstance(v, bool) for v in vals):
 105        return "logical"
 106    if all(isinstance(v, int) and not isinstance(v, bool) for v in vals):
 107        return "integer"
 108    if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in vals):
 109        return "numeric"
 110    return "character"
 111
 112
 113def _qe_frame(df: pd.DataFrame) -> dict:
 114    """Convert a pandas DataFrame to a QEFrame ``{data: [...], types: {...}}``."""
 115    _type_map = {
 116        "object":  "character",
 117        "string":  "character",
 118        "int64":   "integer",
 119        "int32":   "integer",
 120        "int16":   "integer",
 121        "int8":    "integer",
 122        "float64": "numeric",
 123        "float32": "numeric",
 124        "bool":    "logical",
 125    }
 126    types = {
 127        col: _type_map.get(str(df[col].dtype), "character")
 128        for col in df.columns
 129    }
 130    data = []
 131    for _, row in df.iterrows():
 132        data.append({col: _native(val) for col, val in row.items()})
 133    return {"data": data, "types": types}
 134
 135
 136def _frame_from_rows(rows: list, cols: Optional[list] = None) -> dict:
 137    """A QEFrame from row dicts; missing values are padded as None."""
 138    if cols is None:
 139        cols = []
 140        for r in rows:
 141            cols += [k for k in r if k not in cols]
 142    data = [{k: _native(r.get(k)) for k in cols} for r in rows]
 143    types = {k: _value_type([r[k] for r in data]) for k in cols}
 144    return {"data": data, "types": types}
 145
 146
 147def _frame_rows(frame: Optional[dict]) -> list:
 148    return [dict(r) for r in (frame or {}).get("data", [])]
 149
 150
 151def _upsert_rows(frame: Optional[dict], rows: list, key: Optional[str] = None,
 152                 drop=None) -> dict:
 153    """R's .qe_upsert_rows(): replace rows sharing ``key`` (or matching
 154    ``drop``), append ``rows``, pad missing columns."""
 155    old = _frame_rows(frame)
 156    if old:
 157        if drop is not None:
 158            old = [r for r in old if not drop(r)]
 159        else:
 160            new_keys = {r.get(key) for r in rows}
 161            old = [r for r in old if r.get(key) not in new_keys]
 162    cols = list((frame or {}).get("types", {}).keys()) if old else []
 163    for r in rows:
 164        cols += [k for k in r if k not in cols]
 165    return _frame_from_rows(old + rows, cols)
 166
 167
 168def _fmt(v: Any) -> str:
 169    """Format an attribute value as R's as.character() does."""
 170    if isinstance(v, bool):
 171        return "TRUE" if v else "FALSE"
 172    if isinstance(v, float):
 173        return str(int(v)) if v.is_integer() else f"{v:.15g}"
 174    return str(v)
 175
 176
 177def _esc(v: Any) -> str:
 178    return _fmt(v).replace("&", "&amp;").replace("<", "&lt;").replace('"', "&quot;")
 179
 180
 181# ── Student t quantile (exact, no scipy) ──────────────────────────────────────
 182
 183def _betacf(a: float, b: float, x: float) -> float:
 184    """Continued fraction for the regularized incomplete beta (Lentz)."""
 185    tiny, eps = 1e-300, 1e-16
 186    qab, qap, qam = a + b, a + 1.0, a - 1.0
 187    c, d = 1.0, 1.0 - qab * x / qap
 188    d = 1.0 / (d if abs(d) > tiny else tiny)
 189    h = d
 190    for m in range(1, 1000):
 191        m2 = 2 * m
 192        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
 193        d = 1.0 + aa * d; d = 1.0 / (d if abs(d) > tiny else tiny)
 194        c = 1.0 + aa / c; c = c if abs(c) > tiny else tiny
 195        h *= d * c
 196        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
 197        d = 1.0 + aa * d; d = 1.0 / (d if abs(d) > tiny else tiny)
 198        c = 1.0 + aa / c; c = c if abs(c) > tiny else tiny
 199        delta = d * c
 200        h *= delta
 201        if abs(delta - 1.0) < eps:
 202            break
 203    return h
 204
 205
 206def _betainc(a: float, b: float, x: float) -> float:
 207    if x <= 0.0:
 208        return 0.0
 209    if x >= 1.0:
 210        return 1.0
 211    lbt = (math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
 212           + a * math.log(x) + b * math.log1p(-x))
 213    if x < (a + 1.0) / (a + b + 2.0):
 214        return math.exp(lbt) * _betacf(a, b, x) / a
 215    return 1.0 - math.exp(lbt) * _betacf(b, a, 1.0 - x) / b
 216
 217
 218def _t_cdf(t: float, df: float) -> float:
 219    x = df / (df + t * t)
 220    tail = 0.5 * _betainc(df / 2.0, 0.5, x)
 221    return 1.0 - tail if t > 0 else tail
 222
 223
 224def _t_quantile(p: float, df: int) -> float:
 225    """Quantile of Student's t, as R's ``qt(p, df)`` (to ~1e-14)."""
 226    if not 0.0 < p < 1.0:
 227        raise ValueError("_t_quantile(): p must be in (0, 1).")
 228    if p == 0.5:
 229        return 0.0
 230    if p < 0.5:
 231        return -_t_quantile(1.0 - p, df)
 232    lo, hi = 0.0, 1.0
 233    while _t_cdf(hi, df) < p:
 234        hi *= 2.0
 235    for _ in range(200):                     # bisection to machine precision
 236        mid = 0.5 * (lo + hi)
 237        if _t_cdf(mid, df) < p:
 238            lo = mid
 239        else:
 240            hi = mid
 241        if hi - lo <= 1e-15 * max(1.0, hi):
 242            break
 243    return 0.5 * (lo + hi)
 244
 245
 246def _quantile7(v: list, q: float) -> float:
 247    """R's default quantile (type 7)."""
 248    s = sorted(v)
 249    h = (len(s) - 1) * q
 250    lo = math.floor(h)
 251    return s[lo] + (h - lo) * (s[min(lo + 1, len(s) - 1)] - s[lo])
 252
 253
 254def _group_summary(rows: list, x_col: str, y_col: str, group_col: str,
 255                   conf_level: float = 0.95, outlier: bool = False) -> list:
 256    """R's group_summary(): per-group mean, t CI and (optionally) the outlier
 257    interval Q1 − 1.5·IQR … Q3 + 1.5·IQR, one row dict per sorted group."""
 258    groups = sorted({str(r[group_col]) for r in rows if not _is_na(r.get(group_col))})
 259    out = []
 260    for g in groups:
 261        sub = [r for r in rows if str(r.get(group_col)) == g]
 262        n = len(sub)
 263        t_v = _t_quantile((1 + conf_level) / 2, max(1, n - 1))
 264        row: dict = {group_col: g}
 265        stats = {}
 266        for d in (x_col, y_col):
 267            v = [float(r[d]) for r in sub if not _is_na(r.get(d))]
 268            m = sum(v) / len(v) if v else float("nan")
 269            sd = (math.sqrt(sum((a - m) ** 2 for a in v) / (len(v) - 1))
 270                  if len(v) > 1 else float("nan"))
 271            stats[d] = (v, m, sd / math.sqrt(n))
 272            row[d] = m
 273        for d in (x_col, y_col):
 274            _, m, se = stats[d]
 275            row[f"{d}.low"] = m - t_v * se
 276            row[f"{d}.high"] = m + t_v * se
 277        if outlier:
 278            for d in (x_col, y_col):
 279                v = stats[d][0]
 280                q1, q3 = _quantile7(v, 0.25), _quantile7(v, 0.75)
 281                row[f"{d}.olow"] = q1 - 1.5 * (q3 - q1)
 282                row[f"{d}.ohigh"] = q3 + 1.5 * (q3 - q1)
 283        out.append(row)
 284    return out
 285
 286
 287def _group_summaries(points_df: pd.DataFrame, group_col: str, dim_cols: list,
 288                     conf_level: float = 0.95, include_ci: bool = True,
 289                     outlier: bool = False) -> pd.DataFrame:
 290    """Per-group means with t CI bounds (and outlier fences), as a DataFrame."""
 291    rows = _group_summary(points_df.to_dict("records"), dim_cols[0], dim_cols[1],
 292                          group_col, conf_level=conf_level, outlier=outlier)
 293    df = pd.DataFrame(rows)
 294    if not include_ci:
 295        df = df[[c for c in df.columns if not c.endswith((".low", ".high"))]]
 296    return df
 297
 298
 299def _bundle_script_tag() -> str:
 300    """Return a ``<script>`` tag with the inlined UMD bundle."""
 301    bundle_path = os.path.join(
 302        os.path.dirname(os.path.abspath(__file__)), "qeviz.umd.js"
 303    )
 304    if os.path.exists(bundle_path):
 305        with open(bundle_path, "r", encoding="utf-8") as fh:
 306            js = fh.read()
 307        # Inlined, the relative source-map URL would resolve against the page.
 308        js = re.sub(r"\n//# sourceMappingURL=[^\n]*\s*$", "\n", js)
 309        return f"<script>{js}</script>"
 310    return '<script src="qeviz.umd.js"></script>'
 311
 312
 313def _check_range(range_: Any, fn: str) -> None:
 314    if isinstance(range_, (list, tuple, dict)):
 315        raise ValueError(f'{fn}(): only symmetric ranges are supported: "network", "points" or a number.')
 316    if range_ is not None and not (
 317        range_ in ("network", "points")
 318        or (isinstance(range_, (int, float)) and not isinstance(range_, bool)
 319            and math.isfinite(range_) and range_ > 0)
 320    ):
 321        raise ValueError(f'{fn}(): range must be "network", "points" or a positive number.')
 322
 323
 324_SHAPES = {"circle": "circle", "square": "rect", "rect": "rect", "triangle": "triangle",
 325           "triangle-up": "triangle", "diamond": "diamond"}
 326
 327
 328def _shape(shape: Union[str, Sequence[str]], fn: str) -> Union[str, list]:
 329    vals = [shape] if isinstance(shape, str) else list(shape)
 330    bad = [s for s in vals if s not in _SHAPES]
 331    if bad:
 332        raise ValueError(f'{fn}(): shape must be "circle", "square", "triangle" or "diamond".')
 333    out = [_SHAPES[s] for s in vals]
 334    return out[0] if isinstance(shape, str) else out
 335
 336
 337def _norm_names(names: list) -> list:
 338    return [str(n).replace(" & ", ".") for n in names]
 339
 340
 341def _numeric_frame(x: Any) -> pd.DataFrame:
 342    df = x if isinstance(x, pd.DataFrame) else pd.DataFrame(x)
 343    return df.select_dtypes("number")
 344
 345
 346# ── QEPlot ─────────────────────────────────────────────────────────────────────
 347
 348class QEPlot:
 349    """
 350    A lazily-rendered qeviz plot.
 351
 352    Created by :func:`plot` or :func:`from_pyena`. Chain :meth:`edges`,
 353    :meth:`points`, :meth:`group`, :meth:`nodes`, :meth:`labels` and friends
 354    to build the view; they mirror the R package's ``qe_*()`` functions.
 355
 356    Display options:
 357
 358    * Evaluate the object as the last expression in a Jupyter cell — the
 359      ``_repr_html_`` hook triggers automatic inline display.
 360    * Call :meth:`show` explicitly to display in IPython / Jupyter.
 361    * Call :meth:`export_html` to write a self-contained ``.html`` file.
 362
 363    All chain methods return a *new* ``QEPlot``: the original is unchanged, so
 364    several views can branch from a common base. Methods that add data (an
 365    explicit network, point set or mean) copy the model frames they change.
 366    """
 367
 368    def __init__(
 369        self,
 370        model: dict,
 371        title: Optional[str] = None,
 372        width: Union[int, str] = 700,
 373        height: Union[int, str] = 500,
 374        *,
 375        range: Union[str, float, None] = None,
 376        scale_points: bool = True,
 377        point_scale: Optional[float] = None,
 378        center: str = "origin",
 379        palette: Optional[Sequence[str]] = None,
 380    ) -> None:
 381        if center not in ("origin", "content"):
 382            raise ValueError('plot(): center must be "origin" or "content".')
 383        if point_scale is not None and not (
 384            isinstance(point_scale, (int, float)) and math.isfinite(point_scale) and point_scale > 0
 385        ):
 386            raise ValueError("plot(): point_scale must be a positive number.")
 387        _check_range(range, "plot")
 388        if palette is not None and (isinstance(palette, str) or not len(palette)):
 389            raise ValueError("plot(): palette must be a list of colours.")
 390        self._model = dict(model)
 391        if palette is not None:
 392            self._model["palette"] = [str(c) for c in palette]
 393        # Window / file title; the drawn plot title only when one is given.
 394        self._title = title if title is not None else "qeviz"
 395        self._width = str(width) if isinstance(width, str) else f"{width}px"
 396        self._height = str(height) if isinstance(height, str) else f"{height}px"
 397        self._opts: dict = {}
 398        if title is not None:
 399            self._opts["plot-title"] = title
 400        if range is not None:
 401            self._opts["range"] = range
 402        if scale_points is False:
 403            self._opts["scale-points"] = "false"
 404        if center == "content":
 405            self._opts["center"] = "content"
 406        if point_scale is not None:
 407            self._opts["point-scale"] = point_scale
 408
 409    # ── Model access ───────────────────────────────────────────────────────────
 410
 411    @property
 412    def model(self) -> dict:
 413        """The raw ModelData dict (nodes, edges, points, groups, …)."""
 414        return self._model
 415
 416    def _copy(self) -> "QEPlot":
 417        """A copy with independent options. The model dict is copied shallowly:
 418        frames are replaced, never edited in place, so copies stay separate."""
 419        p = QEPlot.__new__(QEPlot)
 420        p._model = dict(self._model)
 421        p._title = self._title
 422        p._width = self._width
 423        p._height = self._height
 424        p._opts = copy.deepcopy(self._opts)
 425        return p
 426
 427    # ── Introspection ──────────────────────────────────────────────────────────
 428
 429    def _group_key(self) -> str:
 430        return self._model.get("group_col") or "group"
 431
 432    def groups(self) -> list:
 433        """Group names in the model's groups frame (named and explicit means)."""
 434        frame = self._model.get("groups")
 435        if not frame:
 436            return []
 437        key = self._group_key()
 438        result = []
 439        for row in frame.get("data", []):
 440            val = row.get(key)
 441            if val is None and row:
 442                val = next(iter(row.values()))
 443            if val is not None:
 444                result.append(str(val))
 445        return result
 446
 447    def units(self) -> list:
 448        """Return the unit IDs present in the model's points frame."""
 449        frame = self._model.get("points")
 450        if not frame:
 451            return []
 452        id_col = self._model.get("id_col") or "QEUNIT"
 453        return [str(row[id_col]) for row in frame.get("data", []) if id_col in row]
 454
 455    def trajectory_units(self) -> list:
 456        """
 457        Return unit IDs present in the trajectories frame.
 458
 459        Falls back to point rows because qeviz can use points as ordered
 460        trajectory states when no separate trajectories frame is supplied.
 461        """
 462        frame = self._model.get("trajectories") or self._model.get("points")
 463        if not frame:
 464            return []
 465        id_col = self._model.get("id_col") or "QEUNIT"
 466        seen: list[str] = []
 467        for row in frame.get("data", []):
 468            if id_col in row:
 469                val = str(row[id_col])
 470                if val not in seen:
 471                    seen.append(val)
 472        return seen
 473
 474    # ── Internal: data helpers ─────────────────────────────────────────────────
 475
 476    def _edge_columns(self) -> list:
 477        m = self._model
 478        node_id = m.get("node_id_col") or "code"
 479        codes = [str(r[node_id]) for r in m["nodes"]["data"]]
 480        pairs = {f"{a}.{b}" for a in codes for b in codes}
 481        return [c for c in m["edges"]["types"] if c in pairs]
 482
 483    def _resolve_weights(self, x: Any, cols: list, arg: str) -> dict:
 484        """Weights as {edge column: value} over every model edge column."""
 485        if isinstance(x, pd.Series):
 486            named = dict(zip(_norm_names(list(x.index)), [float(v) for v in x.values]))
 487        elif isinstance(x, dict):
 488            named = dict(zip(_norm_names(list(x.keys())), [float(v) for v in x.values()]))
 489        elif isinstance(x, pd.DataFrame) or getattr(x, "ndim", 1) == 2:
 490            df = _numeric_frame(x)
 491            means = df.mean(axis=0)
 492            if isinstance(x, pd.DataFrame):
 493                named = dict(zip(_norm_names(list(df.columns)), [float(v) for v in means]))
 494            elif df.shape[1] == len(cols):
 495                named = dict(zip(cols, [float(v) for v in means]))
 496            else:
 497                raise ValueError(
 498                    f"edges(): unnamed '{arg}' has {df.shape[1]} columns; "
 499                    f"the model has {len(cols)} edge columns.")
 500        else:
 501            vals = [float(v) for v in x]
 502            if len(vals) != len(cols):
 503                raise ValueError(
 504                    f"edges(): unnamed '{arg}' has {len(vals)} values; "
 505                    f"the model has {len(cols)} edge columns.")
 506            named = dict(zip(cols, vals))
 507        unknown = [k for k in named if k not in cols]
 508        if unknown:
 509            raise ValueError(
 510                f"edges(): '{arg}' has edges not in the model: {', '.join(unknown[:3])}\n"
 511                f"Examples of valid names: {', '.join(cols[:3])}")
 512        return {c: named.get(c, 0.0) for c in cols}
 513
 514    def _group_network(self, group: str, cols: list) -> dict:
 515        gcol = self._model.get("group_col")
 516        rows = [r for r in self._model["edges"]["data"] if str(r.get(gcol)) == group]
 517        if not rows:
 518            raise ValueError(f"edges(): compare = {group!r} not found in model.")
 519        return {c: sum(float(r[c]) for r in rows) / len(rows) for c in cols}
 520
 521    def _point_frame(self, x: Any) -> list:
 522        """R's .qe_point_frame(): id + the model's x / y (+ group) per row."""
 523        m = self._model
 524        id_col, x_col, y_col = m.get("id_col") or "QEUNIT", m["x_col"], m["y_col"]
 525        df = x if isinstance(x, pd.DataFrame) else pd.DataFrame(x)
 526        df = df.loc[:, ~df.columns.duplicated()]
 527        num = list(df.select_dtypes("number").columns)
 528        dims = [x_col, y_col] if x_col in num and y_col in num else num[:2]
 529        if len(num) < 2:
 530            raise ValueError("need at least two numeric (dimension) columns in 'points'.")
 531        if id_col in df.columns:
 532            ids = [str(v) for v in df[id_col]]
 533        elif isinstance(df.index, pd.RangeIndex):
 534            ids = [str(i + 1) for i in range(len(df))]
 535        else:
 536            ids = [str(v) for v in df.index]
 537        gcol = m.get("group_col")
 538        rows = []
 539        for i in range(len(df)):
 540            r = {id_col: ids[i], x_col: float(df[dims[0]].iloc[i]), y_col: float(df[dims[1]].iloc[i])}
 541            if gcol and gcol in df.columns:
 542                r[gcol] = str(df[gcol].iloc[i])
 543            rows.append(r)
 544        return rows
 545
 546    def _update_groups_filter(self) -> None:
 547        named = self._opts.get("groups-named")
 548        expl = self._opts.get("groups-explicit") or []
 549        if not expl:
 550            groups = ",".join(named) if named else None
 551        elif named is None:
 552            groups = ",".join(expl)
 553        elif not named:
 554            groups = None
 555        else:
 556            groups = ",".join(list(named) + list(expl))
 557        self._set("groups", groups)
 558
 559    def _set(self, key: str, value: Any) -> None:
 560        """Set an option; ``None`` removes it (as assigning NULL does in R)."""
 561        if value is None:
 562            self._opts.pop(key, None)
 563        else:
 564            self._opts[key] = value
 565
 566    # ── Chain methods ──────────────────────────────────────────────────────────
 567
 568    def group(
 569        self,
 570        *names: str,
 571        points: Any = None,
 572        label: Optional[str] = None,
 573        color: Optional[str] = None,
 574        shape: Optional[str] = None,
 575        by: Optional[str] = None,
 576        intervals: Union[str, bool] = "box",
 577        conf_level: float = 0.95,
 578        outlier: bool = False,
 579        fixed_size: bool = False,
 580        show: bool = True,
 581    ) -> "QEPlot":
 582        """
 583        Group means: by name, or the mean of any subset of points.
 584
 585        Pass group names to show only those groups' means; omit names to show
 586        every group. ``points`` (a DataFrame / array of positions) instead adds
 587        the mean of that subset, with its own t interval, as a mean named
 588        ``label`` (default ``"mean 1"``, ``"mean 2"``, …); each such mean keeps
 589        its own ``intervals`` / ``outlier`` setting. ``show=False`` hides all
 590        means. Mirrors R's ``qe_group()``.
 591
 592        Parameters
 593        ----------
 594        intervals   ``"box"`` (default), ``"crosshairs"`` or ``"none"``;
 595                    ``True`` / ``False`` mean ``"box"`` / ``"none"``.
 596        conf_level  Confidence level of the t interval. Default 0.95.
 597        outlier     Also draw the outlier interval (Q1 − 1.5·IQR … Q3 + 1.5·IQR).
 598        color, shape
 599                    Colour and marker shape (``"square"``, ``"circle"``,
 600                    ``"triangle"``, ``"diamond"``) of an explicit mean.
 601        fixed_size  Keep mean markers a constant on-screen pixel size.
 602        """
 603        p = self._copy()
 604        if not show:
 605            p._opts["means-show"] = False
 606            return p
 607        p._opts.pop("means-show", None)
 608
 609        if by is not None:
 610            gcol = p._model.get("group_col")
 611            if gcol is not None and by != gcol:
 612                raise ValueError(
 613                    f"group(): by = {by!r} does not match the model's group column ({gcol!r}).")
 614        if isinstance(intervals, bool):
 615            intervals = "box" if intervals else "none"
 616        if intervals not in ("box", "crosshairs", "none"):
 617            raise ValueError('group(): intervals must be "box", "crosshairs" or "none".')
 618        if not (isinstance(conf_level, (int, float)) and 0 < conf_level < 1):
 619            raise ValueError("group(): conf_level must be a number in (0, 1).")
 620        if points is not None and names:
 621            raise ValueError("group(): supply group names or 'points', not both.")
 622
 623        p._opts["intervals"] = intervals
 624        p._opts["confidence"] = intervals != "none"
 625        p._opts["mean-outlier"] = bool(outlier) or bool(p._opts.get("mean-outlier"))
 626        p._opts["mean-fixed-size"] = bool(fixed_size)
 627
 628        m = p._model
 629        if points is not None:
 630            # ── Explicit: the mean (+ t CI, outlier fences) of a subset ──────
 631            rows = p._point_frame(points)
 632            expl = p._opts.get("groups-explicit") or []
 633            lbl = label if label is not None else f"mean {len(expl) + 1}"
 634            if lbl in p.groups() and lbl not in expl:
 635                raise ValueError(f"group(): label {lbl!r} is already a group in the model.")
 636            gkey = p._group_key()
 637            for r in rows:
 638                r[gkey] = lbl
 639            row = _group_summary(rows, m["x_col"], m["y_col"], gkey,
 640                                 conf_level=conf_level, outlier=outlier)[0]
 641            if color is not None:
 642                row["color"] = color
 643            if shape is not None:
 644                row["shape"] = _shape(shape, "group")
 645            row["intervals"] = intervals
 646            row["outlier"] = bool(outlier)
 647            m["groups"] = _upsert_rows(m.get("groups"), [row], key=gkey)
 648            p._opts["groups-explicit"] = expl + ([lbl] if lbl not in expl else [])
 649        else:
 650            # ── By name ──────────────────────────────────────────────────────
 651            if names:
 652                available = p.groups()
 653                bad = [n for n in names if n not in available]
 654                if bad:
 655                    raise ValueError(
 656                        f"group(): group(s) not found in model: {bad!r}\n"
 657                        f"Available: {available!r}")
 658            p._opts["groups-named"] = [str(n) for n in names]   # [] = all
 659            if (conf_level != 0.95 or outlier) and m.get("points"):
 660                rows = _group_summary(_frame_rows(m["points"]), m["x_col"], m["y_col"],
 661                                      m.get("group_col"), conf_level=conf_level,
 662                                      outlier=outlier)
 663                m["groups"] = _upsert_rows(m.get("groups"), rows, key=m.get("group_col"))
 664        p._update_groups_filter()
 665        return p
 666
 667    def edges(
 668        self,
 669        group: Optional[str] = None,
 670        *,
 671        unit: Optional[str] = None,
 672        weights: Any = None,
 673        compare: Any = None,
 674        also: Optional[str] = None,
 675        colors: Union[str, Sequence[str], None] = None,
 676        threshold: Union[float, Sequence[float], None] = None,
 677        name: Optional[str] = None,
 678        show: bool = True,
 679        color_scale: str = "model",
 680        edge_width: Optional[float] = None,
 681        magnify: Optional[float] = None,
 682    ) -> "QEPlot":
 683        """
 684        Draw an edge network: a group's or unit's (by name), or explicit weights.
 685
 686        By name, ``group`` (a group's mean network) or ``unit`` (one unit's
 687        network), with ``compare`` (subtract a second group) or ``also``
 688        (overlay it); a second call replaces it. ``weights`` instead draws a
 689        network from data: a Series / dict of edge weights, an unnamed list in
 690        the model's edge-column order, a DataFrame / 2-D array (averaged over
 691        rows), or a list of those (one layer each); ``compare`` then subtracts a
 692        group name or a second set of weights. Every ``weights`` call adds a
 693        layer; one with the same ``name`` replaces it. ``show=False`` removes
 694        all networks. Mirrors R's ``qe_edges()``.
 695
 696        Parameters
 697        ----------
 698        colors      One or two colours (positive, negative); with one, negative
 699                    weights use its complement.
 700        threshold   ``min`` or ``(min, max)``: |weight| < min is not drawn,
 701                    |weight| > max is drawn at max (sign kept).
 702        name        Name for this network (reported in edge events).
 703        color_scale ``"model"`` (default), ``"plot"`` or ``"absolute"``: how
 704                    weights map onto webENA's colour ramps.
 705        edge_width  Width of a weight-1 edge as a fraction of the plot width
 706                    (qeviz default 0.04).
 707        magnify     Multiply this plot's edge widths and node sizes (not
 708                    colour); labelled "(scaled N.Nx)" whenever set.
 709        """
 710        if group is not None and unit is not None:
 711            raise ValueError("edges(): supply either 'group' or 'unit', not both.")
 712        if weights is not None and (group is not None or unit is not None):
 713            raise ValueError("edges(): supply 'weights' or a 'group' / 'unit' name, not both.")
 714
 715        p = self._copy()
 716        if not show:
 717            p._opts["edges"] = "false"
 718            for k in ("group", "unit", "compare", "also", "edge-named", "edge-layers"):
 719                p._opts.pop(k, None)
 720            p._model.pop("networks", None)
 721            return p
 722
 723        if color_scale not in ("model", "plot", "absolute"):
 724            raise ValueError('edges(): color_scale must be "model", "plot", or "absolute".')
 725        if edge_width is not None and not (0 < edge_width <= 1):
 726            raise ValueError("edges(): edge_width must be a number in (0, 1].")
 727        if magnify is not None and not (math.isfinite(magnify) and magnify > 0):
 728            raise ValueError("edges(): magnify must be a positive number.")
 729        layer_attrs = _layer_attrs(colors, threshold)
 730
 731        p._opts["edges"] = True
 732        p._set("edge-color-scale", None if color_scale == "model" else color_scale)
 733        if edge_width is not None:
 734            p._opts["edge-width"] = edge_width
 735        if magnify is not None:
 736            p._opts["edge-magnify"] = magnify
 737
 738        # ── Explicit data: append one layer per network ──────────────────────
 739        if weights is not None:
 740            if also is not None:
 741                raise ValueError("edges(): 'also' takes group names; for data, pass a list to 'weights'.")
 742            cols = p._edge_columns()
 743            many = isinstance(weights, (list, tuple)) and weights and not isinstance(
 744                weights[0], (int, float))
 745            nets = list(weights) if many else [weights]
 746            base = len(p._opts.get("edge-layers") or [])
 747            for k, net in enumerate(nets, start=1):
 748                w = p._resolve_weights(net, cols, "weights")
 749                if compare is not None:
 750                    c = (p._group_network(compare, cols) if isinstance(compare, str)
 751                         else p._resolve_weights(compare, cols, "compare"))
 752                    w = {e: w[e] - c[e] for e in cols}
 753                lname = name if (name is not None and len(nets) == 1) else f"network {base + k}"
 754                p._model["networks"] = _append_network(p._model.get("networks"), lname, w)
 755                p._opts["edge-layers"] = (p._opts.get("edge-layers") or []) + [
 756                    {"network": lname, **layer_attrs}]
 757            return p
 758
 759        # ── By name: replace the named network ───────────────────────────────
 760        available_groups = p.groups()
 761
 762        def _check_group(nm: Optional[str], arg: str) -> None:
 763            if nm is not None and nm not in available_groups:
 764                raise ValueError(
 765                    f"edges(): {arg} = {nm!r} not found in model.\n"
 766                    f"Available groups: {available_groups!r}")
 767
 768        if compare is not None and not isinstance(compare, str):
 769            raise ValueError("edges(): 'compare' as data needs 'weights'; with 'group' it takes a group name.")
 770        _check_group(group, "group")
 771        _check_group(compare, "compare")
 772        _check_group(also, "also")
 773        if unit is not None and unit not in p.units():
 774            raise ValueError(
 775                f"edges(): unit = {unit!r} not found in model.\n"
 776                "Use .units() to see available unit IDs.")
 777        if compare is not None and also is not None:
 778            raise ValueError("edges(): supply either 'compare' or 'also', not both.")
 779        if unit is not None and (compare is not None or also is not None):
 780            raise ValueError("edges(): 'compare' and 'also' cannot be combined with 'unit'.")
 781
 782        p._set("group", group)
 783        p._set("unit", unit)
 784        p._set("compare", compare)
 785        p._set("also", also)
 786        named = ({"name": name} if name is not None else {}) | layer_attrs
 787        p._set("edge-named", named or None)
 788        return p
 789
 790    def points(
 791        self,
 792        show: bool = True,
 793        *,
 794        units: Optional[Sequence[str]] = None,
 795        points: Any = None,
 796        color: Union[str, Sequence[str], None] = None,
 797        shape: Union[str, Sequence[str], None] = None,
 798        labels: Union[str, Sequence[str], None] = None,
 799        name: Optional[str] = None,
 800        size: Optional[Union[int, float]] = None,
 801        fixed_size: bool = False,
 802    ) -> "QEPlot":
 803        """
 804        Unit points: all of them (coloured by group), or an explicit point set.
 805
 806        With no ``units`` / ``points``, shows every unit point. ``units`` (unit
 807        IDs) or ``points`` (a DataFrame / array of positions) instead adds a
 808        point set with optional ``color``, ``shape`` (``"circle"``,
 809        ``"square"``, ``"triangle"``, ``"diamond"``) and ``labels``, one value
 810        or one per point. Each set adds a layer; one with the same ``name``
 811        replaces it. ``show=False`` hides all points. ``size`` overrides the
 812        dot size (default 2.5); ``fixed_size`` keeps dots a constant on-screen
 813        size. Mirrors R's ``qe_points()``.
 814        """
 815        p = self._copy()
 816        if not show:
 817            p._opts["points"] = False
 818            p._opts.pop("point-sets", None)
 819            p._model.pop("pointsets", None)
 820            return p
 821        if units is None and points is None:
 822            p._opts["points"] = True
 823            p._set("point-size", size)
 824            p._opts["point-fixed-size"] = bool(fixed_size)
 825            return p
 826        if units is not None and points is not None:
 827            raise ValueError("points(): supply 'units' or 'points', not both.")
 828
 829        m = p._model
 830        id_col = m.get("id_col") or "QEUNIT"
 831        gcol = m.get("group_col")
 832        if units is not None:
 833            units = [units] if isinstance(units, str) else list(units)
 834            all_rows = {str(r.get(id_col)): r for r in _frame_rows(m.get("points"))}
 835            bad = [u for u in units if u not in all_rows]
 836            if bad:
 837                raise ValueError(f"points(): unit(s) not in model: {bad[:3]!r}")
 838            rows = [all_rows[u] for u in units]
 839        else:
 840            rows = p._point_frame(points)
 841
 842        n = len(rows)
 843        sets = p._opts.get("point-sets") or []
 844        set_name = name if name is not None else f"points {len(sets) + 1}"
 845
 846        def per_point(v: Any, arg: str) -> Optional[list]:
 847            if v is None:
 848                return None
 849            vals = [v] if isinstance(v, str) else list(v)
 850            if len(vals) not in (1, n):
 851                raise ValueError(f"points(): '{arg}' must have length 1 or {n}.")
 852            return [str(x) for x in (vals * n if len(vals) == 1 else vals)]
 853
 854        cols = per_point(color, "color")
 855        shapes = per_point(None if shape is None else _shape(shape, "points"), "shape")
 856        labs = per_point(labels, "labels")
 857        new = []
 858        for i, r in enumerate(rows):
 859            row = {"set": set_name, "id": str(r[id_col]),
 860                   m["x_col"]: r[m["x_col"]], m["y_col"]: r[m["y_col"]]}
 861            if gcol and gcol in r:
 862                row["group"] = str(r[gcol])
 863            if cols:
 864                row["color"] = cols[i]
 865            if shapes:
 866                row["shape"] = shapes[i]
 867            if labs:
 868                row["label"] = labs[i]
 869            new.append(row)
 870        m["pointsets"] = _upsert_rows(m.get("pointsets"), new,
 871                                      drop=lambda r: r.get("set") == set_name)
 872        p._opts["point-sets"] = [s for s in sets if s["set"] != set_name] + [
 873            {"set": set_name, "size": size, "fixed": bool(fixed_size)}]
 874        return p
 875
 876    def nodes(
 877        self,
 878        show: Union[bool, str] = "auto",
 879        unconnected: str = "dot",
 880        *,
 881        positions: Any = None,
 882        labels: Optional[dict] = None,
 883    ) -> "QEPlot":
 884        """
 885        Code nodes: when to draw them, and where.
 886
 887        ``"auto"`` (default) draws nodes only with an edge network, matching
 888        rENA; ``"always"`` / ``True`` and ``"never"`` / ``False`` override that.
 889        ``unconnected="hide"`` hides nodes with no drawn edges. ``positions``
 890        (a DataFrame with a code column or index, and x / y columns) moves
 891        nodes; ``labels`` (``{code: text}``) relabels them. Mirrors R's
 892        ``qe_nodes()``.
 893        """
 894        if show is True:
 895            show = "always"
 896        elif show is False:
 897            show = "never"
 898        if show not in ("auto", "always", "never"):
 899            raise ValueError('nodes(): show must be "auto", "always", or "never".')
 900        if unconnected not in ("dot", "hide"):
 901            raise ValueError('nodes(): unconnected must be "dot" or "hide".')
 902        p = self._copy()
 903        p._opts["nodes-show"] = show
 904        p._set("nodes-unconnected", "hide" if unconnected == "hide" else None)
 905
 906        if positions is not None or labels is not None:
 907            m = p._model
 908            idc = m.get("node_id_col") or "code"
 909            rows = _frame_rows(m["nodes"])
 910            codes = [str(r[idc]) for r in rows]
 911
 912            def check(got: list, arg: str) -> None:
 913                bad = [g for g in got if g not in codes]
 914                if bad:
 915                    raise ValueError(
 916                        f"nodes(): '{arg}' has codes not in the model: {bad[:3]!r}\n"
 917                        f"Model codes: {codes[:4]!r}")
 918
 919            if positions is not None:
 920                pos = positions if isinstance(positions, pd.DataFrame) else pd.DataFrame(positions)
 921                if idc in pos.columns:
 922                    pc = [str(v) for v in pos[idc]]
 923                elif "code" in pos.columns:
 924                    pc = [str(v) for v in pos["code"]]
 925                elif not isinstance(pos.index, pd.RangeIndex):
 926                    pc = [str(v) for v in pos.index]
 927                else:
 928                    raise ValueError("nodes(): 'positions' needs a code column or index.")
 929                num = list(pos.select_dtypes("number").columns)
 930                dims = [m["x_col"], m["y_col"]] if m["x_col"] in num and m["y_col"] in num else num[:2]
 931                if len(num) < 2:
 932                    raise ValueError("nodes(): 'positions' needs two numeric (x, y) columns.")
 933                check(pc, "positions")
 934                for i, code in enumerate(pc):
 935                    r = rows[codes.index(code)]
 936                    r[m["x_col"]] = float(pos[dims[0]].iloc[i])
 937                    r[m["y_col"]] = float(pos[dims[1]].iloc[i])
 938            if labels is not None:
 939                if not isinstance(labels, dict):
 940                    raise ValueError("nodes(): 'labels' must be a dict (code -> text).")
 941                check(list(labels), "labels")
 942                for r in rows:
 943                    r.setdefault("label", None)
 944                for code, text in labels.items():
 945                    rows[codes.index(str(code))]["label"] = str(text)
 946            m["nodes"] = _frame_from_rows(rows, list(m["nodes"]["types"]) + (
 947                ["label"] if labels is not None and "label" not in m["nodes"]["types"] else []))
 948        return p
 949
 950    def axes(
 951        self,
 952        x: Union[bool, str] = False,
 953        y: Union[bool, str] = False,
 954        *,
 955        show: bool = True,
 956    ) -> "QEPlot":
 957        """
 958        Show or hide the axes (a ``<qe-axes>`` layer).
 959
 960        Axis labels are opt-in. ``x`` / ``y`` default to ``False`` (no label);
 961        ``True`` uses the dimension name (e.g. ``"SVD1"``), a string sets custom
 962        text. ``show=False`` suppresses the axes entirely.
 963        """
 964        p = self._copy()
 965        if not show:
 966            p._opts["axes"] = False
 967            return p
 968        p._opts["axes"] = True
 969        p._opts["axis-x"] = x
 970        p._opts["axis-y"] = y
 971        return p
 972
 973    def trajectories(
 974        self,
 975        units: Optional[Union[str, list[str]]] = None,
 976        *,
 977        smooth: str = "none",
 978        max_degree: int = 3,
 979        degree_selection: str = "loocv_2d",
 980        points: bool = True,
 981        tips: bool = True,
 982        playhead: Optional[Union[int, float]] = None,
 983        line_style: str = "uniform",
 984        stroke_width: Union[int, float] = 2,
 985        stroke_width_range: tuple[Union[int, float], Union[int, float]] = (1, 6),
 986        opacity_range: tuple[Union[int, float], Union[int, float]] = (0.3, 1),
 987        show: bool = True,
 988    ) -> "QEPlot":
 989        """
 990        Show or hide supplied ordered unit trajectory paths.
 991
 992        qeviz renders rows already present in the model; trajectory modeling,
 993        accumulation, dooring, and inference remain caller-side work.
 994
 995        ``max_degree`` bounds the polynomial degree when ``smooth="poly"``.
 996        ``degree_selection="loocv_2d"`` (default) picks the degree in
 997        ``1..max_degree`` by joint 2D leave-one-out cross-validation;
 998        ``"fixed"`` always uses ``max_degree``. Near-origin points are excluded
 999        from the fit (still drawn), matching ``ena.plot.trajectory()``.
1000        """
1001        p = self._copy()
1002        if not show:
1003            p._opts["trajectories"] = False
1004            return p
1005        if smooth not in {"none", "poly"}:
1006            raise ValueError("trajectories(): smooth must be 'none' or 'poly'.")
1007        if degree_selection not in {"loocv_2d", "fixed"}:
1008            raise ValueError("trajectories(): degree_selection must be 'loocv_2d' or 'fixed'.")
1009        if line_style not in {"uniform", "tapered"}:
1010            raise ValueError("trajectories(): line_style must be 'uniform' or 'tapered'.")
1011        selected = None if units is None else ([units] if isinstance(units, str) else [str(u) for u in units])
1012        if selected:
1013            available = self.trajectory_units()
1014            bad = [u for u in selected if u not in available]
1015            if bad:
1016                raise ValueError(
1017                    f"trajectories(): unit(s) not found in model: {bad!r}\n"
1018                    f"Available: {available!r}")
1019        p._opts["trajectories"] = True
1020        p._set("trajectory-units", None if selected is None else ",".join(selected))
1021        p._opts["trajectory-smooth"] = smooth
1022        p._opts["trajectory-max-degree"] = int(max_degree)
1023        p._opts["trajectory-degree-selection"] = degree_selection
1024        p._opts["trajectory-points"] = bool(points)
1025        p._opts["trajectory-tips"] = bool(tips)
1026        p._set("trajectory-playhead", playhead)
1027        p._opts["trajectory-line-style"] = line_style
1028        p._opts["trajectory-stroke-width"] = stroke_width
1029        p._opts["trajectory-stroke-width-range"] = ",".join(_fmt(v) for v in stroke_width_range)
1030        p._opts["trajectory-opacity-range"] = ",".join(_fmt(v) for v in opacity_range)
1031        return p
1032
1033    def labels(
1034        self,
1035        nodes: str = _UNSET,
1036        means: str = _UNSET,
1037        points: str = _UNSET,
1038        *,
1039        font_size: Optional[float] = _UNSET,
1040        font_family: Optional[str] = _UNSET,
1041        font_color: Optional[str] = _UNSET,
1042    ) -> "QEPlot":
1043        """
1044        Label visibility and font.
1045
1046        ``nodes`` / ``means`` / ``points`` take ``"on"``, ``"off"``,
1047        ``"click"`` or ``"auto"``; ``font_size`` is in pixels (the title is
1048        drawn at 1.35×), ``font_family`` and ``font_color`` apply to labels and
1049        the title. Only the arguments supplied change; a bare ``labels()``
1050        applies the defaults (``"on"``, ``"on"``, ``"auto"``). Mirrors R's
1051        ``qe_labels()``.
1052        """
1053        if font_size is not _UNSET and font_size is not None and not (
1054            isinstance(font_size, (int, float)) and font_size > 0
1055        ):
1056            raise ValueError("labels(): font_size must be a positive number of pixels.")
1057        p = self._copy()
1058        bare = all(v is _UNSET for v in (nodes, means, points, font_size, font_family, font_color))
1059        for key, val, default in (("label-nodes", nodes, "on"), ("label-means", means, "on"),
1060                                  ("label-points", points, "auto")):
1061            if val is not _UNSET:
1062                p._set(key, val)
1063            elif bare:
1064                p._opts[key] = default
1065        for key, val in (("label-font-size", font_size), ("label-font-family", font_family),
1066                         ("label-font-color", font_color)):
1067            if val is not _UNSET:
1068                p._set(key, val)
1069        return p
1070
1071    def colors(self, mapping: Optional[dict] = None, **colors: str) -> "QEPlot":
1072        """
1073        Pin groups to colours: ``.colors(FirstGame="#E69F00")`` or
1074        ``.colors({"First Game": "#E69F00"})``. Each group's mean, unit points
1075        and networks use it; unlisted groups keep the palette colour. Mirrors
1076        R's ``qe_colors()``.
1077        """
1078        cols = {**(mapping or {}), **colors}
1079        if not cols:
1080            raise ValueError('colors(): give named colours, e.g. .colors(FirstGame="#E69F00").')
1081        bad = [g for g in cols if g not in self.groups()]
1082        if bad:
1083            raise ValueError(f"colors(): group(s) not found in model: {bad!r}")
1084        p = self._copy()
1085        rows = _frame_rows(p._model.get("groups"))
1086        gcol = p._model.get("group_col")
1087        for r in rows:
1088            r.setdefault("color", None)
1089            if str(r.get(gcol)) in cols:
1090                r["color"] = cols[str(r.get(gcol))]
1091        names = list(p._model["groups"]["types"])
1092        p._model["groups"] = _frame_from_rows(rows, names + ([] if "color" in names else ["color"]))
1093        return p
1094
1095    def range(self, range: Union[str, float, None]) -> "QEPlot":
1096        """
1097        Set the symmetric axis range: ``"network"`` (node extent × 1.2),
1098        ``"points"`` (unit points' extent × 1.2), a positive number, or ``None``
1099        for the default. Mirrors R's ``qe_range()``.
1100        """
1101        _check_range(range, "range")
1102        p = self._copy()
1103        p._set("range", range)
1104        return p
1105
1106    # ── HTML rendering ─────────────────────────────────────────────────────────
1107
1108    def _build_graph_element(self) -> str:
1109        """``<qe-graph …>…</qe-graph>`` with child layer elements (R's
1110        ``.build_graph_element()``, line for line)."""
1111        opts = self._opts
1112        children: list[str] = []
1113
1114        # <qe-means>: present unless qe_group(show = FALSE).
1115        means_parts: list[str] = []
1116        if opts.get("groups") is not None:
1117            means_parts.append(f'groups="{opts["groups"]}"')
1118        if opts.get("confidence") is not False:
1119            means_parts.append("confidence")
1120        if opts.get("intervals") is not None and opts["intervals"] != "box":
1121            means_parts.append(f'intervals="{opts["intervals"]}"')
1122        if opts.get("mean-outlier") is True:
1123            means_parts.append("outlier")
1124        means_parts.append(f'label="{opts.get("label-means", "on")}"')
1125        if opts.get("mean-fixed-size") is True:
1126            means_parts.append("fixed-size")
1127        if opts.get("means-show") is not False:
1128            children.append(f'    <qe-means {" ".join(means_parts)}></qe-means>')
1129
1130        # <qe-points>: all unit points, then explicit point sets.
1131        pt_label = opts.get("label-points", "auto")
1132        if opts.get("points") is True:
1133            pt_parts = [f'label="{pt_label}"']
1134            if opts.get("point-size") is not None:
1135                pt_parts.append(f'size="{_fmt(opts["point-size"])}"')
1136            if opts.get("point-fixed-size") is True:
1137                pt_parts.append("fixed-size")
1138            children.append(f'    <qe-points {" ".join(pt_parts)}></qe-points>')
1139        for ps in opts.get("point-sets") or []:
1140            pt_parts = [f'set="{ps["set"]}"', f'label="{pt_label}"']
1141            if ps.get("size") is not None:
1142                pt_parts.append(f'size="{_fmt(ps["size"])}"')
1143            if ps.get("fixed"):
1144                pt_parts.append("fixed-size")
1145            children.append(f'    <qe-points {" ".join(pt_parts)}></qe-points>')
1146
1147        # <qe-edges>: the named network, then one per explicit layer.
1148        if opts.get("edges") != "false":
1149            edge_parts = [f'{k}="{opts[k]}"' for k in ("group", "unit", "compare", "also")
1150                          if opts.get(k) is not None]
1151            attr_parts = lambda a: [f'{k}="{_fmt(v)}"' for k, v in a.items()]
1152            layers: list[list[str]] = []
1153            if edge_parts:
1154                layers.append(edge_parts + attr_parts(opts.get("edge-named") or {}))
1155            for L in opts.get("edge-layers") or []:
1156                layers.append(attr_parts(L))
1157            # Plot-wide settings ride on the first layer.
1158            if layers:
1159                if opts.get("edge-magnify") is not None:
1160                    layers[0].append(f'magnify="{_fmt(opts["edge-magnify"])}"')
1161                if opts.get("edge-color-scale") is not None:
1162                    layers[0].append(f'color-scale="{opts["edge-color-scale"]}"')
1163            for parts in layers:
1164                children.append(f'    <qe-edges {" ".join(parts)}></qe-edges>')
1165        has_network = any(c.startswith("    <qe-edges") for c in children)
1166
1167        # <qe-trajectories>
1168        if opts.get("trajectories") is True:
1169            tp: list[str] = []
1170            if opts.get("trajectory-units") is not None:
1171                tp.append(f'units="{opts["trajectory-units"]}"')
1172            tp += [
1173                f'smooth="{opts.get("trajectory-smooth", "none")}"',
1174                f'max-degree="{_fmt(opts.get("trajectory-max-degree", 3))}"',
1175                f'degree-selection="{opts.get("trajectory-degree-selection", "loocv_2d")}"',
1176                f'points="{"false" if opts.get("trajectory-points") is False else "true"}"',
1177                f'tips="{"false" if opts.get("trajectory-tips") is False else "true"}"',
1178            ]
1179            if opts.get("trajectory-playhead") is not None:
1180                tp.append(f'playhead="{_fmt(opts["trajectory-playhead"])}"')
1181            tp += [
1182                f'line-style="{opts.get("trajectory-line-style", "uniform")}"',
1183                f'stroke-width="{_fmt(opts.get("trajectory-stroke-width", 2))}"',
1184                f'stroke-width-range="{opts.get("trajectory-stroke-width-range", "1,6")}"',
1185                f'opacity-range="{opts.get("trajectory-opacity-range", "0.3,1")}"',
1186            ]
1187            children.append(f'    <qe-trajectories {" ".join(tp)}></qe-trajectories>')
1188
1189        # <qe-axes>: lines, plus a label per axis when asked.
1190        if opts.get("axes") is True:
1191            axis_parts: list[str] = []
1192            for attr in ("x", "y"):
1193                val = opts.get(f"axis-{attr}")
1194                if val is True:
1195                    axis_parts.append(attr)
1196                elif isinstance(val, str):
1197                    axis_parts.append(f'{attr}="{val}"')
1198            children.append("    <qe-axes" + (" " + " ".join(axis_parts) if axis_parts else "")
1199                            + "></qe-axes>")
1200
1201        # <qe-nodes>: "auto" draws them only with an edge network, as rENA does.
1202        node_show = opts.get("nodes-show", "auto")
1203        if node_show == "always" or (node_show == "auto" and has_network):
1204            unconn = ' unconnected="hide"' if opts.get("nodes-unconnected") == "hide" else ""
1205            children.insert(0, f'    <qe-nodes label="{opts.get("label-nodes", "on")}"{unconn}></qe-nodes>')
1206
1207        gattr = ("edge-width", "plot-title", "range", "center", "scale-points", "point-scale",
1208                 "label-font-size", "label-font-family", "label-font-color")
1209        ga = "".join(f' {k}="{_esc(opts[k])}"' for k in gattr if opts.get(k) is not None)
1210        return (f'<qe-graph width="{self._width}" height="{self._height}"{ga}>\n'
1211                + "\n".join(children) + "\n  </qe-graph>")
1212
1213    def _model_json(self) -> str:
1214        return json.dumps(self._model, default=str)
1215
1216    def _build_fragment(self) -> str:
1217        """HTML fragment for Jupyter inline display (no ``<html>``/``<head>``)."""
1218        uid = f"qeviz-{int(time.time() * 1000) % 100_000}"
1219        return (
1220            f"{_bundle_script_tag()}\n"
1221            f'<qe-visual id="{uid}">\n'
1222            f"  {self._build_graph_element()}\n"
1223            f"</qe-visual>\n"
1224            f"<script>\n"
1225            f"  (function(){{\n"
1226            f"    document.getElementById('{uid}').setModelData({self._model_json()});\n"
1227            f"  }})();\n"
1228            f"</script>"
1229        )
1230
1231    def _build_html_doc(self) -> str:
1232        """Complete self-contained HTML document."""
1233        return (
1234            f"<!DOCTYPE html>\n"
1235            f'<html lang="en">\n'
1236            f"<head>\n"
1237            f'  <meta charset="UTF-8">\n'
1238            f'  <meta name="viewport" content="width=device-width, initial-scale=1.0">\n'
1239            f"  <title>{self._title}</title>\n"
1240            f"  <style>\n"
1241            f"    * {{ box-sizing: border-box; margin: 0; padding: 0; }}\n"
1242            f"    body {{ font-family: system-ui, sans-serif; background: #fff; }}\n"
1243            f"  </style>\n"
1244            f"  {_bundle_script_tag()}\n"
1245            f"</head>\n"
1246            f"<body>\n"
1247            f'  <qe-visual id="vis">\n'
1248            f"    {self._build_graph_element()}\n"
1249            f"  </qe-visual>\n"
1250            f"  <script>\n"
1251            f"    (function(){{\n"
1252            f"      document.getElementById('vis').setModelData({self._model_json()});\n"
1253            f"    }})();\n"
1254            f"  </script>\n"
1255            f"</body>\n"
1256            f"</html>"
1257        )
1258
1259    # ── Display ────────────────────────────────────────────────────────────────
1260
1261    def show(self) -> None:
1262        """
1263        Display the plot inline in a Jupyter / IPython notebook.
1264
1265        In non-interactive environments (plain Python scripts) this falls back
1266        to printing the HTML document to stdout.
1267        """
1268        try:
1269            from IPython.display import HTML, display  # type: ignore
1270            display(HTML(self._build_fragment()))
1271        except ImportError:
1272            print(self._build_html_doc())
1273
1274    def _repr_html_(self) -> str:
1275        """Jupyter rich-display hook — called automatically when a cell returns a QEPlot."""
1276        return self._build_fragment()
1277
1278    def export_html(self, path: str) -> str:
1279        """
1280        Write a self-contained HTML file (the bundle is inlined).
1281
1282        Returns the resolved absolute path of the written file.
1283        """
1284        abs_path = os.path.abspath(path)
1285        with open(abs_path, "w", encoding="utf-8") as fh:
1286            fh.write(self._build_html_doc())
1287        return abs_path
1288
1289    def __repr__(self) -> str:
1290        opts = {k: v for k, v in self._opts.items() if v is not None}
1291        return f"<QEPlot groups={self.groups()!r} units={len(self.units())} opts={opts!r}>"
1292
1293
1294def _layer_attrs(colors: Any, threshold: Any) -> dict:
1295    """R's .qe_layer_attrs(): validated colors / threshold layer attributes."""
1296    out: dict = {}
1297    if colors is not None:
1298        cols = [colors] if isinstance(colors, str) else list(colors)
1299        if len(cols) not in (1, 2) or not all(isinstance(c, str) for c in cols):
1300            raise ValueError("edges(): colors must be one or two colours.")
1301        out["colors"] = ",".join(cols)
1302    if threshold is not None:
1303        thr = [threshold] if isinstance(threshold, (int, float)) else list(threshold)
1304        if len(thr) not in (1, 2) or not all(
1305            isinstance(t, (int, float)) and math.isfinite(t) and t >= 0 for t in thr
1306        ):
1307            raise ValueError("edges(): threshold must be (min, max) or min, non-negative.")
1308        out["threshold"] = ",".join(_fmt(float(t)) for t in thr)
1309    return out
1310
1311
1312def _append_network(frame: Optional[dict], name: str, w: dict) -> dict:
1313    """R's .qe_append_network(): add (or replace) one explicit network row."""
1314    row = {"name": name, **w}
1315    if not frame:
1316        return {"data": [row], "types": {"name": "character", **{k: "numeric" for k in w}}}
1317    return {"data": [r for r in frame["data"] if r.get("name") != name] + [row],
1318            "types": frame["types"]}
1319
1320
1321# ── Public API ─────────────────────────────────────────────────────────────────
1322
1323def model_data(
1324    nodes:   pd.DataFrame,
1325    edges:   pd.DataFrame,
1326    points:  Optional[pd.DataFrame] = None,
1327    trajectories: Optional[pd.DataFrame] = None,
1328    *,
1329    id_col:       str = "QEUNIT",
1330    node_id_col:  str = "code",
1331    x_col:        str = "SVD1",
1332    y_col:        str = "SVD2",
1333    group_col:    Optional[str] = None,
1334    directed:     bool = False,
1335    conf_level:   float = 0.95,
1336    include_ci:   bool = True,
1337) -> dict:
1338    """
1339    Build a qeviz ModelData dict from pandas DataFrames.
1340
1341    This is the low-level constructor — most users will call :func:`plot`
1342    directly.  Use ``model_data()`` when you need to inspect or transform the
1343    serialised dict before rendering.
1344
1345    Parameters
1346    ----------
1347    nodes         One row per code node.  Must contain ``node_id_col`` plus
1348                  ``x_col`` and ``y_col`` position columns.
1349    edges         One row per unit.  First column is the unit identifier
1350                  (``id_col``); remaining columns are dot-separated edge
1351                  weights (``"A.B"``).
1352    points        Unit projection positions.  Must contain ``id_col``,
1353                  ``x_col``, ``y_col``, and (optionally) ``group_col``.
1354    trajectories  Ordered observations for trajectory rendering.  Must contain
1355                  ``id_col``, ``x_col``, ``y_col``, and ideally ``time``,
1356                  ``RowID``, or ``ActivityNumber``.
1357    id_col        Unit-identifier column in ``edges`` / ``points``.
1358    node_id_col   Node-identifier column in ``nodes``.
1359    x_col         X-position column name.
1360    y_col         Y-position column name.
1361    group_col     Grouping column in ``points``.  When provided, group means
1362                  and t CI bounds are added as the ``groups`` frame; ``None``
1363                  gives a model with no groups (explicit means still work).
1364    directed      ``True`` for ONA / directed networks (arrowheads).
1365    conf_level    Confidence level for CI boxes.  Default 0.95.
1366    include_ci    Include CI bounds in the groups frame.  Default ``True``.
1367
1368    Returns
1369    -------
1370    dict  ModelData dict suitable for :func:`plot` or :func:`export_html`.
1371    """
1372    result: dict = {
1373        "nodes":       _qe_frame(nodes),
1374        "edges":       _qe_frame(edges),
1375        "updated":     int(time.time() * 1000),
1376        "directed":    directed,
1377        "id_col":      id_col,
1378        "node_id_col": node_id_col,
1379        "x_col":       x_col,
1380        "y_col":       y_col,
1381        "group_col":   group_col,
1382    }
1383    if group_col is None:
1384        del result["group_col"]
1385    if points is not None:
1386        result["points"] = _qe_frame(points)
1387        if group_col and group_col in points.columns:
1388            result["groups"] = _qe_frame(_group_summaries(
1389                points, group_col, [x_col, y_col],
1390                conf_level=conf_level, include_ci=include_ci))
1391    if trajectories is not None:
1392        result["trajectories"] = _qe_frame(trajectories)
1393    return result
1394
1395
1396def plot(
1397    x: Union[pd.DataFrame, dict],
1398    edges:  Optional[pd.DataFrame] = None,
1399    points: Optional[pd.DataFrame] = None,
1400    trajectories: Optional[pd.DataFrame] = None,
1401    *,
1402    title:     Optional[str] = None,
1403    width:     Union[int, str] = 700,
1404    height:    Union[int, str] = 500,
1405    group_col: Optional[str] = None,
1406    range:     Union[str, float, None] = None,
1407    scale_points: bool = True,
1408    point_scale:  Optional[float] = None,
1409    center:    str = "origin",
1410    palette:   Optional[Sequence[str]] = None,
1411    **model_kwargs,
1412) -> QEPlot:
1413    """
1414    Create a :class:`QEPlot` (R's ``qe_plot()``).
1415
1416    Accepts either a pre-built ModelData dict **or** raw DataFrames
1417    (``nodes``, ``edges``, ``points``).
1418
1419    Parameters
1420    ----------
1421    x           A ModelData dict from :func:`model_data`, **or** a nodes
1422                DataFrame (in which case ``edges`` must also be supplied).
1423    edges       Edge-weights DataFrame (only when ``x`` is a nodes DataFrame).
1424    points      Unit-positions DataFrame (optional, only with DataFrames).
1425    trajectories Ordered trajectory-state DataFrame (optional, only with DataFrames).
1426    title       Plot title, drawn above the plot when given; also the window /
1427                file title (default ``"qeviz"``).
1428    width, height
1429                Plot dimensions.  Integers are treated as pixels; strings
1430                are passed through as CSS (e.g. ``"100%"``).
1431    group_col   Grouping column (only when building from DataFrames).
1432    range       Symmetric axis range: ``"network"`` (default renderer
1433                behaviour), ``"points"`` or a positive number.
1434    scale_points
1435                ``False`` draws unit points and means at their raw
1436                coordinates instead of rescaling them to the node extent.
1437    point_scale Explicit factor for unit points and means (overrides
1438                ``scale_points``).
1439    center      ``"origin"`` (default) or ``"content"`` (centre the view on the
1440                nodes' and points' bounding box).
1441    palette     Colours for groups / sets / networks with none given
1442                (default: :func:`palette`).
1443    **model_kwargs
1444                Additional keyword arguments forwarded to :func:`model_data`
1445                (e.g. ``id_col``, ``x_col``, ``directed``).
1446    """
1447    if isinstance(x, dict):
1448        m = x
1449    else:
1450        if edges is None:
1451            raise TypeError("plot(): 'edges' is required when 'x' is a DataFrame.")
1452        m = model_data(x, edges, points, trajectories=trajectories,
1453                       group_col=group_col, **model_kwargs)
1454    return QEPlot(m, title=title, width=width, height=height, range=range,
1455                  scale_points=scale_points, point_scale=point_scale,
1456                  center=center, palette=palette)
1457
1458
1459def from_pyena(
1460    model,
1461    group_col: Optional[str] = None,
1462    directed:  bool = False,
1463    id_col:    str = "QEUNIT",
1464    title:     Optional[str] = None,
1465    width:     Union[int, str] = 700,
1466    height:    Union[int, str] = 500,
1467    dims:      tuple[int, int] = (0, 1),
1468) -> QEPlot:
1469    """
1470    Convert a fitted pyENA model to a :class:`QEPlot`.
1471
1472    Python equivalent of R's ``qe_extract()`` — reads nodes, unit positions,
1473    edge weights, and group metadata directly from a fitted ``pyena.ENA``
1474    instance.
1475
1476    Parameters
1477    ----------
1478    model     A fitted ``pyena.ENA`` instance (after ``.fit()``).
1479    group_col Grouping column name in ``model.accum_.meta``
1480              (e.g. ``"Condition"``).
1481    directed  ``True`` for ONA / directed networks.
1482    id_col    Name to give the unit-identifier column.
1483    dims      The two dimensions to plot, as column indices of the model's
1484              positions (as R's ``qe_extract(dims =)``). Default ``(0, 1)``.
1485    title, width, height
1486              Passed to the returned :class:`QEPlot`.
1487
1488    Returns
1489    -------
1490    QEPlot
1491
1492    Examples
1493    --------
1494    ::
1495
1496        p = qeviz.from_pyena(model, group_col="Condition")
1497        p.edges("FirstGame", also="SecondGame").points()  # auto-displays in Jupyter
1498        p.export_html("output.html")
1499    """
1500    # pyENA's attribute names (rotation_nodes_, line_weights_, unit_labels_,
1501    # meta_data_); the older names are accepted as fallbacks.
1502    def attr(*names):
1503        for n in names:
1504            if getattr(model, n, None) is not None:
1505                return getattr(model, n)
1506        raise AttributeError(f"from_pyena(): model has none of {names}; is it a fitted pyena.ENA?")
1507
1508    units     = [str(u) for u in attr("unit_labels_", "units_")]
1509    node_pos  = np.asarray(attr("rotation_nodes_", "positions_"), dtype=float)
1510    pts       = np.asarray(attr("points_"), dtype=float)
1511
1512    # Nodes: code name + (x, y)
1513    nodes_df = pd.DataFrame({
1514        "code": list(attr("codes_")),
1515        "x":    node_pos[:, dims[0]],
1516        "y":    node_pos[:, dims[1]],
1517    })
1518
1519    # Edges: normalised connection weights; "A & B" → "A.B"
1520    conn_cols = [c.replace(" & ", ".").replace("&", ".") for c in attr("connection_names_")]
1521    edges_df  = pd.DataFrame(np.asarray(attr("line_weights_", "normed_networks_"), dtype=float),
1522                             columns=conn_cols)
1523    edges_df.insert(0, id_col, units)
1524
1525    # Points: projected (x, y) per unit
1526    points_df = pd.DataFrame({
1527        id_col: units,
1528        "x":    pts[:, dims[0]],
1529        "y":    pts[:, dims[1]],
1530    })
1531
1532    # Attach group from unit-level metadata (indexed by unit)
1533    if group_col is not None:
1534        meta = getattr(model, "meta_data_", None)
1535        if meta is None:
1536            meta = model.accum_.meta
1537        if group_col not in meta.columns:
1538            raise ValueError(
1539                f"group_col {group_col!r} not found in model metadata. "
1540                f"Available columns: {list(meta.columns)}"
1541            )
1542        group_vals = [str(v) for v in meta.reindex(units)[group_col].tolist()]
1543        points_df[group_col] = group_vals
1544        edges_df[group_col]  = group_vals
1545
1546    m = model_data(
1547        nodes       = nodes_df,
1548        edges       = edges_df,
1549        points      = points_df,
1550        id_col      = id_col,
1551        node_id_col = "code",
1552        x_col       = "x",
1553        y_col       = "y",
1554        group_col   = group_col,
1555        directed    = directed,
1556    )
1557    return QEPlot(m, title=title, width=width, height=height)
1558
1559
1560def export_html(
1561    model_or_plot: Union[dict, QEPlot],
1562    path: str,
1563    options: Optional[dict] = None,
1564    width:  Union[int, str] = 700,
1565    height: Union[int, str] = 500,
1566) -> str:
1567    """
1568    Write a self-contained HTML file.
1569
1570    Accepts either a :class:`QEPlot` **or** a raw ModelData dict (legacy).
1571    When a dict is supplied ``options`` / ``width`` / ``height`` are forwarded
1572    to construct a temporary :class:`QEPlot`.
1573
1574    Returns the resolved absolute path of the written file.
1575    """
1576    if isinstance(model_or_plot, QEPlot):
1577        return model_or_plot.export_html(path)
1578
1579    # Legacy: raw dict path
1580    p = QEPlot(model_or_plot, width=width, height=height)
1581    if options:
1582        # Map old flat options dict onto chain methods for backward compat.
1583        group   = options.get("group")
1584        unit    = options.get("unit")
1585        compare = options.get("compare")
1586        also    = options.get("also")
1587        if group or unit or compare or also:
1588            p = p.edges(group=group, unit=unit, compare=compare, also=also)
1589        if options.get("show_points"):
1590            p = p.points(True)
1591    return p.export_html(path)
1592
1593
1594__all__ = [
1595    "QEPlot",
1596    "model_data",
1597    "plot",
1598    "palette",
1599    "from_pyena",
1600    "export_html",
1601]
class QEPlot:
 349class QEPlot:
 350    """
 351    A lazily-rendered qeviz plot.
 352
 353    Created by :func:`plot` or :func:`from_pyena`. Chain :meth:`edges`,
 354    :meth:`points`, :meth:`group`, :meth:`nodes`, :meth:`labels` and friends
 355    to build the view; they mirror the R package's ``qe_*()`` functions.
 356
 357    Display options:
 358
 359    * Evaluate the object as the last expression in a Jupyter cell — the
 360      ``_repr_html_`` hook triggers automatic inline display.
 361    * Call :meth:`show` explicitly to display in IPython / Jupyter.
 362    * Call :meth:`export_html` to write a self-contained ``.html`` file.
 363
 364    All chain methods return a *new* ``QEPlot``: the original is unchanged, so
 365    several views can branch from a common base. Methods that add data (an
 366    explicit network, point set or mean) copy the model frames they change.
 367    """
 368
 369    def __init__(
 370        self,
 371        model: dict,
 372        title: Optional[str] = None,
 373        width: Union[int, str] = 700,
 374        height: Union[int, str] = 500,
 375        *,
 376        range: Union[str, float, None] = None,
 377        scale_points: bool = True,
 378        point_scale: Optional[float] = None,
 379        center: str = "origin",
 380        palette: Optional[Sequence[str]] = None,
 381    ) -> None:
 382        if center not in ("origin", "content"):
 383            raise ValueError('plot(): center must be "origin" or "content".')
 384        if point_scale is not None and not (
 385            isinstance(point_scale, (int, float)) and math.isfinite(point_scale) and point_scale > 0
 386        ):
 387            raise ValueError("plot(): point_scale must be a positive number.")
 388        _check_range(range, "plot")
 389        if palette is not None and (isinstance(palette, str) or not len(palette)):
 390            raise ValueError("plot(): palette must be a list of colours.")
 391        self._model = dict(model)
 392        if palette is not None:
 393            self._model["palette"] = [str(c) for c in palette]
 394        # Window / file title; the drawn plot title only when one is given.
 395        self._title = title if title is not None else "qeviz"
 396        self._width = str(width) if isinstance(width, str) else f"{width}px"
 397        self._height = str(height) if isinstance(height, str) else f"{height}px"
 398        self._opts: dict = {}
 399        if title is not None:
 400            self._opts["plot-title"] = title
 401        if range is not None:
 402            self._opts["range"] = range
 403        if scale_points is False:
 404            self._opts["scale-points"] = "false"
 405        if center == "content":
 406            self._opts["center"] = "content"
 407        if point_scale is not None:
 408            self._opts["point-scale"] = point_scale
 409
 410    # ── Model access ───────────────────────────────────────────────────────────
 411
 412    @property
 413    def model(self) -> dict:
 414        """The raw ModelData dict (nodes, edges, points, groups, …)."""
 415        return self._model
 416
 417    def _copy(self) -> "QEPlot":
 418        """A copy with independent options. The model dict is copied shallowly:
 419        frames are replaced, never edited in place, so copies stay separate."""
 420        p = QEPlot.__new__(QEPlot)
 421        p._model = dict(self._model)
 422        p._title = self._title
 423        p._width = self._width
 424        p._height = self._height
 425        p._opts = copy.deepcopy(self._opts)
 426        return p
 427
 428    # ── Introspection ──────────────────────────────────────────────────────────
 429
 430    def _group_key(self) -> str:
 431        return self._model.get("group_col") or "group"
 432
 433    def groups(self) -> list:
 434        """Group names in the model's groups frame (named and explicit means)."""
 435        frame = self._model.get("groups")
 436        if not frame:
 437            return []
 438        key = self._group_key()
 439        result = []
 440        for row in frame.get("data", []):
 441            val = row.get(key)
 442            if val is None and row:
 443                val = next(iter(row.values()))
 444            if val is not None:
 445                result.append(str(val))
 446        return result
 447
 448    def units(self) -> list:
 449        """Return the unit IDs present in the model's points frame."""
 450        frame = self._model.get("points")
 451        if not frame:
 452            return []
 453        id_col = self._model.get("id_col") or "QEUNIT"
 454        return [str(row[id_col]) for row in frame.get("data", []) if id_col in row]
 455
 456    def trajectory_units(self) -> list:
 457        """
 458        Return unit IDs present in the trajectories frame.
 459
 460        Falls back to point rows because qeviz can use points as ordered
 461        trajectory states when no separate trajectories frame is supplied.
 462        """
 463        frame = self._model.get("trajectories") or self._model.get("points")
 464        if not frame:
 465            return []
 466        id_col = self._model.get("id_col") or "QEUNIT"
 467        seen: list[str] = []
 468        for row in frame.get("data", []):
 469            if id_col in row:
 470                val = str(row[id_col])
 471                if val not in seen:
 472                    seen.append(val)
 473        return seen
 474
 475    # ── Internal: data helpers ─────────────────────────────────────────────────
 476
 477    def _edge_columns(self) -> list:
 478        m = self._model
 479        node_id = m.get("node_id_col") or "code"
 480        codes = [str(r[node_id]) for r in m["nodes"]["data"]]
 481        pairs = {f"{a}.{b}" for a in codes for b in codes}
 482        return [c for c in m["edges"]["types"] if c in pairs]
 483
 484    def _resolve_weights(self, x: Any, cols: list, arg: str) -> dict:
 485        """Weights as {edge column: value} over every model edge column."""
 486        if isinstance(x, pd.Series):
 487            named = dict(zip(_norm_names(list(x.index)), [float(v) for v in x.values]))
 488        elif isinstance(x, dict):
 489            named = dict(zip(_norm_names(list(x.keys())), [float(v) for v in x.values()]))
 490        elif isinstance(x, pd.DataFrame) or getattr(x, "ndim", 1) == 2:
 491            df = _numeric_frame(x)
 492            means = df.mean(axis=0)
 493            if isinstance(x, pd.DataFrame):
 494                named = dict(zip(_norm_names(list(df.columns)), [float(v) for v in means]))
 495            elif df.shape[1] == len(cols):
 496                named = dict(zip(cols, [float(v) for v in means]))
 497            else:
 498                raise ValueError(
 499                    f"edges(): unnamed '{arg}' has {df.shape[1]} columns; "
 500                    f"the model has {len(cols)} edge columns.")
 501        else:
 502            vals = [float(v) for v in x]
 503            if len(vals) != len(cols):
 504                raise ValueError(
 505                    f"edges(): unnamed '{arg}' has {len(vals)} values; "
 506                    f"the model has {len(cols)} edge columns.")
 507            named = dict(zip(cols, vals))
 508        unknown = [k for k in named if k not in cols]
 509        if unknown:
 510            raise ValueError(
 511                f"edges(): '{arg}' has edges not in the model: {', '.join(unknown[:3])}\n"
 512                f"Examples of valid names: {', '.join(cols[:3])}")
 513        return {c: named.get(c, 0.0) for c in cols}
 514
 515    def _group_network(self, group: str, cols: list) -> dict:
 516        gcol = self._model.get("group_col")
 517        rows = [r for r in self._model["edges"]["data"] if str(r.get(gcol)) == group]
 518        if not rows:
 519            raise ValueError(f"edges(): compare = {group!r} not found in model.")
 520        return {c: sum(float(r[c]) for r in rows) / len(rows) for c in cols}
 521
 522    def _point_frame(self, x: Any) -> list:
 523        """R's .qe_point_frame(): id + the model's x / y (+ group) per row."""
 524        m = self._model
 525        id_col, x_col, y_col = m.get("id_col") or "QEUNIT", m["x_col"], m["y_col"]
 526        df = x if isinstance(x, pd.DataFrame) else pd.DataFrame(x)
 527        df = df.loc[:, ~df.columns.duplicated()]
 528        num = list(df.select_dtypes("number").columns)
 529        dims = [x_col, y_col] if x_col in num and y_col in num else num[:2]
 530        if len(num) < 2:
 531            raise ValueError("need at least two numeric (dimension) columns in 'points'.")
 532        if id_col in df.columns:
 533            ids = [str(v) for v in df[id_col]]
 534        elif isinstance(df.index, pd.RangeIndex):
 535            ids = [str(i + 1) for i in range(len(df))]
 536        else:
 537            ids = [str(v) for v in df.index]
 538        gcol = m.get("group_col")
 539        rows = []
 540        for i in range(len(df)):
 541            r = {id_col: ids[i], x_col: float(df[dims[0]].iloc[i]), y_col: float(df[dims[1]].iloc[i])}
 542            if gcol and gcol in df.columns:
 543                r[gcol] = str(df[gcol].iloc[i])
 544            rows.append(r)
 545        return rows
 546
 547    def _update_groups_filter(self) -> None:
 548        named = self._opts.get("groups-named")
 549        expl = self._opts.get("groups-explicit") or []
 550        if not expl:
 551            groups = ",".join(named) if named else None
 552        elif named is None:
 553            groups = ",".join(expl)
 554        elif not named:
 555            groups = None
 556        else:
 557            groups = ",".join(list(named) + list(expl))
 558        self._set("groups", groups)
 559
 560    def _set(self, key: str, value: Any) -> None:
 561        """Set an option; ``None`` removes it (as assigning NULL does in R)."""
 562        if value is None:
 563            self._opts.pop(key, None)
 564        else:
 565            self._opts[key] = value
 566
 567    # ── Chain methods ──────────────────────────────────────────────────────────
 568
 569    def group(
 570        self,
 571        *names: str,
 572        points: Any = None,
 573        label: Optional[str] = None,
 574        color: Optional[str] = None,
 575        shape: Optional[str] = None,
 576        by: Optional[str] = None,
 577        intervals: Union[str, bool] = "box",
 578        conf_level: float = 0.95,
 579        outlier: bool = False,
 580        fixed_size: bool = False,
 581        show: bool = True,
 582    ) -> "QEPlot":
 583        """
 584        Group means: by name, or the mean of any subset of points.
 585
 586        Pass group names to show only those groups' means; omit names to show
 587        every group. ``points`` (a DataFrame / array of positions) instead adds
 588        the mean of that subset, with its own t interval, as a mean named
 589        ``label`` (default ``"mean 1"``, ``"mean 2"``, …); each such mean keeps
 590        its own ``intervals`` / ``outlier`` setting. ``show=False`` hides all
 591        means. Mirrors R's ``qe_group()``.
 592
 593        Parameters
 594        ----------
 595        intervals   ``"box"`` (default), ``"crosshairs"`` or ``"none"``;
 596                    ``True`` / ``False`` mean ``"box"`` / ``"none"``.
 597        conf_level  Confidence level of the t interval. Default 0.95.
 598        outlier     Also draw the outlier interval (Q1 − 1.5·IQR … Q3 + 1.5·IQR).
 599        color, shape
 600                    Colour and marker shape (``"square"``, ``"circle"``,
 601                    ``"triangle"``, ``"diamond"``) of an explicit mean.
 602        fixed_size  Keep mean markers a constant on-screen pixel size.
 603        """
 604        p = self._copy()
 605        if not show:
 606            p._opts["means-show"] = False
 607            return p
 608        p._opts.pop("means-show", None)
 609
 610        if by is not None:
 611            gcol = p._model.get("group_col")
 612            if gcol is not None and by != gcol:
 613                raise ValueError(
 614                    f"group(): by = {by!r} does not match the model's group column ({gcol!r}).")
 615        if isinstance(intervals, bool):
 616            intervals = "box" if intervals else "none"
 617        if intervals not in ("box", "crosshairs", "none"):
 618            raise ValueError('group(): intervals must be "box", "crosshairs" or "none".')
 619        if not (isinstance(conf_level, (int, float)) and 0 < conf_level < 1):
 620            raise ValueError("group(): conf_level must be a number in (0, 1).")
 621        if points is not None and names:
 622            raise ValueError("group(): supply group names or 'points', not both.")
 623
 624        p._opts["intervals"] = intervals
 625        p._opts["confidence"] = intervals != "none"
 626        p._opts["mean-outlier"] = bool(outlier) or bool(p._opts.get("mean-outlier"))
 627        p._opts["mean-fixed-size"] = bool(fixed_size)
 628
 629        m = p._model
 630        if points is not None:
 631            # ── Explicit: the mean (+ t CI, outlier fences) of a subset ──────
 632            rows = p._point_frame(points)
 633            expl = p._opts.get("groups-explicit") or []
 634            lbl = label if label is not None else f"mean {len(expl) + 1}"
 635            if lbl in p.groups() and lbl not in expl:
 636                raise ValueError(f"group(): label {lbl!r} is already a group in the model.")
 637            gkey = p._group_key()
 638            for r in rows:
 639                r[gkey] = lbl
 640            row = _group_summary(rows, m["x_col"], m["y_col"], gkey,
 641                                 conf_level=conf_level, outlier=outlier)[0]
 642            if color is not None:
 643                row["color"] = color
 644            if shape is not None:
 645                row["shape"] = _shape(shape, "group")
 646            row["intervals"] = intervals
 647            row["outlier"] = bool(outlier)
 648            m["groups"] = _upsert_rows(m.get("groups"), [row], key=gkey)
 649            p._opts["groups-explicit"] = expl + ([lbl] if lbl not in expl else [])
 650        else:
 651            # ── By name ──────────────────────────────────────────────────────
 652            if names:
 653                available = p.groups()
 654                bad = [n for n in names if n not in available]
 655                if bad:
 656                    raise ValueError(
 657                        f"group(): group(s) not found in model: {bad!r}\n"
 658                        f"Available: {available!r}")
 659            p._opts["groups-named"] = [str(n) for n in names]   # [] = all
 660            if (conf_level != 0.95 or outlier) and m.get("points"):
 661                rows = _group_summary(_frame_rows(m["points"]), m["x_col"], m["y_col"],
 662                                      m.get("group_col"), conf_level=conf_level,
 663                                      outlier=outlier)
 664                m["groups"] = _upsert_rows(m.get("groups"), rows, key=m.get("group_col"))
 665        p._update_groups_filter()
 666        return p
 667
 668    def edges(
 669        self,
 670        group: Optional[str] = None,
 671        *,
 672        unit: Optional[str] = None,
 673        weights: Any = None,
 674        compare: Any = None,
 675        also: Optional[str] = None,
 676        colors: Union[str, Sequence[str], None] = None,
 677        threshold: Union[float, Sequence[float], None] = None,
 678        name: Optional[str] = None,
 679        show: bool = True,
 680        color_scale: str = "model",
 681        edge_width: Optional[float] = None,
 682        magnify: Optional[float] = None,
 683    ) -> "QEPlot":
 684        """
 685        Draw an edge network: a group's or unit's (by name), or explicit weights.
 686
 687        By name, ``group`` (a group's mean network) or ``unit`` (one unit's
 688        network), with ``compare`` (subtract a second group) or ``also``
 689        (overlay it); a second call replaces it. ``weights`` instead draws a
 690        network from data: a Series / dict of edge weights, an unnamed list in
 691        the model's edge-column order, a DataFrame / 2-D array (averaged over
 692        rows), or a list of those (one layer each); ``compare`` then subtracts a
 693        group name or a second set of weights. Every ``weights`` call adds a
 694        layer; one with the same ``name`` replaces it. ``show=False`` removes
 695        all networks. Mirrors R's ``qe_edges()``.
 696
 697        Parameters
 698        ----------
 699        colors      One or two colours (positive, negative); with one, negative
 700                    weights use its complement.
 701        threshold   ``min`` or ``(min, max)``: |weight| < min is not drawn,
 702                    |weight| > max is drawn at max (sign kept).
 703        name        Name for this network (reported in edge events).
 704        color_scale ``"model"`` (default), ``"plot"`` or ``"absolute"``: how
 705                    weights map onto webENA's colour ramps.
 706        edge_width  Width of a weight-1 edge as a fraction of the plot width
 707                    (qeviz default 0.04).
 708        magnify     Multiply this plot's edge widths and node sizes (not
 709                    colour); labelled "(scaled N.Nx)" whenever set.
 710        """
 711        if group is not None and unit is not None:
 712            raise ValueError("edges(): supply either 'group' or 'unit', not both.")
 713        if weights is not None and (group is not None or unit is not None):
 714            raise ValueError("edges(): supply 'weights' or a 'group' / 'unit' name, not both.")
 715
 716        p = self._copy()
 717        if not show:
 718            p._opts["edges"] = "false"
 719            for k in ("group", "unit", "compare", "also", "edge-named", "edge-layers"):
 720                p._opts.pop(k, None)
 721            p._model.pop("networks", None)
 722            return p
 723
 724        if color_scale not in ("model", "plot", "absolute"):
 725            raise ValueError('edges(): color_scale must be "model", "plot", or "absolute".')
 726        if edge_width is not None and not (0 < edge_width <= 1):
 727            raise ValueError("edges(): edge_width must be a number in (0, 1].")
 728        if magnify is not None and not (math.isfinite(magnify) and magnify > 0):
 729            raise ValueError("edges(): magnify must be a positive number.")
 730        layer_attrs = _layer_attrs(colors, threshold)
 731
 732        p._opts["edges"] = True
 733        p._set("edge-color-scale", None if color_scale == "model" else color_scale)
 734        if edge_width is not None:
 735            p._opts["edge-width"] = edge_width
 736        if magnify is not None:
 737            p._opts["edge-magnify"] = magnify
 738
 739        # ── Explicit data: append one layer per network ──────────────────────
 740        if weights is not None:
 741            if also is not None:
 742                raise ValueError("edges(): 'also' takes group names; for data, pass a list to 'weights'.")
 743            cols = p._edge_columns()
 744            many = isinstance(weights, (list, tuple)) and weights and not isinstance(
 745                weights[0], (int, float))
 746            nets = list(weights) if many else [weights]
 747            base = len(p._opts.get("edge-layers") or [])
 748            for k, net in enumerate(nets, start=1):
 749                w = p._resolve_weights(net, cols, "weights")
 750                if compare is not None:
 751                    c = (p._group_network(compare, cols) if isinstance(compare, str)
 752                         else p._resolve_weights(compare, cols, "compare"))
 753                    w = {e: w[e] - c[e] for e in cols}
 754                lname = name if (name is not None and len(nets) == 1) else f"network {base + k}"
 755                p._model["networks"] = _append_network(p._model.get("networks"), lname, w)
 756                p._opts["edge-layers"] = (p._opts.get("edge-layers") or []) + [
 757                    {"network": lname, **layer_attrs}]
 758            return p
 759
 760        # ── By name: replace the named network ───────────────────────────────
 761        available_groups = p.groups()
 762
 763        def _check_group(nm: Optional[str], arg: str) -> None:
 764            if nm is not None and nm not in available_groups:
 765                raise ValueError(
 766                    f"edges(): {arg} = {nm!r} not found in model.\n"
 767                    f"Available groups: {available_groups!r}")
 768
 769        if compare is not None and not isinstance(compare, str):
 770            raise ValueError("edges(): 'compare' as data needs 'weights'; with 'group' it takes a group name.")
 771        _check_group(group, "group")
 772        _check_group(compare, "compare")
 773        _check_group(also, "also")
 774        if unit is not None and unit not in p.units():
 775            raise ValueError(
 776                f"edges(): unit = {unit!r} not found in model.\n"
 777                "Use .units() to see available unit IDs.")
 778        if compare is not None and also is not None:
 779            raise ValueError("edges(): supply either 'compare' or 'also', not both.")
 780        if unit is not None and (compare is not None or also is not None):
 781            raise ValueError("edges(): 'compare' and 'also' cannot be combined with 'unit'.")
 782
 783        p._set("group", group)
 784        p._set("unit", unit)
 785        p._set("compare", compare)
 786        p._set("also", also)
 787        named = ({"name": name} if name is not None else {}) | layer_attrs
 788        p._set("edge-named", named or None)
 789        return p
 790
 791    def points(
 792        self,
 793        show: bool = True,
 794        *,
 795        units: Optional[Sequence[str]] = None,
 796        points: Any = None,
 797        color: Union[str, Sequence[str], None] = None,
 798        shape: Union[str, Sequence[str], None] = None,
 799        labels: Union[str, Sequence[str], None] = None,
 800        name: Optional[str] = None,
 801        size: Optional[Union[int, float]] = None,
 802        fixed_size: bool = False,
 803    ) -> "QEPlot":
 804        """
 805        Unit points: all of them (coloured by group), or an explicit point set.
 806
 807        With no ``units`` / ``points``, shows every unit point. ``units`` (unit
 808        IDs) or ``points`` (a DataFrame / array of positions) instead adds a
 809        point set with optional ``color``, ``shape`` (``"circle"``,
 810        ``"square"``, ``"triangle"``, ``"diamond"``) and ``labels``, one value
 811        or one per point. Each set adds a layer; one with the same ``name``
 812        replaces it. ``show=False`` hides all points. ``size`` overrides the
 813        dot size (default 2.5); ``fixed_size`` keeps dots a constant on-screen
 814        size. Mirrors R's ``qe_points()``.
 815        """
 816        p = self._copy()
 817        if not show:
 818            p._opts["points"] = False
 819            p._opts.pop("point-sets", None)
 820            p._model.pop("pointsets", None)
 821            return p
 822        if units is None and points is None:
 823            p._opts["points"] = True
 824            p._set("point-size", size)
 825            p._opts["point-fixed-size"] = bool(fixed_size)
 826            return p
 827        if units is not None and points is not None:
 828            raise ValueError("points(): supply 'units' or 'points', not both.")
 829
 830        m = p._model
 831        id_col = m.get("id_col") or "QEUNIT"
 832        gcol = m.get("group_col")
 833        if units is not None:
 834            units = [units] if isinstance(units, str) else list(units)
 835            all_rows = {str(r.get(id_col)): r for r in _frame_rows(m.get("points"))}
 836            bad = [u for u in units if u not in all_rows]
 837            if bad:
 838                raise ValueError(f"points(): unit(s) not in model: {bad[:3]!r}")
 839            rows = [all_rows[u] for u in units]
 840        else:
 841            rows = p._point_frame(points)
 842
 843        n = len(rows)
 844        sets = p._opts.get("point-sets") or []
 845        set_name = name if name is not None else f"points {len(sets) + 1}"
 846
 847        def per_point(v: Any, arg: str) -> Optional[list]:
 848            if v is None:
 849                return None
 850            vals = [v] if isinstance(v, str) else list(v)
 851            if len(vals) not in (1, n):
 852                raise ValueError(f"points(): '{arg}' must have length 1 or {n}.")
 853            return [str(x) for x in (vals * n if len(vals) == 1 else vals)]
 854
 855        cols = per_point(color, "color")
 856        shapes = per_point(None if shape is None else _shape(shape, "points"), "shape")
 857        labs = per_point(labels, "labels")
 858        new = []
 859        for i, r in enumerate(rows):
 860            row = {"set": set_name, "id": str(r[id_col]),
 861                   m["x_col"]: r[m["x_col"]], m["y_col"]: r[m["y_col"]]}
 862            if gcol and gcol in r:
 863                row["group"] = str(r[gcol])
 864            if cols:
 865                row["color"] = cols[i]
 866            if shapes:
 867                row["shape"] = shapes[i]
 868            if labs:
 869                row["label"] = labs[i]
 870            new.append(row)
 871        m["pointsets"] = _upsert_rows(m.get("pointsets"), new,
 872                                      drop=lambda r: r.get("set") == set_name)
 873        p._opts["point-sets"] = [s for s in sets if s["set"] != set_name] + [
 874            {"set": set_name, "size": size, "fixed": bool(fixed_size)}]
 875        return p
 876
 877    def nodes(
 878        self,
 879        show: Union[bool, str] = "auto",
 880        unconnected: str = "dot",
 881        *,
 882        positions: Any = None,
 883        labels: Optional[dict] = None,
 884    ) -> "QEPlot":
 885        """
 886        Code nodes: when to draw them, and where.
 887
 888        ``"auto"`` (default) draws nodes only with an edge network, matching
 889        rENA; ``"always"`` / ``True`` and ``"never"`` / ``False`` override that.
 890        ``unconnected="hide"`` hides nodes with no drawn edges. ``positions``
 891        (a DataFrame with a code column or index, and x / y columns) moves
 892        nodes; ``labels`` (``{code: text}``) relabels them. Mirrors R's
 893        ``qe_nodes()``.
 894        """
 895        if show is True:
 896            show = "always"
 897        elif show is False:
 898            show = "never"
 899        if show not in ("auto", "always", "never"):
 900            raise ValueError('nodes(): show must be "auto", "always", or "never".')
 901        if unconnected not in ("dot", "hide"):
 902            raise ValueError('nodes(): unconnected must be "dot" or "hide".')
 903        p = self._copy()
 904        p._opts["nodes-show"] = show
 905        p._set("nodes-unconnected", "hide" if unconnected == "hide" else None)
 906
 907        if positions is not None or labels is not None:
 908            m = p._model
 909            idc = m.get("node_id_col") or "code"
 910            rows = _frame_rows(m["nodes"])
 911            codes = [str(r[idc]) for r in rows]
 912
 913            def check(got: list, arg: str) -> None:
 914                bad = [g for g in got if g not in codes]
 915                if bad:
 916                    raise ValueError(
 917                        f"nodes(): '{arg}' has codes not in the model: {bad[:3]!r}\n"
 918                        f"Model codes: {codes[:4]!r}")
 919
 920            if positions is not None:
 921                pos = positions if isinstance(positions, pd.DataFrame) else pd.DataFrame(positions)
 922                if idc in pos.columns:
 923                    pc = [str(v) for v in pos[idc]]
 924                elif "code" in pos.columns:
 925                    pc = [str(v) for v in pos["code"]]
 926                elif not isinstance(pos.index, pd.RangeIndex):
 927                    pc = [str(v) for v in pos.index]
 928                else:
 929                    raise ValueError("nodes(): 'positions' needs a code column or index.")
 930                num = list(pos.select_dtypes("number").columns)
 931                dims = [m["x_col"], m["y_col"]] if m["x_col"] in num and m["y_col"] in num else num[:2]
 932                if len(num) < 2:
 933                    raise ValueError("nodes(): 'positions' needs two numeric (x, y) columns.")
 934                check(pc, "positions")
 935                for i, code in enumerate(pc):
 936                    r = rows[codes.index(code)]
 937                    r[m["x_col"]] = float(pos[dims[0]].iloc[i])
 938                    r[m["y_col"]] = float(pos[dims[1]].iloc[i])
 939            if labels is not None:
 940                if not isinstance(labels, dict):
 941                    raise ValueError("nodes(): 'labels' must be a dict (code -> text).")
 942                check(list(labels), "labels")
 943                for r in rows:
 944                    r.setdefault("label", None)
 945                for code, text in labels.items():
 946                    rows[codes.index(str(code))]["label"] = str(text)
 947            m["nodes"] = _frame_from_rows(rows, list(m["nodes"]["types"]) + (
 948                ["label"] if labels is not None and "label" not in m["nodes"]["types"] else []))
 949        return p
 950
 951    def axes(
 952        self,
 953        x: Union[bool, str] = False,
 954        y: Union[bool, str] = False,
 955        *,
 956        show: bool = True,
 957    ) -> "QEPlot":
 958        """
 959        Show or hide the axes (a ``<qe-axes>`` layer).
 960
 961        Axis labels are opt-in. ``x`` / ``y`` default to ``False`` (no label);
 962        ``True`` uses the dimension name (e.g. ``"SVD1"``), a string sets custom
 963        text. ``show=False`` suppresses the axes entirely.
 964        """
 965        p = self._copy()
 966        if not show:
 967            p._opts["axes"] = False
 968            return p
 969        p._opts["axes"] = True
 970        p._opts["axis-x"] = x
 971        p._opts["axis-y"] = y
 972        return p
 973
 974    def trajectories(
 975        self,
 976        units: Optional[Union[str, list[str]]] = None,
 977        *,
 978        smooth: str = "none",
 979        max_degree: int = 3,
 980        degree_selection: str = "loocv_2d",
 981        points: bool = True,
 982        tips: bool = True,
 983        playhead: Optional[Union[int, float]] = None,
 984        line_style: str = "uniform",
 985        stroke_width: Union[int, float] = 2,
 986        stroke_width_range: tuple[Union[int, float], Union[int, float]] = (1, 6),
 987        opacity_range: tuple[Union[int, float], Union[int, float]] = (0.3, 1),
 988        show: bool = True,
 989    ) -> "QEPlot":
 990        """
 991        Show or hide supplied ordered unit trajectory paths.
 992
 993        qeviz renders rows already present in the model; trajectory modeling,
 994        accumulation, dooring, and inference remain caller-side work.
 995
 996        ``max_degree`` bounds the polynomial degree when ``smooth="poly"``.
 997        ``degree_selection="loocv_2d"`` (default) picks the degree in
 998        ``1..max_degree`` by joint 2D leave-one-out cross-validation;
 999        ``"fixed"`` always uses ``max_degree``. Near-origin points are excluded
1000        from the fit (still drawn), matching ``ena.plot.trajectory()``.
1001        """
1002        p = self._copy()
1003        if not show:
1004            p._opts["trajectories"] = False
1005            return p
1006        if smooth not in {"none", "poly"}:
1007            raise ValueError("trajectories(): smooth must be 'none' or 'poly'.")
1008        if degree_selection not in {"loocv_2d", "fixed"}:
1009            raise ValueError("trajectories(): degree_selection must be 'loocv_2d' or 'fixed'.")
1010        if line_style not in {"uniform", "tapered"}:
1011            raise ValueError("trajectories(): line_style must be 'uniform' or 'tapered'.")
1012        selected = None if units is None else ([units] if isinstance(units, str) else [str(u) for u in units])
1013        if selected:
1014            available = self.trajectory_units()
1015            bad = [u for u in selected if u not in available]
1016            if bad:
1017                raise ValueError(
1018                    f"trajectories(): unit(s) not found in model: {bad!r}\n"
1019                    f"Available: {available!r}")
1020        p._opts["trajectories"] = True
1021        p._set("trajectory-units", None if selected is None else ",".join(selected))
1022        p._opts["trajectory-smooth"] = smooth
1023        p._opts["trajectory-max-degree"] = int(max_degree)
1024        p._opts["trajectory-degree-selection"] = degree_selection
1025        p._opts["trajectory-points"] = bool(points)
1026        p._opts["trajectory-tips"] = bool(tips)
1027        p._set("trajectory-playhead", playhead)
1028        p._opts["trajectory-line-style"] = line_style
1029        p._opts["trajectory-stroke-width"] = stroke_width
1030        p._opts["trajectory-stroke-width-range"] = ",".join(_fmt(v) for v in stroke_width_range)
1031        p._opts["trajectory-opacity-range"] = ",".join(_fmt(v) for v in opacity_range)
1032        return p
1033
1034    def labels(
1035        self,
1036        nodes: str = _UNSET,
1037        means: str = _UNSET,
1038        points: str = _UNSET,
1039        *,
1040        font_size: Optional[float] = _UNSET,
1041        font_family: Optional[str] = _UNSET,
1042        font_color: Optional[str] = _UNSET,
1043    ) -> "QEPlot":
1044        """
1045        Label visibility and font.
1046
1047        ``nodes`` / ``means`` / ``points`` take ``"on"``, ``"off"``,
1048        ``"click"`` or ``"auto"``; ``font_size`` is in pixels (the title is
1049        drawn at 1.35×), ``font_family`` and ``font_color`` apply to labels and
1050        the title. Only the arguments supplied change; a bare ``labels()``
1051        applies the defaults (``"on"``, ``"on"``, ``"auto"``). Mirrors R's
1052        ``qe_labels()``.
1053        """
1054        if font_size is not _UNSET and font_size is not None and not (
1055            isinstance(font_size, (int, float)) and font_size > 0
1056        ):
1057            raise ValueError("labels(): font_size must be a positive number of pixels.")
1058        p = self._copy()
1059        bare = all(v is _UNSET for v in (nodes, means, points, font_size, font_family, font_color))
1060        for key, val, default in (("label-nodes", nodes, "on"), ("label-means", means, "on"),
1061                                  ("label-points", points, "auto")):
1062            if val is not _UNSET:
1063                p._set(key, val)
1064            elif bare:
1065                p._opts[key] = default
1066        for key, val in (("label-font-size", font_size), ("label-font-family", font_family),
1067                         ("label-font-color", font_color)):
1068            if val is not _UNSET:
1069                p._set(key, val)
1070        return p
1071
1072    def colors(self, mapping: Optional[dict] = None, **colors: str) -> "QEPlot":
1073        """
1074        Pin groups to colours: ``.colors(FirstGame="#E69F00")`` or
1075        ``.colors({"First Game": "#E69F00"})``. Each group's mean, unit points
1076        and networks use it; unlisted groups keep the palette colour. Mirrors
1077        R's ``qe_colors()``.
1078        """
1079        cols = {**(mapping or {}), **colors}
1080        if not cols:
1081            raise ValueError('colors(): give named colours, e.g. .colors(FirstGame="#E69F00").')
1082        bad = [g for g in cols if g not in self.groups()]
1083        if bad:
1084            raise ValueError(f"colors(): group(s) not found in model: {bad!r}")
1085        p = self._copy()
1086        rows = _frame_rows(p._model.get("groups"))
1087        gcol = p._model.get("group_col")
1088        for r in rows:
1089            r.setdefault("color", None)
1090            if str(r.get(gcol)) in cols:
1091                r["color"] = cols[str(r.get(gcol))]
1092        names = list(p._model["groups"]["types"])
1093        p._model["groups"] = _frame_from_rows(rows, names + ([] if "color" in names else ["color"]))
1094        return p
1095
1096    def range(self, range: Union[str, float, None]) -> "QEPlot":
1097        """
1098        Set the symmetric axis range: ``"network"`` (node extent × 1.2),
1099        ``"points"`` (unit points' extent × 1.2), a positive number, or ``None``
1100        for the default. Mirrors R's ``qe_range()``.
1101        """
1102        _check_range(range, "range")
1103        p = self._copy()
1104        p._set("range", range)
1105        return p
1106
1107    # ── HTML rendering ─────────────────────────────────────────────────────────
1108
1109    def _build_graph_element(self) -> str:
1110        """``<qe-graph …>…</qe-graph>`` with child layer elements (R's
1111        ``.build_graph_element()``, line for line)."""
1112        opts = self._opts
1113        children: list[str] = []
1114
1115        # <qe-means>: present unless qe_group(show = FALSE).
1116        means_parts: list[str] = []
1117        if opts.get("groups") is not None:
1118            means_parts.append(f'groups="{opts["groups"]}"')
1119        if opts.get("confidence") is not False:
1120            means_parts.append("confidence")
1121        if opts.get("intervals") is not None and opts["intervals"] != "box":
1122            means_parts.append(f'intervals="{opts["intervals"]}"')
1123        if opts.get("mean-outlier") is True:
1124            means_parts.append("outlier")
1125        means_parts.append(f'label="{opts.get("label-means", "on")}"')
1126        if opts.get("mean-fixed-size") is True:
1127            means_parts.append("fixed-size")
1128        if opts.get("means-show") is not False:
1129            children.append(f'    <qe-means {" ".join(means_parts)}></qe-means>')
1130
1131        # <qe-points>: all unit points, then explicit point sets.
1132        pt_label = opts.get("label-points", "auto")
1133        if opts.get("points") is True:
1134            pt_parts = [f'label="{pt_label}"']
1135            if opts.get("point-size") is not None:
1136                pt_parts.append(f'size="{_fmt(opts["point-size"])}"')
1137            if opts.get("point-fixed-size") is True:
1138                pt_parts.append("fixed-size")
1139            children.append(f'    <qe-points {" ".join(pt_parts)}></qe-points>')
1140        for ps in opts.get("point-sets") or []:
1141            pt_parts = [f'set="{ps["set"]}"', f'label="{pt_label}"']
1142            if ps.get("size") is not None:
1143                pt_parts.append(f'size="{_fmt(ps["size"])}"')
1144            if ps.get("fixed"):
1145                pt_parts.append("fixed-size")
1146            children.append(f'    <qe-points {" ".join(pt_parts)}></qe-points>')
1147
1148        # <qe-edges>: the named network, then one per explicit layer.
1149        if opts.get("edges") != "false":
1150            edge_parts = [f'{k}="{opts[k]}"' for k in ("group", "unit", "compare", "also")
1151                          if opts.get(k) is not None]
1152            attr_parts = lambda a: [f'{k}="{_fmt(v)}"' for k, v in a.items()]
1153            layers: list[list[str]] = []
1154            if edge_parts:
1155                layers.append(edge_parts + attr_parts(opts.get("edge-named") or {}))
1156            for L in opts.get("edge-layers") or []:
1157                layers.append(attr_parts(L))
1158            # Plot-wide settings ride on the first layer.
1159            if layers:
1160                if opts.get("edge-magnify") is not None:
1161                    layers[0].append(f'magnify="{_fmt(opts["edge-magnify"])}"')
1162                if opts.get("edge-color-scale") is not None:
1163                    layers[0].append(f'color-scale="{opts["edge-color-scale"]}"')
1164            for parts in layers:
1165                children.append(f'    <qe-edges {" ".join(parts)}></qe-edges>')
1166        has_network = any(c.startswith("    <qe-edges") for c in children)
1167
1168        # <qe-trajectories>
1169        if opts.get("trajectories") is True:
1170            tp: list[str] = []
1171            if opts.get("trajectory-units") is not None:
1172                tp.append(f'units="{opts["trajectory-units"]}"')
1173            tp += [
1174                f'smooth="{opts.get("trajectory-smooth", "none")}"',
1175                f'max-degree="{_fmt(opts.get("trajectory-max-degree", 3))}"',
1176                f'degree-selection="{opts.get("trajectory-degree-selection", "loocv_2d")}"',
1177                f'points="{"false" if opts.get("trajectory-points") is False else "true"}"',
1178                f'tips="{"false" if opts.get("trajectory-tips") is False else "true"}"',
1179            ]
1180            if opts.get("trajectory-playhead") is not None:
1181                tp.append(f'playhead="{_fmt(opts["trajectory-playhead"])}"')
1182            tp += [
1183                f'line-style="{opts.get("trajectory-line-style", "uniform")}"',
1184                f'stroke-width="{_fmt(opts.get("trajectory-stroke-width", 2))}"',
1185                f'stroke-width-range="{opts.get("trajectory-stroke-width-range", "1,6")}"',
1186                f'opacity-range="{opts.get("trajectory-opacity-range", "0.3,1")}"',
1187            ]
1188            children.append(f'    <qe-trajectories {" ".join(tp)}></qe-trajectories>')
1189
1190        # <qe-axes>: lines, plus a label per axis when asked.
1191        if opts.get("axes") is True:
1192            axis_parts: list[str] = []
1193            for attr in ("x", "y"):
1194                val = opts.get(f"axis-{attr}")
1195                if val is True:
1196                    axis_parts.append(attr)
1197                elif isinstance(val, str):
1198                    axis_parts.append(f'{attr}="{val}"')
1199            children.append("    <qe-axes" + (" " + " ".join(axis_parts) if axis_parts else "")
1200                            + "></qe-axes>")
1201
1202        # <qe-nodes>: "auto" draws them only with an edge network, as rENA does.
1203        node_show = opts.get("nodes-show", "auto")
1204        if node_show == "always" or (node_show == "auto" and has_network):
1205            unconn = ' unconnected="hide"' if opts.get("nodes-unconnected") == "hide" else ""
1206            children.insert(0, f'    <qe-nodes label="{opts.get("label-nodes", "on")}"{unconn}></qe-nodes>')
1207
1208        gattr = ("edge-width", "plot-title", "range", "center", "scale-points", "point-scale",
1209                 "label-font-size", "label-font-family", "label-font-color")
1210        ga = "".join(f' {k}="{_esc(opts[k])}"' for k in gattr if opts.get(k) is not None)
1211        return (f'<qe-graph width="{self._width}" height="{self._height}"{ga}>\n'
1212                + "\n".join(children) + "\n  </qe-graph>")
1213
1214    def _model_json(self) -> str:
1215        return json.dumps(self._model, default=str)
1216
1217    def _build_fragment(self) -> str:
1218        """HTML fragment for Jupyter inline display (no ``<html>``/``<head>``)."""
1219        uid = f"qeviz-{int(time.time() * 1000) % 100_000}"
1220        return (
1221            f"{_bundle_script_tag()}\n"
1222            f'<qe-visual id="{uid}">\n'
1223            f"  {self._build_graph_element()}\n"
1224            f"</qe-visual>\n"
1225            f"<script>\n"
1226            f"  (function(){{\n"
1227            f"    document.getElementById('{uid}').setModelData({self._model_json()});\n"
1228            f"  }})();\n"
1229            f"</script>"
1230        )
1231
1232    def _build_html_doc(self) -> str:
1233        """Complete self-contained HTML document."""
1234        return (
1235            f"<!DOCTYPE html>\n"
1236            f'<html lang="en">\n'
1237            f"<head>\n"
1238            f'  <meta charset="UTF-8">\n'
1239            f'  <meta name="viewport" content="width=device-width, initial-scale=1.0">\n'
1240            f"  <title>{self._title}</title>\n"
1241            f"  <style>\n"
1242            f"    * {{ box-sizing: border-box; margin: 0; padding: 0; }}\n"
1243            f"    body {{ font-family: system-ui, sans-serif; background: #fff; }}\n"
1244            f"  </style>\n"
1245            f"  {_bundle_script_tag()}\n"
1246            f"</head>\n"
1247            f"<body>\n"
1248            f'  <qe-visual id="vis">\n'
1249            f"    {self._build_graph_element()}\n"
1250            f"  </qe-visual>\n"
1251            f"  <script>\n"
1252            f"    (function(){{\n"
1253            f"      document.getElementById('vis').setModelData({self._model_json()});\n"
1254            f"    }})();\n"
1255            f"  </script>\n"
1256            f"</body>\n"
1257            f"</html>"
1258        )
1259
1260    # ── Display ────────────────────────────────────────────────────────────────
1261
1262    def show(self) -> None:
1263        """
1264        Display the plot inline in a Jupyter / IPython notebook.
1265
1266        In non-interactive environments (plain Python scripts) this falls back
1267        to printing the HTML document to stdout.
1268        """
1269        try:
1270            from IPython.display import HTML, display  # type: ignore
1271            display(HTML(self._build_fragment()))
1272        except ImportError:
1273            print(self._build_html_doc())
1274
1275    def _repr_html_(self) -> str:
1276        """Jupyter rich-display hook — called automatically when a cell returns a QEPlot."""
1277        return self._build_fragment()
1278
1279    def export_html(self, path: str) -> str:
1280        """
1281        Write a self-contained HTML file (the bundle is inlined).
1282
1283        Returns the resolved absolute path of the written file.
1284        """
1285        abs_path = os.path.abspath(path)
1286        with open(abs_path, "w", encoding="utf-8") as fh:
1287            fh.write(self._build_html_doc())
1288        return abs_path
1289
1290    def __repr__(self) -> str:
1291        opts = {k: v for k, v in self._opts.items() if v is not None}
1292        return f"<QEPlot groups={self.groups()!r} units={len(self.units())} opts={opts!r}>"

A lazily-rendered qeviz plot.

Created by plot() or from_pyena(). Chain edges(), points(), group(), nodes(), labels() and friends to build the view; they mirror the R package's qe_*() functions.

Display options:

  • Evaluate the object as the last expression in a Jupyter cell — the _repr_html_ hook triggers automatic inline display.
  • Call show() explicitly to display in IPython / Jupyter.
  • Call export_html() to write a self-contained .html file.

All chain methods return a new QEPlot: the original is unchanged, so several views can branch from a common base. Methods that add data (an explicit network, point set or mean) copy the model frames they change.

QEPlot( model: dict, title: Optional[str] = None, width: Union[int, str] = 700, height: Union[int, str] = 500, *, range: Union[str, float, NoneType] = None, scale_points: bool = True, point_scale: Optional[float] = None, center: str = 'origin', palette: Optional[Sequence[str]] = None)
369    def __init__(
370        self,
371        model: dict,
372        title: Optional[str] = None,
373        width: Union[int, str] = 700,
374        height: Union[int, str] = 500,
375        *,
376        range: Union[str, float, None] = None,
377        scale_points: bool = True,
378        point_scale: Optional[float] = None,
379        center: str = "origin",
380        palette: Optional[Sequence[str]] = None,
381    ) -> None:
382        if center not in ("origin", "content"):
383            raise ValueError('plot(): center must be "origin" or "content".')
384        if point_scale is not None and not (
385            isinstance(point_scale, (int, float)) and math.isfinite(point_scale) and point_scale > 0
386        ):
387            raise ValueError("plot(): point_scale must be a positive number.")
388        _check_range(range, "plot")
389        if palette is not None and (isinstance(palette, str) or not len(palette)):
390            raise ValueError("plot(): palette must be a list of colours.")
391        self._model = dict(model)
392        if palette is not None:
393            self._model["palette"] = [str(c) for c in palette]
394        # Window / file title; the drawn plot title only when one is given.
395        self._title = title if title is not None else "qeviz"
396        self._width = str(width) if isinstance(width, str) else f"{width}px"
397        self._height = str(height) if isinstance(height, str) else f"{height}px"
398        self._opts: dict = {}
399        if title is not None:
400            self._opts["plot-title"] = title
401        if range is not None:
402            self._opts["range"] = range
403        if scale_points is False:
404            self._opts["scale-points"] = "false"
405        if center == "content":
406            self._opts["center"] = "content"
407        if point_scale is not None:
408            self._opts["point-scale"] = point_scale
model: dict
412    @property
413    def model(self) -> dict:
414        """The raw ModelData dict (nodes, edges, points, groups, …)."""
415        return self._model

The raw ModelData dict (nodes, edges, points, groups, …).

def groups(self) -> list:
433    def groups(self) -> list:
434        """Group names in the model's groups frame (named and explicit means)."""
435        frame = self._model.get("groups")
436        if not frame:
437            return []
438        key = self._group_key()
439        result = []
440        for row in frame.get("data", []):
441            val = row.get(key)
442            if val is None and row:
443                val = next(iter(row.values()))
444            if val is not None:
445                result.append(str(val))
446        return result

Group names in the model's groups frame (named and explicit means).

def units(self) -> list:
448    def units(self) -> list:
449        """Return the unit IDs present in the model's points frame."""
450        frame = self._model.get("points")
451        if not frame:
452            return []
453        id_col = self._model.get("id_col") or "QEUNIT"
454        return [str(row[id_col]) for row in frame.get("data", []) if id_col in row]

Return the unit IDs present in the model's points frame.

def trajectory_units(self) -> list:
456    def trajectory_units(self) -> list:
457        """
458        Return unit IDs present in the trajectories frame.
459
460        Falls back to point rows because qeviz can use points as ordered
461        trajectory states when no separate trajectories frame is supplied.
462        """
463        frame = self._model.get("trajectories") or self._model.get("points")
464        if not frame:
465            return []
466        id_col = self._model.get("id_col") or "QEUNIT"
467        seen: list[str] = []
468        for row in frame.get("data", []):
469            if id_col in row:
470                val = str(row[id_col])
471                if val not in seen:
472                    seen.append(val)
473        return seen

Return unit IDs present in the trajectories frame.

Falls back to point rows because qeviz can use points as ordered trajectory states when no separate trajectories frame is supplied.

def group( self, *names: str, points: Any = None, label: Optional[str] = None, color: Optional[str] = None, shape: Optional[str] = None, by: Optional[str] = None, intervals: Union[str, bool] = 'box', conf_level: float = 0.95, outlier: bool = False, fixed_size: bool = False, show: bool = True) -> QEPlot:
569    def group(
570        self,
571        *names: str,
572        points: Any = None,
573        label: Optional[str] = None,
574        color: Optional[str] = None,
575        shape: Optional[str] = None,
576        by: Optional[str] = None,
577        intervals: Union[str, bool] = "box",
578        conf_level: float = 0.95,
579        outlier: bool = False,
580        fixed_size: bool = False,
581        show: bool = True,
582    ) -> "QEPlot":
583        """
584        Group means: by name, or the mean of any subset of points.
585
586        Pass group names to show only those groups' means; omit names to show
587        every group. ``points`` (a DataFrame / array of positions) instead adds
588        the mean of that subset, with its own t interval, as a mean named
589        ``label`` (default ``"mean 1"``, ``"mean 2"``, …); each such mean keeps
590        its own ``intervals`` / ``outlier`` setting. ``show=False`` hides all
591        means. Mirrors R's ``qe_group()``.
592
593        Parameters
594        ----------
595        intervals   ``"box"`` (default), ``"crosshairs"`` or ``"none"``;
596                    ``True`` / ``False`` mean ``"box"`` / ``"none"``.
597        conf_level  Confidence level of the t interval. Default 0.95.
598        outlier     Also draw the outlier interval (Q1 − 1.5·IQR … Q3 + 1.5·IQR).
599        color, shape
600                    Colour and marker shape (``"square"``, ``"circle"``,
601                    ``"triangle"``, ``"diamond"``) of an explicit mean.
602        fixed_size  Keep mean markers a constant on-screen pixel size.
603        """
604        p = self._copy()
605        if not show:
606            p._opts["means-show"] = False
607            return p
608        p._opts.pop("means-show", None)
609
610        if by is not None:
611            gcol = p._model.get("group_col")
612            if gcol is not None and by != gcol:
613                raise ValueError(
614                    f"group(): by = {by!r} does not match the model's group column ({gcol!r}).")
615        if isinstance(intervals, bool):
616            intervals = "box" if intervals else "none"
617        if intervals not in ("box", "crosshairs", "none"):
618            raise ValueError('group(): intervals must be "box", "crosshairs" or "none".')
619        if not (isinstance(conf_level, (int, float)) and 0 < conf_level < 1):
620            raise ValueError("group(): conf_level must be a number in (0, 1).")
621        if points is not None and names:
622            raise ValueError("group(): supply group names or 'points', not both.")
623
624        p._opts["intervals"] = intervals
625        p._opts["confidence"] = intervals != "none"
626        p._opts["mean-outlier"] = bool(outlier) or bool(p._opts.get("mean-outlier"))
627        p._opts["mean-fixed-size"] = bool(fixed_size)
628
629        m = p._model
630        if points is not None:
631            # ── Explicit: the mean (+ t CI, outlier fences) of a subset ──────
632            rows = p._point_frame(points)
633            expl = p._opts.get("groups-explicit") or []
634            lbl = label if label is not None else f"mean {len(expl) + 1}"
635            if lbl in p.groups() and lbl not in expl:
636                raise ValueError(f"group(): label {lbl!r} is already a group in the model.")
637            gkey = p._group_key()
638            for r in rows:
639                r[gkey] = lbl
640            row = _group_summary(rows, m["x_col"], m["y_col"], gkey,
641                                 conf_level=conf_level, outlier=outlier)[0]
642            if color is not None:
643                row["color"] = color
644            if shape is not None:
645                row["shape"] = _shape(shape, "group")
646            row["intervals"] = intervals
647            row["outlier"] = bool(outlier)
648            m["groups"] = _upsert_rows(m.get("groups"), [row], key=gkey)
649            p._opts["groups-explicit"] = expl + ([lbl] if lbl not in expl else [])
650        else:
651            # ── By name ──────────────────────────────────────────────────────
652            if names:
653                available = p.groups()
654                bad = [n for n in names if n not in available]
655                if bad:
656                    raise ValueError(
657                        f"group(): group(s) not found in model: {bad!r}\n"
658                        f"Available: {available!r}")
659            p._opts["groups-named"] = [str(n) for n in names]   # [] = all
660            if (conf_level != 0.95 or outlier) and m.get("points"):
661                rows = _group_summary(_frame_rows(m["points"]), m["x_col"], m["y_col"],
662                                      m.get("group_col"), conf_level=conf_level,
663                                      outlier=outlier)
664                m["groups"] = _upsert_rows(m.get("groups"), rows, key=m.get("group_col"))
665        p._update_groups_filter()
666        return p

Group means: by name, or the mean of any subset of points.

Pass group names to show only those groups' means; omit names to show every group. points (a DataFrame / array of positions) instead adds the mean of that subset, with its own t interval, as a mean named label (default "mean 1", "mean 2", …); each such mean keeps its own intervals / outlier setting. show=False hides all means. Mirrors R's qe_group().

Parameters

intervals "box" (default), "crosshairs" or "none"; True / False mean "box" / "none". conf_level Confidence level of the t interval. Default 0.95. outlier Also draw the outlier interval (Q1 − 1.5·IQR … Q3 + 1.5·IQR). color, shape Colour and marker shape ("square", "circle", "triangle", "diamond") of an explicit mean. fixed_size Keep mean markers a constant on-screen pixel size.

def edges( self, group: Optional[str] = None, *, unit: Optional[str] = None, weights: Any = None, compare: Any = None, also: Optional[str] = None, colors: Union[str, Sequence[str], NoneType] = None, threshold: Union[float, Sequence[float], NoneType] = None, name: Optional[str] = None, show: bool = True, color_scale: str = 'model', edge_width: Optional[float] = None, magnify: Optional[float] = None) -> QEPlot:
668    def edges(
669        self,
670        group: Optional[str] = None,
671        *,
672        unit: Optional[str] = None,
673        weights: Any = None,
674        compare: Any = None,
675        also: Optional[str] = None,
676        colors: Union[str, Sequence[str], None] = None,
677        threshold: Union[float, Sequence[float], None] = None,
678        name: Optional[str] = None,
679        show: bool = True,
680        color_scale: str = "model",
681        edge_width: Optional[float] = None,
682        magnify: Optional[float] = None,
683    ) -> "QEPlot":
684        """
685        Draw an edge network: a group's or unit's (by name), or explicit weights.
686
687        By name, ``group`` (a group's mean network) or ``unit`` (one unit's
688        network), with ``compare`` (subtract a second group) or ``also``
689        (overlay it); a second call replaces it. ``weights`` instead draws a
690        network from data: a Series / dict of edge weights, an unnamed list in
691        the model's edge-column order, a DataFrame / 2-D array (averaged over
692        rows), or a list of those (one layer each); ``compare`` then subtracts a
693        group name or a second set of weights. Every ``weights`` call adds a
694        layer; one with the same ``name`` replaces it. ``show=False`` removes
695        all networks. Mirrors R's ``qe_edges()``.
696
697        Parameters
698        ----------
699        colors      One or two colours (positive, negative); with one, negative
700                    weights use its complement.
701        threshold   ``min`` or ``(min, max)``: |weight| < min is not drawn,
702                    |weight| > max is drawn at max (sign kept).
703        name        Name for this network (reported in edge events).
704        color_scale ``"model"`` (default), ``"plot"`` or ``"absolute"``: how
705                    weights map onto webENA's colour ramps.
706        edge_width  Width of a weight-1 edge as a fraction of the plot width
707                    (qeviz default 0.04).
708        magnify     Multiply this plot's edge widths and node sizes (not
709                    colour); labelled "(scaled N.Nx)" whenever set.
710        """
711        if group is not None and unit is not None:
712            raise ValueError("edges(): supply either 'group' or 'unit', not both.")
713        if weights is not None and (group is not None or unit is not None):
714            raise ValueError("edges(): supply 'weights' or a 'group' / 'unit' name, not both.")
715
716        p = self._copy()
717        if not show:
718            p._opts["edges"] = "false"
719            for k in ("group", "unit", "compare", "also", "edge-named", "edge-layers"):
720                p._opts.pop(k, None)
721            p._model.pop("networks", None)
722            return p
723
724        if color_scale not in ("model", "plot", "absolute"):
725            raise ValueError('edges(): color_scale must be "model", "plot", or "absolute".')
726        if edge_width is not None and not (0 < edge_width <= 1):
727            raise ValueError("edges(): edge_width must be a number in (0, 1].")
728        if magnify is not None and not (math.isfinite(magnify) and magnify > 0):
729            raise ValueError("edges(): magnify must be a positive number.")
730        layer_attrs = _layer_attrs(colors, threshold)
731
732        p._opts["edges"] = True
733        p._set("edge-color-scale", None if color_scale == "model" else color_scale)
734        if edge_width is not None:
735            p._opts["edge-width"] = edge_width
736        if magnify is not None:
737            p._opts["edge-magnify"] = magnify
738
739        # ── Explicit data: append one layer per network ──────────────────────
740        if weights is not None:
741            if also is not None:
742                raise ValueError("edges(): 'also' takes group names; for data, pass a list to 'weights'.")
743            cols = p._edge_columns()
744            many = isinstance(weights, (list, tuple)) and weights and not isinstance(
745                weights[0], (int, float))
746            nets = list(weights) if many else [weights]
747            base = len(p._opts.get("edge-layers") or [])
748            for k, net in enumerate(nets, start=1):
749                w = p._resolve_weights(net, cols, "weights")
750                if compare is not None:
751                    c = (p._group_network(compare, cols) if isinstance(compare, str)
752                         else p._resolve_weights(compare, cols, "compare"))
753                    w = {e: w[e] - c[e] for e in cols}
754                lname = name if (name is not None and len(nets) == 1) else f"network {base + k}"
755                p._model["networks"] = _append_network(p._model.get("networks"), lname, w)
756                p._opts["edge-layers"] = (p._opts.get("edge-layers") or []) + [
757                    {"network": lname, **layer_attrs}]
758            return p
759
760        # ── By name: replace the named network ───────────────────────────────
761        available_groups = p.groups()
762
763        def _check_group(nm: Optional[str], arg: str) -> None:
764            if nm is not None and nm not in available_groups:
765                raise ValueError(
766                    f"edges(): {arg} = {nm!r} not found in model.\n"
767                    f"Available groups: {available_groups!r}")
768
769        if compare is not None and not isinstance(compare, str):
770            raise ValueError("edges(): 'compare' as data needs 'weights'; with 'group' it takes a group name.")
771        _check_group(group, "group")
772        _check_group(compare, "compare")
773        _check_group(also, "also")
774        if unit is not None and unit not in p.units():
775            raise ValueError(
776                f"edges(): unit = {unit!r} not found in model.\n"
777                "Use .units() to see available unit IDs.")
778        if compare is not None and also is not None:
779            raise ValueError("edges(): supply either 'compare' or 'also', not both.")
780        if unit is not None and (compare is not None or also is not None):
781            raise ValueError("edges(): 'compare' and 'also' cannot be combined with 'unit'.")
782
783        p._set("group", group)
784        p._set("unit", unit)
785        p._set("compare", compare)
786        p._set("also", also)
787        named = ({"name": name} if name is not None else {}) | layer_attrs
788        p._set("edge-named", named or None)
789        return p

Draw an edge network: a group's or unit's (by name), or explicit weights.

By name, group (a group's mean network) or unit (one unit's network), with compare (subtract a second group) or also (overlay it); a second call replaces it. weights instead draws a network from data: a Series / dict of edge weights, an unnamed list in the model's edge-column order, a DataFrame / 2-D array (averaged over rows), or a list of those (one layer each); compare then subtracts a group name or a second set of weights. Every weights call adds a layer; one with the same name replaces it. show=False removes all networks. Mirrors R's qe_edges().

Parameters

colors One or two colours (positive, negative); with one, negative weights use its complement. threshold min or (min, max): |weight| < min is not drawn, |weight| > max is drawn at max (sign kept). name Name for this network (reported in edge events). color_scale "model" (default), "plot" or "absolute": how weights map onto webENA's colour ramps. edge_width Width of a weight-1 edge as a fraction of the plot width (qeviz default 0.04). magnify Multiply this plot's edge widths and node sizes (not colour); labelled "(scaled N.Nx)" whenever set.

def points( self, show: bool = True, *, units: Optional[Sequence[str]] = None, points: Any = None, color: Union[str, Sequence[str], NoneType] = None, shape: Union[str, Sequence[str], NoneType] = None, labels: Union[str, Sequence[str], NoneType] = None, name: Optional[str] = None, size: Union[int, float, NoneType] = None, fixed_size: bool = False) -> QEPlot:
791    def points(
792        self,
793        show: bool = True,
794        *,
795        units: Optional[Sequence[str]] = None,
796        points: Any = None,
797        color: Union[str, Sequence[str], None] = None,
798        shape: Union[str, Sequence[str], None] = None,
799        labels: Union[str, Sequence[str], None] = None,
800        name: Optional[str] = None,
801        size: Optional[Union[int, float]] = None,
802        fixed_size: bool = False,
803    ) -> "QEPlot":
804        """
805        Unit points: all of them (coloured by group), or an explicit point set.
806
807        With no ``units`` / ``points``, shows every unit point. ``units`` (unit
808        IDs) or ``points`` (a DataFrame / array of positions) instead adds a
809        point set with optional ``color``, ``shape`` (``"circle"``,
810        ``"square"``, ``"triangle"``, ``"diamond"``) and ``labels``, one value
811        or one per point. Each set adds a layer; one with the same ``name``
812        replaces it. ``show=False`` hides all points. ``size`` overrides the
813        dot size (default 2.5); ``fixed_size`` keeps dots a constant on-screen
814        size. Mirrors R's ``qe_points()``.
815        """
816        p = self._copy()
817        if not show:
818            p._opts["points"] = False
819            p._opts.pop("point-sets", None)
820            p._model.pop("pointsets", None)
821            return p
822        if units is None and points is None:
823            p._opts["points"] = True
824            p._set("point-size", size)
825            p._opts["point-fixed-size"] = bool(fixed_size)
826            return p
827        if units is not None and points is not None:
828            raise ValueError("points(): supply 'units' or 'points', not both.")
829
830        m = p._model
831        id_col = m.get("id_col") or "QEUNIT"
832        gcol = m.get("group_col")
833        if units is not None:
834            units = [units] if isinstance(units, str) else list(units)
835            all_rows = {str(r.get(id_col)): r for r in _frame_rows(m.get("points"))}
836            bad = [u for u in units if u not in all_rows]
837            if bad:
838                raise ValueError(f"points(): unit(s) not in model: {bad[:3]!r}")
839            rows = [all_rows[u] for u in units]
840        else:
841            rows = p._point_frame(points)
842
843        n = len(rows)
844        sets = p._opts.get("point-sets") or []
845        set_name = name if name is not None else f"points {len(sets) + 1}"
846
847        def per_point(v: Any, arg: str) -> Optional[list]:
848            if v is None:
849                return None
850            vals = [v] if isinstance(v, str) else list(v)
851            if len(vals) not in (1, n):
852                raise ValueError(f"points(): '{arg}' must have length 1 or {n}.")
853            return [str(x) for x in (vals * n if len(vals) == 1 else vals)]
854
855        cols = per_point(color, "color")
856        shapes = per_point(None if shape is None else _shape(shape, "points"), "shape")
857        labs = per_point(labels, "labels")
858        new = []
859        for i, r in enumerate(rows):
860            row = {"set": set_name, "id": str(r[id_col]),
861                   m["x_col"]: r[m["x_col"]], m["y_col"]: r[m["y_col"]]}
862            if gcol and gcol in r:
863                row["group"] = str(r[gcol])
864            if cols:
865                row["color"] = cols[i]
866            if shapes:
867                row["shape"] = shapes[i]
868            if labs:
869                row["label"] = labs[i]
870            new.append(row)
871        m["pointsets"] = _upsert_rows(m.get("pointsets"), new,
872                                      drop=lambda r: r.get("set") == set_name)
873        p._opts["point-sets"] = [s for s in sets if s["set"] != set_name] + [
874            {"set": set_name, "size": size, "fixed": bool(fixed_size)}]
875        return p

Unit points: all of them (coloured by group), or an explicit point set.

With no units / points, shows every unit point. units (unit IDs) or points (a DataFrame / array of positions) instead adds a point set with optional color, shape ("circle", "square", "triangle", "diamond") and labels, one value or one per point. Each set adds a layer; one with the same name replaces it. show=False hides all points. size overrides the dot size (default 2.5); fixed_size keeps dots a constant on-screen size. Mirrors R's qe_points().

def nodes( self, show: Union[bool, str] = 'auto', unconnected: str = 'dot', *, positions: Any = None, labels: Optional[dict] = None) -> QEPlot:
877    def nodes(
878        self,
879        show: Union[bool, str] = "auto",
880        unconnected: str = "dot",
881        *,
882        positions: Any = None,
883        labels: Optional[dict] = None,
884    ) -> "QEPlot":
885        """
886        Code nodes: when to draw them, and where.
887
888        ``"auto"`` (default) draws nodes only with an edge network, matching
889        rENA; ``"always"`` / ``True`` and ``"never"`` / ``False`` override that.
890        ``unconnected="hide"`` hides nodes with no drawn edges. ``positions``
891        (a DataFrame with a code column or index, and x / y columns) moves
892        nodes; ``labels`` (``{code: text}``) relabels them. Mirrors R's
893        ``qe_nodes()``.
894        """
895        if show is True:
896            show = "always"
897        elif show is False:
898            show = "never"
899        if show not in ("auto", "always", "never"):
900            raise ValueError('nodes(): show must be "auto", "always", or "never".')
901        if unconnected not in ("dot", "hide"):
902            raise ValueError('nodes(): unconnected must be "dot" or "hide".')
903        p = self._copy()
904        p._opts["nodes-show"] = show
905        p._set("nodes-unconnected", "hide" if unconnected == "hide" else None)
906
907        if positions is not None or labels is not None:
908            m = p._model
909            idc = m.get("node_id_col") or "code"
910            rows = _frame_rows(m["nodes"])
911            codes = [str(r[idc]) for r in rows]
912
913            def check(got: list, arg: str) -> None:
914                bad = [g for g in got if g not in codes]
915                if bad:
916                    raise ValueError(
917                        f"nodes(): '{arg}' has codes not in the model: {bad[:3]!r}\n"
918                        f"Model codes: {codes[:4]!r}")
919
920            if positions is not None:
921                pos = positions if isinstance(positions, pd.DataFrame) else pd.DataFrame(positions)
922                if idc in pos.columns:
923                    pc = [str(v) for v in pos[idc]]
924                elif "code" in pos.columns:
925                    pc = [str(v) for v in pos["code"]]
926                elif not isinstance(pos.index, pd.RangeIndex):
927                    pc = [str(v) for v in pos.index]
928                else:
929                    raise ValueError("nodes(): 'positions' needs a code column or index.")
930                num = list(pos.select_dtypes("number").columns)
931                dims = [m["x_col"], m["y_col"]] if m["x_col"] in num and m["y_col"] in num else num[:2]
932                if len(num) < 2:
933                    raise ValueError("nodes(): 'positions' needs two numeric (x, y) columns.")
934                check(pc, "positions")
935                for i, code in enumerate(pc):
936                    r = rows[codes.index(code)]
937                    r[m["x_col"]] = float(pos[dims[0]].iloc[i])
938                    r[m["y_col"]] = float(pos[dims[1]].iloc[i])
939            if labels is not None:
940                if not isinstance(labels, dict):
941                    raise ValueError("nodes(): 'labels' must be a dict (code -> text).")
942                check(list(labels), "labels")
943                for r in rows:
944                    r.setdefault("label", None)
945                for code, text in labels.items():
946                    rows[codes.index(str(code))]["label"] = str(text)
947            m["nodes"] = _frame_from_rows(rows, list(m["nodes"]["types"]) + (
948                ["label"] if labels is not None and "label" not in m["nodes"]["types"] else []))
949        return p

Code nodes: when to draw them, and where.

"auto" (default) draws nodes only with an edge network, matching rENA; "always" / True and "never" / False override that. unconnected="hide" hides nodes with no drawn edges. positions (a DataFrame with a code column or index, and x / y columns) moves nodes; labels ({code: text}) relabels them. Mirrors R's qe_nodes().

def axes( self, x: Union[bool, str] = False, y: Union[bool, str] = False, *, show: bool = True) -> QEPlot:
951    def axes(
952        self,
953        x: Union[bool, str] = False,
954        y: Union[bool, str] = False,
955        *,
956        show: bool = True,
957    ) -> "QEPlot":
958        """
959        Show or hide the axes (a ``<qe-axes>`` layer).
960
961        Axis labels are opt-in. ``x`` / ``y`` default to ``False`` (no label);
962        ``True`` uses the dimension name (e.g. ``"SVD1"``), a string sets custom
963        text. ``show=False`` suppresses the axes entirely.
964        """
965        p = self._copy()
966        if not show:
967            p._opts["axes"] = False
968            return p
969        p._opts["axes"] = True
970        p._opts["axis-x"] = x
971        p._opts["axis-y"] = y
972        return p

Show or hide the axes (a <qe-axes> layer).

Axis labels are opt-in. x / y default to False (no label); True uses the dimension name (e.g. "SVD1"), a string sets custom text. show=False suppresses the axes entirely.

def trajectories( self, units: Union[str, list[str], NoneType] = None, *, smooth: str = 'none', max_degree: int = 3, degree_selection: str = 'loocv_2d', points: bool = True, tips: bool = True, playhead: Union[int, float, NoneType] = None, line_style: str = 'uniform', stroke_width: Union[int, float] = 2, stroke_width_range: tuple[typing.Union[int, float], typing.Union[int, float]] = (1, 6), opacity_range: tuple[typing.Union[int, float], typing.Union[int, float]] = (0.3, 1), show: bool = True) -> QEPlot:
 974    def trajectories(
 975        self,
 976        units: Optional[Union[str, list[str]]] = None,
 977        *,
 978        smooth: str = "none",
 979        max_degree: int = 3,
 980        degree_selection: str = "loocv_2d",
 981        points: bool = True,
 982        tips: bool = True,
 983        playhead: Optional[Union[int, float]] = None,
 984        line_style: str = "uniform",
 985        stroke_width: Union[int, float] = 2,
 986        stroke_width_range: tuple[Union[int, float], Union[int, float]] = (1, 6),
 987        opacity_range: tuple[Union[int, float], Union[int, float]] = (0.3, 1),
 988        show: bool = True,
 989    ) -> "QEPlot":
 990        """
 991        Show or hide supplied ordered unit trajectory paths.
 992
 993        qeviz renders rows already present in the model; trajectory modeling,
 994        accumulation, dooring, and inference remain caller-side work.
 995
 996        ``max_degree`` bounds the polynomial degree when ``smooth="poly"``.
 997        ``degree_selection="loocv_2d"`` (default) picks the degree in
 998        ``1..max_degree`` by joint 2D leave-one-out cross-validation;
 999        ``"fixed"`` always uses ``max_degree``. Near-origin points are excluded
1000        from the fit (still drawn), matching ``ena.plot.trajectory()``.
1001        """
1002        p = self._copy()
1003        if not show:
1004            p._opts["trajectories"] = False
1005            return p
1006        if smooth not in {"none", "poly"}:
1007            raise ValueError("trajectories(): smooth must be 'none' or 'poly'.")
1008        if degree_selection not in {"loocv_2d", "fixed"}:
1009            raise ValueError("trajectories(): degree_selection must be 'loocv_2d' or 'fixed'.")
1010        if line_style not in {"uniform", "tapered"}:
1011            raise ValueError("trajectories(): line_style must be 'uniform' or 'tapered'.")
1012        selected = None if units is None else ([units] if isinstance(units, str) else [str(u) for u in units])
1013        if selected:
1014            available = self.trajectory_units()
1015            bad = [u for u in selected if u not in available]
1016            if bad:
1017                raise ValueError(
1018                    f"trajectories(): unit(s) not found in model: {bad!r}\n"
1019                    f"Available: {available!r}")
1020        p._opts["trajectories"] = True
1021        p._set("trajectory-units", None if selected is None else ",".join(selected))
1022        p._opts["trajectory-smooth"] = smooth
1023        p._opts["trajectory-max-degree"] = int(max_degree)
1024        p._opts["trajectory-degree-selection"] = degree_selection
1025        p._opts["trajectory-points"] = bool(points)
1026        p._opts["trajectory-tips"] = bool(tips)
1027        p._set("trajectory-playhead", playhead)
1028        p._opts["trajectory-line-style"] = line_style
1029        p._opts["trajectory-stroke-width"] = stroke_width
1030        p._opts["trajectory-stroke-width-range"] = ",".join(_fmt(v) for v in stroke_width_range)
1031        p._opts["trajectory-opacity-range"] = ",".join(_fmt(v) for v in opacity_range)
1032        return p

Show or hide supplied ordered unit trajectory paths.

qeviz renders rows already present in the model; trajectory modeling, accumulation, dooring, and inference remain caller-side work.

max_degree bounds the polynomial degree when smooth="poly". degree_selection="loocv_2d" (default) picks the degree in 1..max_degree by joint 2D leave-one-out cross-validation; "fixed" always uses max_degree. Near-origin points are excluded from the fit (still drawn), matching ena.plot.trajectory().

def labels( self, nodes: str = <object object>, means: str = <object object>, points: str = <object object>, *, font_size: Optional[float] = <object object>, font_family: Optional[str] = <object object>, font_color: Optional[str] = <object object>) -> QEPlot:
1034    def labels(
1035        self,
1036        nodes: str = _UNSET,
1037        means: str = _UNSET,
1038        points: str = _UNSET,
1039        *,
1040        font_size: Optional[float] = _UNSET,
1041        font_family: Optional[str] = _UNSET,
1042        font_color: Optional[str] = _UNSET,
1043    ) -> "QEPlot":
1044        """
1045        Label visibility and font.
1046
1047        ``nodes`` / ``means`` / ``points`` take ``"on"``, ``"off"``,
1048        ``"click"`` or ``"auto"``; ``font_size`` is in pixels (the title is
1049        drawn at 1.35×), ``font_family`` and ``font_color`` apply to labels and
1050        the title. Only the arguments supplied change; a bare ``labels()``
1051        applies the defaults (``"on"``, ``"on"``, ``"auto"``). Mirrors R's
1052        ``qe_labels()``.
1053        """
1054        if font_size is not _UNSET and font_size is not None and not (
1055            isinstance(font_size, (int, float)) and font_size > 0
1056        ):
1057            raise ValueError("labels(): font_size must be a positive number of pixels.")
1058        p = self._copy()
1059        bare = all(v is _UNSET for v in (nodes, means, points, font_size, font_family, font_color))
1060        for key, val, default in (("label-nodes", nodes, "on"), ("label-means", means, "on"),
1061                                  ("label-points", points, "auto")):
1062            if val is not _UNSET:
1063                p._set(key, val)
1064            elif bare:
1065                p._opts[key] = default
1066        for key, val in (("label-font-size", font_size), ("label-font-family", font_family),
1067                         ("label-font-color", font_color)):
1068            if val is not _UNSET:
1069                p._set(key, val)
1070        return p

Label visibility and font.

nodes / means / points take "on", "off", "click" or "auto"; font_size is in pixels (the title is drawn at 1.35×), font_family and font_color apply to labels and the title. Only the arguments supplied change; a bare labels() applies the defaults ("on", "on", "auto"). Mirrors R's qe_labels().

def colors(self, mapping: Optional[dict] = None, **colors: str) -> QEPlot:
1072    def colors(self, mapping: Optional[dict] = None, **colors: str) -> "QEPlot":
1073        """
1074        Pin groups to colours: ``.colors(FirstGame="#E69F00")`` or
1075        ``.colors({"First Game": "#E69F00"})``. Each group's mean, unit points
1076        and networks use it; unlisted groups keep the palette colour. Mirrors
1077        R's ``qe_colors()``.
1078        """
1079        cols = {**(mapping or {}), **colors}
1080        if not cols:
1081            raise ValueError('colors(): give named colours, e.g. .colors(FirstGame="#E69F00").')
1082        bad = [g for g in cols if g not in self.groups()]
1083        if bad:
1084            raise ValueError(f"colors(): group(s) not found in model: {bad!r}")
1085        p = self._copy()
1086        rows = _frame_rows(p._model.get("groups"))
1087        gcol = p._model.get("group_col")
1088        for r in rows:
1089            r.setdefault("color", None)
1090            if str(r.get(gcol)) in cols:
1091                r["color"] = cols[str(r.get(gcol))]
1092        names = list(p._model["groups"]["types"])
1093        p._model["groups"] = _frame_from_rows(rows, names + ([] if "color" in names else ["color"]))
1094        return p

Pin groups to colours: .colors(FirstGame="#E69F00") or .colors({"First Game": "#E69F00"}). Each group's mean, unit points and networks use it; unlisted groups keep the palette colour. Mirrors R's qe_colors().

def range(self, range: Union[str, float, NoneType]) -> QEPlot:
1096    def range(self, range: Union[str, float, None]) -> "QEPlot":
1097        """
1098        Set the symmetric axis range: ``"network"`` (node extent × 1.2),
1099        ``"points"`` (unit points' extent × 1.2), a positive number, or ``None``
1100        for the default. Mirrors R's ``qe_range()``.
1101        """
1102        _check_range(range, "range")
1103        p = self._copy()
1104        p._set("range", range)
1105        return p

Set the symmetric axis range: "network" (node extent × 1.2), "points" (unit points' extent × 1.2), a positive number, or None for the default. Mirrors R's qe_range().

def show(self) -> None:
1262    def show(self) -> None:
1263        """
1264        Display the plot inline in a Jupyter / IPython notebook.
1265
1266        In non-interactive environments (plain Python scripts) this falls back
1267        to printing the HTML document to stdout.
1268        """
1269        try:
1270            from IPython.display import HTML, display  # type: ignore
1271            display(HTML(self._build_fragment()))
1272        except ImportError:
1273            print(self._build_html_doc())

Display the plot inline in a Jupyter / IPython notebook.

In non-interactive environments (plain Python scripts) this falls back to printing the HTML document to stdout.

def export_html(self, path: str) -> str:
1279    def export_html(self, path: str) -> str:
1280        """
1281        Write a self-contained HTML file (the bundle is inlined).
1282
1283        Returns the resolved absolute path of the written file.
1284        """
1285        abs_path = os.path.abspath(path)
1286        with open(abs_path, "w", encoding="utf-8") as fh:
1287            fh.write(self._build_html_doc())
1288        return abs_path

Write a self-contained HTML file (the bundle is inlined).

Returns the resolved absolute path of the written file.

def model_data( nodes: pandas.DataFrame, edges: pandas.DataFrame, points: Optional[pandas.DataFrame] = None, trajectories: Optional[pandas.DataFrame] = None, *, id_col: str = 'QEUNIT', node_id_col: str = 'code', x_col: str = 'SVD1', y_col: str = 'SVD2', group_col: Optional[str] = None, directed: bool = False, conf_level: float = 0.95, include_ci: bool = True) -> dict:
1324def model_data(
1325    nodes:   pd.DataFrame,
1326    edges:   pd.DataFrame,
1327    points:  Optional[pd.DataFrame] = None,
1328    trajectories: Optional[pd.DataFrame] = None,
1329    *,
1330    id_col:       str = "QEUNIT",
1331    node_id_col:  str = "code",
1332    x_col:        str = "SVD1",
1333    y_col:        str = "SVD2",
1334    group_col:    Optional[str] = None,
1335    directed:     bool = False,
1336    conf_level:   float = 0.95,
1337    include_ci:   bool = True,
1338) -> dict:
1339    """
1340    Build a qeviz ModelData dict from pandas DataFrames.
1341
1342    This is the low-level constructor — most users will call :func:`plot`
1343    directly.  Use ``model_data()`` when you need to inspect or transform the
1344    serialised dict before rendering.
1345
1346    Parameters
1347    ----------
1348    nodes         One row per code node.  Must contain ``node_id_col`` plus
1349                  ``x_col`` and ``y_col`` position columns.
1350    edges         One row per unit.  First column is the unit identifier
1351                  (``id_col``); remaining columns are dot-separated edge
1352                  weights (``"A.B"``).
1353    points        Unit projection positions.  Must contain ``id_col``,
1354                  ``x_col``, ``y_col``, and (optionally) ``group_col``.
1355    trajectories  Ordered observations for trajectory rendering.  Must contain
1356                  ``id_col``, ``x_col``, ``y_col``, and ideally ``time``,
1357                  ``RowID``, or ``ActivityNumber``.
1358    id_col        Unit-identifier column in ``edges`` / ``points``.
1359    node_id_col   Node-identifier column in ``nodes``.
1360    x_col         X-position column name.
1361    y_col         Y-position column name.
1362    group_col     Grouping column in ``points``.  When provided, group means
1363                  and t CI bounds are added as the ``groups`` frame; ``None``
1364                  gives a model with no groups (explicit means still work).
1365    directed      ``True`` for ONA / directed networks (arrowheads).
1366    conf_level    Confidence level for CI boxes.  Default 0.95.
1367    include_ci    Include CI bounds in the groups frame.  Default ``True``.
1368
1369    Returns
1370    -------
1371    dict  ModelData dict suitable for :func:`plot` or :func:`export_html`.
1372    """
1373    result: dict = {
1374        "nodes":       _qe_frame(nodes),
1375        "edges":       _qe_frame(edges),
1376        "updated":     int(time.time() * 1000),
1377        "directed":    directed,
1378        "id_col":      id_col,
1379        "node_id_col": node_id_col,
1380        "x_col":       x_col,
1381        "y_col":       y_col,
1382        "group_col":   group_col,
1383    }
1384    if group_col is None:
1385        del result["group_col"]
1386    if points is not None:
1387        result["points"] = _qe_frame(points)
1388        if group_col and group_col in points.columns:
1389            result["groups"] = _qe_frame(_group_summaries(
1390                points, group_col, [x_col, y_col],
1391                conf_level=conf_level, include_ci=include_ci))
1392    if trajectories is not None:
1393        result["trajectories"] = _qe_frame(trajectories)
1394    return result

Build a qeviz ModelData dict from pandas DataFrames.

This is the low-level constructor — most users will call plot() directly. Use model_data() when you need to inspect or transform the serialised dict before rendering.

Parameters

nodes One row per code node. Must contain node_id_col plus x_col and y_col position columns. edges One row per unit. First column is the unit identifier (id_col); remaining columns are dot-separated edge weights ("A.B"). points Unit projection positions. Must contain id_col, x_col, y_col, and (optionally) group_col. trajectories Ordered observations for trajectory rendering. Must contain id_col, x_col, y_col, and ideally time, RowID, or ActivityNumber. id_col Unit-identifier column in edges / points. node_id_col Node-identifier column in nodes. x_col X-position column name. y_col Y-position column name. group_col Grouping column in points. When provided, group means and t CI bounds are added as the groups frame; None gives a model with no groups (explicit means still work). directed True for ONA / directed networks (arrowheads). conf_level Confidence level for CI boxes. Default 0.95. include_ci Include CI bounds in the groups frame. Default True.

Returns

dict ModelData dict suitable for plot() or export_html().

def plot( x: Union[pandas.DataFrame, dict], edges: Optional[pandas.DataFrame] = None, points: Optional[pandas.DataFrame] = None, trajectories: Optional[pandas.DataFrame] = None, *, title: Optional[str] = None, width: Union[int, str] = 700, height: Union[int, str] = 500, group_col: Optional[str] = None, range: Union[str, float, NoneType] = None, scale_points: bool = True, point_scale: Optional[float] = None, center: str = 'origin', palette: Optional[Sequence[str]] = None, **model_kwargs) -> QEPlot:
1397def plot(
1398    x: Union[pd.DataFrame, dict],
1399    edges:  Optional[pd.DataFrame] = None,
1400    points: Optional[pd.DataFrame] = None,
1401    trajectories: Optional[pd.DataFrame] = None,
1402    *,
1403    title:     Optional[str] = None,
1404    width:     Union[int, str] = 700,
1405    height:    Union[int, str] = 500,
1406    group_col: Optional[str] = None,
1407    range:     Union[str, float, None] = None,
1408    scale_points: bool = True,
1409    point_scale:  Optional[float] = None,
1410    center:    str = "origin",
1411    palette:   Optional[Sequence[str]] = None,
1412    **model_kwargs,
1413) -> QEPlot:
1414    """
1415    Create a :class:`QEPlot` (R's ``qe_plot()``).
1416
1417    Accepts either a pre-built ModelData dict **or** raw DataFrames
1418    (``nodes``, ``edges``, ``points``).
1419
1420    Parameters
1421    ----------
1422    x           A ModelData dict from :func:`model_data`, **or** a nodes
1423                DataFrame (in which case ``edges`` must also be supplied).
1424    edges       Edge-weights DataFrame (only when ``x`` is a nodes DataFrame).
1425    points      Unit-positions DataFrame (optional, only with DataFrames).
1426    trajectories Ordered trajectory-state DataFrame (optional, only with DataFrames).
1427    title       Plot title, drawn above the plot when given; also the window /
1428                file title (default ``"qeviz"``).
1429    width, height
1430                Plot dimensions.  Integers are treated as pixels; strings
1431                are passed through as CSS (e.g. ``"100%"``).
1432    group_col   Grouping column (only when building from DataFrames).
1433    range       Symmetric axis range: ``"network"`` (default renderer
1434                behaviour), ``"points"`` or a positive number.
1435    scale_points
1436                ``False`` draws unit points and means at their raw
1437                coordinates instead of rescaling them to the node extent.
1438    point_scale Explicit factor for unit points and means (overrides
1439                ``scale_points``).
1440    center      ``"origin"`` (default) or ``"content"`` (centre the view on the
1441                nodes' and points' bounding box).
1442    palette     Colours for groups / sets / networks with none given
1443                (default: :func:`palette`).
1444    **model_kwargs
1445                Additional keyword arguments forwarded to :func:`model_data`
1446                (e.g. ``id_col``, ``x_col``, ``directed``).
1447    """
1448    if isinstance(x, dict):
1449        m = x
1450    else:
1451        if edges is None:
1452            raise TypeError("plot(): 'edges' is required when 'x' is a DataFrame.")
1453        m = model_data(x, edges, points, trajectories=trajectories,
1454                       group_col=group_col, **model_kwargs)
1455    return QEPlot(m, title=title, width=width, height=height, range=range,
1456                  scale_points=scale_points, point_scale=point_scale,
1457                  center=center, palette=palette)

Create a QEPlot (R's qe_plot()).

Accepts either a pre-built ModelData dict or raw DataFrames (nodes, edges, points).

Parameters

x A ModelData dict from model_data(), or a nodes DataFrame (in which case edges must also be supplied). edges Edge-weights DataFrame (only when x is a nodes DataFrame). points Unit-positions DataFrame (optional, only with DataFrames). trajectories Ordered trajectory-state DataFrame (optional, only with DataFrames). title Plot title, drawn above the plot when given; also the window / file title (default "qeviz"). width, height Plot dimensions. Integers are treated as pixels; strings are passed through as CSS (e.g. "100%"). group_col Grouping column (only when building from DataFrames). range Symmetric axis range: "network" (default renderer behaviour), "points" or a positive number. scale_points False draws unit points and means at their raw coordinates instead of rescaling them to the node extent. point_scale Explicit factor for unit points and means (overrides scale_points). center "origin" (default) or "content" (centre the view on the nodes' and points' bounding box). palette Colours for groups / sets / networks with none given (default: palette()). **model_kwargs Additional keyword arguments forwarded to model_data() (e.g. id_col, x_col, directed).

def palette() -> list:
82def palette() -> list:
83    """The default qeviz colour palette (Paul Tol "bright"), as in R's ``qe_palette()``."""
84    return list(_PALETTE)

The default qeviz colour palette (Paul Tol "bright"), as in R's qe_palette().

def from_pyena( model, group_col: Optional[str] = None, directed: bool = False, id_col: str = 'QEUNIT', title: Optional[str] = None, width: Union[int, str] = 700, height: Union[int, str] = 500, dims: tuple[int, int] = (0, 1)) -> QEPlot:
1460def from_pyena(
1461    model,
1462    group_col: Optional[str] = None,
1463    directed:  bool = False,
1464    id_col:    str = "QEUNIT",
1465    title:     Optional[str] = None,
1466    width:     Union[int, str] = 700,
1467    height:    Union[int, str] = 500,
1468    dims:      tuple[int, int] = (0, 1),
1469) -> QEPlot:
1470    """
1471    Convert a fitted pyENA model to a :class:`QEPlot`.
1472
1473    Python equivalent of R's ``qe_extract()`` — reads nodes, unit positions,
1474    edge weights, and group metadata directly from a fitted ``pyena.ENA``
1475    instance.
1476
1477    Parameters
1478    ----------
1479    model     A fitted ``pyena.ENA`` instance (after ``.fit()``).
1480    group_col Grouping column name in ``model.accum_.meta``
1481              (e.g. ``"Condition"``).
1482    directed  ``True`` for ONA / directed networks.
1483    id_col    Name to give the unit-identifier column.
1484    dims      The two dimensions to plot, as column indices of the model's
1485              positions (as R's ``qe_extract(dims =)``). Default ``(0, 1)``.
1486    title, width, height
1487              Passed to the returned :class:`QEPlot`.
1488
1489    Returns
1490    -------
1491    QEPlot
1492
1493    Examples
1494    --------
1495    ::
1496
1497        p = qeviz.from_pyena(model, group_col="Condition")
1498        p.edges("FirstGame", also="SecondGame").points()  # auto-displays in Jupyter
1499        p.export_html("output.html")
1500    """
1501    # pyENA's attribute names (rotation_nodes_, line_weights_, unit_labels_,
1502    # meta_data_); the older names are accepted as fallbacks.
1503    def attr(*names):
1504        for n in names:
1505            if getattr(model, n, None) is not None:
1506                return getattr(model, n)
1507        raise AttributeError(f"from_pyena(): model has none of {names}; is it a fitted pyena.ENA?")
1508
1509    units     = [str(u) for u in attr("unit_labels_", "units_")]
1510    node_pos  = np.asarray(attr("rotation_nodes_", "positions_"), dtype=float)
1511    pts       = np.asarray(attr("points_"), dtype=float)
1512
1513    # Nodes: code name + (x, y)
1514    nodes_df = pd.DataFrame({
1515        "code": list(attr("codes_")),
1516        "x":    node_pos[:, dims[0]],
1517        "y":    node_pos[:, dims[1]],
1518    })
1519
1520    # Edges: normalised connection weights; "A & B" → "A.B"
1521    conn_cols = [c.replace(" & ", ".").replace("&", ".") for c in attr("connection_names_")]
1522    edges_df  = pd.DataFrame(np.asarray(attr("line_weights_", "normed_networks_"), dtype=float),
1523                             columns=conn_cols)
1524    edges_df.insert(0, id_col, units)
1525
1526    # Points: projected (x, y) per unit
1527    points_df = pd.DataFrame({
1528        id_col: units,
1529        "x":    pts[:, dims[0]],
1530        "y":    pts[:, dims[1]],
1531    })
1532
1533    # Attach group from unit-level metadata (indexed by unit)
1534    if group_col is not None:
1535        meta = getattr(model, "meta_data_", None)
1536        if meta is None:
1537            meta = model.accum_.meta
1538        if group_col not in meta.columns:
1539            raise ValueError(
1540                f"group_col {group_col!r} not found in model metadata. "
1541                f"Available columns: {list(meta.columns)}"
1542            )
1543        group_vals = [str(v) for v in meta.reindex(units)[group_col].tolist()]
1544        points_df[group_col] = group_vals
1545        edges_df[group_col]  = group_vals
1546
1547    m = model_data(
1548        nodes       = nodes_df,
1549        edges       = edges_df,
1550        points      = points_df,
1551        id_col      = id_col,
1552        node_id_col = "code",
1553        x_col       = "x",
1554        y_col       = "y",
1555        group_col   = group_col,
1556        directed    = directed,
1557    )
1558    return QEPlot(m, title=title, width=width, height=height)

Convert a fitted pyENA model to a QEPlot.

Python equivalent of R's qe_extract() — reads nodes, unit positions, edge weights, and group metadata directly from a fitted pyena.ENA instance.

Parameters

model A fitted pyena.ENA instance (after .fit()). group_col Grouping column name in model.accum_.meta (e.g. "Condition"). directed True for ONA / directed networks. id_col Name to give the unit-identifier column. dims The two dimensions to plot, as column indices of the model's positions (as R's qe_extract(dims =)). Default (0, 1). title, width, height Passed to the returned QEPlot.

Returns

QEPlot

Examples

::

p = qeviz.from_pyena(model, group_col="Condition")
p.edges("FirstGame", also="SecondGame").points()  # auto-displays in Jupyter
p.export_html("output.html")
def export_html( model_or_plot: Union[dict, QEPlot], path: str, options: Optional[dict] = None, width: Union[int, str] = 700, height: Union[int, str] = 500) -> str:
1561def export_html(
1562    model_or_plot: Union[dict, QEPlot],
1563    path: str,
1564    options: Optional[dict] = None,
1565    width:  Union[int, str] = 700,
1566    height: Union[int, str] = 500,
1567) -> str:
1568    """
1569    Write a self-contained HTML file.
1570
1571    Accepts either a :class:`QEPlot` **or** a raw ModelData dict (legacy).
1572    When a dict is supplied ``options`` / ``width`` / ``height`` are forwarded
1573    to construct a temporary :class:`QEPlot`.
1574
1575    Returns the resolved absolute path of the written file.
1576    """
1577    if isinstance(model_or_plot, QEPlot):
1578        return model_or_plot.export_html(path)
1579
1580    # Legacy: raw dict path
1581    p = QEPlot(model_or_plot, width=width, height=height)
1582    if options:
1583        # Map old flat options dict onto chain methods for backward compat.
1584        group   = options.get("group")
1585        unit    = options.get("unit")
1586        compare = options.get("compare")
1587        also    = options.get("also")
1588        if group or unit or compare or also:
1589            p = p.edges(group=group, unit=unit, compare=compare, also=also)
1590        if options.get("show_points"):
1591            p = p.points(True)
1592    return p.export_html(path)

Write a self-contained HTML file.

Accepts either a QEPlot or a raw ModelData dict (legacy). When a dict is supplied options / width / height are forwarded to construct a temporary QEPlot.

Returns the resolved absolute path of the written file.