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).

overrides re-tunes analysis-category parameters before the fit re-runs (the reanalysis path); acquisition/metadata fields cannot be overridden. n_selected_elements is 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.

Parameters:
Return type:

Any

bragi_quantum.gui.find_step(timeline, step_index)[source]#
Parameters:
Return type:

dict[str, Any]

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.

Parameters:
Return type:

list[str]

bragi_quantum.gui.load_timeline(session_root)[source]#
Parameters:

session_root (Path)

Return type:

list[dict[str, Any]]

bragi_quantum.gui.open_dataset(path)[source]#
Parameters:

path (Path)

Return type:

Dataset

bragi_quantum.gui.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). overrides re-tunes analysis parameters.

Parameters:
Return type:

bytes

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:

  1. Resolves the HDF5 dataset file for the step.

  2. Imports the recorded analysis / parameters / QOI classes (allowlisted).

  3. Re-instantiates the analysis with the recorded parameters.

  4. Calls analyse_element against the saved data — this re-runs the fit and rebuilds the in-memory state figure() needs.

  5. Calls analysis.figure() to build the plotly figure.

  6. 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: RuntimeError

Raised for any expected failure of replay (bad step, missing data, etc).

exception bragi_quantum.gui.replay.PlotRenderError(message, analysis_fields)[source]#

Bases: RuntimeError

Raised 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).

Parameters:
Return type:

None

bragi_quantum.gui.replay.load_timeline(session_root)[source]#
Parameters:

session_root (Path)

Return type:

list[dict[str, Any]]

bragi_quantum.gui.replay.find_step(timeline, step_index)[source]#
Parameters:
Return type:

dict[str, Any]

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.

Parameters:
Return type:

Path

bragi_quantum.gui.replay.open_dataset(path)[source]#
Parameters:

path (Path)

Return type:

Dataset

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}] where value is the value the run actually used (from the recorded parameters), kind is a UI hint ("number" / "bool" / "text") and description (or None) is the field’s pydantic description, shown as a form placeholder. Empty when the parameters class or its categories cannot be introspected.

Parameters:

step (dict[str, Any])

Return type:

list[dict[str, Any]]

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).

overrides re-tunes analysis-category parameters before the fit re-runs (the reanalysis path); acquisition/metadata fields cannot be overridden. n_selected_elements is 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.

Parameters:
Return type:

Any

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.

Parameters:
Return type:

list[str]

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). overrides re-tunes analysis parameters.

Parameters:
Return type:

bytes

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.

overrides re-tunes analysis parameters before the fit re-runs. n_selected_elements is how many elements are selected together in the caller’s UI (see build_analysis_for_element()).

Parameters:
Return type:

tuple[str, list[str]]

bragi_quantum.gui.replay.step_summary(step)[source]#

A small JSON-safe summary of a step for the /steps endpoint.

Parameters:

step (dict[str, Any])

Return type:

dict[str, Any]

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

Parameters:

steps (list[dict[str, Any]])

steps: list[dict[str, Any]]#
classmethod load(session_root)[source]#

Load a session’s timeline from disk; empty on any read failure.

Parameters:

session_root (Path)

Return type:

Timeline

property start_config: dict[str, Any]#

The leading start_config step, or {} if absent.

property qubits: list[str]#
property couplers: list[str]#
property node_steps: list[dict[str, Any]]#
property start_ts: str#

Sortable start timestamp (ISO strings sort chronologically).

property run_name: str#

The orchestrator’s name (unsanitized) recorded at session start.

Distinct from title()’s session_options.run_name lookup, which disambiguates multiple runs replayed from one session folder — this is the top-level field SessionTimeline.record_start_config stamps from CalibrationOrchestrator.name.

split_runs()[source]#

Split a timeline that holds several runs into one Timeline per run.

Empty in → empty out (a session with no timeline yields no run). A single start_config (or none) returns the whole thing unchanged.

Return type:

list[Timeline]

title(fallback_name)[source]#

Human-readable session title and node-step count.

Title joins session_id, template_name and run_name (when distinct); falls back to fallback_name when the timeline is empty.

Parameters:

fallback_name (str)

