class PhasePlaneWidget(anywidget.AnyWidget):
"""Interactive phase plane widget.
In Jupyter / VS Code the widget is backed by anywidget. All numerical
work (ODE integration, fixed-point search, nullclines, sweeps) is done
in the browser by the JS front-end, so interactivity is instantaneous.
For static sites use :meth:`to_standalone_html` to obtain a self-contained
``.html`` file that can be dropped into mkdocs, GitHub Pages, etc.
"""
# Inline JS/CSS so the widget is self-contained and standalone HTML exports work.
_esm = (_STATIC_DIR / "widget.js").read_text()
_css = (_STATIC_DIR / "widget.css").read_text()
# ── Initial state (synced to JS front-end) ──
model_name = traitlets.Unicode("wilson_cowan").tag(sync=True)
params = traitlets.Dict({}).tag(sync=True)
param_info = traitlets.Dict({}).tag(sync=True)
state_names = traitlets.List(["x", "y"]).tag(sync=True)
x0 = traitlets.Float(0.1).tag(sync=True)
y0 = traitlets.Float(0.1).tag(sync=True)
xlim = traitlets.List([-0.5, 1.5]).tag(sync=True)
ylim = traitlets.List([-0.5, 1.5]).tag(sync=True)
t_max = traitlets.Float(100.0).tag(sync=True)
dt = traitlets.Float(0.01).tag(sync=True)
# Pre-computed data (populated by JS, kept for inspection / export)
nullcline_x = traitlets.List([]).tag(sync=True)
nullcline_y = traitlets.List([]).tag(sync=True)
vector_field = traitlets.List([]).tag(sync=True)
fixed_points = traitlets.List([]).tag(sync=True)
trajectory = traitlets.List([]).tag(sync=True)
sweep_results = traitlets.List([]).tag(sync=True)
sweep_fixed_points = traitlets.List([]).tag(sync=True)
sweep_running = traitlets.Bool(False).tag(sync=True)
sweep_metadata = traitlets.Dict({}).tag(sync=True)
# Display toggles
show_nullclines = traitlets.Bool(True).tag(sync=True)
show_vector_field = traitlets.Bool(True).tag(sync=True)
show_trajectory = traitlets.Bool(True).tag(sync=True)
show_fixed_points = traitlets.Bool(True).tag(sync=True)
# Integrator / noise
integrator = traitlets.Unicode("rk4").tag(sync=True)
noise_enable = traitlets.Bool(False).tag(sync=True)
noise_sigma = traitlets.List([]).tag(sync=True)
noise_seed = traitlets.Int(0).tag(sync=True)
reference_trajectory = traitlets.List([]).tag(sync=True)
reference_scene = traitlets.Dict({}).tag(sync=True)
initial_conditions = traitlets.List([]).tag(sync=True)
observation_cards = traitlets.List([]).tag(sync=True)
show_reference = traitlets.Bool(True).tag(sync=True)
reference_metadata = traitlets.Dict({}).tag(sync=True)
trajectory_fraction = traitlets.Float(1.0).tag(sync=True)
# Custom model specification (JSON-serialisable dict for JS)
model_spec = traitlets.Dict(allow_none=True, default_value=None).tag(sync=True)
# Display indices for multi-variable projections
display = traitlets.List([0, 1]).tag(sync=True)
# Clamped values for non-displayed state variables
clamped = traitlets.List(default_value=None, allow_none=True).tag(sync=True)
# Layout mode: "full" shows controls + phase plane + time series + sweep
# "phase_plane" shows only the phase plane canvas (useful in notebooks / iframes)
display_mode = traitlets.Unicode("full").tag(sync=True)
panels = traitlets.List(traitlets.Unicode(), default_value=[]).tag(sync=True)
visible_parameters = traitlets.List(traitlets.Unicode(), allow_none=True, default_value=None).tag(sync=True)
panel_layout = traitlets.Enum(["horizontal", "vertical"], default_value="horizontal").tag(sync=True)
presentation = traitlets.Enum(["panels", "figure", "bench", "drawer", "comparison", "lesson", "multiples", "navigator", "basin", "evidence", "prediction", "ensemble", "bifurcation"], default_value="panels").tag(sync=True)
view_switcher = traitlets.Bool(False).tag(sync=True)
sweep_param = traitlets.Unicode("").tag(sync=True)
experiment_id = traitlets.Unicode("").tag(sync=True)
# Bifurcation / AUTO2000 continuation state
bifurcation_branches = traitlets.List(traitlets.Dict(), default_value=[]).tag(sync=True)
bifurcation_special_points = traitlets.List(traitlets.Dict(), default_value=[]).tag(sync=True)
bifurcation_config = traitlets.Dict(default_value={}).tag(sync=True)
bifurcation_running = traitlets.Bool(False).tag(sync=True)
bifurcation_metadata = traitlets.Dict(default_value={}).tag(sync=True)
bifurcation_presets = traitlets.List(traitlets.Dict(), default_value=[]).tag(sync=True)
auto_wasm_url = traitlets.Unicode("").tag(sync=True)
auto_worker_url = traitlets.Unicode("").tag(sync=True)
PANEL_NAMES = frozenset({"model", "parameters", "projection", "limits", "noise", "layers", "editor", "export", "comparison", "phase_plane", "time_series", "sweep", "bifurcation"})
@traitlets.validate("panels")
def _validate_panels(self, proposal):
values = proposal["value"]
if len(set(values)) != len(values) or not set(values) <= self.PANEL_NAMES:
raise traitlets.TraitError(f"Invalid panels: {values!r}")
return values
_DISPLAY_MODES = frozenset({"full", "phase_plane"})
@traitlets.validate("display_mode")
def _validate_display_mode(self, proposal):
v = proposal["value"]
if v not in self._DISPLAY_MODES:
raise traitlets.TraitError(
f"display_mode must be one of {self._DISPLAY_MODES}, got {v!r}"
)
return v
_model_instance = None
def __init__(self, model=None, **kwargs):
if model is not None:
self._model_instance = model
kwargs.setdefault("model_name", model.name)
super().__init__(**kwargs)
if kwargs.get("model_spec") is not None:
self.set_model_spec(kwargs["model_spec"])
else:
self._update_model()
self.experiment_id = self.model_id
for name in ("params", "xlim", "ylim", "x0", "y0", "dt", "display", "clamped",
"state_names", "param_info", "integrator", "noise_enable", "noise_sigma"):
if name in kwargs:
setattr(self, name, {**self.params, **kwargs[name]} if name == "params" else kwargs[name])
# Register handler for custom JS → Python messages (e.g. TikZ export)
self.on_msg(self._on_custom_msg)
def _get_model(self):
from .models import MODEL_REGISTRY
if self._model_instance is not None:
return self._model_instance
cls = MODEL_REGISTRY.get(self.model_name, MODEL_REGISTRY["wilson_cowan"])
return cls()
def _update_model(self):
"""Push model metadata to the JS front-end."""
model = self._get_model()
self.param_info = model.param_info
self.state_names = model.state_names
self.params = {k: v[2] for k, v in model.param_info.items()}
self.xlim = model.default_xlim
self.ylim = model.default_ylim
@traitlets.observe("model_name")
def _on_model_change(self, change):
if self.model_name != "custom":
self._update_model()
def set_model_spec(self, spec: dict):
"""Load a custom model from a ``ModelSpec`` dict.
Parameters
----------
spec : dict
JSON-serialisable model specification (see
:meth:`ModelSpec.to_widget_state`).
"""
self.model_spec = spec
self.model_name = "custom"
# Derive initial params / limits from the spec so the widget
# has sensible defaults before JS takes over.
params = {n: v["default"] for n, v in spec.get("parameters", {}).items()}
self.params = params
# Sync param_info for the existing slider infrastructure
param_info = {}
for n, v in spec.get("parameters", {}).items():
lo, hi = v["range"]
step = v.get("step", (hi - lo) / 500)
param_info[n] = [lo, hi, v["default"], f"Parameter {n}"]
self.param_info = param_info
state_names = list(spec.get("state_vars", {}).keys())
self.state_names = state_names
# Sync display indices
display = spec.get("display", [0, min(1, len(state_names) - 1)])
self.display = display
# Set default display limits from state variable ranges
state_vars = spec.get("state_vars", {})
if state_names:
first = state_names[display[0]]
lo, hi = state_vars[first]["range"]
self.xlim = [lo, hi]
self.x0 = state_vars[first]["default"]
if len(state_names) > 1:
second = state_names[display[1]] if len(display) > 1 else state_names[1]
lo, hi = state_vars[second]["range"]
self.ylim = [lo, hi]
self.y0 = state_vars[second]["default"]
# Initialize clamped values for non-displayed vars
n = len(state_names)
clamped = []
for i, name in enumerate(state_names):
if i in display:
clamped.append(None) # displayed vars are not clamped
else:
lo, hi = state_vars[name]["range"]
clamped.append((lo + hi) / 2.0)
self.clamped = clamped
self.integrator = spec.get("integrator", "rk4")
self.noise_sigma = spec.get("noise_per_var") or [0.0] * n
self.noise_enable = spec.get("noise_per_var") is not None
def view(self, panels, *, parameters=None, layout="horizontal"):
"""Create a separately displayable view sharing this experiment."""
return ExperimentView(experiment=self, panels=list(panels),
visible_parameters=parameters, panel_layout=layout)
def explore(self, presentation="figure", *, parameters=None):
"""Create a linked notebook view with a picker for the experimental layouts.
Layout switches retain experiment state. Leaving a running sweep cancels
it; parameters, frozen references and completed results are preserved.
"""
return ExperimentView(experiment=self, panels=["phase_plane"],
presentation=presentation, visible_parameters=parameters,
view_switcher=True)
def present(self, presentation="figure", *, parameters=None):
"""Create a composed view of this experiment (experimental layout API)."""
return ExperimentView(experiment=self, panels=["phase_plane"],
presentation=presentation, visible_parameters=parameters)
# ── Python-side helpers (for programmatic use / validation) ──
def run_sweep(self, param_name: str, values: list):
"""Run a parameter sweep from Python (delegates to JS in the widget).
Parameters
----------
param_name : str
Parameter to vary.
values : list of float
Values to evaluate.
"""
# The JS front-end handles sweeps interactively. This method is a
# convenience for programmatic access; it simply ensures the sweep
# traitlets are in a consistent state. For actual computation in
# a headless environment use the model classes in ``models.py``.
pass # sweeps are computed client-side by the JS front-end
# ── Standalone HTML export ──
def to_standalone_html(
self,
filename: str | pathlib.Path,
title: str = "Phase Plane Widget",
*,
on_render_js: str = "",
views: list[dict] | None = None,
include_auto: bool = False,
):
"""Export the widget to a self-contained HTML file.
The resulting ``.html`` file contains the full JS computation engine,
all model definitions, the CSS, and the current widget state. It works
in any modern browser with **no Python runtime and no Jupyter kernel**.
Parameters
----------
filename : str or pathlib.Path
Output path (e.g. ``"widget.html"``).
title : str
Page ``<title>``.
on_render_js : str
Optional JavaScript snippet executed after the widget renders.
Useful for auto-opening UI panels (e.g. the live editor).
views : list[dict], optional
Separate panel configurations sharing this experiment on one page.
Each dict accepts panels, visible_parameters and panel_layout.
"""
js_code = self._esm
css_code = self._css
state = {
"model_name": self.model_name,
"params": self.params,
"param_info": self.param_info,
"state_names": self.state_names,
"x0": self.x0,
"y0": self.y0,
"xlim": self.xlim,
"ylim": self.ylim,
"t_max": self.t_max,
"dt": self.dt,
"show_nullclines": self.show_nullclines,
"show_vector_field": self.show_vector_field,
"show_trajectory": self.show_trajectory,
"show_fixed_points": self.show_fixed_points,
"nullcline_x": self.nullcline_x,
"nullcline_y": self.nullcline_y,
"vector_field": self.vector_field,
"fixed_points": self.fixed_points,
"trajectory": self.trajectory,
"sweep_results": self.sweep_results,
"sweep_fixed_points": self.sweep_fixed_points,
"sweep_param": self.sweep_param,
"sweep_running": False,
"sweep_metadata": self.sweep_metadata,
"model_spec": self.model_spec,
"display": list(self.display) if self.display else [0, 1],
"clamped": list(self.clamped) if self.clamped else None,
"integrator": self.integrator,
"noise_enable": self.noise_enable,
"noise_sigma": self.noise_sigma,
"noise_seed": self.noise_seed,
"reference_trajectory": self.reference_trajectory,
"reference_scene": self.reference_scene,
"initial_conditions": self.initial_conditions,
"observation_cards": self.observation_cards,
"show_reference": self.show_reference,
"reference_metadata": self.reference_metadata,
"trajectory_fraction": self.trajectory_fraction,
"display_mode": self.display_mode,
"panels": self.panels,
"visible_parameters": self.visible_parameters,
"panel_layout": self.panel_layout,
"presentation": self.presentation,
"view_switcher": self.view_switcher,
"bifurcation_branches": self.bifurcation_branches,
"bifurcation_special_points": self.bifurcation_special_points,
"bifurcation_config": self.bifurcation_config,
"bifurcation_running": False,
"bifurcation_metadata": self.bifurcation_metadata,
"bifurcation_presets": self.bifurcation_presets,
"auto_wasm_url": self.auto_wasm_url,
"auto_worker_url": self.auto_worker_url,
}
auto_assets_js = ""
if include_auto:
wasm_b64 = base64.b64encode((_STATIC_DIR / "auto2000_core.wasm").read_bytes()).decode("ascii")
worker_src = (_STATIC_DIR / "auto2000-worker.js").read_text(encoding="utf-8")
payload = json.dumps({"wasmBase64": wasm_b64, "workerSource": worker_src}).replace("<", "\\u003c")
auto_assets_js = f"globalThis.__PPW_AUTO_ASSETS__ = {payload};\n"
extra_js = f"\n{on_render_js}\n" if on_render_js else ""
if views is not None:
for config in views:
presentation = config.get("presentation", "panels")
if presentation not in self.traits()["presentation"].values:
raise ValueError(f"Invalid presentation: {presentation!r}")
panels = config.get("panels", [])
if (presentation == "panels" and not panels) or len(set(panels)) != len(panels) or not set(panels) <= self.PANEL_NAMES:
raise ValueError(f"Invalid view panels: {config!r}")
view_config = json.dumps(views).replace("<", "\\u003c")
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>
{css_code}
</style>
</head>
<body>
<div id="ppw-root"></div>
<script type="module">
{auto_assets_js}{js_code}
const initialState = {json.dumps(state, indent=2)};
const mockModel = {{
_isMock: true,
_data: initialState,
_callbacks: {{}},
get(name) {{ return this._data[name]; }},
set(name, value) {{
if (Object.is(this._data[name], value)) return;
this._data[name] = value;
for (const cb of [...(this._callbacks['change:' + name] || [])]) cb(this, value);
}},
save_changes() {{}},
on(event, cb) {{
if (!this._callbacks[event]) this._callbacks[event] = [];
this._callbacks[event].push(cb);
}},
off(event, cb) {{ this._callbacks[event] = (this._callbacks[event] || []).filter(fn => fn !== cb); }},
send() {{}},
}};
const root = document.getElementById('ppw-root');
const viewConfigs = {view_config};
if (viewConfigs === null) {{
render({{ model: mockModel, el: root }});
}} else {{
for (const config of viewConfigs) {{
const el = document.createElement('div');
root.appendChild(el);
render({{ model: mockModel, el, options: {{get: name => config[name]}} }});
}}
}}
{extra_js}
</script>
</body>
</html>"""
pathlib.Path(filename).write_text(html, encoding="utf-8")
# ── TikZ / PGFPlots export ──
STABILITY_MARKERS = {
"stable_node": ("circle", "green!70!black", "green!70!black"),
"stable_focus": ("circle", "green!70!black", "green!70!black"),
"unstable_node": ("circle", "red!70!black", "white"),
"unstable_focus": ("circle", "red!70!black", "white"),
"saddle": ("diamond", "purple", "purple"),
}
def _compute_vector_field_for_tikz(self, nx=15, ny=15):
r"""Compute a normalized vector-field grid for embedding in TikZ.
Returns a list of arrow endpoints ``[x1, y1, x2, y2]`` suitable for
``\draw[-stealth] (axis cs:x1,y1) -- (axis cs:x2,y2);``.
"""
model = self._get_model()
x = np.linspace(self.xlim[0], self.xlim[1], nx)
y = np.linspace(self.ylim[0], self.ylim[1], ny)
dx = self.xlim[1] - self.xlim[0]
dy = self.ylim[1] - self.ylim[0]
scale = 0.03 * min(dx, dy)
arrows = []
for xi in x:
for yi in y:
state = [0.0] * model.dim
if self.display and len(self.display) >= 2:
state[self.display[0]] = xi
state[self.display[1]] = yi
else:
state[0] = xi
if model.dim > 1:
state[1] = yi
if self.clamped:
for i, val in enumerate(self.clamped):
if val is not None and i < model.dim:
state[i] = val
d = model.f(0, state, self.params)
norm = np.sqrt(d[0] ** 2 + d[1] ** 2)
if norm > 1e-12:
x2 = xi + scale * d[0] / norm
y2 = yi + scale * d[1] / norm
arrows.append([float(xi), float(yi), float(x2), float(y2)])
return arrows
@staticmethod
def _fmt_coords(data):
"""Format a list of [x, y] pairs as PGFPlots ``coordinates`` block."""
if not data:
return "coordinates {(0,0)}"
pairs = " ".join(f"({row[0]:.6f},{row[1]:.6f})" for row in data)
return f"coordinates {{\n {pairs}\n}}"
def export_tikz(self, filename: str | pathlib.Path = "phase_plane.tex"):
"""Generate a self-contained ``.tex`` file.
The resulting file can be compiled with ``pdflatex`` or ``lualatex``
(requires the ``pgfplots`` package).
Parameters
----------
filename : str or pathlib.Path
Output path for the ``.tex`` file.
"""
filename = pathlib.Path(filename)
x_label = (
self.state_names[self.display[0]]
if self.display and len(self.state_names) > self.display[0]
else "x"
)
y_label = (
self.state_names[self.display[1]]
if self.display and len(self.state_names) > self.display[1]
else "y"
)
xlim = self.xlim
ylim = self.ylim
# ── vector field ──
vfield_data = []
if self.show_vector_field:
vfield_data = self._compute_vector_field_for_tikz()
# ── trajectories ──
traj_data = []
if self.show_trajectory and self.trajectory:
idx_x = 1 + self.display[0]
idx_y = 1 + self.display[1]
traj_data = [
[float(row[idx_x]), float(row[idx_y])] for row in self.trajectory
]
# ── nullclines ──
nc_x = self.nullcline_x if self.show_nullclines else []
nc_y = self.nullcline_y if self.show_nullclines else []
# ── fixed points ──
fps = self.fixed_points if self.show_fixed_points else []
# ── build plot commands ──
plots = []
if vfield_data:
lines = "\n".join(
f" \\draw[-stealth, gray] (axis cs:{x1:.6f},{y1:.6f}) -- (axis cs:{x2:.6f},{y2:.6f});"
for x1, y1, x2, y2 in vfield_data
)
plots.append(lines)
if nc_x:
plots.append(
f" \\addplot[blue, thick, no marks, smooth] {self._fmt_coords(nc_x)};"
)
if nc_y:
plots.append(
f" \\addplot[red, thick, no marks, smooth] {self._fmt_coords(nc_y)};"
)
if traj_data:
plots.append(
f" \\addplot[green!60!black, thick, no marks, smooth] {self._fmt_coords(traj_data)};"
)
plots_block = "\n".join(plots)
# ── fixed-point nodes ──
fp_nodes = []
for fp in fps:
if len(fp) < 3:
continue
x_fp, y_fp, stability = float(fp[0]), float(fp[1]), fp[2]
shape, color, fill = self.STABILITY_MARKERS.get(
stability, ("circle", "black", "white")
)
inner = ""
if stability == "stable_focus":
inner = (
f"\\node[fill={color}, circle, inner sep=0.8pt] "
f"at (axis cs:{x_fp:.6f},{y_fp:.6f}) {{}};"
)
elif stability == "unstable_focus":
inner = (
f"\\node[draw={color}, fill={color}, circle, inner sep=0.8pt] "
f"at (axis cs:{x_fp:.6f},{y_fp:.6f}) {{}};"
)
opts = f"draw={color}"
if fill == "white":
opts += ", fill=white"
elif fill != color:
opts += f", fill={fill}"
node_tex = (
f"\\node[{opts}, {shape}, inner sep=1.5pt] "
f"at (axis cs:{x_fp:.6f},{y_fp:.6f}) {{}};"
)
if inner:
node_tex += "\n " + inner
fp_nodes.append(node_tex)
fp_block = "\n ".join(fp_nodes)
# ── parameter annotation ──
param_lines = ", ".join("{}={:.4g}".format(k.replace("_", r"\_"), v) for k, v in self.params.items())
escaped_model_name = self.model_name.replace("_", r"\_")
param_node = (
r"\path (rel axis cs:0.02,0.98) node[anchor=north west, font=\tiny, align=left] "
f"{{{escaped_model_name}\\\\ {param_lines}}};"
)
tex = (
r"\documentclass[border=5pt]{standalone}" + "\n"
r"\usepackage{pgfplots}" + "\n"
r"\usepackage{tikz}" + "\n"
r"\pgfplotsset{compat=1.17}" + "\n"
r"\usetikzlibrary{shapes.geometric}" + "\n"
r"\begin{document}" + "\n"
r"\begin{tikzpicture}" + "\n"
r"\begin{axis}[" + "\n"
" width=10cm, height=10cm,\n"
f" xmin={xlim[0]}, xmax={xlim[1]}, ymin={ylim[0]}, ymax={ylim[1]},\n"
f" xlabel=${x_label}$, ylabel=${y_label}$,\n"
" axis lines=middle,\n"
" enlargelimits=true,\n"
"]\n"
+ plots_block + "\n"
+ (fp_block + "\n" if fp_block else "")
+ " " + param_node + "\n"
r"\end{axis}" + "\n"
r"\end{tikzpicture}" + "\n"
r"\end{document}" + "\n"
)
filename.write_text(tex, encoding="utf-8")
return str(filename)
def _resolve_bifurcation_obs(self):
cfg = self.bifurcation_config or {}
raw = cfg.get("observable")
if raw in ("L2", "l2"):
return "L2", "L2 norm"
names = list(self.state_names or [])
if isinstance(raw, str) and raw in names:
idx = names.index(raw)
return idx, names[idx]
try:
idx = int(raw) if raw not in (None, "") else 0
except (TypeError, ValueError):
idx = 0
idx = max(0, min(max(0, len(names) - 1), idx))
return idx, (names[idx] if idx < len(names) else f"u{idx}")
@staticmethod
def _bif_obs_value(pt, obs_key, field="u"):
if obs_key == "L2":
val = pt.get("L2")
return float(val) if val is not None else None
arr = pt.get(field)
if isinstance(arr, (list, tuple)) and obs_key < len(arr):
return float(arr[obs_key])
if field == "u" and pt.get("u") is not None and not isinstance(pt.get("u"), (list, tuple)):
return float(pt["u"])
return None
@staticmethod
def _split_stable_segments(points):
segments = []
cur_stable = None
cur_pts = []
for pt in points or []:
st = bool(pt.get("stable"))
if cur_pts and st != cur_stable:
segments.append((cur_stable, cur_pts + [pt]))
cur_pts = [pt]
else:
cur_pts.append(pt)
cur_stable = st
if cur_pts:
segments.append((cur_stable, cur_pts))
return segments
def export_bifurcation_tikz(self, filename: str | pathlib.Path | None = None):
"""Generate a self-contained PGFPlots ``.tex`` file for the bifurcation diagram.
Parameters
----------
filename : str or pathlib.Path, optional
If provided, writes the ``.tex`` file to ``filename`` and returns
its path as a string. If ``None``, returns the LaTeX source string.
"""
cfg = self.bifurcation_config or {}
all_branches = self.bifurcation_branches or []
all_sps = self.bifurcation_special_points or []
branches_1d = [b for b in all_branches if b and b.get("type") in ("EP", "LC")]
branches_2d = [b for b in all_branches if b and b.get("type") in ("LP2", "HB2", "LPC2", "PD2", "TR2", "HOM2")]
is_2d = (cfg.get("viewMode") == "2d" and branches_2d) or (not branches_1d and bool(branches_2d))
obs_key, obs_label = self._resolve_bifurcation_obs()
param_names = list((self.params or {}).keys())
meta = self.bifurcation_metadata or {}
plots = []
sp_nodes = []
if is_2d:
param1 = branches_2d[0].get("param1") or cfg.get("param1") or (param_names[0] if param_names else "p1")
param2 = branches_2d[0].get("param2") or cfg.get("param2") or next((k for k in param_names if k != param1), "p2")
xlabel, ylabel = param1.replace("_", r"\_"), param2.replace("_", r"\_")
color_map = {
"LP2": "blue!75!black",
"HB2": "red!75!black",
"LPC2": "green!60!black, dashed",
"PD2": "orange!85!black",
"TR2": "cyan!70!black",
"HOM2": "violet!80!black, dash pattern=on 6pt off 3pt on 2pt off 3pt",
}
for br in branches_2d:
coords = [[float(pt["p"]), float(pt["p2"])] for pt in br.get("points") or [] if "p" in pt and "p2" in pt]
if len(coords) >= 2:
color = color_map.get(br.get("type"), "blue!75!black")
plots.append(f" \\addplot[{color}, thick, no marks] {self._fmt_coords(coords)};")
b_ids = {br.get("id") for br in branches_2d}
for sp in all_sps:
if not sp or (sp.get("branch_id") not in b_ids and "p2" not in sp):
continue
if "p" in sp and "p2" in sp:
lbl = str(sp.get("label") or sp.get("id") or sp.get("ty") or "").replace("_", r"\_")
sp_nodes.append(
f"\\node[circle, fill=black, inner sep=1.5pt, label={{[font=\\tiny]above right:{lbl}}}] "
f"at (axis cs:{float(sp['p']):.6f},{float(sp['p2']):.6f}) {{}};"
)
else:
param1 = cfg.get("param1") or (branches_1d[0].get("param1") if branches_1d else None) or (meta.get("active_params") or [None])[0] or (param_names[0] if param_names else "p")
xlabel, ylabel = param1.replace("_", r"\_"), obs_label.replace("_", r"\_")
for br in branches_1d:
btype = br.get("type")
for stable, seg in self._split_stable_segments(br.get("points")):
if btype == "EP":
coords = [
[float(pt["p"]), val]
for pt in seg
if "p" in pt and (val := self._bif_obs_value(pt, obs_key, "u")) is not None
]
if len(coords) >= 2:
style = "blue!75!black, thick, no marks" if stable else "gray, thick, dashed, no marks"
plots.append(f" \\addplot[{style}] {self._fmt_coords(coords)};")
elif btype == "LC":
style = "green!60!black, very thick, no marks" if stable else "orange!85!black, thick, dashed, no marks"
for field in ("u_max", "u_min"):
coords = [
[float(pt["p"]), val]
for pt in seg
if "p" in pt and (val := self._bif_obs_value(pt, obs_key, field)) is not None
]
if len(coords) >= 2:
plots.append(f" \\addplot[{style}] {self._fmt_coords(coords)};")
for sp in all_sps:
if not sp or sp.get("ty") in ("CP", "BT", "GH") or sp.get("param2"):
continue
val = self._bif_obs_value(sp, obs_key, "u")
if "p" in sp and val is not None:
lbl = str(sp.get("label") or sp.get("id") or sp.get("ty") or "").replace("_", r"\_")
sp_nodes.append(
f"\\node[circle, draw=black, fill=white, inner sep=1.5pt, label={{[font=\\tiny]above right:{lbl}}}] "
f"at (axis cs:{float(sp['p']):.6f},{val:.6f}) {{}};"
)
escaped_model = self.model_name.replace("_", r"\_")
plots_block = "\n".join(plots)
sp_block = "\n ".join(sp_nodes)
tex = (
r"\documentclass[border=5pt]{standalone}" + "\n"
r"\usepackage{pgfplots}" + "\n"
r"\usepackage{tikz}" + "\n"
r"\pgfplotsset{compat=1.17}" + "\n"
r"\begin{document}" + "\n"
r"\begin{tikzpicture}" + "\n"
r"\begin{axis}[" + "\n"
" width=12cm, height=8cm,\n"
f" xlabel=${xlabel}$, ylabel=${ylabel}$,\n"
f" title={{{escaped_model} bifurcation diagram}},\n"
" grid=major,\n"
" enlargelimits=true,\n"
"]\n"
+ (plots_block + "\n" if plots_block else "")
+ (" " + sp_block + "\n" if sp_block else "")
+ r"\end{axis}" + "\n"
r"\end{tikzpicture}" + "\n"
r"\end{document}" + "\n"
)
if filename is None:
return tex
out = pathlib.Path(filename)
out.write_text(tex, encoding="utf-8")
return str(out)
# ── Custom message handler (JS → Python) ──
def _on_custom_msg(self, _widget, content, buffers):
"""Handle messages from the JS front-end."""
msg_type = content.get("type")
if msg_type == "export_tikz":
fd, tmppath = tempfile.mkstemp(suffix=".tex", prefix="phase_plane_")
os.close(fd)
try:
self.export_tikz(tmppath)
tex_content = pathlib.Path(tmppath).read_text(encoding="utf-8")
self.send(
{
"type": "tikz_data",
"content": tex_content,
"filename": "phase_plane.tex",
}
)
finally:
os.unlink(tmppath)
elif msg_type == "request_auto_assets":
wasm_bytes = (_STATIC_DIR / "auto2000_core.wasm").read_bytes()
worker_bytes = (_STATIC_DIR / "auto2000-worker.js").read_bytes()
self.send({"type": "auto_assets"}, buffers=[wasm_bytes, worker_bytes])