bragi_quantum.gui API#
The all-seeing guardian — the on-demand replot and monitoring server. For the usage guide and REST reference see The Replot Server (bragi_quantum.gui).
Public replay API#
The functions re-exported from the top-level bragi_quantum.gui package — the
programmatic entry point to the replay engine.
bragi_quantum.gui — on-demand replot server for QC2 calibration sessions.
- bragi_quantum.gui.build_analysis_for_element(step, element, session_root=None, overrides=None, n_selected_elements=1, analysis_field_reads=None)[source]#
Re-instantiate the analysis and run it on a single element so that its internal state (fit results, cached arrays) is populated and plotting can proceed. Slicing is delegated to the unified analysis’
analyse_element(no duplicated slicing here).overridesre-tunes analysis-category parameters before the fit re-runs (the reanalysis path); acquisition/metadata fields cannot be overridden.n_selected_elementsis how many elements the caller’s UI currently has selected together (e.g. bragi_quantum.gui’s marquee multi-select) — some analyses use it to skip expensive per-element plots when rendering many at once.analysis_field_reads, when given, collects every analysis field the fit (and any later plotting on the returned analysis) reads, even if it raises.
- bragi_quantum.gui.list_plots_for_element(step, element, session_root=None)[source]#
Return the list of plot names available for this (step, element).
Cheap path: if the analysis class exposes a class-level (or instance-cheap) list_plots, we instantiate without running the fit. That works when list_plots is static. For analyses where the available plots depend on runtime data, we fall back to a full replay.
Replay engine#
Replay analysis on a saved calibration session.
Given a step from the session timeline plus an element name (qubit or coupler) and a plot name, this module:
Resolves the HDF5 dataset file for the step.
Imports the recorded analysis / parameters / QOI classes (allowlisted).
Re-instantiates the analysis with the recorded parameters.
Calls analyse_element against the saved data — this re-runs the fit and rebuilds the in-memory state figure() needs.
Calls analysis.figure() to build the plotly figure.
Either encodes it to PNG bytes via kaleido (render_to_png) or returns its JSON for the browser to draw interactively with plotly.js (render_figure_json).
The server uses this from request handlers; the CLI uses it for sanity checks at startup.
- exception bragi_quantum.gui.replay.ReplayError[source]#
Bases:
RuntimeErrorRaised for any expected failure of replay (bad step, missing data, etc).
- exception bragi_quantum.gui.replay.PlotRenderError(message, analysis_fields)[source]#
Bases:
RuntimeErrorRaised when re-fitting or rendering a plot fails.
Carries the analysis fields read before the failure, so the UI can still offer them for re-tuning (e.g. a filter the plot requires).
- bragi_quantum.gui.replay.resolve_dataset_path(step, session_root=None)[source]#
Pick the HDF5 file for a step. Datasets are saved as dataset_<run_name>_<count>.hdf5 with monotonically increasing counts; we pick the highest count (the most recent run for this name).
dataset_dir may be an absolute path (sessions recorded after the fix) or a relative path (older sessions recorded before root_path.resolve() was added to the orchestrator). When relative, it is resolved against session_root if provided, then against cwd.
- bragi_quantum.gui.replay.analysis_fields_for_step(step)[source]#
Describe the re-tunable (analysis-category) parameters for a step.
Returns
[{name, value, kind, default, description}]wherevalueis the value the run actually used (from the recorded parameters),kindis a UI hint ("number"/"bool"/"text") anddescription(orNone) is the field’s pydantic description, shown as a form placeholder. Empty when the parameters class or its categories cannot be introspected.
- bragi_quantum.gui.replay.build_analysis_for_element(step, element, session_root=None, overrides=None, n_selected_elements=1, analysis_field_reads=None)[source]#
Re-instantiate the analysis and run it on a single element so that its internal state (fit results, cached arrays) is populated and plotting can proceed. Slicing is delegated to the unified analysis’
analyse_element(no duplicated slicing here).overridesre-tunes analysis-category parameters before the fit re-runs (the reanalysis path); acquisition/metadata fields cannot be overridden.n_selected_elementsis how many elements the caller’s UI currently has selected together (e.g. bragi_quantum.gui’s marquee multi-select) — some analyses use it to skip expensive per-element plots when rendering many at once.analysis_field_reads, when given, collects every analysis field the fit (and any later plotting on the returned analysis) reads, even if it raises.
- bragi_quantum.gui.replay.list_plots_for_element(step, element, session_root=None)[source]#
Return the list of plot names available for this (step, element).
Cheap path: if the analysis class exposes a class-level (or instance-cheap) list_plots, we instantiate without running the fit. That works when list_plots is static. For analyses where the available plots depend on runtime data, we fall back to a full replay.
- bragi_quantum.gui.replay.render_to_png(step, element, plot_name, session_root=None, overrides=None, n_selected_elements=1)[source]#
Render the plot for the given (step, element) as a plotly figure and return PNG bytes (via kaleido).
overridesre-tunes analysis parameters.
- bragi_quantum.gui.replay.render_figure_json(step, element, plot_name, session_root=None, overrides=None, n_selected_elements=1)[source]#
Render the plot as plotly JSON (drawn interactively by plotly.js), plus the sorted analysis fields the fit and this plot read, i.e. those worth offering for re-tuning on this plot. A failed fit/render raises
PlotRenderError.overridesre-tunes analysis parameters before the fit re-runs.n_selected_elementsis how many elements are selected together in the caller’s UI (seebuild_analysis_for_element()).
Timeline#
The Timeline value object.
A calibration session’s timeline is a flat list[dict] whose first step is a
start_config followed by node steps. The same handful of pokes at that
raw shape — “give me the start config”, “the qubits”, “the node steps”, “split a
file that holds several runs” — were duplicated a dozen times across the server.
Timeline is the one place that knows the shape; everything else asks it.
- class bragi_quantum.gui.timeline.Timeline(steps: 'list[dict[str, Any]]')[source]#
Bases:
object- classmethod load(session_root)[source]#
Load a session’s timeline from disk; empty on any read failure.
- property run_name: str#
The orchestrator’s
name(unsanitized) recorded at session start.Distinct from
title()’ssession_options.run_namelookup, which disambiguates multiple runs replayed from one session folder — this is the top-level fieldSessionTimeline.record_start_configstamps fromCalibrationOrchestrator.name.
Command-line interface#
The qc2-show entry point.
Command-line entry point for the qc2-show archive browser.
- Usage:
qc2-show <archive_dir> [–host 127.0.0.1] [–port 9999] [–traffic-saver-mode]
<archive_dir> is a directory of timestamped YYYYMMDD_HHMMSS[_sanitized_name] run
folders (e.g. calibration_outputs/). All viewing goes through the archive
browser.
Archive & server#
The archive browser server.
Archive owns the live state for a directory of timestamped run folders —
the session-bundle map, per-run bundle lists and the qubit/text search indexes — plus
the lock that guards them. A background thread (started by the app’s lifespan)
periodically calls Archive.discover(), the only writer, so the route
handlers are pure readers and the route table never changes at runtime: every
session/pipeline route carries its id in the path and resolves it here.
- bragi_quantum.gui.archive.build_qubit_index(bundles)[source]#
Map each run-folder name to the set of qubits measured in it.
A run’s measured qubits are the union of every node step’s
target_qubits(the dataset-derived elements that actually produced data).
- bragi_quantum.gui.archive.build_text_index(bundles)[source]#
Map each run-folder name to the text terms it can be found by.
Terms are read straight off each session’s raw timeline (mirroring
build_qubit_index, noTimeline/SessionBundleproperties needed): the session directory name, the run’s sanitized display name, the orchestrator’s recorded name(s), the session id / template name, and every node step’s name. Case is preserved — matching (in/againstarchive_search()) decides case-sensitivity, not the index.
- bragi_quantum.gui.archive.archive_search(q, qubit_index, text_index=None, *, case_sensitive=False, whole_word=False, use_regex=False)[source]#
Resolve an archive search query to the run ids that match it.
Two modes:
Plain (the default): the query is split into whitespace/comma-separated tokens. A token that’s a qubit reference (
q05,5,qubit:q5, …) requires the run to have measured it; any other token is matched as a substring against the run’s name, session names and step names — every token must match (AND semantics), same as the qubit-only matching this replaces.case_sensitive/whole_wordrefine that substring match.use_regex: the whole (stripped) query is one regular expression, tested against each run’s combined searchable text — no token splitting, same “one pattern, no AND-ing” behaviour as the session log search’s regex mode.
Returns
{"names": [...]}(newest first), or{"names": None}when the query is empty after stripping — the sidebar reads that as “no filter”. Raisesre.erroron an invalid regex (either mode).
- class bragi_quantum.gui.archive.Archive(target, traffic_saver=False)[source]#
Bases:
objectLive state + FastAPI app for a directory of timestamped run folders.
- Parameters:
target (Path)
traffic_saver (bool)
- bundle(key)[source]#
- Parameters:
key (str)
- Return type:
SessionBundle | None
- run_descriptor(folder)[source]#
One scan → a run folder’s sidebar/JSON metadata (single source).
Shared by the initial page render and the
/runspoll so a folder is never described two ways.done(bragi_quantum.api wroteindex.html) drives the spinner;fresh(newest timeline mtime) drives the live iframe reload;errorflags any session whose timeline ended in error.
- generate_run_page(run_dir, run_ts)[source]#
Render a run’s index page on demand, in memory.
Read-only: bragi_quantum.gui never writes
index.htmlback to the run folder. That file is bragi_quantum.api’s alone — its presence is the run-complete signal (written bygenerate_html_reportwhen the run finishes), so bragi_quantum.gui must not forge it by persisting its own render.
- discover()[source]#
(Re)bundle any run whose timelines changed since last seen.
The signature is each session timeline’s mtime, so this fires on a brand- new run, a new session, and a new step or completion inside an existing session — that last case is what un-freezes a live-growing timeline. Runs under the lock so the background poller and any on-demand call can’t corrupt the maps.
- Return type:
None
Routing layer for the bragi_quantum.gui archive server.
Defines the session value type (SessionBundle + _make_bundles), the
FastAPI dependencies and error handlers, and two APIRouter factories whose
routes resolve their target from the live Archive on app.state:
- session_router() /session/{key}/… per-session replot API
GET /health -> liveness + paths GET /steps -> node step summaries GET /step/{i}/element/{name}/plots -> available plot names POST /plot -> PNG bytes GET /report -> rendered HTML report
pipeline_router() /pipeline/{run_ts}/… cross-session whole-pipeline view
The app itself (lifespan, routers, static mounts) is assembled in
archive.py; the pipeline/QoI domain logic lives in pipeline.py.
- class bragi_quantum.gui.server.SessionBundle(key: 'str', session_root: 'Path', title: 'str', step_count: 'int', total_steps: 'int', timeline: 'list[dict[str, Any]]')[source]#
Bases:
object- Parameters:
- bragi_quantum.gui.server.get_bundle(key, request)[source]#
- Parameters:
key (str)
request (fastapi.Request)
- Return type:
- bragi_quantum.gui.server.get_run(run_ts, request)[source]#
- Parameters:
run_ts (str)
request (fastapi.Request)
- Return type:
- bragi_quantum.gui.server.session_router()[source]#
Per-session replot API, resolved by
{key}against the archive.- Return type:
fastapi.APIRouter
- bragi_quantum.gui.server.pipeline_router()[source]#
Cross-session whole-pipeline view for one run, resolved by
{run_ts}.A single router serves every run’s pipeline (
/pipeline/{run_ts}/…); the run’s bundles are resolved from the archive, so there is no per-run route registration and no OpenAPI operation-id juggling.- Return type:
fastapi.APIRouter
Pipeline / QoI domain logic for the whole-pipeline view.
Pure data + plotting helpers over a run’s SessionBundle list: building the
cross-session pipeline graph, collecting and tracking quantities of interest
(QoIs) across nodes, locating node output PNGs, and reading device-template
defaults. Nothing here touches FastAPI — the routes in server.py call these
and wrap the results in responses.
Allowlist for dynamic imports.
The replot server has to import analysis / parameters / QOI classes whose fully qualified names come from a JSON file on disk (the session timeline). A malformed or tampered timeline could otherwise be used to import arbitrary code. We restrict imports to a fixed set of trusted top-level packages.
- exception bragi_quantum.gui.registry.DisallowedImportError[source]#
Bases:
ImportErrorRaised when a dotted name is not under an allowed root.
Rendering#
Interactive HTML device visualization showing qubit topology, couplers, live parameters from Redis, per-element execution history, and a session-level pipeline (DAG) view of executed steps.
- bragi_quantum.gui.rendering.html_rendering.create_html_rendering(qubits, couplers, redis_connection=None, output_path=None, session_root_path=None, session_timeline=None, replot_endpoint_override=None, pipeline_href='/pipeline', plotly_src=None)[source]#
Create an interactive HTML device visualization.
The QPU-topology diagram itself is rendered client-side by
wiring-logic.jsfrom the wiring blob (see rendering/wiring.py); this function embeds the data blobs and page scaffolding.- Parameters:
qubits (list[str]) – List of qubit names (e.g., [‘q16’, ‘q17’, …])
couplers (list[str]) – List of coupler names (e.g., [‘q16_q17’, ‘q17_q18’, …])
redis_connection (Any | None) – Optional Redis connection for fetching live parameters
output_path (Path | None) – Optional path to save the HTML file
session_root_path (Path | None) – Optional path to session root for loading execution history, session timeline, and the timing trace.
session_timeline (list[dict[str, Any]] | None) – Optional pre-loaded session timeline. If not provided and session_root_path is given, will attempt to load it.
plotly_src (str | None) – URL to load plotly.js from. If None, plotly.js is inlined so the page works offline.
replot_endpoint_override (str | None)
pipeline_href (str)
- Returns:
HTML content as string
- Return type:
- bragi_quantum.gui.rendering.html_rendering.create_whole_pipeline_html()[source]#
Build the shared, cross-session “whole pipeline” page.
The page is data-driven: at load time its JS fetches
/pipeline/datafrom the serving app to learn about every session and its executed node steps, draws a single Mermaid graph (nodes coloured per session), and — when a node is clicked — fetches and renders that node’s already-stored PNGs in a carousel (/pipeline/node-plots+/pipeline/png).- Return type:
- bragi_quantum.gui.rendering.html_rendering.create_multi_session_html(session_names, datetime_hour_path, output_path=None, incomplete_session_names=None, pipeline_url='/pipeline', generated_at='', generated_by='', run_name='')[source]#
Create a master HTML page that aggregates multiple session renderings.
- Parameters:
session_names (list[str]) – Session names with complete data (get an iframe tab each).
datetime_hour_path (Path) – Path to the run directory containing all sessions.
output_path (Path | None) – Optional path to write the HTML to disk.
incomplete_session_names (list[str] | None) – Session folders that exist but have no session_timeline.json (e.g. cancelled mid-run). Retained for API compatibility but not rendered as tabs.
pipeline_url (str) – Base URL for the whole-pipeline tab (e.g. /pipeline/run_ts).
generated_at (str) – ISO-formatted timestamp of when this page was rendered.
generated_by (str) – Human-readable source label (e.g. “qc2-show”, “bragi_quantum.api”).
run_name (str) – The orchestrator’s
name(e.g. from the session timeline’sstart_config.run_name), shown as the header subtitle. Falls back to a generic subtitle when the run has no name.
- Return type:
Standalone HTML renderer for the archive sidebar view.
The archive view is a two-pane layout: a fixed sidebar listing timestamped run folders (newest first) and an iframe that loads the selected run’s index.html. The sidebar polls /runs on an interval (see POLL_INTERVAL_SECONDS) so new runs appear live without a page reload.
- The markup lives in sibling files so the HTML/CSS/JS is editable as such:
archive.htmlfull page;<!-- RUN_ITEMS -->marks wherethe server-rendered date groups are injected, and
@@ARCHIVE_JS@@marks wherearchive-logic.js(the sidebar’s client logic — linted/type-checked as a real .js file) is embedded.
archive_date_group.htmlone date’s collapsible group;{date}/{count}/{collapsed_class}are filled in, and<!-- DATE_GROUP_ITEMS -->marks where that date’s run rows are injected.
archive_run_item.htmlone run row;{name}/{src}/{date}/{time}/{title}/{sessions}/{qubits}/{meta_html}are filled from a run descriptor ({meta_html}is the pluralized “N sessions”/”N qubits” column).
This module is pure rendering — it does no filesystem I/O. Callers pass run
descriptors (the same dicts the /runs endpoint returns), so the initial
server render and the live poll can never describe a folder differently.
Runs are grouped into one collapsible section per calendar day (date).
Callers must pass runs newest-first (the /runs contract already
guarantees this), so same-day runs are contiguous and a single pass of
itertools.groupby is enough to bucket them. Only the most recent day
starts expanded; every other day starts collapsed. The sidebar JS then
layers the user’s own per-date toggles (persisted in localStorage) on
top of that default when the page loads.
Usage:
from bragi_quantum.gui.rendering.archive_rendering import build_archive_html
html = build_archive_html(run_descriptors)
- bragi_quantum.gui.rendering.archive_rendering.build_archive_html(runs)[source]#
Build the archive sidebar page from pre-computed run descriptors.
Each
runis one of the dicts/runsreturns. Required keys:name,src,date,time,sanitized_run_name,sessions_display,qubits_display. The display values are pre-gated by the descriptor (—while a run is live, final counts once done). The.run-statusslot is left empty here — the poll JS fills it (spinner / done / error) so status lives in one place, not duplicated in Python.runsmust be newest-first, same as the/runscontract.
Single entry point for the front-end source files.
All non-Python sources live under rendering/<language>/ — html/,
css/ and js/. load("replot.html") resolves the language subdir
from the file extension, so no caller spells out a path and the directory
layout has exactly one owner: this module.
The Python assembles a page by loading a shell template and substituting the
@@MARKER@@ placeholders with other loaded fragments; the source files
never reference each other by path.