Return type:

tuple[str, int]

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.

bragi_quantum.gui.cli.main_show(argv=None)[source]#
Parameters:

argv (list[str] | None)

Return type:

int

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).

Return type:

dict[str, set[str]]

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, no Timeline/SessionBundle properties 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/against archive_search()) decides case-sensitivity, not the index.

Return type:

dict[str, set[str]]

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_word refine 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”. Raises re.error on an invalid regex (either mode).

Parameters:
Return type:

dict

class bragi_quantum.gui.archive.Archive(target, traffic_saver=False)[source]#

Bases: object

Live 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(run_ts)[source]#
Parameters:

run_ts (str)

Return type:

list[SessionBundle]

scan_run_folders()[source]#
Return type:

list[Path]

run_descriptor(folder)[source]#

One scan → a run folder’s sidebar/JSON metadata (single source).

Shared by the initial page render and the /runs poll so a folder is never described two ways. done (bragi_quantum.api wrote index.html) drives the spinner; fresh (newest timeline mtime) drives the live iframe reload; error flags any session whose timeline ended in error.

Parameters:

folder (Path)

Return type:

dict

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.html back to the run folder. That file is bragi_quantum.api’s alone — its presence is the run-complete signal (written by generate_html_report when the run finishes), so bragi_quantum.gui must not forge it by persisting its own render.

Parameters:
Return type:

str

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

build_app()[source]#
Return type:

fastapi.FastAPI

serve(host, port, log_level)[source]#
Parameters:
Return type:

int

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.

pydantic model bragi_quantum.gui.server.CommentBody[source]#

Bases: BaseModel

Fields:
field text: str [Required]#
Constraints:
  • min_length = 1

  • max_length = 20000

pydantic model bragi_quantum.gui.server.PlotRequest[source]#

Bases: BaseModel

Fields:
field step_index: int [Required]#
Constraints:
  • ge = 0

field element: str [Required]#
field plot_name: str = 'main'#
field overrides: dict[str, Any] | None = None#
field n_selected_elements: int = 1#
Constraints:
  • ge = 1

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:
key: str#
session_root: Path#
title: str#
step_count: int#
total_steps: int#
timeline: list[dict[str, Any]]#
property tl: Timeline#

The timeline as a value object (start config, qubits, node steps…).

property routes_prefix: str#
property start_ts: str#
bragi_quantum.gui.server.get_bundle(key, request)[source]#
Parameters:
  • key (str)

  • request (fastapi.Request)

Return type:

SessionBundle

bragi_quantum.gui.server.get_run(run_ts, request)[source]#
Parameters:
  • run_ts (str)

  • request (fastapi.Request)

Return type:

list[SessionBundle]

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: ImportError

Raised when a dotted name is not under an allowed root.

bragi_quantum.gui.registry.safe_import_class(module_name, qualname)[source]#

Import qualname from module_name, refusing to import anything outside the allowed roots. Supports dotted qualnames like ‘Outer.Inner’.

Parameters:
  • module_name (str)

  • qualname (str)

Return type:

Any

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.js from 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:

str

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/data from 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:

str

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’s start_config.run_name), shown as the header subtitle. Falls back to a generic subtitle when the run has no name.

Return type:

str

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.html full page; <!-- RUN_ITEMS --> marks where

    the server-rendered date groups are injected, and @@ARCHIVE_JS@@ marks where archive-logic.js (the sidebar’s client logic — linted/type-checked as a real .js file) is embedded.

  • archive_date_group.html one 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.html one 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 run is one of the dicts /runs returns. 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-status slot is left empty here — the poll JS fills it (spinner / done / error) so status lives in one place, not duplicated in Python. runs must be newest-first, same as the /runs contract.

Parameters:

runs (list[dict])

Return type:

str

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.

bragi_quantum.gui.rendering.templates.template_path(name)[source]#

Resolve a template file name to its on-disk path under the right dir.

Parameters:

name (str)

Return type:

Path

bragi_quantum.gui.rendering.templates.load(name)[source]#

Read a template file’s text by name (e.g. load('replot.css')).

Parameters:

name (str)

Return type:

str