"""Shared look and result rendering of the flagship and paper Spaces (deploy/GNN_SPACE.md): SQuADDS theme and CSS, the header,
the Maxwell matrix view (conductor names as headers, 3 decimals shown; the CSV / JSON downloads keep full precision), the status
callout above the matrix, stale-result marking, inline errors and the layer-role editor."""
from __future__ import annotations
import base64
import html
import re
import traceback
import warnings
from pathlib import Path
import gradio as gr
import numpy as np
from tlsq_infer.layout import LayoutError
from . import api as A
STATIC = Path(__file__).parent / "static"
ROLES = ["ground", "conductor", "ground+conductor", "ignore"]
MAT = ["tl-matrix"]
REEXPORT = ("Re-export the layout as GDSII (.gds) from KLayout (File > Save As, format GDS2) or gdstk (Library.write_gds), then "
"upload it again.")
EMPTY = "
The matrix appears here after Predict.
"
STALE = ("
Inputs changed. The matrix shown is for the previous inputs. "
"Press Predict to update it.
")
MATRIX_NOTE = ("
The diagonal holds the self capacitances and the off-diagonal entries are minus the mutual "
"capacitances, in fF. The table shows 3 decimals, and the CSV and JSON keep full precision. † "
"The ground self term is only indicative, since it depends on the chip boundary.
"
CITE_MD = r"""If you use SQuADDS or QCap in your work, please cite:
- S. Shanto *et al.*, "SQuADDS: A validated design database and simulation workflow for superconducting qubit design," *Quantum* **8**, 1465 (2024), [doi:10.22331/q-2024-09-09-1465](https://doi.org/10.22331/q-2024-09-09-1465).
- S. A. Shanto, S. Das and E. Levenson-Falk, "QCap: a physics-corrected graph neural network for the capacitance matrix of any planar superconducting device layout," [arXiv:2611.22057](https://arxiv.org/abs/2611.22057) (2026).
```bibtex
@article{Shanto2024squaddsvalidated,
doi = {10.22331/q-2024-09-09-1465},
url = {https://doi.org/10.22331/q-2024-09-09-1465},
title = {{SQ}u{ADDS}: {A} validated design database and simulation workflow for superconducting qubit design},
author = {Shanto, Sadman and Kuo, Andre and Miyamoto, Clark and Zhang, Haimeng and Maurya, Vivek and Vlachos, Evangelos and Hecht, Malida and Shum, Chung Wa and Levenson-Falk, Eli},
journal = {{Quantum}},
issn = {2521-327X},
publisher = {{Verein zur F{\"{o}}rderung des Open Access Publizierens in den Quantenwissenschaften}},
volume = {8},
pages = {1465},
month = sep,
year = {2024}
}
@misc{Shanto2026planarcapacitance,
title = {{QCap}: a physics-corrected graph neural network for the capacitance matrix of any planar superconducting device layout},
author = {Shanto, Sadman Ahmed and Das, Saikat and Levenson-Falk, Eli},
year = {2026},
eprint = {2611.22057},
archivePrefix = {arXiv},
primaryClass = {quant-ph},
url = {https://arxiv.org/abs/2611.22057}
}
```
"""
def footer() -> str:
"""Credit and copyright, as on the SQuADDS paper page."""
site = "Sadman Ahmed Shanto"
return (f"")
def examples(comp, paths, **kw):
"""gr.Examples whose cached copies survive delete_cache. Gradio 6.29 copies a File example into the cache with
Blocks.temp_files but does not add it to keep_in_cache (the Dataset only stores the file name), so the delete_cache sweep
removed the copy PURGE_AGE_S after startup (at the first sweep when the copy was left by an earlier run) and every later
click on the example failed with FileNotFoundError."""
e = gr.Examples([[str(p)] for p in paths], inputs=[comp], **kw)
for v in e.non_none_processed_examples.values():
for d in v:
if isinstance(d, dict) and d.get("path"):
comp.keep_in_cache.add(d["path"])
return e
def fig_files(fig, d: Path, stem: str) -> tuple[str, str]:
"""A matplotlib figure as PNG (shown, downloadable) and SVG (download), closed afterwards."""
import matplotlib.pyplot as plt
png, svg = d / f"{stem}.png", d / f"{stem}.svg"
fig.savefig(png, dpi=130)
fig.savefig(svg)
plt.close(fig)
return str(png), str(svg)
def matrix_note(res) -> str:
flag = "indicative" in str(res.get("self_capacitance", "")) and list(res.get("names") or [])[:1] == ["G"]
return ("
The diagonal holds the self capacitances and the off-diagonal entries are minus the mutual capacitances, "
"in fF. The table shows 3 decimals, and the CSV and JSON keep full precision." + (f" {GROUND_FLAG}" if flag else "") +
"
"
"Swipe the matrix sideways for more columns.
")
def md(s) -> str:
"""Markdown-safe text: a pair of '~' renders as strikethrough, so approximate values use '≈'."""
return str(s or "").replace("~", "≈")
def pct(e) -> str:
"""'1.05 % median (MAE 0.132 fF, RMSE 0.188 fF)': every % with its MAE / RMSE."""
return f"{e['median_pct']:g} % median (MAE {e['mae_ff']:g} fF, RMSE {e['rmse_ff']:g} fF)"
def _inline(s: str) -> str:
return re.sub(r"\*\*(.+?)\*\*", r"\1", html.escape(s))
def callout(kind: str, head: str, lines) -> str:
body = "".join(f"
{x}
" for x in lines if x)
return f"
{html.escape(head)}
{body}
"
def checks_of(res) -> dict | None:
"""The result's physical checks; for arms that report none, the same checks on the matrix (entries that are None skipped)."""
c = res.get("checks") or {}
if "symmetric_max_abs" in c:
return c
C = np.array([[np.nan if x is None else float(x) for x in r] for r in res.get("matrix_fF") or []], float)
if C.ndim != 2 or len(C) < 2:
return None
off = C[~np.eye(len(C), dtype=bool)]
sig = C[1:, 1:]
return {"symmetric_max_abs": float(np.nanmax(np.abs(C - C.T))), "offdiag_all_negative": bool(np.all(off[np.isfinite(off)] < 0)),
"signal_block_min_eig": float(np.linalg.eigvalsh(sig).min()) if np.isfinite(sig).all() else None}
def _checks(c) -> str:
eig = c.get("signal_block_min_eig")
return (f"Symmetric (max |C − Cᵀ| {c['symmetric_max_abs']:.2g} fF), every off-diagonal negative"
+ (f", signal block positive definite (smallest eigenvalue {eig:.4g} fF)." if eig is not None else
". There are no self terms, so positive definiteness is not checked."))
def _offstack(res) -> str:
sub = res.get("substrate_route") or {}
e, t = res.get("eps_r"), res.get("thickness_um")
if sub.get("route") == A.FAST_ROUTE:
return (f"Substrate eps_r {e:g}, {t:g} µm. This model does not solve the physics prior at your stack. It rescales its "
f"training-stack prediction by (1 + eps_r) / (1 + 11.45) = {sub['eps_rescale_factor']:.4f} and does not model thickness. "
"Off the training stack we measured a median error of 6.4 % (MAE 1.7 fF, RMSE 2.4 fF), so use QCap for other substrates.")
head = (f"Substrate eps_r {e:g}, {t:g} µm. The physics prior was solved at this stack, and the networks (trained on Si, eps_r "
"11.45, 350 µm) are unchanged.")
if not sub.get("tested", True):
return head + f" This is outside the tested range ({A.TESTED_RANGE}), so its error is unknown."
return head + f" This combination was tested. {A.CALIBRATED_SCORE}"
def status_html(res, expected: str | None = None) -> str:
"""Callout above the matrix: red when a physical check fails (the physical_banner text), yellow off the training stack, green
otherwise with the one expected-error line for a new design."""
bad = A.physical_banner(res)
c = checks_of(res)
if not bad and c and "checks" not in res:
C = np.nan_to_num(np.array([[np.nan if x is None else float(x) for x in r] for r in res["matrix_fF"]], float))
w = A.physical_warning({**c, "signal_block_min_eig": c["signal_block_min_eig"] if c["signal_block_min_eig"] is not None else 1.0}, C)
bad = [f"> **Not a physical matrix.** {w}"] if w else []
if bad:
return callout("bad", "Not a physical matrix: do not use it", [_inline(bad[0].lstrip("> ").replace("**Not a physical matrix.** ", ""))])
chk = _checks(c) if c else None
if (res.get("substrate_route") or {}).get("route", "training stack") != "training stack":
return callout("warn", "Off the training stack" + (": physical checks passed" if chk else ""), [chk, html.escape(_offstack(res))])
if chk:
return callout("ok", "Physical checks passed", [chk, html.escape(expected) if expected else None])
return callout("", "Result", [html.escape(expected) if expected else None])
def error_text(e: BaseException) -> str:
if isinstance(e, MemoryError):
return "Out of memory: crop the layout to the region of interest and try again."
if not isinstance(e, (LayoutError, ValueError, KeyError, FileNotFoundError)):
traceback.print_exception(e)
return f"Internal error ({type(e).__name__}): {e}. Please report it with the file if you can."
msg = str(e).strip()
if msg == "upload a GDS file first":
return "No layout yet: upload a GDS file (or pick an example) in step 1, then press Predict."
if msg.startswith("not a readable GDS"):
return f"This file could not be read as GDSII ({msg.rstrip('.')}). {REEXPORT}"
return msg[:1].upper() + msg[1:]
def error_html(e: BaseException, head: str = "Could not predict") -> str:
if getattr(e, "limit_html", None): # a limit of the demo (geomgnn.access.LimitReached): its own head and the local-use link
return callout("warn", e.head, [e.limit_html])
return callout("bad", head, [html.escape(error_text(e))])
def matrix_view(res):
"""The matrix for the UI: conductor names as headers (blank top-left), 3 decimals shown, the ground self term flagged when the
result calls it indicative. The underlying values are the 4-decimal table the /predict endpoint always returned."""
if not res:
return None
import pandas as pd
names = list(res["names"])
rows = [[a] + [np.nan if x is None else round(float(x), 4) for x in row] for a, row in zip(names, res["matrix_fF"])]
df = pd.DataFrame(rows, columns=["", *names])
st = df.style.format("{:.3f}", subset=names, na_rep="").set_properties(subset=names, **{"text-align": "right"})
st = st.set_properties(subset=[""], **{"font-weight": "600"})
if "indicative" in str(res.get("self_capacitance", "")) and names and names[0] == "G" and np.isfinite(rows[0][1]):
st = st.format(lambda v: f"{v:.3f} †", subset=pd.IndexSlice[[0], [names[0]]])
return st
def stale(res):
if res is None:
return gr.update(), gr.update(), gr.update()
return STALE, gr.update(elem_classes=MAT + ["tl-stale"]), gr.update(elem_classes=["tl-stale"])
def mark_stale(res_state, status, mat, report, events):
for ev in events:
ev(stale, res_state, [status, mat, report], api_visibility="private", show_progress="hidden")
def predict_ui(fn, expected, note: bool = False):
"""Visible Predict: the /predict function plus the status callout and the result group (hidden until the first result); errors
become an inline callout instead of a toast and grey out an earlier result. note = also return the matrix note (last output)."""
def run(*a):
try:
mat, csv_f, json_f, rep, res = fn(*a)
except Exception as e: # noqa: BLE001
return (gr.update(elem_classes=MAT + ["tl-stale"]), gr.update(), gr.update(), gr.update(elem_classes=["tl-stale"]), gr.update(),
error_html(e), gr.update()) + ((gr.update(),) if note else ())
return (gr.update(value=mat, elem_classes=MAT), csv_f, json_f, gr.update(value=rep, elem_classes=[]), res,
status_html(res, expected(res)), gr.update(visible=True)) + ((matrix_note(res),) if note else ())
run.__name__ = fn.__name__ + "_ui"
return run
def _rows(table) -> list:
if table is None:
return []
rows = table.values.tolist() if hasattr(table, "values") else list(table)
return [list(r) for r in rows if len(r) >= 3 and str(r[0]).strip() not in ("", "nan", "None")]
def _key(r) -> str:
return f"{int(float(r[0]))}/{int(float(r[1]))}"
def inspect_ui(inspect_fn):
"""Inspect on every file change (upload, example, clear): layer table, plot, inline message, layer picker, role."""
def run(f):
none = gr.update(choices=[], value=None)
if f is None:
return [], None, "", none, gr.update(value=None)
try:
table, fig = inspect_fn(f)
except Exception as e: # noqa: BLE001
return [], None, error_html(e, "Could not read this file"), none, gr.update(value=None)
keys = [_key(r) for r in table]
return table, fig, "", gr.update(choices=keys, value=keys[0] if keys else None), gr.update(value=table[0][2] if table else None)
return run
def layer_editor():
with gr.Row(elem_classes="tl-roles"):
pick = gr.Dropdown([], label="layer", interactive=True, min_width=140)
role = gr.Dropdown(ROLES, value=None, label="role", interactive=True, min_width=200)
return pick, role
def wire_editor(layers, pick, role):
"""Fixed role choices instead of free text: pick a layer (or click its row), choose its role. Returns the edit event."""
def show(table, key):
r = next((r for r in _rows(table) if _key(r) == key), None)
return gr.update(value=r[2] if r else None)
def choose(table, evt: gr.SelectData):
rows = _rows(table)
return gr.update(value=_key(rows[evt.index[0]])) if rows and evt.index[0] < len(rows) else gr.update()
def edit(table, key, new):
return [r[:2] + [new] + r[3:] if _key(r) == key else r for r in _rows(table)]
pick.change(show, [layers, pick], role, api_visibility="private", show_progress="hidden")
layers.select(choose, layers, pick, api_visibility="private", show_progress="hidden")
return role.input(edit, [layers, pick, role], layers, api_visibility="private", show_progress="hidden")