shanto268 commited on
Commit
62310ab
·
verified ·
1 Parent(s): 4f5e603

v4 flagship Space (3 tiers) from registry v2 (earlier contents: 906bc45ae05c)

Browse files
README.md CHANGED
@@ -13,55 +13,61 @@ short_description: 'Maxwell capacitance of planar layouts: 3 tiers'
13
  # Planar Capacitance Model
14
 
15
  Upload a GDS of a planar superconducting layout (ground 1/0, conductors 1/10, or assign your layers) and get its full Maxwell
16
- capacitance matrix in fF, self terms included. Three tiers in one selector, each the best recipe of the paper at its speed,
17
  **retrained on all 45,771 on-stack Q3D layouts** (Si, eps_r 11.45, 350 µm: training, validation and every test
18
- layout that passed label QC). Private preview while the paper is in preparation. To reproduce the paper's numbers with the paper's own
19
- models, use the paper Space [shanto268/2026PaperModels](https://huggingface.co/spaces/shanto268/2026PaperModels).
20
 
21
  ## Accuracy: what can honestly be said
22
- Trained on everything, **these models have no held-out score of their own.** Each tier lists (a) the paper's held-out numbers for the
23
- **same recipe** trained on the 35,354-layout TRAIN split (validation = 4,608 layouts of 13 families; test = the paper's test benchmark,
24
- read once: in family 4,009 layouts, zero-shot macro over nine component cohorts 1,878 layouts; held-out family = leave one family out,
25
- 4,071 layouts) and (b) **one fresh check, B5**: 39 new layouts of one generated family (campaign450 B5, 3-4 conductors) that no
26
- component of any tier ever saw, against its physics reference. Layout-mean median relative error % (MAE / RMSE fF) over mutual
27
- entries against Q3D, 0.1 fF floor. "–" = not measured.
28
-
29
- | id | tier | paper VAL | paper test in family | paper test zero-shot | paper held-out family | B5 (this model) | B5 physics alone | time on this Space (2 vCPU) | time, x86 node (2 CPUs) |
30
- |---|---|---|---|---|---|---|---|---|---|
31
- | `accurate` (default) | Accurate (~1 s) | 0.229 % (0.0674 / 0.0792 fF) | 0.177 % (0.0203 / 0.025 fF) | 0.587 % (1.092 / 1.152 fF) | 0.408 % (0.049 / 0.059 fF) | 1.05 % (0.132 / 0.188 fF) | 1.765 % (0.275 / 0.376 fF) | interdigital 0.47 s, xmon 0.91 s, 1-qubit lattice (N 15) 19.0 s, 16-conductor layout 9.9 s, 9-qubit lattice (N 67) 154 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s) | 0.845 / 5.96 s in family, 1.75 / 18.1 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.99 s median (1.14 s on the 2026-10-20 re-run, Xeon E5-2640 v4) |
32
- | `balanced` | Balanced (~0.5 s) | 0.343 % (0.123 / 0.138 fF) | – | – | – | 2.044 % (0.258 / 0.348 fF) | 2.681 % (0.396 / 0.583 fF) | interdigital 0.29 s, xmon 0.51 s, 1-qubit lattice (N 15) 7.7 s, 16-conductor layout 2.4 s, 9-qubit lattice (N 67) 54 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s) | 0.490 / 2.31 s in family, 1.00 / 10.0 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.56 s median |
33
- | `fast` | Fast (~0.1 s) | 0.846 % (0.491 / 0.549 fF) | 0.63 % (0.113 / 0.1414 fF) | 3.576 % (4.608 / 5.058 fF) | 3.113 % (0.533 / 0.633 fF) | 3.175 % (0.583 / 0.824 fF) | 1.765 % (0.275 / 0.376 fF) | interdigital 0.036 s, xmon 0.11 s, 1-qubit lattice (N 15) 0.82 s, 16-conductor layout 0.49 s, 9-qubit lattice (N 67) 3.9 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s) | 0.091 / 0.274 s in family, 0.30 / 2.45 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.24 s median |
34
-
35
- * **Accurate** (default) beats the physics it corrects on B5 by 0.73 pp of median error (paired bootstrap 95 % CI [0.35, 1.12]), 0.144 fF
36
- of MAE and 0.187 fF of RMSE. Use it for anything that matters.
37
- * **Balanced** is about 2x faster than Accurate at 1.5-1.7x its error (paper VAL 0.343 % (0.123 / 0.138 fF) vs
 
 
38
  0.229 % (0.0674 / 0.0792 fF); B5 2.044 % (0.258 / 0.348 fF) vs 1.05 % (0.132 / 0.188 fF)).
39
- * **Fast** is for quick screening of the component families it was trained on (interdigital, paddle, concentric, star, multipad star,
 
40
  Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated and synthetic campaign layouts). **On B5 (new designs
41
  of a trained family) it was worse than the physics alone**: 3.175 % (0.583 / 0.824 fF) against 1.765 % (0.275 / 0.376 fF); and in
42
- the paper, on a component family held out of its training, it was worse than the physics alone too: 3.113 % (0.533 / 0.633 fF)
43
- against 1.554 % (0.166 / 0.205 fF). Its error comes from the learned prior. Paper validation of this surrogate recipe with
44
- the networks: 0.722 % (0.387 / 0.436 fF).
 
45
 
46
- Sources: `agents/flagship_v4/RESULTS.md` (training, B5, timings), paper_v4 (tab:ladder-test, tab:routes) for the reference rows.
 
 
47
 
48
  ### `accurate`: Accurate (~1 s): extrapolated physics R(1.5, 3) on the corrected prior + residual networks, compiled solver
49
 
50
  Two thin-film method-of-moments solves (corrected prior with substrate far field, 1.5 and 3 panels per gap), Richardson-extrapolated, corrected by a 3-seed ensemble of the paper model's networks (89,858 parameters per seed, bounded residual) with a learned row-sum closure: the complete Maxwell matrix, self terms included. Networks retrained on all 45,771 on-stack Q3D layouts (2026-10-20, on the corrected prior with substrate far field).
51
 
52
- Reference recipe: the paper's model (same networks and prior stack at inference; its networks were trained on 35,354 TRAIN layouts on the uncorrected prior; retrained on the corrected prior, as here, they score validation 0.218 % (0.0774 / 0.0888 fF)).
53
 
54
  ### `balanced`: Balanced (~0.5 s): the same recipe on the coarser pair R(0.75, 1.5) of the corrected prior, networks retrained
55
 
56
  The Accurate recipe on the coarser Richardson pair (0.75 and 1.5 panels per gap, about half the solve time), networks retrained on that pair on all 45,771 on-stack layouts. About 2x faster than Accurate at 1.5-1.7x its error.
57
 
58
- Reference recipe: the paper's coarser pair + the model's recipe (trained on 35,354 TRAIN layouts; validation only, never test-scored).
59
 
60
  ### `fast`: Fast (~0.1 s): learned prior surrogate + residual networks, no field solve (trained component families only)
61
 
62
- A learned surrogate (1.02M parameters, trained on the prior of every on-stack layout plus 432,697 generated layouts labelled by the prior alone) predicts the two uncorrected-prior solves at 1.5 and 3 panels per gap; networks retrained on all 45,771 on-stack layouts on that prior correct them. No field solve: the time is the geometric embedding.
63
 
64
- Reference recipe: the paper's fast model (learned prior surrogate + the networks on its prior, trained on 35,354 TRAIN layouts).
65
 
66
  The models were trained on Si (eps_r 11.45), 350 µm only. On other substrates Accurate and Balanced solve the physics prior at the requested eps_r and thickness and the unchanged networks correct it (calibrated route; on 15 held-out designs 0.21-1.02 % (MAE 0.07-0.33 fF, RMSE 0.09-0.45 fF) on every tested stack (Si 10-1000 µm, eps_r 3.8-24 at 350 µm), against 0.23 % (0.080 / 0.111 fF) on the training stack; self terms up to 1.22 % (0.79 / 0.86 fF); a bounded error, not training-stack accuracy; untested combinations are flagged). Fast cannot solve a prior: off the stack they rescale by (1+eps_r)/(1+11.45) and warn. Accurate and Balanced are dominated by the
67
  two thin-film solves; Fast by the geometric embedding. Ground self term: indicative only (it depends on the chip boundary).
@@ -70,9 +76,13 @@ two thin-film solves; Fast by the geometric embedding. Ground self term: indicat
70
  * `/models` () -> served tiers with their reference numbers and times.
71
  * `/inspect` (gds) -> layer table; `/prepare` (gds, layers, crop, margin_gaps, margin_um, select) -> preview and summary.
72
  * `/predict` (gds, layers, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness_um, model).
73
- * `/predict_gds` (gds, ground "1/0", conductor "1/10", margin_gaps, substrate, custom_eps, thickness_um, model) -> result dict
74
- (`matrix_fF`, `names`, `timing_s`, `prior_stack`, `reference`, `b5`). model = `accurate`, `balanced`, `fast` (default `accurate`).
75
  Up to 70 conductors + ground per layout.
 
 
 
 
76
 
77
  ```python
78
  import os
@@ -85,8 +95,8 @@ print(r["names"], r["matrix_fF"], r["timing_s"]["total_s"])
85
 
86
  Speed: the pair vectors of every tier use far-sample decimation (blocks of 64 boundary samples farther than 100 µm from the other
87
  conductor are represented by one sample); on the paper's 4,608 validation layouts and the 1-, 5- and 9-qubit lattices it ties
88
- the exact embedding under the paper's tie rule, and it cuts the embedding time of a 100-qubit chip 2.6x. To reproduce the paper's
89
- numbers exactly use the paper Space, which keeps the exact embedding.
90
 
91
  Privacy: uploads are held in memory only while the Space is running, to speed up repeat requests; nothing is written to
92
  permanent storage. No analytics, no file names or geometry in the logs. Hugging Face keeps ordinary web access logs under its
 
13
  # Planar Capacitance Model
14
 
15
  Upload a GDS of a planar superconducting layout (ground 1/0, conductors 1/10, or assign your layers) and get its full Maxwell
16
+ capacitance matrix in fF, self terms included. Three tiers (Accurate, the default, and Balanced in the selector; Fast under "Tiers and their accuracy"), each the best recipe of the paper at its speed,
17
  **retrained on all 45,771 on-stack Q3D layouts** (Si, eps_r 11.45, 350 µm: training, validation and every test
18
+ layout that passed label QC). Private preview while the paper is in preparation. The paper's own models are model repositories:
19
+ [SQuADDS/PlanarCapacitance-paper](https://huggingface.co/SQuADDS/PlanarCapacitance-paper) and the earlier draft's `SQuADDS/2026PaperModels-*`.
20
 
21
  ## Accuracy: what can honestly be said
22
+ Trained on everything, **these models have no held-out score of their own.** Each tier lists (a) **its own in-sample fit** on the
23
+ 45,771 layouts it was trained on (training, validation and the paper's test split: a fit, not a generalisation score), (b) **one fresh
24
+ check, B5**: 39 new layouts of one generated family (campaign450 B5, 3-4 conductors) that no component of any tier ever saw, against
25
+ its physics reference, and (c) **the held-out numbers of the paper's version** of the tier, which was trained on the 35,354-layout TRAIN
26
+ split only (validation = 4,608 layouts of 13 families; test = the paper's test benchmark, read once: in family 4,009 layouts, zero-shot
27
+ macro over nine component cohorts 1,878 layouts; held-out family = leave one family out, 4,071 layouts). The (c) numbers belong to the
28
+ paper's versions, not to these models. Layout-mean median relative error % (MAE / RMSE fF) over mutual entries against Q3D, 0.1 fF
29
+ floor. "–" = not measured.
30
+
31
+ | id | tier | this model: in-sample (45,771) | this model: B5 | B5 physics alone | paper's version: VAL | paper's version: test in family | paper's version: test zero-shot | paper's version: held-out family | time on this Space (2 vCPU) | time, x86 node (2 CPUs) |
32
+ |---|---|---|---|---|---|---|---|---|---|---|
33
+ | `accurate` (default) | Accurate (~1 s) | 0.207 % (0.0679 / 0.077 fF) | 1.05 % (0.132 / 0.188 fF) | 1.765 % (0.275 / 0.376 fF) | 0.229 % (0.0674 / 0.0792 fF) | 0.177 % (0.0203 / 0.025 fF) | 0.587 % (1.092 / 1.152 fF) | 0.408 % (0.049 / 0.059 fF) | interdigital 0.47 s, xmon 0.91 s, 1-qubit lattice (N 15) 19.0 s, 16-conductor layout 9.9 s, 9-qubit lattice (N 67) 154 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s) | 0.845 / 5.96 s in family, 1.75 / 18.1 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.99 s median (1.14 s on the 2026-10-20 re-run, Xeon E5-2640 v4) |
34
+ | `balanced` | Balanced (~0.5 s) | 0.3 % (0.0872 / 0.0999 fF) | 2.044 % (0.258 / 0.348 fF) | 2.681 % (0.396 / 0.583 fF) | 0.343 % (0.123 / 0.138 fF) | – | – | – | interdigital 0.29 s, xmon 0.51 s, 1-qubit lattice (N 15) 7.7 s, 16-conductor layout 2.4 s, 9-qubit lattice (N 67) 54 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s) | 0.490 / 2.31 s in family, 1.00 / 10.0 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.56 s median |
35
+ | `fast` | Fast (~0.1 s) | 0.671 % (0.353 / 0.395 fF) | 3.175 % (0.583 / 0.824 fF) | 1.765 % (0.275 / 0.376 fF) | 0.846 % (0.491 / 0.549 fF) | 0.63 % (0.113 / 0.1414 fF) | 3.576 % (4.608 / 5.058 fF) | 3.113 % (0.533 / 0.633 fF) | interdigital 0.036 s, xmon 0.11 s, 1-qubit lattice (N 15) 0.82 s, 16-conductor layout 0.49 s, 9-qubit lattice (N 67) 3.9 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s) | 0.091 / 0.274 s in family, 0.30 / 2.45 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.24 s median |
36
+
37
+ * **Accurate** (default) beats the physics it corrects on B5 by 0.71 pp of median error (paired bootstrap 95 % CI [0.33, 1.11]), 0.143 fF
38
+ of MAE and 0.188 fF of RMSE (after the 2026-10-20 far-field retrain, agents/farfield/ADOPTION.md). Use it for anything that matters.
39
+ * **Balanced** is about 2x faster than Accurate at 1.5-1.7x its error (paper's versions, VAL 0.343 % (0.123 / 0.138 fF) vs
40
  0.229 % (0.0674 / 0.0792 fF); B5 2.044 % (0.258 / 0.348 fF) vs 1.05 % (0.132 / 0.188 fF)).
41
+ * **Fast** is an improved release of the paper's fast model (same architecture; its surrogate is trained on more generated layouts and
42
+ its networks on every labelled design, the paper's test split included). It is for quick screening of the component families it was trained on (interdigital, paddle, concentric, star, multipad star,
43
  Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated and synthetic campaign layouts). **On B5 (new designs
44
  of a trained family) it was worse than the physics alone**: 3.175 % (0.583 / 0.824 fF) against 1.765 % (0.275 / 0.376 fF); and in
45
+ the paper, the paper's version of it, on a component family held out of its training, was worse than the physics alone too:
46
+ 3.113 % (0.533 / 0.633 fF) against 1.554 % (0.166 / 0.205 fF). Its error comes from the learned prior. Its surrogate
47
+ recipe trained without the validation layouts, with the paper's TRAIN-only networks, scores 0.722 % (0.387 / 0.436 fF) on
48
+ validation (held out), against 0.846 % (0.491 / 0.549 fF) for the paper's version.
49
 
50
+ Sources: `agents/flagship_v4/RESULTS.md` (training, in-sample, B5, timings), `agents/farfield/ADOPTION.md` (Accurate / Balanced in-sample after
51
+ the far-field retrain), `agents/surcov_p6/RESULTS_P6.md` (Fast surrogate recipe on validation), paper_v4 (tab:ladder-test, tab:routes) for the
52
+ paper's-version rows.
53
 
54
  ### `accurate`: Accurate (~1 s): extrapolated physics R(1.5, 3) on the corrected prior + residual networks, compiled solver
55
 
56
  Two thin-film method-of-moments solves (corrected prior with substrate far field, 1.5 and 3 panels per gap), Richardson-extrapolated, corrected by a 3-seed ensemble of the paper model's networks (89,858 parameters per seed, bounded residual) with a learned row-sum closure: the complete Maxwell matrix, self terms included. Networks retrained on all 45,771 on-stack Q3D layouts (2026-10-20, on the corrected prior with substrate far field).
57
 
58
+ Paper's version: the paper's version of this model (same architecture and prior stack at inference; its networks were trained on the 35,354 TRAIN layouts only, on the uncorrected prior; retrained on the corrected prior, as here, they score validation 0.218 % (0.0774 / 0.0888 fF)). These held-out numbers belong to the paper's version, not to this release, whose networks were retrained on every labelled design, the paper's test split included.
59
 
60
  ### `balanced`: Balanced (~0.5 s): the same recipe on the coarser pair R(0.75, 1.5) of the corrected prior, networks retrained
61
 
62
  The Accurate recipe on the coarser Richardson pair (0.75 and 1.5 panels per gap, about half the solve time), networks retrained on that pair on all 45,771 on-stack layouts. About 2x faster than Accurate at 1.5-1.7x its error.
63
 
64
+ Paper's version: the paper's version: the coarser pair + the model's recipe, trained on the 35,354 TRAIN layouts only (validation only, never test-scored). These numbers belong to the paper's version, not to this release.
65
 
66
  ### `fast`: Fast (~0.1 s): learned prior surrogate + residual networks, no field solve (trained component families only)
67
 
68
+ An improved release of the paper's fast model, same architecture: a learned surrogate (1.02M parameters) predicts the two uncorrected-prior solves at 1.5 and 3 panels per gap and residual networks correct them. The surrogate is trained on more generated layouts (the prior of every on-stack layout plus 432,697 generated layouts labelled by the prior alone, against 385,593 for the paper's) and the networks are retrained on every labelled design (all 45,771 on-stack layouts, the paper's test split included). No field solve: the time is the geometric embedding.
69
 
70
+ Paper's version: the paper's version of the fast model (surrogate t100_norm trained on 385,593 generated layouts + the TRAIN geometry; networks trained on the 35,354 TRAIN layouts only). These held-out numbers belong to the paper's version, not to this release, which was trained on the paper's test split too.
71
 
72
  The models were trained on Si (eps_r 11.45), 350 µm only. On other substrates Accurate and Balanced solve the physics prior at the requested eps_r and thickness and the unchanged networks correct it (calibrated route; on 15 held-out designs 0.21-1.02 % (MAE 0.07-0.33 fF, RMSE 0.09-0.45 fF) on every tested stack (Si 10-1000 µm, eps_r 3.8-24 at 350 µm), against 0.23 % (0.080 / 0.111 fF) on the training stack; self terms up to 1.22 % (0.79 / 0.86 fF); a bounded error, not training-stack accuracy; untested combinations are flagged). Fast cannot solve a prior: off the stack they rescale by (1+eps_r)/(1+11.45) and warn. Accurate and Balanced are dominated by the
73
  two thin-film solves; Fast by the geometric embedding. Ground self term: indicative only (it depends on the chip boundary).
 
76
  * `/models` () -> served tiers with their reference numbers and times.
77
  * `/inspect` (gds) -> layer table; `/prepare` (gds, layers, crop, margin_gaps, margin_um, select) -> preview and summary.
78
  * `/predict` (gds, layers, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness_um, model).
79
+ * `/predict_gds` (gds, ground "1/0", conductor "1/10", margin_gaps, substrate, custom_eps, thickness_um, model, ground_pieces "") -> result dict
80
+ (`matrix_fF`, `names`, `timing_s`, `prior_stack`, `reference`, `own`, `b5`). model = `accurate`, `balanced`, `fast` (default `accurate`).
81
  Up to 70 conductors + ground per layout.
82
+ Ground and conductors on one layer: pass that layer as both (e.g. "2/0", "2/0"); the ground is detected automatically among the
83
+ connected pieces (`ground_detection` in the result: pieces, reason, confidence, plus a warning); if it is wrong, pass the
84
+ ground's piece numbers as `ground_pieces` (e.g. "1" or "1,4", the last argument). In the web app the pick is shown on a numbered
85
+ image and Predict waits until you confirm or fix it.
86
 
87
  ```python
88
  import os
 
95
 
96
  Speed: the pair vectors of every tier use far-sample decimation (blocks of 64 boundary samples farther than 100 µm from the other
97
  conductor are represented by one sample); on the paper's 4,608 validation layouts and the 1-, 5- and 9-qubit lattices it ties
98
+ the exact embedding under the paper's tie rule, and it cuts the embedding time of a 100-qubit chip 2.6x. The paper's numbers use the
99
+ exact embedding (`TLSQ_EMBEDDING_EXACT=1` in the package).
100
 
101
  Privacy: uploads are held in memory only while the Space is running, to speed up repeat requests; nothing is written to
102
  permanent storage. No analytics, no file names or geometry in the logs. Hugging Face keeps ordinary web access logs under its
app.py CHANGED
@@ -38,7 +38,17 @@ os.environ.setdefault("TLSQ_NUM_THREADS", str(set_num_threads()))
38
  from geomgnn.app_flagship import build_app # noqa: E402
39
 
40
  reg = load_registry()
41
- ex = HERE / "examples" if (HERE / "examples").exists() else HERE.parent / "PlanarCapacitanceModel" / "examples"
 
 
 
 
 
 
 
 
 
 
42
  if os.environ.get("TLSQ_PRELOAD", "1") != "0": # load every tier (SHA checks) + numba warmup + one small prediction before the queue opens
43
  from geomgnn import flagship as FS # noqa: E402
44
 
 
38
  from geomgnn.app_flagship import build_app # noqa: E402
39
 
40
  reg = load_registry()
41
+ ex = HERE / "examples"
42
+ if not ex.exists(): # repository checkout: the bundle's examples (sync.py --flagship adds the lattices from data_local)
43
+ import shutil
44
+ import tempfile
45
+
46
+ ex = Path(tempfile.mkdtemp()) / "examples"
47
+ shutil.copytree(HERE.parent / "PlanarCapacitanceModel" / "examples", ex, ignore=shutil.ignore_patterns("__pycache__", "client.py"))
48
+ for name, src in (("lattice_1q.gds", "grid_qubit_1.gds"), ("lattice_5q.gds", "grid_qubit_5.gds")):
49
+ f = HERE.parents[2] / "data_local" / "release_core" / "gds" / "ref" / "grid" / src
50
+ if f.exists():
51
+ shutil.copy(f, ex / name)
52
  if os.environ.get("TLSQ_PRELOAD", "1") != "0": # load every tier (SHA checks) + numba warmup + one small prediction before the queue opens
53
  from geomgnn import flagship as FS # noqa: E402
54
 
geomgnn/.ruff_cache/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Automatically created by ruff.
2
+ *
geomgnn/.ruff_cache/0.3.2/1469527473019908334 ADDED
Binary file (376 Bytes). View file
 
geomgnn/.ruff_cache/0.3.2/15008937266116554827 ADDED
Binary file (138 Bytes). View file
 
geomgnn/.ruff_cache/0.3.2/16722831700881126324 ADDED
Binary file (195 Bytes). View file
 
geomgnn/.ruff_cache/CACHEDIR.TAG ADDED
@@ -0,0 +1 @@
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
geomgnn/api.py CHANGED
@@ -48,6 +48,9 @@ CALIBRATED_CAVEAT = (
48
  "the mutual entries were 0.21-1.02 % (MAE 0.07-0.33 fF, RMSE 0.09-0.45 fF) on every tested stack, against 0.23 % (0.080 / "
49
  "0.111 fF) on the training stack; self terms 0.96-1.22 % (MAE 0.48-0.79, RMSE 0.52-0.86 fF) at 10-50 um Si and 0.89 % "
50
  "(0.92 / 1.07 fF) at 1000 um, against 0.24 % (0.18 / 0.22 fF)")
 
 
 
51
  FAST_ROUTE = "fast: eps-rescaled training-stack prediction; thickness not modelled"
52
  FAST_WARNING = ("Fast does not solve the prior at your stack; use tier='accurate' (prior solved at your eps_r and thickness) for other "
53
  "substrates.")
@@ -99,8 +102,9 @@ def substrate_line(res: dict) -> str:
99
  if r == "training stack":
100
  return head + "the training stack"
101
  if r == FAST_ROUTE:
102
- return head + f"{r} (factor (1+eps_r)/(1+11.45) = {sub['eps_rescale_factor']:.4f}). {FAST_WARNING}"
103
- return head + r + ("" if sub.get("tested") else " (UNTESTED combination)") + f". {sub.get('caveat', '')}"
 
104
 
105
  PRIOR_IMPLS = ("frozen", "cpu_fast")
106
  _HMAT0 = dict(proxy.HMAT)
@@ -456,6 +460,27 @@ def physical_checks(C: np.ndarray) -> dict:
456
  "signal_block_min_eig": float(np.linalg.eigvalsh(sig).min()) if n > 1 else None}
457
 
458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  def predict_gnn(prepared, name: str, reg, substrate="Si (cryogenic, training)", thickness_um: float = 350.0, model_dir=None,
460
  threads: int | None = None) -> dict:
461
  """Full N x N Maxwell matrix (fF; ground row/column 0, self terms learned) of a prepared layout with a gnn_models entry."""
@@ -482,9 +507,9 @@ def predict_gnn(prepared, name: str, reg, substrate="Si (cryogenic, training)",
482
  warnings = [w for w in prepared.warnings if "beyond the validated range" not in w]
483
  if m.get("warning"):
484
  warnings.insert(0, m["warning"])
485
- if not (chk["symmetric_max_abs"] <= 1e-6 * max(1.0, float(np.abs(C).max())) and chk["offdiag_all_negative"]
486
- and (chk["signal_block_min_eig"] is None or chk["signal_block_min_eig"] > 0)):
487
- warnings.append(f"physical check failed: {chk}")
488
  warnings += sub_w
489
  tm = r["timing"]
490
  return {"names": labels, "matrix_fF": C.tolist(), "units": "fF",
 
48
  "the mutual entries were 0.21-1.02 % (MAE 0.07-0.33 fF, RMSE 0.09-0.45 fF) on every tested stack, against 0.23 % (0.080 / "
49
  "0.111 fF) on the training stack; self terms 0.96-1.22 % (MAE 0.48-0.79, RMSE 0.52-0.86 fF) at 10-50 um Si and 0.89 % "
50
  "(0.92 / 1.07 fF) at 1000 um, against 0.24 % (0.18 / 0.22 fF)")
51
+ TESTED_RANGE = "Si at 10-1000 µm, or eps_r 3.8-24 at 350 µm"
52
+ CALIBRATED_SCORE = ("On 15 held-out designs the mutual entries were 0.21-1.02 % (MAE 0.07-0.33 fF, RMSE 0.09-0.45 fF), against 0.23 % "
53
+ "(MAE 0.080 fF, RMSE 0.111 fF) on the training stack; self terms up to 1.22 % (MAE up to 0.92 fF, RMSE up to 1.07 fF).")
54
  FAST_ROUTE = "fast: eps-rescaled training-stack prediction; thickness not modelled"
55
  FAST_WARNING = ("Fast does not solve the prior at your stack; use tier='accurate' (prior solved at your eps_r and thickness) for other "
56
  "substrates.")
 
102
  if r == "training stack":
103
  return head + "the training stack"
104
  if r == FAST_ROUTE:
105
+ return head + f"eps-rescaled training-stack prediction (factor (1+eps_r)/(1+11.45) = {sub['eps_rescale_factor']:.4f}), thickness not modelled"
106
+ return head + "physics prior solved at your stack, networks and embedding at the training stack (calibrated route" + (
107
+ "" if sub.get("tested") else "; UNTESTED combination") + ")"
108
 
109
  PRIOR_IMPLS = ("frozen", "cpu_fast")
110
  _HMAT0 = dict(proxy.HMAT)
 
460
  "signal_block_min_eig": float(np.linalg.eigvalsh(sig).min()) if n > 1 else None}
461
 
462
 
463
+ def physical_banner(res: dict) -> list[str]:
464
+ """Report lines that put a failed physical check first."""
465
+ w = next((w for w in res.get("warnings") or [] if w.startswith("physical check failed")), None)
466
+ return [f"> **Not a physical matrix.** {w}", ""] if w else []
467
+
468
+
469
+ def physical_warning(chk: dict, C: np.ndarray) -> str | None:
470
+ """Readable warning when the checks of physical_checks fail (None when the matrix passes)."""
471
+ bad = []
472
+ if not chk["symmetric_max_abs"] <= 1e-6 * max(1.0, float(np.abs(C).max())):
473
+ bad.append(f"not symmetric (max |C - C^T| {chk['symmetric_max_abs']:.3g} fF)")
474
+ if not chk["offdiag_all_negative"]:
475
+ bad.append(f"{int(np.sum(C[~np.eye(len(C), dtype=bool)] >= 0))} off-diagonal entries are not negative")
476
+ if chk["signal_block_min_eig"] is not None and not chk["signal_block_min_eig"] > 0:
477
+ bad.append(f"the signal block is not positive definite (smallest eigenvalue {chk['signal_block_min_eig']:.4g} fF)")
478
+ if not bad:
479
+ return None
480
+ return ("physical check failed: " + "; ".join(bad) + ". This matrix is not physical: do not use it. A tier that solves the physics "
481
+ "(Accurate, or the paper's model) is the safer choice, especially outside the trained component families.")
482
+
483
+
484
  def predict_gnn(prepared, name: str, reg, substrate="Si (cryogenic, training)", thickness_um: float = 350.0, model_dir=None,
485
  threads: int | None = None) -> dict:
486
  """Full N x N Maxwell matrix (fF; ground row/column 0, self terms learned) of a prepared layout with a gnn_models entry."""
 
507
  warnings = [w for w in prepared.warnings if "beyond the validated range" not in w]
508
  if m.get("warning"):
509
  warnings.insert(0, m["warning"])
510
+ pw = physical_warning(chk, C)
511
+ if pw:
512
+ warnings.insert(0, pw)
513
  warnings += sub_w
514
  tm = r["timing"]
515
  return {"names": labels, "matrix_fF": C.tolist(), "units": "fF",
geomgnn/app_flagship.py CHANGED
@@ -6,18 +6,21 @@ order as the GNN Space:
6
  /inspect (gds file) -> layer table, layer plot
7
  /prepare (gds, layers table, crop, margin_gaps, margin_um, select) -> preview, warnings, summary, simplified GDS
8
  /predict (gds, layers table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness_um, model) -> matrix, CSV, JSON, report
9
- /predict_gds (gds, ground "1/0", conductor "1/10", margin_gaps, substrate, custom_eps, thickness_um, model) -> result dict;
10
- model = accurate (default) | balanced | fast
 
11
  """
12
 
13
  from __future__ import annotations
14
 
 
15
  import json
16
  import time
17
  from pathlib import Path
18
 
19
  from tlsq_infer import __version__ as TLSQ_VERSION
20
- from tlsq_infer.app_ui import CUSTOM, HEAVY, INTRO, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fn, matrix_table
 
21
  from tlsq_infer.app_v2 import PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fn
22
  from tlsq_infer.layout import LayoutError, prepare
23
  from tlsq_infer.predict import matrix_csv
@@ -25,7 +28,9 @@ from tlsq_infer.registry import load_registry
25
 
26
  from . import __version__
27
  from . import api as A
 
28
  from . import flagship as FS
 
29
 
30
  ORDER = ["accurate", "balanced", "fast"]
31
 
@@ -42,42 +47,23 @@ def resolve(reg, model) -> str:
42
  return m
43
 
44
 
45
- def pct(e) -> str:
46
- """'0.177 % (0.0203 / 0.0250 fF)': every % with its MAE / RMSE."""
47
- return "n/a" if not e else f"{e['median_pct']:g} % ({e['mae_ff']:g} / {e['rmse_ff']:g} fF)"
48
-
49
-
50
- def numbers(t) -> list[str]:
51
- r = t.get("reference") or {}
52
- rows = [("paper, validation (4,608 layouts)", r.get("val")), ("paper, test in family (4,009)", r.get("test_infamily")),
53
- ("paper, test zero-shot macro (1,878)", r.get("test_zeroshot")), ("paper, held-out family (4,071)", r.get("heldout_family")),
54
- ("paper, held-out family: physics alone", r.get("heldout_family_physics")),
55
- ("paper, validation: " + (r.get("val_same_surrogate") or {}).get("note", ""), r.get("val_same_surrogate")),
56
- ("B5 fresh check (39 new layouts, never seen)", t.get("b5")),
57
- (f"B5: {(t.get('b5_physics') or {}).get('name', 'physics alone')}", t.get("b5_physics"))]
58
- out = [f"| {k} | {pct(v)} |" for k, v in rows if v]
59
- if t.get("time_space"):
60
- out.append(f"| time on this Space (2 vCPU) | {t['time_space']} |")
61
- if t.get("time_x86"):
62
- out.append(f"| time, x86 cluster node | {t['time_x86']} |")
63
- return ["| reference | layout-mean median % (MAE / RMSE fF) |", "|---|---|"] + out
64
-
65
-
66
- def tier_md(reg, k) -> str:
67
- t = FS.tiers(reg)[k]
68
- lines = [f"**{t['title']}**", "", t.get("summary", "")]
69
- if t.get("warning"):
70
- lines += ["", f"> **Warning.** {t['warning']}"]
71
- lines += ["", f"Reference recipe: {(t.get('reference') or {}).get('recipe', '')}.", "", *numbers(t), "",
72
- "These networks are trained on all 45,771 on-stack layouts, so they have no held-out score of their own: the paper rows are "
73
- "the same recipe trained on the TRAIN split; B5 is one fresh check (one generated family, 3-4 conductors). Layout-mean median "
74
- "relative error over mutual entries against Q3D, 0.1 fF floor."]
75
- e = t.get("embedding") or {}
76
- if e.get("far_k"):
77
- lines += ["", f"Speed: the pair vectors use far-sample decimation (blocks of {int(e['far_k'])} boundary samples farther than "
78
- f"{float(e.get('d_far_um', 100.0)):g} µm from the other conductor are represented by one sample); it ties the exact embedding "
79
- "on the paper's 4,608 validation layouts and the 1-, 5- and 9-qubit lattices. The paper Space keeps the exact embedding."]
80
- return "\n".join(lines)
81
 
82
 
83
  def _predict(lay, model, substrate, thickness_um):
@@ -98,41 +84,50 @@ def _predict(lay, model, substrate, thickness_um):
98
 
99
 
100
  def report_md(res: dict, reg) -> str:
 
 
101
  t = res["timing_s"]
102
  st = res.get("prior_stack")
103
  lv = res.get("levels_ppg") or []
104
- lines = [f"**Tier** `{res['tier']}`: {res['tier_title']}, {res['package_version']}, registry v{res['registry_version']}",
105
- "**Physics** " + (f"thin-film solves at {', '.join(f'{p:g}' for p in lv)} panels per gap, prior `{st['name']}` "
106
- f"(patches {st['patches'] or 'none'}, solver `{st['mode']}`)" if st else "learned prior surrogate (no field solve)"),
107
- A.substrate_line(res),
108
- "**Timing** " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in t.items() if isinstance(v, float)) + f" ({t.get('threads')} threads)",
109
- f"**Physical checks** symmetric (max |C - Cᵀ| {res['checks']['symmetric_max_abs']:.2g} fF), off-diagonals negative: "
110
- f"{res['checks']['offdiag_all_negative']}, smallest eigenvalue of the signal block {res['checks']['signal_block_min_eig']:.4g} fF",
111
- "", tier_md(reg, res["tier"])]
112
- if res["warnings"]:
113
- lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]]
114
- lines += ["", f"Self capacitance: {res['self_capacitance']}.", "Planar single-layer layouts only (zero-thickness metal). Uploads are held in memory "
115
- "only while the Space is running, to speed up repeat requests; nothing is written to permanent storage."]
 
116
  return "\n".join(lines)
117
 
118
 
119
- def predict_fn(f, table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness, model):
120
  reg = load_registry()
121
- lay = _prepare(f, table, crop, margin_gaps, margin_um, select)
122
  res = _predict(lay, model, _eps(substrate, custom_eps), float(thickness))
 
123
  d = _outdir()
124
- (d / "capacitance_fF.csv").write_text(matrix_csv(res))
125
  (d / "capacitance.json").write_text(json.dumps(res, indent=1, default=float))
126
- return matrix_table(res), str(d / "capacitance_fF.csv"), str(d / "capacitance.json"), report_md(res, reg), res
 
 
 
 
127
 
128
 
129
  def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps=0.0, substrate="Si (cryogenic, training)",
130
- custom_eps=11.45, thickness_um=350.0, model="accurate"):
131
  t = time.perf_counter()
132
  lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers),
133
- margin_gaps=_margin_api(margin_gaps), max_conductors=LIMITS["max_conductors"])
134
  res = _predict(lay, model, _eps(substrate, custom_eps), float(thickness_um))
135
  res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t
 
136
  return res
137
 
138
 
@@ -143,102 +138,325 @@ def models_fn():
143
  for k in served(reg):
144
  t = FS.tiers(reg)[k]
145
  out.append({"id": k, "title": t["title"], "summary": t.get("summary"), "warning": t.get("warning"), "reference": t.get("reference") or {},
146
- "b5": t.get("b5"), "b5_physics": t.get("b5_physics"), "time_space": t.get("time_space"), "time_x86": t.get("time_x86"),
147
  "stack": t.get("stack"), "levels_ppg": [float(p) for p in t.get("ppg") or []], "default": k == h["default_arm"],
148
  "max_conductors": int(h["max_conductors"])})
149
  from . import paper as PA
150
  return out + [{"geomgnn_version": __version__, "tlsq_infer_version": TLSQ_VERSION, "registry_version": reg["version"],
151
- "training_layouts": h.get("training_layouts"), "paper_space": h.get("paper_space"), "startup": dict(PA.STARTUP)}]
 
152
 
153
 
154
- def header(reg) -> str:
 
155
  h = reg["flagship_hub"]
156
- ps = h.get("paper_space")
157
- return ("Full **Maxwell capacitance matrix** (fF, self terms included) of a planar superconducting layout from its GDS. Three tiers, "
158
- "each the best recipe of the paper at its speed, **retrained on all 45,771 on-stack Q3D layouts** (Si, eps_r 11.45, 350 µm): "
159
- "**Accurate** (default, ~1 s: two thin-film solves + networks), **Balanced** (~0.5 s: a coarser solve pair + networks; about 2x "
160
- "faster at 1.5-1.7x the error) and **Fast** (~0.1 s: a learned prior, no field solve; quick screening of the trained component "
161
- "families only, worse than the physics alone on new designs). Use **Accurate** for anything that matters. Trained on everything, "
162
- "these models have no held-out score of their own: each tier shows the paper's held-out numbers for the same recipe and one fresh "
163
- f"check on 39 never-seen layouts. To reproduce the paper, use [{ps}](https://huggingface.co/spaces/{ps}). **Private preview**.")
164
 
165
 
166
- def build_app(title: str, examples_dir=None):
167
- import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  reg = load_registry()
170
  subs = list(reg.substrates()) + [CUSTOM]
171
  ms = served(reg)
172
  default = reg["flagship_hub"]["default_arm"]
173
  ex = sorted(Path(examples_dir).glob("*.gds")) if examples_dir and Path(examples_dir).exists() else []
174
- label = {"accurate": "Accurate (~1 s, default)", "balanced": "Balanced (~0.5 s)", "fast": "Fast (~0.1 s; trained families only)"}
175
- with gr.Blocks(title=title, delete_cache=(60, PURGE_AGE_S)) as demo:
176
- gr.Markdown(f"# {title}\n{header(reg)}")
177
- with gr.Accordion("Planar circuits and the layer convention", open=False):
178
- gr.Markdown(INTRO.replace("A thin-film method-of-moments solve\nprovides a physics prior and a graph network trained on 40,153 Q3D simulations corrects it.",
179
- "See the tier descriptions below."))
180
- gr.Markdown("## Tier")
181
- model = gr.Radio([(label.get(k, k), k) for k in ms], value=default, label="model", interactive=True)
182
- model_info = gr.Markdown(tier_md(reg, default))
183
- model.change(lambda k: tier_md(reg, k), model, model_info, api_visibility="private")
184
- gr.Markdown("## 1. Upload a GDS and assign layer roles")
185
  with gr.Row():
186
  with gr.Column(scale=1):
187
  gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"])
188
  if ex:
189
- gr.Examples([[str(p)] for p in ex], inputs=[gds], label="or start from an example")
190
- layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"],
191
- label="detected layers: edit 'role' (ground / conductor / ignore)", interactive=True,
192
- value=[[1, 0, "ground", 0, 0, ""], [1, 10, "conductor", 0, 0, ""]])
193
- layer_plot = gr.Plot(label="layers")
194
- gr.Markdown("## 2. Prepare: extract the nets (full ground, as in training)")
195
- with gr.Row():
 
 
 
 
 
 
 
196
  with gr.Column(scale=1):
197
- select = gr.Textbox(label="conductors to model (e.g. 1,2,3; empty = all)", value="")
198
- with gr.Accordion("Advanced: crop the ground (not the training geometry)", open=False):
199
- crop = gr.Checkbox(False, label="crop the ground plane around the conductors")
200
- margin = gr.Slider(0, 300, value=0, step=1, label="margin in conductor-ground gaps (0 = auto window)")
201
- margin_um = gr.Number(value=None, label="or absolute margin (µm); overrides the slider")
202
- prep_btn = gr.Button("Prepare", variant="secondary")
203
- warn_md = gr.Markdown()
204
- summary = gr.JSON(label="prepared layout")
205
- prepared_gds = gr.File(label="simplified GDS (1/0 ground, 1/10 conductors)")
206
- prep_plot = gr.Plot(label="prepared layout")
207
- gr.Markdown("## 3. Substrate\nTraining stack: Si, eps_r 11.45, 350 µm. On other substrates the physics prior is solved at your eps_r and "
208
- "thickness and the networks correct it unchanged (calibrated route; tested on Si at 10-1000 µm and eps_r 3.8-24 at 350 µm: "
209
- "0.21-1.02 % (MAE 0.07-0.33, RMSE 0.09-0.45 fF) on 15 held-out designs, against 0.23 % (0.080 / 0.111 fF) on the "
210
- "training stack; self terms up to 1.22 % (0.79 / 0.86 fF)). Fast does not solve a prior: off the stack it rescales its "
211
- "training-stack prediction by (1+eps)/(1+11.45) and warns.")
212
- with gr.Row():
213
- substrate = gr.Dropdown(subs, value=subs[0], label="substrate")
214
- custom_eps = gr.Number(value=11.45, label="custom eps_r (when 'custom')")
215
- thickness = gr.Number(value=350, label="substrate thickness (µm)")
 
 
 
 
 
 
216
  pred_btn = gr.Button("Predict", variant="primary")
217
- gr.Markdown("## 4. Maxwell capacitance matrix (fF)")
218
- with gr.Row():
219
  with gr.Column(scale=2):
220
- mat = gr.Dataframe(label="Maxwell matrix (fF): diagonal = self, off-diagonal = -mutual", interactive=False)
 
 
221
  with gr.Column():
222
- csv_f = gr.File(label="CSV")
223
  json_f = gr.File(label="JSON (matrix + metadata)")
224
- report = gr.Markdown()
 
 
 
225
  res_state = gr.State(None)
 
226
  with gr.Row(visible=False):
227
  a_g = gr.Textbox("1/0")
228
  a_c = gr.Textbox("1/10")
229
  a_m = gr.Number(0)
 
230
  a_out = gr.JSON()
231
  a_btn = gr.Button("api")
232
  m_btn = gr.Button("models")
233
  m_out = gr.JSON()
234
- gds.upload(_safe(inspect_fn, 2), gds, [layers, layer_plot], api_name="inspect")
235
- prep_btn.click(_safe(prepare_fn, 4), [gds, layers, crop, margin, margin_um, select], [prep_plot, warn_md, summary, prepared_gds],
236
- api_name="prepare")
237
- pred_btn.click(_safe(predict_fn, 5), [gds, layers, crop, margin, margin_um, select, substrate, custom_eps, thickness, model],
238
- [mat, csv_f, json_f, report, res_state], api_name="predict")
239
- a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model], a_out, api_name="predict_gds")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  m_btn.click(models_fn, None, m_out, api_name="models")
241
- gr.Markdown(f"<small>geomgnn {__version__}, tlsq_infer {TLSQ_VERSION}. Demo-server caps (not limits of the models): "
242
- f"{LIMITS['max_file_mb']:g} MB per file, {LIMITS['max_polygons']:,} polygons, {reg['flagship_hub']['max_conductors']} conductors "
243
- "+ ground. One request runs at a time; a 66-qubit lattice takes minutes on Accurate.</small>")
244
  return demo
 
6
  /inspect (gds file) -> layer table, layer plot
7
  /prepare (gds, layers table, crop, margin_gaps, margin_um, select) -> preview, warnings, summary, simplified GDS
8
  /predict (gds, layers table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness_um, model) -> matrix, CSV, JSON, report
9
+ /predict_gds (gds, ground "1/0", conductor "1/10", margin_gaps, substrate, custom_eps, thickness_um, model, ground_pieces "") -> result dict;
10
+ model = accurate (default) | balanced | fast; ground_pieces = e.g. "1,4" when ground and conductors share one layer
11
+ (default "": detected automatically, see result warnings / layout info)
12
  """
13
 
14
  from __future__ import annotations
15
 
16
+ import html
17
  import json
18
  import time
19
  from pathlib import Path
20
 
21
  from tlsq_infer import __version__ as TLSQ_VERSION
22
+ import gradio as gr
23
+ from tlsq_infer.app_ui import CUSTOM, HEAVY, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fn
24
  from tlsq_infer.app_v2 import PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fn
25
  from tlsq_infer.layout import LayoutError, prepare
26
  from tlsq_infer.predict import matrix_csv
 
28
 
29
  from . import __version__
30
  from . import api as A
31
+ from . import ground_ui as GU
32
  from . import flagship as FS
33
+ from . import ui as UI
34
 
35
  ORDER = ["accurate", "balanced", "fast"]
36
 
 
47
  return m
48
 
49
 
50
+ def tiers_md(reg) -> str:
51
+ """The tier accordion: one row per served tier with its one fresh check (B5) against the physics alone; the full tables are on
52
+ the model card."""
53
+ rows = [f"| **{UI.md(t['title'].split(':')[0])}** | {UI.md(t['title'].split(':', 1)[-1].strip())} | "
54
+ f"{UI.pct(t['b5']) if t.get('b5') else 'n/a'} | {UI.pct(t['b5_physics']) if t.get('b5_physics') else 'n/a'} |"
55
+ for t in (FS.tiers(reg)[k] for k in served(reg))]
56
+ sid = reg["flagship_hub"]["space"]
57
+ return "\n".join(["| tier | method | error on new designs (B5) | physics alone (B5) |", "|---|---|---|---|", *rows, "",
58
+ f"These networks are trained on all {int(reg['flagship_hub']['training_layouts']):,} on-stack Q3D layouts, so their "
59
+ "one held-out check is B5: 39 layouts of one generated family (3-4 conductors) that no component ever saw. Layout-mean "
60
+ "median relative error over the mutual entries against Q3D. In-sample fits, the paper's held-out numbers and timings: "
61
+ f"[model card](https://huggingface.co/spaces/{sid}/blob/main/README.md)."])
62
+
63
+
64
+ def expected(reg, k) -> str | None:
65
+ b5 = FS.tiers(reg)[k].get("b5")
66
+ return f"Expected error on a new design of a trained family: {UI.pct(b5)}; B5 fresh check, 39 never-seen layouts." if b5 else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
 
69
  def _predict(lay, model, substrate, thickness_um):
 
84
 
85
 
86
  def report_md(res: dict, reg) -> str:
87
+ """Run details under the matrix. The physical checks, the off-stack route and the expected error are in the callout above the
88
+ matrix and the ground-self-term flag in the matrix note, so they are not repeated here."""
89
  t = res["timing_s"]
90
  st = res.get("prior_stack")
91
  lv = res.get("levels_ppg") or []
92
+ sub = (res.get("substrate_route") or {}).get("route", "training stack")
93
+ lines = [f"- **Tier** {UI.md(res['tier_title'].split(':')[0])}; {res['package_version']}, registry v{res['registry_version']}",
94
+ "- **Physics** " + (f"thin-film solves at {', '.join(f'{p:g}' for p in lv)} panels per gap, prior `{st['name']}` "
95
+ f"(patches {', '.join(st['patches'] or []) or 'none'}, solver `{st['mode']}`)" if st else
96
+ "learned prior surrogate (no field solve)")]
97
+ if sub == "training stack":
98
+ lines.append("- " + A.substrate_line(res))
99
+ lines.append("- **Timing** " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in t.items() if isinstance(v, float))
100
+ + f" ({t.get('threads')} threads)")
101
+ ws = [w for w in res["warnings"] if not (w.startswith("physical check failed") or w == A.FAST_WARNING or
102
+ w.startswith("substrate eps_r "))]
103
+ if ws:
104
+ lines += ["", "**Warnings**", ""] + [f"- {UI.md(w)}" for w in ws]
105
  return "\n".join(lines)
106
 
107
 
108
+ def predict_fn(f, table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness, model, gstate=None):
109
  reg = load_registry()
110
+ lay = _prepare(f, table, crop, margin_gaps, margin_um, select, GU.pieces_of(gstate))
111
  res = _predict(lay, model, _eps(substrate, custom_eps), float(thickness))
112
+ res["ground_detection"] = lay.info.get("ground_detection")
113
  d = _outdir()
114
+ (d / "capacitance_fF.csv").write_text(matrix_csv(res, corner="fF"))
115
  (d / "capacitance.json").write_text(json.dumps(res, indent=1, default=float))
116
+ return UI.matrix_view(res), str(d / "capacitance_fF.csv"), str(d / "capacitance.json"), report_md(res, reg), res
117
+
118
+
119
+ def prepare_gfn(f, table, crop, margin_gaps, margin_um, select, gstate=None):
120
+ return prepare_fn(f, table, crop, margin_gaps, margin_um, select, GU.pieces_of(gstate))
121
 
122
 
123
  def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps=0.0, substrate="Si (cryogenic, training)",
124
+ custom_eps=11.45, thickness_um=350.0, model="accurate", ground_pieces=""):
125
  t = time.perf_counter()
126
  lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers),
127
+ margin_gaps=_margin_api(margin_gaps), max_conductors=LIMITS["max_conductors"], ground_pieces=str(ground_pieces or "").strip() or None)
128
  res = _predict(lay, model, _eps(substrate, custom_eps), float(thickness_um))
129
  res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t
130
+ res["ground_detection"] = lay.info.get("ground_detection")
131
  return res
132
 
133
 
 
138
  for k in served(reg):
139
  t = FS.tiers(reg)[k]
140
  out.append({"id": k, "title": t["title"], "summary": t.get("summary"), "warning": t.get("warning"), "reference": t.get("reference") or {},
141
+ "own": t.get("own") or {}, "b5": t.get("b5"), "b5_physics": t.get("b5_physics"), "time_space": t.get("time_space"), "time_x86": t.get("time_x86"),
142
  "stack": t.get("stack"), "levels_ppg": [float(p) for p in t.get("ppg") or []], "default": k == h["default_arm"],
143
  "max_conductors": int(h["max_conductors"])})
144
  from . import paper as PA
145
  return out + [{"geomgnn_version": __version__, "tlsq_infer_version": TLSQ_VERSION, "registry_version": reg["version"],
146
+ "training_layouts": h.get("training_layouts"), "paper_space": None, "paper_models": paper_models(reg),
147
+ "startup": dict(PA.STARTUP)}]
148
 
149
 
150
+ def paper_models(reg) -> dict:
151
+ """The paper's models on Hugging Face (model repositories; there is no paper Space)."""
152
  h = reg["flagship_hub"]
153
+ return {"paper": h["paper_models"], "earlier_draft": sorted({m["repo_id"] for m in reg.models.values() if m.get("repo_id")})}
 
 
 
 
 
 
 
154
 
155
 
156
+ LEDE = "Full Maxwell capacitance matrix (fF) of a planar superconducting layout, from its GDS."
157
+ VIEWS = ["Layers", "Nets"]
158
+ EXAMPLE_NOTES = {"lattice_1q.gds": "≈20 s on Accurate", "lattice_5q.gds": "≈20 s on Accurate"}
159
+ LAYER_HELP = ("Set each layer's role (pick the layer, or click its row): **ground** = the ground plane, one net; **conductor** = metal "
160
+ "islands, each connected body one net (C1, C2, …); **ground+conductor** = both on one layer (the ground is detected); "
161
+ "**ignore** = markers, junctions, labels. Defaults: 1/0 ground, 1/10 conductor.")
162
+
163
+
164
+ def about_md(reg) -> str:
165
+ h = reg["flagship_hub"]
166
+ pm = paper_models(reg)
167
+ return f"""Planar layouts only: one metal layer of zero thickness on a dielectric substrate. Each tier corrects thin-film physics (Fast: a learned prior) with networks trained on Q3D. Private preview while the paper is in preparation.
168
+
169
+ **The paper's models** are model repositories on Hugging Face: [{pm['paper']}](https://huggingface.co/{pm['paper']}), and the earlier draft's [SQuADDS/2026PaperModels-*](https://huggingface.co/models?search=SQuADDS%2F2026PaperModels) ({len(pm['earlier_draft'])} repositories).
170
+
171
+ **This demo server** takes up to {LIMITS['max_file_mb']:g} MB per file, {LIMITS['max_polygons']:,} polygons and {h['max_conductors']} conductors + ground, one request at a time (a 66-qubit lattice takes minutes on Accurate). These are caps of the server, not of the models.
172
+
173
+ **API** (gradio_client; "Use via API" below lists every endpoint):
174
+
175
+ ```python
176
+ from gradio_client import Client, handle_file
177
+ c = Client("{h['space']}", token=HF_TOKEN) # token while the Space is private
178
+ r = c.predict(handle_file("layout.gds"), "1/0", "1/10", 0, "Si (cryogenic, training)", 11.45, 350, "{h['default_arm']}",
179
+ api_name="/predict_gds")
180
+ r["names"], r["matrix_fF"]
181
+ ```
182
+
183
+ Arguments: GDS, ground layers, conductor layers, crop margin in gaps (0 = training geometry), substrate, eps_r (custom substrate), thickness (µm), tier ({', '.join(served(reg))}), ground pieces ("" = automatic, for ground and conductors on one layer).
184
+
185
+ **Privacy.** Uploads are held in memory only while the Space runs, to answer repeat requests; nothing is written to permanent storage.
186
+
187
+ <small>geomgnn {__version__}, tlsq_infer {TLSQ_VERSION}, registry v{reg['version']}.</small>"""
188
+
189
+
190
+ def _stem(f) -> str:
191
+ return Path(_path(f)).stem
192
+
193
+
194
+ def _roles_label(table) -> str:
195
+ rows = UI._rows(table)
196
+ s = [f"{UI._key(r)} {r[2]}" for r in rows]
197
+ return "Layers: " + " · ".join(s[:4]) + (f" · {len(s) - 4} more" if len(s) > 4 else "")
198
 
199
+
200
+ def _default_layers(table) -> bool:
201
+ """True when the file has the convention's 1/0 ground and 1/10 conductors, or one shared layer (the ground check covers it)."""
202
+ rows = UI._rows(table)
203
+ roles = {UI._key(r): str(r[2]) for r in rows}
204
+ return (roles.get("1/0") == "ground" and roles.get("1/10") == "conductor") or any("+" in v for v in roles.values())
205
+
206
+
207
+ def layers_view(f):
208
+ table, fig = inspect_fn(f)
209
+ return table, UI.fig_files(fig, _outdir(), f"{_stem(f)}_layers")
210
+
211
+
212
+ def _size(b) -> str:
213
+ return f"{b[2] - b[0]:,.0f} × {b[3] - b[1]:,.0f} µm"
214
+
215
+
216
+ def _names(names) -> str:
217
+ return ", ".join(names) if len(names) <= 6 else f"{names[0]} … {names[-1]}"
218
+
219
+
220
+ def nets_caption(lay, full_ground=None, select="") -> str:
221
+ """What Predict will model: the nets, the ground extent (before / after the crop) and the subset."""
222
+ n_all = int(lay.info.get("n_bodies_total") or lay.n_conductors)
223
+ lines = [f"Nets numbered as in the matrix: G and {_names(lay.names)}."]
224
+ if lay.window is not None and full_ground and _size(full_ground) == _size(lay.ground.bounds):
225
+ lines.append(f"Crop window (dashed, margin {lay.info['margin_um']:,.0f} µm) holds the whole ground plane, "
226
+ f"{_size(full_ground)}: nothing is cut.")
227
+ elif lay.window is not None:
228
+ lines.append(f"Ground cropped from {_size(full_ground)} to {_size(lay.ground.bounds)} (dashed window, margin "
229
+ f"{lay.info['margin_um']:,.0f} µm): not the training geometry." if full_ground else
230
+ f"Ground cropped to {_size(lay.ground.bounds)} (dashed window).")
231
+ else:
232
+ lines.append(f"Full ground plane, {_size(lay.ground.bounds)} (the training geometry).")
233
+ if lay.n_conductors < n_all:
234
+ sel = ", ".join(f"C{x.strip()}" for x in str(select).split(",") if x.strip())
235
+ lines.append(f"Modelling {lay.n_conductors} of {n_all} conductors ({sel}; {_names(lay.names)} in the matrix). Hatched = "
236
+ "not modelled.")
237
+ return "".join(f"<p class='tl-note'>{html.escape(x)}</p>" for x in lines)
238
+
239
+
240
+ def nets_view(f, table, crop, margin_gaps, margin_um, select, gstate):
241
+ """The extracted nets, labelled as the matrix: G (ground, or G #k pieces on a shared layer) and C1, C2, ...; the crop window and
242
+ the unmodelled bodies when cropped or a subset is selected. Returns ((png, svg), warnings, caption, prepared-layout key)."""
243
+ import matplotlib
244
+ matplotlib.use("Agg")
245
+ from matplotlib.lines import Line2D
246
+ from matplotlib.patches import Patch
247
+
248
+ from . import respcache
249
+ pieces = GU.pieces_of(gstate)
250
+ lay = _prepare(f, table, crop, margin_gaps, margin_um, select, pieces)
251
+ full = _prepare(f, table, False, 0, None, select, pieces).ground.bounds if lay.window is not None else None
252
+ fig = lay.render(compact=lay.n_conductors > 12)
253
+ ax = fig.axes[0]
254
+ if not lay.info.get("ground_detection") and not lay.ground.is_empty:
255
+ q = lay.ground.representative_point()
256
+ ax.annotate("G", (q.x, q.y), ha="center", va="center", fontsize=11, weight="bold", color="#111827",
257
+ bbox=dict(boxstyle="round,pad=0.2", fc="#e5e7eb", ec="#374151", lw=0.6))
258
+ keys = [Patch(fc="none", ec="#dc2626", hatch="///", label="not modelled")] if lay.extra_metal else []
259
+ if lay.window is not None:
260
+ keys.append(Line2D([], [], ls="--", color="#2563eb", lw=1.0, label="crop window"))
261
+ if keys:
262
+ ax.legend(handles=keys, loc="upper center", bbox_to_anchor=(0.5, -0.11), ncol=len(keys), frameon=False, fontsize=9)
263
+ fig.tight_layout()
264
+ return (UI.fig_files(fig, _outdir(), f"{_stem(f)}_nets"), list(lay.warnings), nets_caption(lay, full, select),
265
+ respcache.key(lay))
266
+
267
+
268
+ def _alive(pair) -> bool:
269
+ return bool(pair) and all(Path(x).exists() for x in pair[:2])
270
+
271
+
272
+ def show_view(mode, vst, f, table, crop, margin_gaps, margin_um, select, gstate):
273
+ """(image, SVG button, message, state) for the chosen view; Nets runs the prepare step when its picture is missing or stale."""
274
+ vst = dict(vst or {})
275
+ if f is None:
276
+ return None, gr.update(visible=False, value=None), "", vst
277
+ try:
278
+ if mode == "Nets":
279
+ if not _alive(vst.get("nets")):
280
+ pair, warns, cap, key = nets_view(f, table, crop, margin_gaps, margin_um, select, gstate)
281
+ vst["nets"], vst["nets_key"] = [*pair, warns, cap], key
282
+ pair = vst["nets"]
283
+ msg = pair[3] + (UI.callout("warn", "Layout warnings", [html.escape(w) for w in pair[2]]) if pair[2] else "")
284
+ else:
285
+ if not _alive(vst.get("layers")):
286
+ vst["layers"] = list(layers_view(f)[1])
287
+ pair, msg = vst["layers"], ""
288
+ except Exception as e: # noqa: BLE001
289
+ vst["nets_key"] = None
290
+ return None, gr.update(visible=False, value=None), UI.error_html(e, "Could not extract the nets" if mode == "Nets" else
291
+ "Could not draw the layers"), vst
292
+ return pair[0], gr.update(visible=True, value=pair[1]), msg, vst
293
+
294
+
295
+ def refresh_view(mode, vst, *a):
296
+ """An input of the extraction changed: forget the Nets picture; redraw it when it is on screen."""
297
+ vst = dict(vst or {}, nets=None, nets_key=None)
298
+ if mode != "Nets":
299
+ return gr.update(), gr.update(), gr.update(), vst
300
+ return show_view(mode, vst, *a)
301
+
302
+
303
+ def preview_fn(mode, vst, f, *a):
304
+ """Options changed (crop, margins, subset): switch to the Nets view of exactly the layout Predict will model (≈0.1 s on the
305
+ examples, so it runs live)."""
306
+ if f is None:
307
+ return gr.update(), gr.update(), gr.update(), gr.update(), vst
308
+ return ("Nets", *refresh_view("Nets", vst, f, *a))
309
+
310
+
311
+ def upload_fn(f, mode):
312
+ """File change (upload, example, clear): layer table and roles, the Layers picture, the viewer bar."""
313
+ none = gr.update(choices=[], value=None)
314
+ off = gr.update(visible=False)
315
+ if f is None:
316
+ return [], off, off, "", none, gr.update(value=None), None, gr.update(visible=False, value=None), off, {}, ""
317
+ try:
318
+ table, pair = layers_view(f)
319
+ except Exception as e: # noqa: BLE001
320
+ return ([], off, off, UI.error_html(e, "Could not read this file"), none, gr.update(value=None), None,
321
+ gr.update(visible=False, value=None), off, {}, "")
322
+ keys = [UI._key(r) for r in table]
323
+ odd = not _default_layers(table)
324
+ lay_mode = mode != "Nets"
325
+ return (table, gr.update(visible=True, open=odd, label=_roles_label(table)), gr.update(visible=odd), "",
326
+ gr.update(choices=keys, value=keys[0] if keys else None), gr.update(value=table[0][2] if table else None),
327
+ pair[0] if lay_mode else gr.update(), gr.update(visible=True, value=pair[1]) if lay_mode else gr.update(),
328
+ gr.update(visible=True), {"layers": list(pair), "nets": None}, "")
329
+
330
+
331
+ def stack_note(reg, substrate, custom_eps, thickness) -> str:
332
+ try:
333
+ eps = float(custom_eps) if substrate == CUSTOM else float(reg.substrates()[substrate])
334
+ on = A.on_training_stack(eps, float(thickness))
335
+ except (TypeError, ValueError, KeyError):
336
+ return ""
337
+ if on:
338
+ return ""
339
+ return UI.callout("warn", "Off the training stack (Si, eps_r 11.45, 350 µm)", [
340
+ f"Accurate and Balanced solve the physics prior at your stack and the networks correct it unchanged; tested on {A.TESTED_RANGE}. "
341
+ "Fast rescales its prediction and warns."])
342
+
343
+
344
+ def build_app(title: str, examples_dir=None):
345
  reg = load_registry()
346
  subs = list(reg.substrates()) + [CUSTOM]
347
  ms = served(reg)
348
  default = reg["flagship_hub"]["default_arm"]
349
  ex = sorted(Path(examples_dir).glob("*.gds")) if examples_dir and Path(examples_dir).exists() else []
350
+ label = {"accurate": "Accurate (≈1 s, default)", "balanced": "Balanced (≈0.5 s)", "fast": "Fast (≈0.1 s; trained families only)"}
351
+ with UI.blocks(title, delete_cache=(60, PURGE_AGE_S)) as demo:
352
+ gr.HTML(UI.header(reg["flagship_hub"]["title"], LEDE), container=False, padding=False, elem_classes="tl-flush")
 
 
 
 
 
 
 
 
353
  with gr.Row():
354
  with gr.Column(scale=1):
355
  gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"])
356
  if ex:
357
+ demo.tl_examples = UI.examples(gds, ex, label="Examples", example_labels=[
358
+ p.name + (f" ({EXAMPLE_NOTES[p.name]})" if p.name in EXAMPLE_NOTES else "") for p in ex])
359
+ upload_msg = gr.HTML(elem_classes="tl-flush")
360
+ with gr.Accordion("Layers", open=False, visible=False) as layer_acc:
361
+ layer_help = gr.Markdown(LAYER_HELP, visible=False)
362
+ layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"], value=None,
363
+ label="layers in the file", show_label=False, interactive=False)
364
+ pick, role = UI.layer_editor()
365
+ with gr.Accordion("Options: model a subset, crop the ground", open=False):
366
+ select = gr.Textbox(label="conductors to model (e.g. 1,2,3; empty = all)", value="")
367
+ crop = gr.Checkbox(False, label="crop the ground plane around the conductors (not the training geometry)", elem_classes="tl-check")
368
+ with gr.Row(visible=False) as crop_row:
369
+ margin = gr.Slider(0, 300, value=0, step=1, label="margin in conductor-ground gaps (0 = auto window)")
370
+ margin_um = gr.Number(value=None, label="or absolute margin (µm); overrides the slider")
371
  with gr.Column(scale=1):
372
+ with gr.Row(visible=False, elem_classes="tl-viewbar") as viewbar:
373
+ view = gr.Radio(VIEWS, value=VIEWS[0], show_label=False, container=False, elem_id="tl-view", label="view", scale=0,
374
+ min_width=180)
375
+ svg_btn = gr.DownloadButton("Download SVG", value=None, size="sm", variant="secondary", visible=False, scale=0,
376
+ min_width=130)
377
+ img = gr.Image(type="filepath", interactive=False, show_label=False, label="layout", elem_id="tl-viewer", buttons=["download", "fullscreen"],
378
+ height=440, alt_text="The uploaded layout: by layer (Layers) or as the extracted nets G, C1, C2, … "
379
+ "numbered as the matrix (Nets).")
380
+ view_msg = gr.HTML(elem_classes="tl-flush")
381
+ gparts = GU.build()
382
+ gst = gparts[0]
383
+ with gr.Row(equal_height=False):
384
+ model = gr.Radio([(label.get(k, k), k) for k in ms], value=default, label="Tier", interactive=True, elem_id="tl-tier",
385
+ scale=3, min_width=300)
386
+ substrate = gr.Dropdown(subs, value=subs[0], label="substrate", scale=2, min_width=220)
387
+ custom_eps = gr.Number(value=11.45, label="eps_r", visible=False, scale=1, min_width=110)
388
+ thickness = gr.Number(value=350, label="thickness (µm)", scale=1, min_width=120)
389
+ sub_note = gr.HTML(elem_classes="tl-flush")
390
+ with gr.Accordion("Tiers and their accuracy", open=False):
391
+ gr.Markdown(tiers_md(reg))
392
+ fast_cb = None
393
+ if "fast" in ms:
394
+ gr.Markdown("**Fast** is for quick screening of the component families it was trained on; on new designs (B5) it "
395
+ "was worse than the physics alone (table above). Use Accurate for anything that matters.")
396
+ fast_cb = gr.Checkbox(False, label="Use Fast (≈0.1 s) instead of the tier above", elem_classes="tl-check")
397
  pred_btn = gr.Button("Predict", variant="primary")
398
+ status = gr.HTML(elem_classes="tl-flush")
399
+ with gr.Column(visible=False) as result_box, gr.Row():
400
  with gr.Column(scale=2):
401
+ mat = gr.Dataframe(label="Maxwell matrix (fF)", interactive=False, elem_classes=UI.MAT, pinned_columns=1,
402
+ buttons=["copy", "fullscreen"])
403
+ mat_note = gr.HTML(container=False, padding=False, elem_classes="tl-flush")
404
  with gr.Column():
405
+ csv_f = gr.File(label="CSV (fF, full precision)")
406
  json_f = gr.File(label="JSON (matrix + metadata)")
407
+ with result_box:
408
+ report = gr.Markdown()
409
+ with gr.Accordion("About", open=False):
410
+ gr.Markdown(about_md(reg))
411
  res_state = gr.State(None)
412
+ vst = gr.State({})
413
  with gr.Row(visible=False):
414
  a_g = gr.Textbox("1/0")
415
  a_c = gr.Textbox("1/10")
416
  a_m = gr.Number(0)
417
+ a_gp = gr.Textbox("")
418
  a_out = gr.JSON()
419
  a_btn = gr.Button("api")
420
  m_btn = gr.Button("models")
421
  m_out = gr.JSON()
422
+ i_btn = gr.Button("inspect")
423
+ p_btn = gr.Button("predict")
424
+ r_btn = gr.Button("prepare")
425
+ layer_plot = gr.Plot()
426
+ prep_plot = gr.Plot()
427
+ warn_md = gr.Markdown()
428
+ summary = gr.JSON()
429
+ prepared_gds = gr.File()
430
+ pins = [gds, layers, crop, margin, margin_um, select, substrate, custom_eps, thickness, model, gst]
431
+ pouts = [mat, csv_f, json_f, report, res_state]
432
+ vin = [view, vst, gds, layers, crop, margin, margin_um, select, gst]
433
+ vout = [img, svg_btn, view_msg, vst]
434
+ ui_predict = UI.predict_ui(predict_fn, lambda r: expected(reg, r["tier"]), note=True)
435
+ uouts = pouts + [status, result_box, mat_note]
436
+ hidden = dict(api_visibility="private", show_progress="hidden")
437
+ if fast_cb:
438
+ model.change(lambda k: gr.update(value=k == "fast"), model, fast_cb, **hidden)
439
+ fast_cb.input(lambda on: "fast" if on else default, fast_cb, model, **hidden)
440
+ substrate.change(lambda s: gr.update(visible=s == CUSTOM), substrate, custom_eps, **hidden)
441
+ for ev in (substrate.change, custom_eps.change, thickness.change):
442
+ ev(lambda s, e, t: stack_note(reg, s, e, t), [substrate, custom_eps, thickness], sub_note, **hidden)
443
+ crop.change(lambda c: gr.update(visible=bool(c)), crop, crop_row, **hidden)
444
+ up = gds.change(upload_fn, [gds, view], [layers, layer_acc, layer_help, upload_msg, pick, role, img, svg_btn, viewbar, vst, view_msg],
445
+ api_visibility="private")
446
+ view.input(show_view, vin, vout, api_visibility="private")
447
+ i_btn.click(_safe(inspect_fn, 2), gds, [layers, layer_plot], api_name="inspect")
448
+ edit = UI.wire_editor(layers, pick, role)
449
+ edit.then(lambda t: gr.update(label=_roles_label(t)), layers, layer_acc, **hidden)
450
+ r_btn.click(_safe(prepare_gfn, 4), [gds, layers, crop, margin, margin_um, select, gst], [prep_plot, warn_md, summary, prepared_gds],
451
+ api_name="prepare")
452
+ after = lambda ev: ev.then(refresh_view, vin, vout, **hidden) # noqa: E731
453
+ GU.wire(gds, layers, pred_btn, gparts, [up, edit], after=after).then(ui_predict, pins, uouts, api_visibility="private")
454
+ for ev in (crop.change, margin.change, margin_um.change, select.change):
455
+ ev(preview_fn, vin, [view] + vout, trigger_mode="always_last", **hidden)
456
+ pred_btn.click(ui_predict, pins, uouts, api_visibility="private")
457
+ p_btn.click(_safe(predict_fn, 5), pins, pouts, api_name="predict")
458
+ UI.mark_stale(res_state, status, mat, report, [gds.change, model.change, substrate.change, custom_eps.change, thickness.change,
459
+ select.change, crop.change, margin.change, margin_um.change, edit.then])
460
+ a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model, a_gp], a_out, api_name="predict_gds")
461
  m_btn.click(models_fn, None, m_out, api_name="models")
 
 
 
462
  return demo
geomgnn/app_gnn.py CHANGED
@@ -31,6 +31,7 @@ from tlsq_infer.registry import load_registry
31
 
32
  from . import __version__
33
  from . import api as A
 
34
 
35
  ALIASES = {"gnn": "GNN", "accurate": "GNN", "fast": "GNN-LP", "gnn-lp": "GNN-LP", "learned prior": "GNN-LP", "model": "E3",
36
  "physics": "C0", "physics only": "C0"}
@@ -252,7 +253,7 @@ def build_app(title: str, examples_dir=None):
252
  with gr.Column(scale=1):
253
  gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"])
254
  if ex:
255
- gr.Examples([[str(p)] for p in ex], inputs=[gds], label="or start from an example")
256
  layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"],
257
  label="detected layers: edit 'role' (ground / conductor / ignore)", interactive=True,
258
  value=[[1, 0, "ground", 0, 0, ""], [1, 10, "conductor", 0, 0, ""]])
 
31
 
32
  from . import __version__
33
  from . import api as A
34
+ from . import ui as UI
35
 
36
  ALIASES = {"gnn": "GNN", "accurate": "GNN", "fast": "GNN-LP", "gnn-lp": "GNN-LP", "learned prior": "GNN-LP", "model": "E3",
37
  "physics": "C0", "physics only": "C0"}
 
253
  with gr.Column(scale=1):
254
  gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"])
255
  if ex:
256
+ UI.examples(gds, ex, label="or start from an example")
257
  layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"],
258
  label="detected layers: edit 'role' (ground / conductor / ignore)", interactive=True,
259
  value=[[1, 0, "ground", 0, 0, ""], [1, 10, "conductor", 0, 0, ""]])
geomgnn/app_paper.py CHANGED
@@ -6,8 +6,9 @@ arm of the paper's ladder and routes tables that runs on a CPU (geomgnn.paper).
6
  /prepare (gds, layers table, crop, margin_gaps, margin_um, select) -> preview, warnings, summary, simplified GDS
7
  /predict (gds, layers table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness_um, arm, self_from_rows,
8
  trust_rule) -> matrix table, CSV, JSON, report
9
- /predict_gds (gds, ground "1/0", conductor "1/10", margin_gaps, substrate, custom_eps, thickness_um, arm, self_from_rows, trust_rule)
10
- -> result dict; arm = an id of /models (default "model")
 
11
  """
12
 
13
  from __future__ import annotations
@@ -17,7 +18,8 @@ import time
17
  from pathlib import Path
18
 
19
  from tlsq_infer import __version__ as TLSQ_VERSION
20
- from tlsq_infer.app_ui import CUSTOM, HEAVY, INTRO, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fn, matrix_table
 
21
  from tlsq_infer.app_v2 import NETWORK_CAP, PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fn
22
  from tlsq_infer.app_v2 import report_md as report_md_v2
23
  from tlsq_infer.layout import LayoutError, prepare
@@ -26,7 +28,9 @@ from tlsq_infer.registry import load_registry
26
 
27
  from . import __version__
28
  from . import api as A
 
29
  from . import paper as PA
 
30
 
31
  ROUTES = ["(d) good physics", "(c) cheap physics", "(b) learned physics", "(a) no physics", "baseline"]
32
 
@@ -89,9 +93,9 @@ def numbers(a) -> list[str]:
89
  def arm_md(reg, k) -> str:
90
  a = PA.arms(reg)[k]
91
  tabs = ", ".join((a.get("paper") or {}).get("tables") or [])
92
- lines = [f"**{a['paper_name']}** ({a.get('route')}; paper: {tabs}). {a.get('summary', '')}"]
93
  if a.get("warning"):
94
- lines.append(f"\n> **Warning.** {a['warning']}")
95
  lines += ["", *numbers(a), "", "Layout-mean median relative error over mutual entries against Q3D, 0.1 fF floor; MAE / RMSE in fF. "
96
  "Test = the paper's test benchmark, read once; validation = development data."]
97
  if a["kind"] == "final":
@@ -104,47 +108,71 @@ def arm_md(reg, k) -> str:
104
  return "\n".join(lines)
105
 
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  def report_md(res: dict, reg) -> str:
108
  a = PA.arms(reg)[res["arm"]]
109
  if a["kind"] == "final":
110
- return report_md_v2(res, reg)
111
  t = res["timing_s"]
112
  st = res.get("prior_stack")
113
  lv = res.get("levels_ppg") or []
114
- lines = [f"**Arm** `{res['arm']}`: {res['paper_name']} ({res['route']}), {res['package_version']}, registry v{res['registry_version']}",
115
- "**Physics** " + (f"thin-film solves at {', '.join(f'{p:g}' for p in lv)} panels per gap, prior `{st['name']}` "
116
- f"(patches {st['patches'] or 'none'}, solver `{st['mode']}`)" if st else
117
- "learned prior surrogate (no field solve)" if res.get("learned_prior_sha256") else "none (solver-free)"),
118
- A.substrate_line(res),
119
- "**Timing** " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in t.items() if isinstance(v, float))
 
120
  + f" ({t.get('threads')} threads)",
121
- f"**Physical checks** symmetric (max |C - Cᵀ| {res['checks']['symmetric_max_abs']:.2g} fF), off-diagonals negative: "
122
- f"{res['checks']['offdiag_all_negative']}, smallest eigenvalue of the signal block {res['checks']['signal_block_min_eig']:.4g} fF",
123
- "", arm_md(reg, res["arm"])]
124
  if res["warnings"]:
125
- lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]]
126
- lines += ["", f"Self capacitance: {res['self_capacitance']}.", "Planar single-layer layouts only (zero-thickness metal). Uploads are held in memory "
127
- "only while the Space is running, to speed up repeat requests; nothing is written to permanent storage."]
 
 
128
  return "\n".join(lines)
129
 
130
 
131
- def predict_fn(f, table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness, arm, self_rows, trust_rule=True):
132
  reg = load_registry()
133
- lay = _prepare(f, table, crop, margin_gaps, margin_um, select)
134
  res = _predict(lay, arm, _eps(substrate, custom_eps), float(thickness), self_from_rows=bool(self_rows), trust_rule=trust_rule)
 
135
  d = _outdir()
136
- (d / "capacitance_fF.csv").write_text(matrix_csv(res))
137
  (d / "capacitance.json").write_text(json.dumps(res, indent=1, default=float))
138
- return matrix_table(res), str(d / "capacitance_fF.csv"), str(d / "capacitance.json"), report_md(res, reg), res
 
 
 
 
139
 
140
 
141
  def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps=0.0, substrate="Si (cryogenic, training)",
142
- custom_eps=11.45, thickness_um=350.0, arm="model", self_from_rows=True, trust_rule=True):
143
  t = time.perf_counter()
144
  lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers),
145
- margin_gaps=_margin_api(margin_gaps), max_conductors=LIMITS["max_conductors"])
146
  res = _predict(lay, arm, _eps(substrate, custom_eps), float(thickness_um), self_from_rows=bool(self_from_rows), trust_rule=trust_rule)
147
  res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t
 
148
  return res
149
 
150
 
@@ -161,94 +189,133 @@ def models_fn():
161
  "checkpoints_repo": reg["paper_hub"].get("checkpoints_repo"), "startup": dict(PA.STARTUP)}]
162
 
163
 
 
 
 
 
 
164
  def header(reg) -> str:
165
  h = reg["paper_hub"]
166
- ck = h.get("checkpoints_repo")
167
- return ("Full **Maxwell capacitance matrix** of a planar superconducting layout from its GDS, with **every route of the paper that "
168
- "runs on a CPU**: the model, the fast model, the solver-free network, the cheap-physics networks, the mesh ladder of single "
169
- "solves and Richardson pairs, the extrapolated physics alone, the ablations and controls, the solver modes and the "
170
- "prior-generation baseline. Each arm shows its paper numbers (layout-mean median %, MAE / RMSE fF). Every other checkpoint the "
171
- f"paper reports (k-curves, learning curves, leave-one-family-out folds, the solver-free series, ...) with its training and "
172
- f"scoring scripts is in the model repository [{ck}](https://huggingface.co/{ck}). **Private preview** (paper in preparation).")
173
 
174
 
175
- def build_app(title: str, examples_dir=None):
176
- import gradio as gr
 
 
 
 
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  reg = load_registry()
179
  subs = list(reg.substrates()) + [CUSTOM]
180
  ms = served(reg)
181
  default = reg["paper_hub"]["default_arm"]
182
  ex = sorted(Path(examples_dir).glob("*.gds")) if examples_dir and Path(examples_dir).exists() else []
183
  choices = [(f"{PA.arms(reg)[k].get('route')}: {PA.arms(reg)[k]['paper_name']}", k) for k in ms]
184
- with gr.Blocks(title=title, delete_cache=(60, PURGE_AGE_S)) as demo:
185
- gr.Markdown(f"# {title}\n{header(reg)}")
186
- with gr.Accordion("Planar circuits and the layer convention", open=False):
187
- gr.Markdown(INTRO.replace("A thin-film method-of-moments solve\nprovides a physics prior and a graph network trained on 40,153 Q3D simulations corrects it.",
188
- "See the arm descriptions below."))
189
- gr.Markdown("## Arm (route of the paper)")
190
- model = gr.Dropdown(choices, value=default, label="arm", interactive=True)
191
- model_info = gr.Markdown(arm_md(reg, default))
192
- model.change(lambda k: arm_md(reg, k), model, model_info, api_visibility="private")
193
- gr.Markdown("## 1. Upload a GDS and assign layer roles")
194
  with gr.Row():
195
  with gr.Column(scale=1):
196
  gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"])
197
  if ex:
198
- gr.Examples([[str(p)] for p in ex], inputs=[gds], label="or start from an example (the lattices are the paper's 1-, 5- and 9-qubit layouts)")
199
- layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"],
200
- label="detected layers: edit 'role' (ground / conductor / ignore)", interactive=True,
201
- value=[[1, 0, "ground", 0, 0, ""], [1, 10, "conductor", 0, 0, ""]])
 
 
 
202
  layer_plot = gr.Plot(label="layers")
203
- gr.Markdown("## 2. Prepare: extract the nets (full ground, as in training)")
204
- with gr.Row():
205
- with gr.Column(scale=1):
206
- select = gr.Textbox(label="conductors to model (e.g. 1,2,3; empty = all)", value="")
207
- with gr.Accordion("Advanced: crop the ground (not the training geometry)", open=False):
208
- crop = gr.Checkbox(False, label="crop the ground plane around the conductors")
209
- margin = gr.Slider(0, 300, value=0, step=1, label="margin in conductor-ground gaps (0 = auto window)")
210
- margin_um = gr.Number(value=None, label="or absolute margin (µm); overrides the slider")
211
- prep_btn = gr.Button("Prepare", variant="secondary")
212
- warn_md = gr.Markdown()
213
- summary = gr.JSON(label="prepared layout")
214
- prepared_gds = gr.File(label="simplified GDS (1/0 ground, 1/10 conductors)")
215
- prep_plot = gr.Plot(label="prepared layout")
216
- gr.Markdown("## 3. Substrate\nTraining stack: Si, eps_r 11.45, 350 µm. On other substrates the physics prior is solved at your eps_r and "
217
- "thickness and the networks correct it unchanged (calibrated route; tested on Si at 10-1000 µm and eps_r 3.8-24 at 350 µm: "
218
- "0.21-1.02 % (MAE 0.07-0.33, RMSE 0.09-0.45 fF) on 15 held-out designs, against 0.23 % (0.080 / 0.111 fF) on the "
219
- "training stack; self terms up to 1.22 % (0.79 / 0.86 fF)). Fast does not solve a prior: off the stack it rescales its "
220
- "training-stack prediction by (1+eps)/(1+11.45) and warns.")
 
 
 
 
221
  with gr.Row():
222
- substrate = gr.Dropdown(subs, value=subs[0], label="substrate")
223
- custom_eps = gr.Number(value=11.45, label="custom eps_r (when 'custom')")
224
- thickness = gr.Number(value=350, label="substrate thickness (µm)")
225
- self_rows = gr.Checkbox(True, label="prior-generation baseline: self-capacitance from row sums")
226
- trust_cb = gr.Checkbox(bool(reg["final_defaults"].get("trust_rule", True)),
 
227
  label="prior-generation model: apply its trust rule (default on)")
228
  pred_btn = gr.Button("Predict", variant="primary")
229
- gr.Markdown("## 4. Maxwell capacitance matrix (fF)")
230
- with gr.Row():
 
231
  with gr.Column(scale=2):
232
- mat = gr.Dataframe(label="Maxwell matrix (fF): diagonal = self, off-diagonal = -mutual", interactive=False)
 
 
233
  with gr.Column():
234
- csv_f = gr.File(label="CSV")
235
  json_f = gr.File(label="JSON (matrix + metadata)")
236
- report = gr.Markdown()
 
237
  res_state = gr.State(None)
238
  with gr.Row(visible=False):
239
  a_g = gr.Textbox("1/0")
240
  a_c = gr.Textbox("1/10")
241
  a_m = gr.Number(0)
 
242
  a_out = gr.JSON()
243
  a_btn = gr.Button("api")
244
  m_btn = gr.Button("models")
245
  m_out = gr.JSON()
246
- gds.upload(_safe(inspect_fn, 2), gds, [layers, layer_plot], api_name="inspect")
247
- prep_btn.click(_safe(prepare_fn, 4), [gds, layers, crop, margin, margin_um, select], [prep_plot, warn_md, summary, prepared_gds],
 
 
 
 
 
 
 
 
 
 
248
  api_name="prepare")
249
- pred_btn.click(_safe(predict_fn, 5), [gds, layers, crop, margin, margin_um, select, substrate, custom_eps, thickness, model, self_rows, trust_cb],
250
- [mat, csv_f, json_f, report, res_state], api_name="predict")
251
- a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model, self_rows, trust_cb], a_out,
 
 
 
252
  api_name="predict_gds")
253
  m_btn.click(models_fn, None, m_out, api_name="models")
254
  gr.Markdown(f"<small>geomgnn {__version__}, tlsq_infer {TLSQ_VERSION}. Demo-server caps (not limits of the models): "
 
6
  /prepare (gds, layers table, crop, margin_gaps, margin_um, select) -> preview, warnings, summary, simplified GDS
7
  /predict (gds, layers table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness_um, arm, self_from_rows,
8
  trust_rule) -> matrix table, CSV, JSON, report
9
+ /predict_gds (gds, ground "1/0", conductor "1/10", margin_gaps, substrate, custom_eps, thickness_um, arm, self_from_rows, trust_rule,
10
+ ground_pieces "") -> result dict; arm = an id of /models (default "model"); ground_pieces = e.g. "1,4" when ground and
11
+ conductors share one layer (default "": detected automatically)
12
  """
13
 
14
  from __future__ import annotations
 
18
  from pathlib import Path
19
 
20
  from tlsq_infer import __version__ as TLSQ_VERSION
21
+ import gradio as gr
22
+ from tlsq_infer.app_ui import CUSTOM, HEAVY, INTRO, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fn
23
  from tlsq_infer.app_v2 import NETWORK_CAP, PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fn
24
  from tlsq_infer.app_v2 import report_md as report_md_v2
25
  from tlsq_infer.layout import LayoutError, prepare
 
28
 
29
  from . import __version__
30
  from . import api as A
31
+ from . import ground_ui as GU
32
  from . import paper as PA
33
+ from . import ui as UI
34
 
35
  ROUTES = ["(d) good physics", "(c) cheap physics", "(b) learned physics", "(a) no physics", "baseline"]
36
 
 
93
  def arm_md(reg, k) -> str:
94
  a = PA.arms(reg)[k]
95
  tabs = ", ".join((a.get("paper") or {}).get("tables") or [])
96
+ lines = [f"**{UI.md(a['paper_name'])}** ({a.get('route')}; paper: {tabs}). {UI.md(a.get('summary', ''))}"]
97
  if a.get("warning"):
98
+ lines.append(f"\n> **Warning.** {UI.md(a['warning'])}")
99
  lines += ["", *numbers(a), "", "Layout-mean median relative error over mutual entries against Q3D, 0.1 fF floor; MAE / RMSE in fF. "
100
  "Test = the paper's test benchmark, read once; validation = development data."]
101
  if a["kind"] == "final":
 
108
  return "\n".join(lines)
109
 
110
 
111
+ def expected(reg, k) -> str | None:
112
+ p = PA.arms(reg)[k].get("paper") or {}
113
+ for key, lab in (("test_zeroshot", "the paper's zero-shot test (1,878 layouts)"), ("heldout_family", "a held-out family (4,071 layouts)"),
114
+ ("val", "the paper's validation set (4,608 layouts)")):
115
+ if p.get(key):
116
+ return f"Expected error on a new design: {UI.pct(p[key])}, from {lab}."
117
+ return None
118
+
119
+
120
+ def arm_line(reg, k) -> str:
121
+ a = PA.arms(reg)[k]
122
+ e = expected(reg, k)
123
+ return f"**{UI.md(a['paper_name'])}**, route {a.get('route')}." + (f" {e}" if e else "")
124
+
125
+
126
  def report_md(res: dict, reg) -> str:
127
  a = PA.arms(reg)[res["arm"]]
128
  if a["kind"] == "final":
129
+ return UI.md(report_md_v2(res, reg))
130
  t = res["timing_s"]
131
  st = res.get("prior_stack")
132
  lv = res.get("levels_ppg") or []
133
+ c = res["checks"]
134
+ lines = [f"- **Arm** `{res['arm']}`: {UI.md(res['paper_name'])}, route {res['route']}; {res['package_version']}, registry v{res['registry_version']}",
135
+ "- **Physics** " + (f"thin-film solves at {', '.join(f'{p:g}' for p in lv)} panels per gap, prior `{st['name']}` "
136
+ f"(patches {', '.join(st['patches'] or []) or 'none'}, solver `{st['mode']}`)" if st else
137
+ "learned prior surrogate (no field solve)" if res.get("learned_prior_sha256") else "none (solver-free)"),
138
+ "- " + A.substrate_line(res),
139
+ "- **Timing** " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in t.items() if isinstance(v, float))
140
  + f" ({t.get('threads')} threads)",
141
+ f"- **Physical checks** max |C - Cᵀ| {c['symmetric_max_abs']:.2g} fF, off-diagonals negative: "
142
+ f"{'yes' if c['offdiag_all_negative'] else 'no'}, smallest eigenvalue of the signal block "
143
+ + (f"{c['signal_block_min_eig']:.4g} fF" if c.get("signal_block_min_eig") is not None else "n/a")]
144
  if res["warnings"]:
145
+ lines += ["", "**Warnings**", ""] + [f"- {UI.md(w)}" for w in res["warnings"]]
146
+ lines += ["", f"Self capacitance: {res['self_capacitance']}.", "",
147
+ "This arm's paper numbers: *How accurate is this arm?* in step 2. Planar single-layer layouts only (zero-thickness metal). "
148
+ "Uploads are held in memory only while the Space is running, to speed up repeat requests; nothing is written to "
149
+ "permanent storage."]
150
  return "\n".join(lines)
151
 
152
 
153
+ def predict_fn(f, table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness, arm, self_rows, trust_rule=True, gstate=None):
154
  reg = load_registry()
155
+ lay = _prepare(f, table, crop, margin_gaps, margin_um, select, GU.pieces_of(gstate))
156
  res = _predict(lay, arm, _eps(substrate, custom_eps), float(thickness), self_from_rows=bool(self_rows), trust_rule=trust_rule)
157
+ res["ground_detection"] = lay.info.get("ground_detection")
158
  d = _outdir()
159
+ (d / "capacitance_fF.csv").write_text(matrix_csv(res, corner="fF"))
160
  (d / "capacitance.json").write_text(json.dumps(res, indent=1, default=float))
161
+ return UI.matrix_view(res), str(d / "capacitance_fF.csv"), str(d / "capacitance.json"), report_md(res, reg), res
162
+
163
+
164
+ def prepare_gfn(f, table, crop, margin_gaps, margin_um, select, gstate=None):
165
+ return prepare_fn(f, table, crop, margin_gaps, margin_um, select, GU.pieces_of(gstate))
166
 
167
 
168
  def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps=0.0, substrate="Si (cryogenic, training)",
169
+ custom_eps=11.45, thickness_um=350.0, arm="model", self_from_rows=True, trust_rule=True, ground_pieces=""):
170
  t = time.perf_counter()
171
  lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers),
172
+ margin_gaps=_margin_api(margin_gaps), max_conductors=LIMITS["max_conductors"], ground_pieces=str(ground_pieces or "").strip() or None)
173
  res = _predict(lay, arm, _eps(substrate, custom_eps), float(thickness_um), self_from_rows=bool(self_from_rows), trust_rule=trust_rule)
174
  res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t
175
+ res["ground_detection"] = lay.info.get("ground_detection")
176
  return res
177
 
178
 
 
189
  "checkpoints_repo": reg["paper_hub"].get("checkpoints_repo"), "startup": dict(PA.STARTUP)}]
190
 
191
 
192
+ LEDE = ("Run every route of the paper that works on a CPU on your own planar layout and get its full Maxwell capacitance matrix in "
193
+ "fF. Start with <strong>the model</strong> (the default arm); each arm's paper numbers are under <em>How accurate is this "
194
+ "arm?</em>")
195
+
196
+
197
  def header(reg) -> str:
198
  h = reg["paper_hub"]
199
+ return UI.header(h["title"], LEDE, "Private preview (paper in preparation). Programmatic use: <code>/predict_gds</code> through "
200
+ "gradio_client (\"Use via API\" below).")
 
 
 
 
 
201
 
202
 
203
+ def routes_md(reg) -> str:
204
+ ck = reg["paper_hub"].get("checkpoints_repo")
205
+ return ("The arms: the model, the fast model, the solver-free network, the cheap-physics networks, the mesh ladder of single solves "
206
+ "and Richardson pairs, the extrapolated physics alone, the ablations and controls, the solver modes and the prior-generation "
207
+ "baseline. Every other checkpoint the paper reports (k-curves, learning curves, leave-one-family-out folds, the solver-free "
208
+ f"series, ...) with its training and scoring scripts is in the model repository [{ck}](https://huggingface.co/{ck}).")
209
 
210
+
211
+ def intro(reg) -> str:
212
+ return INTRO.replace("A thin-film method-of-moments solve\nprovides a physics prior and a graph network trained on 40,153 Q3D "
213
+ "simulations corrects it.", "Each arm is one route of the paper; most correct thin-film physics with networks "
214
+ "trained on Q3D.").replace(
215
+ "Any number of conductors (this free demo accepts up to 30; the models are validated up to 7 including ground, and larger "
216
+ "layouts get a warning).", f"This server takes up to {reg['paper_hub']['max_conductors']} conductors + ground "
217
+ f"({NETWORK_CAP} for the prior-generation network).")
218
+
219
+
220
+ SUBSTRATE_MD = ("Training stack: Si, eps_r 11.45, 350 µm. On other substrates the arms that solve physics solve it at your stack and the "
221
+ f"networks correct it unchanged (calibrated route), tested on {A.TESTED_RANGE}. Learned-prior arms rescale and warn; "
222
+ "the solver-free arm refuses other substrates.")
223
+
224
+
225
+ def build_app(title: str, examples_dir=None):
226
  reg = load_registry()
227
  subs = list(reg.substrates()) + [CUSTOM]
228
  ms = served(reg)
229
  default = reg["paper_hub"]["default_arm"]
230
  ex = sorted(Path(examples_dir).glob("*.gds")) if examples_dir and Path(examples_dir).exists() else []
231
  choices = [(f"{PA.arms(reg)[k].get('route')}: {PA.arms(reg)[k]['paper_name']}", k) for k in ms]
232
+ with UI.blocks(title, delete_cache=(60, PURGE_AGE_S)) as demo:
233
+ gr.HTML(header(reg), container=False, padding=False, elem_classes="tl-flush")
234
+ gr.Markdown("## 1. Upload a GDS")
 
 
 
 
 
 
 
235
  with gr.Row():
236
  with gr.Column(scale=1):
237
  gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"])
238
  if ex:
239
+ UI.examples(gds, ex, label="or start from an example (the lattices are the paper's 1-, 5- and 9-qubit layouts)")
240
+ upload_msg = gr.HTML(elem_classes="tl-flush")
241
+ layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"], value=None,
242
+ label="detected layers (choose each layer's role below, or click its row)", interactive=False)
243
+ pick, role = UI.layer_editor()
244
+ with gr.Accordion("Planar circuits and the layer convention", open=False):
245
+ gr.Markdown(intro(reg))
246
  layer_plot = gr.Plot(label="layers")
247
+ gparts = GU.build()
248
+ gst = gparts[0]
249
+ with gr.Accordion("Optional: preview the extracted nets, model a subset, crop the ground", open=False):
250
+ with gr.Row():
251
+ with gr.Column(scale=1):
252
+ select = gr.Textbox(label="conductors to model (e.g. 1,2,3; empty = all)", value="")
253
+ with gr.Accordion("Advanced: crop the ground (not the training geometry)", open=False):
254
+ crop = gr.Checkbox(False, label="crop the ground plane around the conductors", elem_classes="tl-check")
255
+ margin = gr.Slider(0, 300, value=0, step=1, label="margin in conductor-ground gaps (0 = auto window)")
256
+ margin_um = gr.Number(value=None, label="or absolute margin (µm); overrides the slider")
257
+ prep_btn = gr.Button("Preview the nets", variant="secondary")
258
+ warn_md = gr.Markdown()
259
+ summary = gr.JSON(label="extracted nets (summary)")
260
+ prepared_gds = gr.File(label="simplified GDS (1/0 ground, 1/10 conductors)")
261
+ prep_plot = gr.Plot(label="extracted nets: grey = ground, colours = conductors")
262
+ gr.Markdown("## 2. Arm and substrate")
263
+ model = gr.Dropdown(choices, value=default, label="Arm (route of the paper)", interactive=True)
264
+ model_info = gr.Markdown(arm_line(reg, default))
265
+ with gr.Accordion("How accurate is this arm?", open=False):
266
+ arm_info = gr.Markdown(arm_md(reg, default))
267
+ gr.Markdown(routes_md(reg))
268
+ gr.Markdown(SUBSTRATE_MD)
269
  with gr.Row():
270
+ substrate = gr.Dropdown(subs, value=subs[0], label="substrate", min_width=300)
271
+ custom_eps = gr.Number(value=11.45, label="eps_r (custom substrate)", interactive=False, min_width=160)
272
+ thickness = gr.Number(value=350, label="substrate thickness (µm)", min_width=160)
273
+ with gr.Accordion("Options of the prior-generation arms", open=False):
274
+ self_rows = gr.Checkbox(True, label="prior-generation baseline: self-capacitance from row sums", elem_classes="tl-check")
275
+ trust_cb = gr.Checkbox(bool(reg["final_defaults"].get("trust_rule", True)), elem_classes="tl-check",
276
  label="prior-generation model: apply its trust rule (default on)")
277
  pred_btn = gr.Button("Predict", variant="primary")
278
+ gr.Markdown("## 3. Maxwell capacitance matrix")
279
+ status = gr.HTML(UI.EMPTY, elem_classes="tl-flush")
280
+ with gr.Column(visible=False) as result_box, gr.Row():
281
  with gr.Column(scale=2):
282
+ mat = gr.Dataframe(label="Maxwell matrix (fF)", interactive=False, elem_classes=UI.MAT, pinned_columns=1,
283
+ buttons=["copy", "fullscreen"])
284
+ gr.HTML(UI.MATRIX_NOTE, container=False, padding=False, elem_classes="tl-flush")
285
  with gr.Column():
286
+ csv_f = gr.File(label="CSV (fF, full precision)")
287
  json_f = gr.File(label="JSON (matrix + metadata)")
288
+ with result_box:
289
+ report = gr.Markdown()
290
  res_state = gr.State(None)
291
  with gr.Row(visible=False):
292
  a_g = gr.Textbox("1/0")
293
  a_c = gr.Textbox("1/10")
294
  a_m = gr.Number(0)
295
+ a_gp = gr.Textbox("")
296
  a_out = gr.JSON()
297
  a_btn = gr.Button("api")
298
  m_btn = gr.Button("models")
299
  m_out = gr.JSON()
300
+ i_btn = gr.Button("inspect")
301
+ p_btn = gr.Button("predict")
302
+ pins = [gds, layers, crop, margin, margin_um, select, substrate, custom_eps, thickness, model, self_rows, trust_cb, gst]
303
+ pouts = [mat, csv_f, json_f, report, res_state]
304
+ ui_predict = UI.predict_ui(predict_fn, lambda r: expected(reg, r["arm"]))
305
+ model.change(lambda k: (arm_line(reg, k), arm_md(reg, k)), model, [model_info, arm_info], api_visibility="private",
306
+ show_progress="hidden")
307
+ substrate.change(lambda s: gr.update(interactive=s == CUSTOM), substrate, custom_eps, api_visibility="private", show_progress="hidden")
308
+ up = gds.change(UI.inspect_ui(inspect_fn), gds, [layers, layer_plot, upload_msg, pick, role], api_visibility="private")
309
+ i_btn.click(_safe(inspect_fn, 2), gds, [layers, layer_plot], api_name="inspect")
310
+ edit = UI.wire_editor(layers, pick, role)
311
+ prep_btn.click(_safe(prepare_gfn, 4), [gds, layers, crop, margin, margin_um, select, gst], [prep_plot, warn_md, summary, prepared_gds],
312
  api_name="prepare")
313
+ GU.wire(gds, layers, pred_btn, gparts, [up, edit]).then(ui_predict, pins, pouts + [status, result_box], api_visibility="private")
314
+ pred_btn.click(ui_predict, pins, pouts + [status, result_box], api_visibility="private")
315
+ p_btn.click(_safe(predict_fn, 5), pins, pouts, api_name="predict")
316
+ UI.mark_stale(res_state, status, mat, report, [gds.change, model.change, substrate.change, custom_eps.change, thickness.change,
317
+ select.change, self_rows.change, trust_cb.change, edit.then])
318
+ a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model, self_rows, trust_cb, a_gp], a_out,
319
  api_name="predict_gds")
320
  m_btn.click(models_fn, None, m_out, api_name="models")
321
  gr.Markdown(f"<small>geomgnn {__version__}, tlsq_infer {TLSQ_VERSION}. Demo-server caps (not limits of the models): "
geomgnn/flagship.py CHANGED
@@ -35,7 +35,7 @@ def predict(prepared, tier, reg, **kw) -> dict:
35
  res = PA.predict(prepared, tier, v, **kw)
36
  t = v["paper_arms"][tier]
37
  res.pop("paper", None)
38
- res.update(tier=tier, tier_title=t["title"], reference=t.get("reference") or {}, b5=t.get("b5"), b5_physics=t.get("b5_physics"))
39
  return res
40
 
41
 
 
35
  res = PA.predict(prepared, tier, v, **kw)
36
  t = v["paper_arms"][tier]
37
  res.pop("paper", None)
38
+ res.update(tier=tier, tier_title=t["title"], reference=t.get("reference") or {}, own=t.get("own") or {}, b5=t.get("b5"), b5_physics=t.get("b5_physics"))
39
  return res
40
 
41
 
geomgnn/ground_ui.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """'Check the ground' step of the Space apps, for layouts whose ground and conductors share one layer: the automatic pick
2
+ (tlsq_infer.layout.detect_ground) is shown on a numbered image; the user confirms it, or clicks shapes / edits the table to switch
3
+ pieces between ground and conductor. Predict stays disabled until the pick is confirmed."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import gradio as gr
8
+ import numpy as np
9
+ import shapely
10
+ from tlsq_infer.app_ui import _path, _roles
11
+ from tlsq_infer.layout import prepare
12
+
13
+ COLS = ["piece", "ground", "name", "area (µm²)", "bbox (µm)"]
14
+ PRED_LOCKED = "Predict (confirm the ground first)"
15
+
16
+
17
+ def _lay(st, pieces=None):
18
+ return prepare(st["path"], ground_layers=st["g"], conductor_layers=st["c"], ignore_layers=st["i"], ground_pieces=pieces,
19
+ max_conductors=10**6)
20
+
21
+
22
+ def _zoom(pieces) -> tuple | None:
23
+ """View box around every piece but the largest (normally the ground plane), when they fill a small part of the layout."""
24
+ big = int(np.argmax([g.area for g in pieces]))
25
+ full = shapely.union_all(pieces).bounds
26
+ b = shapely.union_all([g for i, g in enumerate(pieces) if i != big]).bounds
27
+ m = max(0.25 * max(b[2] - b[0], b[3] - b[1]), 0.03 * max(full[2] - full[0], full[3] - full[1]))
28
+ box = (max(b[0] - m, full[0]), max(b[1] - m, full[1]), min(b[2] + m, full[2]), min(b[3] + m, full[3]))
29
+ small = (box[2] - box[0]) * (box[3] - box[1]) < 0.5 * (full[2] - full[0]) * (full[3] - full[1])
30
+ return box if small and pieces[big].intersects(shapely.box(*box)) else None
31
+
32
+
33
+ def _title(st) -> str:
34
+ cur = ", ".join(f"#{i}" for i in st["current"])
35
+ if st["current"] == st["auto"]:
36
+ return f"ground = piece {cur} (automatic, confidence {st['confidence']})"
37
+ return f"ground = piece {cur} (your choice; automatic: {', '.join(f'#{i}' for i in st['auto'])})"
38
+
39
+
40
+ def _image(lay, st):
41
+ import matplotlib
42
+ matplotlib.use("Agg")
43
+ import matplotlib.pyplot as plt
44
+
45
+ fig = lay.render(figsize=(6.4, 6.4), compact=True, title=_title(st))
46
+ ax = fig.axes[0]
47
+ box = _zoom(st["pieces"])
48
+ if box:
49
+ ax.set_xlim(box[0], box[2])
50
+ ax.set_ylim(box[1], box[3])
51
+ ax.set_title(_title(st) + "\nzoomed to the conductors; the table lists every piece", fontsize=10)
52
+ view = shapely.box(*box)
53
+ for r in lay.info["ground_detection"]["pieces"]:
54
+ g = st["pieces"][r["id"] - 1]
55
+ if r["role"] == "ground" and not view.contains(shapely.Point(r["label_xy"])) and g.intersects(view):
56
+ q = g.intersection(view).representative_point()
57
+ ax.annotate(f"G #{r['id']}", (q.x, q.y), ha="center", va="center", fontsize=8, weight="bold", color="#111827",
58
+ bbox=dict(boxstyle="round,pad=0.2", fc="#e5e7eb", ec="#374151", lw=0.6))
59
+ fig.tight_layout()
60
+ fig.canvas.draw()
61
+ bb = ax.get_window_extent()
62
+ img = np.asarray(fig.canvas.buffer_rgba())[..., :3].copy()
63
+ tr = {"box": [bb.x0, bb.y0, bb.x1, bb.y1], "xlim": list(ax.get_xlim()), "ylim": list(ax.get_ylim()), "h": img.shape[0]}
64
+ plt.close(fig)
65
+ return img, tr
66
+
67
+
68
+ def to_um(tr, px, py) -> tuple[float, float]:
69
+ """Image pixel (origin top-left) -> layout µm."""
70
+ x0, y0, x1, y1 = tr["box"]
71
+ (a, b), (c, d) = tr["xlim"], tr["ylim"]
72
+ return a + (px - x0) / (x1 - x0) * (b - a), c + ((tr["h"] - py) - y0) / (y1 - y0) * (d - c)
73
+
74
+
75
+ def to_px(tr, x, y) -> tuple[float, float]:
76
+ x0, y0, x1, y1 = tr["box"]
77
+ (a, b), (c, d) = tr["xlim"], tr["ylim"]
78
+ return x0 + (x - a) / (b - a) * (x1 - x0), tr["h"] - (y0 + (y - c) / (d - c) * (y1 - y0))
79
+
80
+
81
+ def hit(pieces, x, y, tol_frac=0.015) -> int | None:
82
+ """1-based number of the piece under (x, y) µm, else of the nearest piece within tol_frac of the layout size."""
83
+ pt = shapely.Point(x, y)
84
+ d = [float(shapely.distance(g, pt)) for g in pieces]
85
+ b = shapely.union_all(pieces).bounds
86
+ k = int(np.argmin(d))
87
+ return k + 1 if d[k] <= tol_frac * max(b[2] - b[0], b[3] - b[1]) else None
88
+
89
+
90
+ def _md(st, lay) -> str:
91
+ gd = lay.info["ground_detection"]
92
+ cur = ", ".join(f"#{i}" for i in st["current"])
93
+ auto = ", ".join(f"#{i}" for i in st["auto"])
94
+ if st["current"] == st["auto"]:
95
+ head = f"**Ground found automatically: piece {cur}** (confidence **{st['confidence']}**)."
96
+ else:
97
+ head = f"**Your choice: ground = piece {cur}** (the automatic pick was {auto})."
98
+ low = "\n\n**Please check: the automatic pick is uncertain.**" if st["confidence"] == "low" and st["current"] == st["auto"] else ""
99
+ ok = "Ground confirmed: Predict uses this choice." if st["confirmed"] else "Not confirmed yet: Predict is locked until you confirm."
100
+ n = len(lay.names)
101
+ return (f"{head}{low}\n\nWhy the automatic pick: {st['reason']}.\n\nGrey = ground (G #k), coloured = conductors: conductor Ck is piece #k in the image, the table and the matrix "
102
+ f"({n} conductor{'s' if n != 1 else ''}, {gd['n_pieces']} pieces on layer "
103
+ f"{', '.join(f'{a}/{b}' for a, b in gd['layers'])}).\n\nIf this is right, press **Looks right → Predict**. Otherwise turn on "
104
+ f"**Fix it** and click a shape (or tick the table) to switch it between ground and conductor.\n\n_{ok}_")
105
+
106
+
107
+ def _rows(lay):
108
+ """Ground pieces first, then the conductors in piece order (piece #k = conductor Ck)."""
109
+ ps = sorted(lay.info["ground_detection"]["pieces"], key=lambda r: (r["role"] != "ground", r["id"]))
110
+ return [[r["id"], r["role"] == "ground", r["name"] or "", round(r["area_um2"], 1), "(" + ", ".join(f"{v:.0f}" for v in r["bbox_um"]) + ")"]
111
+ for r in ps]
112
+
113
+
114
+ def _view(st):
115
+ lay = _lay(st, st["current"])
116
+ img, st["tr"] = _image(lay, st)
117
+ return img, _md(st, lay), _rows(lay)
118
+
119
+
120
+ def _locked(st):
121
+ ok = st is None or st["confirmed"]
122
+ return gr.update(interactive=ok, value="Predict" if ok else PRED_LOCKED)
123
+
124
+
125
+ def check_fn(f, table):
126
+ """After upload / a layer-role edit: (group, image, text, table, state, predict button, fix mode)."""
127
+ hide = (gr.update(visible=False), None, "", [], None, gr.update(interactive=True, value="Predict"), False)
128
+ if f is None:
129
+ return hide
130
+ g, c, i = _roles(table)
131
+ st = {"path": _path(f), "g": g, "c": c, "i": i}
132
+ try:
133
+ lay = _lay(st)
134
+ except Exception: # noqa: BLE001 (the inspect step reports the file error inline)
135
+ return hide
136
+ gd = lay.info.get("ground_detection")
137
+ if not gd:
138
+ return hide
139
+ st.update(auto=gd["ground_pieces"], current=gd["ground_pieces"], reason=gd["reason"], confidence=gd["confidence"], history=[],
140
+ confirmed=False, pieces=lay.pieces)
141
+ img, md, rows = _view(st)
142
+ return gr.update(visible=True), img, md, rows, st, _locked(st), False
143
+
144
+
145
+ def _set(st, new):
146
+ new = sorted(set(new))
147
+ if not new:
148
+ gr.Warning("The ground needs at least one piece.")
149
+ elif len(new) == len(st["pieces"]):
150
+ gr.Warning("At least one piece must stay a conductor.")
151
+ elif new != st["current"]:
152
+ st["history"].append(st["current"])
153
+ st["current"], st["confirmed"] = new, False
154
+ img, md, rows = _view(st)
155
+ return img, md, rows, st, _locked(st)
156
+
157
+
158
+ def click_fn(st, fix, evt=None):
159
+ if st is None or evt is None:
160
+ raise gr.Error("upload a layout first")
161
+ if not fix:
162
+ gr.Info("Turn on 'Fix it' to change the roles by clicking.")
163
+ img, md, rows = _view(st)
164
+ return img, md, rows, st, _locked(st)
165
+ k = hit(st["pieces"], *to_um(st["tr"], *evt.index))
166
+ if k is None:
167
+ gr.Info("No shape there: click on a piece of metal.")
168
+ img, md, rows = _view(st)
169
+ return img, md, rows, st, _locked(st)
170
+ cur = set(st["current"])
171
+ return _set(st, cur ^ {k})
172
+
173
+
174
+ def select_fn(st, fix, evt: gr.SelectData):
175
+ return click_fn(st, fix, evt)
176
+
177
+
178
+ def table_fn(st, rows):
179
+ rows = rows.values.tolist() if hasattr(rows, "values") else rows
180
+ return _set(st, [int(r[0]) for r in rows if str(r[1]).strip().lower() in ("true", "1", "yes")])
181
+
182
+
183
+ def undo_fn(st):
184
+ if st and st["history"]:
185
+ st["current"], st["confirmed"] = st["history"].pop(), False
186
+ img, md, rows = _view(st)
187
+ return img, md, rows, st, _locked(st)
188
+
189
+
190
+ def reset_fn(st):
191
+ return _set(st, st["auto"])
192
+
193
+
194
+ def confirm_fn(st):
195
+ if st is not None:
196
+ st["confirmed"] = True
197
+ return _md(st, _lay(st, st["current"])), st, _locked(st)
198
+ return "", st, gr.update(interactive=True, value="Predict")
199
+
200
+
201
+ def pieces_of(st):
202
+ """ground_pieces for prepare: the confirmed choice, or None (automatic) when there is no check step."""
203
+ return None if st is None else list(st["current"])
204
+
205
+
206
+ def build():
207
+ """The step's components, created inside the current Blocks (hidden until a layout needs the check)."""
208
+ st = gr.State(None)
209
+ with gr.Column(visible=False, variant="panel") as box:
210
+ gr.Markdown("## Check the ground\nGround and conductors are on the same layer, so the ground was picked automatically. "
211
+ "Check it before predicting.")
212
+ with gr.Row():
213
+ with gr.Column(scale=3, min_width=300):
214
+ img = gr.Image(label="pieces (grey = ground, coloured = conductors)", type="numpy", interactive=False,
215
+ show_label=False, buttons=["download", "fullscreen"], elem_id="tl-ground-img",
216
+ alt_text="Layout pieces, numbered: grey = ground, coloured = conductors. With 'Fix it' on, click a "
217
+ "piece to switch it between ground and conductor; the table below does the same.")
218
+ with gr.Column(scale=2, min_width=280):
219
+ info = gr.Markdown()
220
+ confirm = gr.Button("Looks right → Predict", variant="primary")
221
+ fix = gr.Checkbox(False, label="Fix it: click a shape to switch it between ground and conductor", elem_classes="tl-check")
222
+ with gr.Row(elem_classes="tl-touch"):
223
+ undo = gr.Button("Undo", variant="secondary", size="sm")
224
+ reset = gr.Button("Reset to automatic", variant="secondary", size="sm")
225
+ gr.HTML("<style>#ground-pieces .select-all-checkbox{display:none !important}</style>", container=False, padding=False)
226
+ table = gr.Dataframe(headers=COLS, elem_id="ground-pieces", show_search="none", datatype=["number", "bool", "str", "number", "str"], interactive=True, static_columns=[0, 2, 3, 4],
227
+ label="pieces: tick 'ground' to make a piece part of the ground (several pieces form one ground net)",
228
+ wrap=True)
229
+ return st, box, img, info, confirm, fix, undo, reset, table
230
+
231
+
232
+ def wire(gds, layers, pred_btn, parts, events, after=None):
233
+ """Event wiring: file changes / layer-role edits (events) -> check; image clicks, table edits, undo, reset -> re-render; confirm
234
+ unlocks Predict. after(event) is applied to every event that can change the ground pick."""
235
+ st, box, img, info, confirm, fix, undo, reset, table = parts
236
+ outs = [box, img, info, table, st, pred_btn, fix]
237
+ evs = [ev.then(check_fn, [gds, layers], outs, api_visibility="private") for ev in events]
238
+ view = [img, info, table, st, pred_btn]
239
+
240
+ evs += [img.select(select_fn, [st, fix], view, api_visibility="private"),
241
+ table.input(table_fn, [st, table], view, api_visibility="private"),
242
+ undo.click(undo_fn, st, view, api_visibility="private"),
243
+ reset.click(reset_fn, st, view, api_visibility="private")]
244
+ for ev in evs if after else ():
245
+ after(ev)
246
+ return confirm.click(confirm_fn, st, [info, st, pred_btn], api_visibility="private")
geomgnn/paper.py CHANGED
@@ -310,9 +310,9 @@ def predict(prepared, name, reg, substrate="Si (cryogenic, training)", thickness
310
  warnings = [w for w in prepared.warnings if "beyond the validated range" not in w]
311
  if a.get("warning"):
312
  warnings.insert(0, a["warning"])
313
- if not (chk["symmetric_max_abs"] <= 1e-6 * max(1.0, float(np.abs(C).max())) and chk["offdiag_all_negative"]
314
- and (chk["signal_block_min_eig"] is None or chk["signal_block_min_eig"] > 0)):
315
- warnings.append(f"physical check failed: {chk}")
316
  warnings += sub_w
317
  st = stack_of(reg, a)
318
  tm = r["timing"]
 
310
  warnings = [w for w in prepared.warnings if "beyond the validated range" not in w]
311
  if a.get("warning"):
312
  warnings.insert(0, a["warning"])
313
+ pw = A.physical_warning(chk, C)
314
+ if pw:
315
+ warnings.insert(0, pw)
316
  warnings += sub_w
317
  st = stack_of(reg, a)
318
  tm = r["timing"]
geomgnn/static/squadds_dark.png ADDED
geomgnn/static/squadds_light.png ADDED
geomgnn/ui.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared look and result rendering of the flagship and paper Spaces (deploy/GNN_SPACE.md): SQuADDS theme and CSS, the header,
2
+ the Maxwell matrix view (conductor names as headers, 3 decimals shown; the CSV / JSON downloads keep full precision), the status
3
+ callout above the matrix, stale-result marking, inline errors and the layer-role editor."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+ import html
9
+ import re
10
+ import traceback
11
+ import warnings
12
+ from pathlib import Path
13
+
14
+ import gradio as gr
15
+ import numpy as np
16
+ from tlsq_infer.layout import LayoutError
17
+
18
+ from . import api as A
19
+
20
+ STATIC = Path(__file__).parent / "static"
21
+ ROLES = ["ground", "conductor", "ground+conductor", "ignore"]
22
+ MAT = ["tl-matrix"]
23
+ REEXPORT = ("Re-export the layout as GDSII (.gds) from KLayout (File > Save As, format GDS2) or gdstk (Library.write_gds), then "
24
+ "upload it again.")
25
+ EMPTY = "<p class='tl-note'>The matrix appears here after Predict.</p>"
26
+ STALE = ("<div class='tl-status stale' role='status'><strong>Inputs changed.</strong> Press Predict to update the matrix; the one "
27
+ "shown belongs to the previous inputs.</div>")
28
+ MATRIX_NOTE = ("<p class='tl-note'>Diagonal = self capacitance, off-diagonal = minus the mutual capacitance, in fF. Shown to 3 "
29
+ "decimals; the CSV and JSON keep full precision. <span class='tl-flag'>†</span> Ground self term: indicative only "
30
+ "(it depends on the chip boundary).</p><p class='tl-note tl-scroll-hint'>Swipe the matrix sideways for more "
31
+ "columns.</p>")
32
+ GROUND_FLAG = "<span class='tl-flag'>†</span> Ground self term: indicative only (it depends on the chip boundary)."
33
+
34
+
35
+ INK = gr.themes.Color(c50="#f3f6fa", c100="#e4eaf2", c200="#c9d5e4", c300="#a3b6cf", c400="#7590b3", c500="#4f6d94", c600="#3b5a80",
36
+ c700="#2d4a6e", c800="#1e3a5f", c900="#152b47", c950="#0c1a2d", name="ink")
37
+
38
+ CSS = """
39
+ .gradio-container { --tl-ok: #14532d; --tl-ok-bg: #effaf3; --tl-ok-line: #9fd8b4; --tl-warn: #6b3d0a; --tl-warn-bg: #fff8e6;
40
+ --tl-warn-line: #e9c46a; --tl-bad: #7f1d1d; --tl-bad-bg: #fdf1f1; --tl-bad-line: #eba3a3; --tl-mute: #4b5563; --tl-mute-bg: #f3f4f6;
41
+ --tl-mute-line: #d1d5db; --tl-subtle: #4b5563; }
42
+ .dark .gradio-container, .gradio-container.dark { --tl-ok: #bbf0cf; --tl-ok-bg: #0f2a1b; --tl-ok-line: #2f6b47; --tl-warn: #f8dfa4;
43
+ --tl-warn-bg: #2d2208; --tl-warn-line: #7a5a17; --tl-bad: #f9c8c8; --tl-bad-bg: #2f1212; --tl-bad-line: #7f2d2d; --tl-mute: #cbd5e1;
44
+ --tl-mute-bg: #1f2937; --tl-mute-line: #374151; --tl-subtle: #b6bfcc; }
45
+ ::selection { background: #c9d5e4; color: #0c1a2d; }
46
+ .gradio-container input, .gradio-container textarea { caret-color: #1e3a5f; }
47
+ #tl-header { display: flex; flex-direction: column; gap: 6px; margin-bottom: 4px; }
48
+ #tl-header .tl-brand { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
49
+ #tl-header img { height: 34px; width: auto; }
50
+ #tl-header .tl-logo-dark, .dark #tl-header .tl-logo-light { display: none; }
51
+ .dark #tl-header .tl-logo-dark { display: inline-block; }
52
+ #tl-header h1 { font-family: "Source Serif 4", Georgia, serif; font-weight: 600; font-size: 1.9rem; letter-spacing: -0.01em;
53
+ margin: 0; line-height: 1.15; border-left: 1px solid var(--border-color-primary); padding-left: 14px; }
54
+ #tl-header p { margin: 0; max-width: 78ch; line-height: 1.55; }
55
+ #tl-header .tl-meta { font-size: 0.875rem; color: var(--tl-subtle); }
56
+ #tl-header a { padding: 0; margin: 0; text-underline-offset: 2px; }
57
+ .gradio-container .label-wrap { text-align: left; align-items: center; gap: 12px; }
58
+ .gradio-container .label-wrap .icon { flex: 0 0 auto; }
59
+ .gradio-container button.secondary { border: 1px solid var(--button-secondary-border-color); font-size: 0.875rem; font-weight: 500;
60
+ padding: 0 16px; }
61
+ .tl-flush .html-container { padding: 0 !important; }
62
+ #tl-tier label:has(input[value="fast"]) { display: none; }
63
+ .gradio-container h2 { font-family: "Source Serif 4", Georgia, serif; font-weight: 600; margin-top: 18px; }
64
+ .gradio-container .prose p, .gradio-container .prose li, .gradio-container .prose blockquote { max-width: 80ch; }
65
+ .tl-status { border: 1px solid var(--tl-mute-line); background: var(--tl-mute-bg); color: var(--tl-mute); border-radius: 8px;
66
+ padding: 12px 16px; line-height: 1.5; }
67
+ .tl-status p { margin: 0; max-width: 80ch; }
68
+ .tl-status p + p { margin-top: 4px; }
69
+ .tl-status.ok { border-color: var(--tl-ok-line); background: var(--tl-ok-bg); color: var(--tl-ok); }
70
+ .tl-status.warn { border-color: var(--tl-warn-line); background: var(--tl-warn-bg); color: var(--tl-warn); }
71
+ .tl-status.bad { border-color: var(--tl-bad-line); background: var(--tl-bad-bg); color: var(--tl-bad); }
72
+ .tl-matrix table { font-variant-numeric: tabular-nums; }
73
+ .tl-matrix th:not(:first-child) .cell-wrap, .tl-matrix th:not(:first-child) .header-content { justify-content: flex-end; text-align: right;
74
+ width: 100%; }
75
+ .tl-stale { opacity: 0.4; filter: grayscale(1); transition: opacity 0.2s ease-out; }
76
+ .tl-note { font-size: 0.875rem; color: var(--tl-subtle); margin: 6px 0 0; max-width: 80ch; }
77
+ .tl-flag { font-weight: 600; }
78
+ .tl-scroll-hint { display: none; }
79
+ .gradio-container input[type=radio]:focus-visible, .gradio-container input[type=checkbox]:focus-visible {
80
+ outline: 2px solid #1e3a5f !important; outline-offset: 2px !important; }
81
+ .dark .gradio-container input[type=radio]:focus-visible, .dark .gradio-container input[type=checkbox]:focus-visible {
82
+ outline-color: #a3b6cf !important; }
83
+ .gradio-container label:has(input[type=radio]:focus-visible), .gradio-container label:has(input[type=checkbox]:focus-visible) {
84
+ box-shadow: 0 0 0 2px #1e3a5f; }
85
+ .gradio-container button:focus-visible { outline: 2px solid #1e3a5f; outline-offset: 2px; }
86
+ #tl-tier label, .tl-check label, .tl-touch button, .gradio-container button.primary, .gradio-container button.secondary {
87
+ min-height: 44px !important; }
88
+ @media (max-width: 640px) { /* Gradio prefixes rules inside @media with its container: no .gradio-container here */
89
+ #tl-header h1 { font-size: 1.5rem; border-left: none; padding-left: 0; }
90
+ .tl-scroll-hint { display: block; }
91
+ .tl-matrix table { font-size: 0.8125rem; }
92
+ .label-wrap, .gallery-item, button.sm, input[type=number] { min-height: 44px !important; }
93
+ button.icon-button { min-width: 44px !important; min-height: 44px !important; }
94
+ #tl-viewer:not(:has(img)) { display: none !important; }
95
+ #tl-viewer, #tl-ground-img { padding-top: 52px !important; }
96
+ #tl-viewer .image-container > .icon-button-wrapper, #tl-ground-img .image-container > .icon-button-wrapper { top: -52px !important; }
97
+ }
98
+ #tl-viewer:not(:has(img)) { height: 340px !important; }
99
+ .gradio-container footer, .gradio-container footer a, .gradio-container footer button, .gradio-container footer .divider {
100
+ color: var(--tl-subtle) !important; }
101
+ .gradio-container footer img { opacity: 0.75; }
102
+ .gradio-container .wrap .or { color: var(--tl-subtle) !important; }
103
+ #tl-view { flex-grow: 0; }
104
+ #tl-view .wrap { gap: 0; }
105
+ #tl-view label { min-height: 44px; border-radius: 0; margin: 0; padding: 0 16px; }
106
+ #tl-view label:first-child { border-radius: 6px 0 0 6px; }
107
+ #tl-view label:last-child { border-radius: 0 6px 6px 0; }
108
+ #tl-view input { position: absolute; opacity: 0; width: 1px; height: 1px; }
109
+ .tl-viewbar { align-items: center; gap: 8px; }
110
+ .tl-viewbar { flex-wrap: nowrap !important; }
111
+ .tl-viewbar > fieldset, .tl-viewbar > button { flex: 0 0 auto !important; width: auto !important; min-width: 0 !important; }
112
+
113
+ """
114
+
115
+
116
+ def theme():
117
+ return gr.themes.Default(primary_hue=INK, secondary_hue=INK, neutral_hue=gr.themes.colors.gray,
118
+ font=[gr.themes.GoogleFont("Source Sans 3"), "ui-sans-serif", "system-ui", "sans-serif",
119
+ gr.themes.GoogleFont("Source Serif 4", (600,))],
120
+ font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace"]).set(
121
+ button_primary_background_fill="*primary_800", button_primary_background_fill_hover="*primary_900",
122
+ button_primary_border_color="*primary_800", button_primary_border_color_hover="*primary_900",
123
+ button_primary_text_color="white", button_primary_text_color_hover="white",
124
+ button_primary_background_fill_dark="*primary_200", button_primary_background_fill_hover_dark="*primary_100",
125
+ button_primary_border_color_dark="*primary_200", button_primary_border_color_hover_dark="*primary_100",
126
+ button_primary_text_color_dark="*primary_950", button_primary_text_color_hover_dark="*primary_950",
127
+ checkbox_background_color_selected="*primary_800", checkbox_border_color_selected="*primary_800",
128
+ checkbox_background_color_selected_dark="*primary_300", checkbox_border_color_selected_dark="*primary_300",
129
+ checkbox_label_background_fill_selected="*primary_50", checkbox_label_border_color_selected="*primary_800",
130
+ checkbox_label_text_color_selected="*primary_950", checkbox_label_background_fill_selected_dark="*primary_900",
131
+ checkbox_label_border_color_selected_dark="*primary_300", checkbox_label_text_color_selected_dark="*primary_50",
132
+ link_text_color="*primary_800", link_text_color_hover="*primary_950", link_text_color_visited="*primary_800",
133
+ link_text_color_dark="*primary_300", link_text_color_hover_dark="*primary_200", link_text_color_visited_dark="*primary_300",
134
+ color_accent="*primary_800", color_accent_soft="*primary_50", color_accent_soft_dark="*primary_900", loader_color="*primary_800",
135
+ slider_color="*primary_800", input_border_color_focus="*primary_700",
136
+ button_secondary_background_fill="*background_fill_primary", button_secondary_background_fill_hover="*primary_50",
137
+ button_secondary_border_color="*primary_300", button_secondary_border_color_hover="*primary_800",
138
+ button_secondary_text_color="*primary_900", button_secondary_text_color_hover="*primary_950",
139
+ button_secondary_background_fill_dark="*background_fill_primary", button_secondary_background_fill_hover_dark="*primary_900",
140
+ button_secondary_border_color_dark="*primary_500", button_secondary_border_color_hover_dark="*primary_300",
141
+ button_secondary_text_color_dark="*primary_100", button_secondary_text_color_hover_dark="*primary_50")
142
+
143
+
144
+ def blocks(title: str, **kw):
145
+ """gr.Blocks with the theme and CSS (Gradio 6 reads them at launch; passing them here keeps app.py's plain launch())."""
146
+ with warnings.catch_warnings():
147
+ warnings.filterwarnings("ignore", message="The parameters have been moved", category=UserWarning)
148
+ return gr.Blocks(title=title, theme=theme(), css=CSS, **kw)
149
+
150
+
151
+ def _logo(kind: str) -> str:
152
+ b = base64.b64encode((STATIC / f"squadds_{kind}.png").read_bytes()).decode()
153
+ return f"<img class='tl-logo-{kind}' src='data:image/png;base64,{b}' alt='SQuADDS'>"
154
+
155
+
156
+ def header(title: str, lede: str, meta: str | None = None) -> str:
157
+ """Logo + title, a short lede (HTML) and an optional small meta line."""
158
+ return (f"<div id='tl-header'><div class='tl-brand'>{_logo('light')}{_logo('dark')}<h1>{html.escape(title)}</h1></div>"
159
+ f"<p>{lede}</p>" + (f"<p class='tl-meta'>{meta}</p>" if meta else "") + "</div>")
160
+
161
+
162
+ def examples(comp, paths, **kw):
163
+ """gr.Examples whose cached copies survive delete_cache. Gradio 6.29 copies a File example into the cache with
164
+ Blocks.temp_files but does not add it to keep_in_cache (the Dataset only stores the file name), so the delete_cache sweep
165
+ removed the copy PURGE_AGE_S after startup (at the first sweep when the copy was left by an earlier run) and every later
166
+ click on the example failed with FileNotFoundError."""
167
+ e = gr.Examples([[str(p)] for p in paths], inputs=[comp], **kw)
168
+ for v in e.non_none_processed_examples.values():
169
+ for d in v:
170
+ if isinstance(d, dict) and d.get("path"):
171
+ comp.keep_in_cache.add(d["path"])
172
+ return e
173
+
174
+
175
+ def fig_files(fig, d: Path, stem: str) -> tuple[str, str]:
176
+ """A matplotlib figure as PNG (shown, downloadable) and SVG (download), closed afterwards."""
177
+ import matplotlib.pyplot as plt
178
+
179
+ png, svg = d / f"{stem}.png", d / f"{stem}.svg"
180
+ fig.savefig(png, dpi=130)
181
+ fig.savefig(svg)
182
+ plt.close(fig)
183
+ return str(png), str(svg)
184
+
185
+
186
+ def matrix_note(res) -> str:
187
+ flag = "indicative" in str(res.get("self_capacitance", "")) and list(res.get("names") or [])[:1] == ["G"]
188
+ return ("<p class='tl-note'>Diagonal = self capacitance, off-diagonal = minus the mutual capacitance, in fF; 3 decimals shown, "
189
+ "the CSV and JSON keep full precision." + (f" {GROUND_FLAG}" if flag else "") + "</p><p class='tl-note tl-scroll-hint'>"
190
+ "Swipe the matrix sideways for more columns.</p>")
191
+
192
+
193
+ def md(s) -> str:
194
+ """Markdown-safe text: a pair of '~' renders as strikethrough, so approximate values use '≈'."""
195
+ return str(s or "").replace("~", "≈")
196
+
197
+
198
+ def pct(e) -> str:
199
+ """'1.05 % median (MAE 0.132 fF, RMSE 0.188 fF)': every % with its MAE / RMSE."""
200
+ return f"{e['median_pct']:g} % median (MAE {e['mae_ff']:g} fF, RMSE {e['rmse_ff']:g} fF)"
201
+
202
+
203
+ def _inline(s: str) -> str:
204
+ return re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", html.escape(s))
205
+
206
+
207
+ def callout(kind: str, head: str, lines) -> str:
208
+ body = "".join(f"<p>{x}</p>" for x in lines if x)
209
+ return f"<div class='tl-status {kind}' role='status'><p><strong>{html.escape(head)}</strong></p>{body}</div>"
210
+
211
+
212
+ def checks_of(res) -> dict | None:
213
+ """The result's physical checks; for arms that report none, the same checks on the matrix (entries that are None skipped)."""
214
+ c = res.get("checks") or {}
215
+ if "symmetric_max_abs" in c:
216
+ return c
217
+ 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)
218
+ if C.ndim != 2 or len(C) < 2:
219
+ return None
220
+ off = C[~np.eye(len(C), dtype=bool)]
221
+ sig = C[1:, 1:]
222
+ return {"symmetric_max_abs": float(np.nanmax(np.abs(C - C.T))), "offdiag_all_negative": bool(np.all(off[np.isfinite(off)] < 0)),
223
+ "signal_block_min_eig": float(np.linalg.eigvalsh(sig).min()) if np.isfinite(sig).all() else None}
224
+
225
+
226
+ def _checks(c) -> str:
227
+ eig = c.get("signal_block_min_eig")
228
+ return (f"Symmetric (max |C − Cᵀ| {c['symmetric_max_abs']:.2g} fF), every off-diagonal negative"
229
+ + (f", signal block positive definite (smallest eigenvalue {eig:.4g} fF)." if eig is not None else
230
+ "; no self terms, so positive definiteness is not checked."))
231
+
232
+
233
+ def _offstack(res) -> str:
234
+ sub = res.get("substrate_route") or {}
235
+ e, t = res.get("eps_r"), res.get("thickness_um")
236
+ if sub.get("route") == A.FAST_ROUTE:
237
+ return (f"Substrate eps_r {e:g}, {t:g} µm. This route does not solve the physics prior at your stack: the training-stack "
238
+ f"prediction was rescaled by (1 + eps_r) / (1 + 11.45) = {sub['eps_rescale_factor']:.4f}, and thickness is not modelled. "
239
+ "Not scored off the training stack: use Accurate for other substrates.")
240
+ head = f"Substrate eps_r {e:g}, {t:g} µm: physics prior solved at this stack, networks (trained on Si, eps_r 11.45, 350 µm) unchanged."
241
+ if not sub.get("tested", True):
242
+ return head + f" Outside the tested range ({A.TESTED_RANGE}): untested, its error is unknown."
243
+ return head + f" A tested combination. {A.CALIBRATED_SCORE}"
244
+
245
+
246
+ def status_html(res, expected: str | None = None) -> str:
247
+ """Callout above the matrix: red when a physical check fails (the physical_banner text), yellow off the training stack, green
248
+ otherwise with the one expected-error line for a new design."""
249
+ bad = A.physical_banner(res)
250
+ c = checks_of(res)
251
+ if not bad and c and "checks" not in res:
252
+ 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))
253
+ 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)
254
+ bad = [f"> **Not a physical matrix.** {w}"] if w else []
255
+ if bad:
256
+ return callout("bad", "Not a physical matrix: do not use it", [_inline(bad[0].lstrip("> ").replace("**Not a physical matrix.** ", ""))])
257
+ chk = _checks(c) if c else None
258
+ if (res.get("substrate_route") or {}).get("route", "training stack") != "training stack":
259
+ return callout("warn", "Off the training stack" + (": physical checks passed" if chk else ""), [chk, html.escape(_offstack(res))])
260
+ if chk:
261
+ return callout("ok", "Physical checks passed", [chk, html.escape(expected) if expected else None])
262
+ return callout("", "Result", [html.escape(expected) if expected else None])
263
+
264
+
265
+ def error_text(e: BaseException) -> str:
266
+ if isinstance(e, MemoryError):
267
+ return "Out of memory: crop the layout to the region of interest and try again."
268
+ if not isinstance(e, (LayoutError, ValueError, KeyError, FileNotFoundError)):
269
+ traceback.print_exception(e)
270
+ return f"Internal error ({type(e).__name__}): {e}. Please report it with the file if you can."
271
+ msg = str(e).strip()
272
+ if msg == "upload a GDS file first":
273
+ return "No layout yet: upload a GDS file (or pick an example) in step 1, then press Predict."
274
+ if msg.startswith("not a readable GDS"):
275
+ return f"This file could not be read as GDSII ({msg.rstrip('.')}). {REEXPORT}"
276
+ return msg[:1].upper() + msg[1:]
277
+
278
+
279
+ def error_html(e: BaseException, head: str = "Could not predict") -> str:
280
+ return callout("bad", head, [html.escape(error_text(e))])
281
+
282
+
283
+ def matrix_view(res):
284
+ """The matrix for the UI: conductor names as headers (blank top-left), 3 decimals shown, the ground self term flagged when the
285
+ result calls it indicative. The underlying values are the 4-decimal table the /predict endpoint always returned."""
286
+ if not res:
287
+ return None
288
+ import pandas as pd
289
+
290
+ names = list(res["names"])
291
+ 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"])]
292
+ df = pd.DataFrame(rows, columns=["", *names])
293
+ st = df.style.format("{:.3f}", subset=names, na_rep="").set_properties(subset=names, **{"text-align": "right"})
294
+ st = st.set_properties(subset=[""], **{"font-weight": "600"})
295
+ if "indicative" in str(res.get("self_capacitance", "")) and names and names[0] == "G" and np.isfinite(rows[0][1]):
296
+ st = st.format(lambda v: f"{v:.3f} †", subset=pd.IndexSlice[[0], [names[0]]])
297
+ return st
298
+
299
+
300
+ def stale(res):
301
+ if res is None:
302
+ return gr.update(), gr.update(), gr.update()
303
+ return STALE, gr.update(elem_classes=MAT + ["tl-stale"]), gr.update(elem_classes=["tl-stale"])
304
+
305
+
306
+ def mark_stale(res_state, status, mat, report, events):
307
+ for ev in events:
308
+ ev(stale, res_state, [status, mat, report], api_visibility="private", show_progress="hidden")
309
+
310
+
311
+ def predict_ui(fn, expected, note: bool = False):
312
+ """Visible Predict: the /predict function plus the status callout and the result group (hidden until the first result); errors
313
+ become an inline callout instead of a toast and grey out an earlier result. note = also return the matrix note (last output)."""
314
+ def run(*a):
315
+ try:
316
+ mat, csv_f, json_f, rep, res = fn(*a)
317
+ except Exception as e: # noqa: BLE001
318
+ return (gr.update(elem_classes=MAT + ["tl-stale"]), gr.update(), gr.update(), gr.update(elem_classes=["tl-stale"]), gr.update(),
319
+ error_html(e), gr.update()) + ((gr.update(),) if note else ())
320
+ return (gr.update(value=mat, elem_classes=MAT), csv_f, json_f, gr.update(value=rep, elem_classes=[]), res,
321
+ status_html(res, expected(res)), gr.update(visible=True)) + ((matrix_note(res),) if note else ())
322
+ run.__name__ = fn.__name__ + "_ui"
323
+ return run
324
+
325
+
326
+ def _rows(table) -> list:
327
+ if table is None:
328
+ return []
329
+ rows = table.values.tolist() if hasattr(table, "values") else list(table)
330
+ return [list(r) for r in rows if len(r) >= 3 and str(r[0]).strip() not in ("", "nan", "None")]
331
+
332
+
333
+ def _key(r) -> str:
334
+ return f"{int(float(r[0]))}/{int(float(r[1]))}"
335
+
336
+
337
+ def inspect_ui(inspect_fn):
338
+ """Inspect on every file change (upload, example, clear): layer table, plot, inline message, layer picker, role."""
339
+ def run(f):
340
+ none = gr.update(choices=[], value=None)
341
+ if f is None:
342
+ return [], None, "", none, gr.update(value=None)
343
+ try:
344
+ table, fig = inspect_fn(f)
345
+ except Exception as e: # noqa: BLE001
346
+ return [], None, error_html(e, "Could not read this file"), none, gr.update(value=None)
347
+ keys = [_key(r) for r in table]
348
+ return table, fig, "", gr.update(choices=keys, value=keys[0] if keys else None), gr.update(value=table[0][2] if table else None)
349
+ return run
350
+
351
+
352
+ def layer_editor():
353
+ with gr.Row(elem_classes="tl-roles"):
354
+ pick = gr.Dropdown([], label="layer", interactive=True, min_width=140)
355
+ role = gr.Dropdown(ROLES, value=None, label="role", interactive=True, min_width=200)
356
+ return pick, role
357
+
358
+
359
+ def wire_editor(layers, pick, role):
360
+ """Fixed role choices instead of free text: pick a layer (or click its row), choose its role. Returns the edit event."""
361
+ def show(table, key):
362
+ r = next((r for r in _rows(table) if _key(r) == key), None)
363
+ return gr.update(value=r[2] if r else None)
364
+
365
+ def choose(table, evt: gr.SelectData):
366
+ rows = _rows(table)
367
+ return gr.update(value=_key(rows[evt.index[0]])) if rows and evt.index[0] < len(rows) else gr.update()
368
+
369
+ def edit(table, key, new):
370
+ return [r[:2] + [new] + r[3:] if _key(r) == key else r for r in _rows(table)]
371
+
372
+ pick.change(show, [layers, pick], role, api_visibility="private", show_progress="hidden")
373
+ layers.select(choose, layers, pick, api_visibility="private", show_progress="hidden")
374
+ return role.input(edit, [layers, pick, role], layers, api_visibility="private", show_progress="hidden")
registry.yaml CHANGED
@@ -939,6 +939,7 @@ gnn_models:
939
  # layout, median / 90th percentile, two CPUs of an x86 cluster node (tab:ladder-test) unless stated.
940
  paper_hub:
941
  space: shanto268/2026PaperModels # reused (same gradio SDK): its earlier contents are archived (archive below)
 
942
  title: Planar Capacitance (paper models)
943
  private: true # Spaces stay private (CLAUDE.md rule 11)
944
  space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM
@@ -959,7 +960,9 @@ paper_hub:
959
  local_copy: data_local/hf_archive/2026PaperModels_34091ebf}} # agents/embedspeed sped-up exact pipeline + baked numba cache; outputs bitwise = the Gradio build (12 live matrices)
960
  farfield: {commit: e0695caed5075ed8df70ffb0933d8e51d6e3b4cd, date: 2026-10-20, rollback: fa7caa49ddd11421b04b44ee2d03fbf4ba632d90,
961
  gate: deploy/tests/results/paper_space_gate_farfield_20261020.json, live: deploy/tests/results/paper_space_live_farfield_20261020.json} # stack 'corrected' = the corrected prior with substrate far field (agents/farfield/ADOPTION.md)
962
- substrate: {commit: null, date: 2026-11-03, rollback: e0695caed5075ed8df70ffb0933d8e51d6e3b4cd} # calibrated substrate route (tl_squadds e60c67a): prior arms solve at the user's stack, learned-prior arms rescale + warn, solver-free refuses; rollback = the live farfield commit
 
 
963
  prior_stacks: # process-wide prior settings (geomgnn.api.set_prior_stack), installed per request
964
  corrected: &stack_corrected # since 2026-10-20: the corrected prior with substrate far field + compiled exact solver = the model's prior; also flagship_hub
965
  title: "corrected prior with substrate far field"
@@ -1392,7 +1395,7 @@ flagship_hub:
1392
  space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM
1393
  default_arm: accurate
1394
  max_conductors: 70 # signal conductors per layout (the nine-qubit lattice has 66 + ground)
1395
- paper_space: shanto268/2026PaperModels # every route of the paper, for reproducing it
1396
  checkpoints: data_local/flagship_v4/checkpoints.json # sha256 of every flagship checkpoint; sync.py refuses any other file
1397
  results: agents/flagship_v4/RESULTS.md
1398
  training_layouts: 45771
@@ -1408,7 +1411,10 @@ flagship_hub:
1408
  local_copy: data_local/hf_archive/PlanarCapacitanceModel_8db73f7d}} # agents/embedspeed: F64 embedding default (TLSQ_EMBEDDING_EXACT=1 = exact recipe) + baked numba cache
1409
  farfield: {commit: 6f16a03ab7d2f7a41e66261de3c98d5051960290, date: 2026-10-20, rollback: e3e5a832e04ede8088bd91d7c0567cd68330ff51,
1410
  gate: deploy/tests/results/flagship_space_gate_farfield_20261020.json, live: deploy/tests/results/flagship_space_live_farfield_20261020.json} # corrected prior with substrate far field + Accurate / Balanced retrained (agents/farfield/ADOPTION.md)
1411
- substrate: {commit: null, date: 2026-11-03, rollback: 6f16a03ab7d2f7a41e66261de3c98d5051960290} # calibrated substrate route (tl_squadds e60c67a; handoff/squadds_integration/reports/calibrated_substrate.md): Accurate solves the prior at the user's stack, Fast rescales + warns; rollback = the live farfield commit
 
 
 
1412
  prior_stacks:
1413
  corrected: *stack_corrected # the corrected prior with substrate far field + compiled exact solver (the same stack as the paper Space's model)
1414
 
@@ -1427,8 +1433,10 @@ flagship_tiers:
1427
  - {name: acc_v2m_sf_s1, path: data_local/flagship_v4/hpc/runs/acc_v2m_sf_s1/model.pt, sha256: 2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57} # was acc_v2m_s1 ae9c4be5 (half-space far field)
1428
  - {name: acc_v2m_sf_s2, path: data_local/flagship_v4/hpc/runs/acc_v2m_sf_s2/model.pt, sha256: d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed} # was acc_v2m_s2 0841acc6 (half-space far field)
1429
  summary: "Two thin-film method-of-moments solves (corrected prior with substrate far field, 1.5 and 3 panels per gap), Richardson-extrapolated, corrected by a 3-seed ensemble of the paper model's networks (89,858 parameters per seed, bounded residual) with a learned row-sum closure: the complete Maxwell matrix, self terms included. Networks retrained on all 45,771 on-stack Q3D layouts (2026-10-20, on the corrected prior with substrate far field)."
 
 
1430
  reference:
1431
- recipe: "the paper's model (same networks and prior stack at inference; its networks were trained on 35,354 TRAIN layouts on the uncorrected prior; retrained on the corrected prior, as here, they score validation 0.218 % (0.0774 / 0.0888 fF))"
1432
  val: {median_pct: 0.229, mae_ff: 0.0674, rmse_ff: 0.0792}
1433
  test_infamily: {median_pct: 0.177, mae_ff: 0.0203, rmse_ff: 0.0250}
1434
  test_zeroshot: {median_pct: 0.587, mae_ff: 1.092, rmse_ff: 1.152}
@@ -1451,8 +1459,10 @@ flagship_tiers:
1451
  - {name: bal_v2m_sf_s1, path: data_local/flagship_v4/hpc/runs/bal_v2m_sf_s1/model.pt, sha256: 486466473eba61c090f4e3fa7988bf880fc183570c5d02bd78f4c1356691f926} # was bal_v2m_s1 5d1f0ffb (half-space far field)
1452
  - {name: bal_v2m_sf_s2, path: data_local/flagship_v4/hpc/runs/bal_v2m_sf_s2/model.pt, sha256: 1b55ded04fd624585eeeccf2ab6e4a8e9354a9b96694131e1737dde43ad3ff58} # was bal_v2m_s2 dcd14c61 (half-space far field)
1453
  summary: "The Accurate recipe on the coarser Richardson pair (0.75 and 1.5 panels per gap, about half the solve time), networks retrained on that pair on all 45,771 on-stack layouts. About 2x faster than Accurate at 1.5-1.7x its error."
 
 
1454
  reference:
1455
- recipe: "the paper's coarser pair + the model's recipe (trained on 35,354 TRAIN layouts; validation only, never test-scored)"
1456
  val: {median_pct: 0.343, mae_ff: 0.123, rmse_ff: 0.138}
1457
  b5: {median_pct: 2.044, mae_ff: 0.258, rmse_ff: 0.348} # retrained 2026-10-20 (substrate far field); before 1.753 % (0.236 / 0.308 fF); B5 priors unchanged (N 3-4), within the earlier seed range 1.79-2.07 %
1458
  b5_physics: {name: "physics alone R(0.75, 1.5)", median_pct: 2.681, mae_ff: 0.396, rmse_ff: 0.583}
@@ -1473,16 +1483,18 @@ flagship_tiers:
1473
  learned_prior:
1474
  name: sall_all_s0 # surrogate seed 0 by declaration (PROTOCOL.md section 3, amendment A1)
1475
  checkpoint: {name: sall_all_s0, path: data_local/flagship_v4/hpc/sur/sall_all_s0/model.pt, sha256: 132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac}
1476
- summary: "A learned surrogate (1.02M parameters, trained on the prior of every on-stack layout plus 432,697 generated layouts labelled by the prior alone) predicts the two uncorrected-prior solves at 1.5 and 3 panels per gap; networks retrained on all 45,771 on-stack layouts on that prior correct them. No field solve: the time is the geometric embedding."
1477
- warning: "Use Fast only for quick screening of the component families it was trained on (interdigital, paddle, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated and synthetic campaign layouts). On new designs of a trained family (B5) it was worse than the physics alone, 3.175 % (MAE 0.583 / RMSE 0.824 fF) against 1.765 % (0.275 / 0.376 fF), and in the paper it was worse than the physics alone on a held-out family too, 3.11 % (0.533 / 0.633 fF) against 1.55 % (0.166 / 0.205 fF). Use Accurate for anything that matters."
 
 
1478
  reference:
1479
- recipe: "the paper's fast model (learned prior surrogate + the networks on its prior, trained on 35,354 TRAIN layouts)"
1480
  val: {median_pct: 0.846, mae_ff: 0.491, rmse_ff: 0.549}
1481
  test_infamily: {median_pct: 0.630, mae_ff: 0.1130, rmse_ff: 0.1414}
1482
  test_zeroshot: {median_pct: 3.576, mae_ff: 4.608, rmse_ff: 5.058}
1483
  heldout_family: {median_pct: 3.113, mae_ff: 0.533, rmse_ff: 0.633}
1484
  heldout_family_physics: {median_pct: 1.554, mae_ff: 0.166, rmse_ff: 0.205}
1485
- val_same_surrogate: {median_pct: 0.722, mae_ff: 0.387, rmse_ff: 0.436, note: "this surrogate recipe (SUR-ALL) + the networks, validation"}
1486
  b5: {median_pct: 3.175, mae_ff: 0.583, rmse_ff: 0.824}
1487
  b5_physics: {name: "physics alone C^R = R(1.5, 3) (worse than the physics: Fast is behind it here)", median_pct: 1.765, mae_ff: 0.275, rmse_ff: 0.376}
1488
  time_space: "interdigital 0.036 s, xmon 0.11 s, 1-qubit lattice (N 15) 0.82 s, 16-conductor layout 0.49 s, 9-qubit lattice (N 67) 3.9 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s)"
 
939
  # layout, median / 90th percentile, two CPUs of an x86 cluster node (tab:ladder-test) unless stated.
940
  paper_hub:
941
  space: shanto268/2026PaperModels # reused (same gradio SDK): its earlier contents are archived (archive below)
942
+ retired: {date: 2026-11-06, note: "author decision: no dedicated paper Space; the paper's models stay on HF as model repos only (SQuADDS/PlanarCapacitance-paper, SQuADDS/2026PaperModels-*). The Space itself is not deleted or modified; app_paper.py, sync.py --paper and its gate stay working, not deployed"}
943
  title: Planar Capacitance (paper models)
944
  private: true # Spaces stay private (CLAUDE.md rule 11)
945
  space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM
 
960
  local_copy: data_local/hf_archive/2026PaperModels_34091ebf}} # agents/embedspeed sped-up exact pipeline + baked numba cache; outputs bitwise = the Gradio build (12 live matrices)
961
  farfield: {commit: e0695caed5075ed8df70ffb0933d8e51d6e3b4cd, date: 2026-10-20, rollback: fa7caa49ddd11421b04b44ee2d03fbf4ba632d90,
962
  gate: deploy/tests/results/paper_space_gate_farfield_20261020.json, live: deploy/tests/results/paper_space_live_farfield_20261020.json} # stack 'corrected' = the corrected prior with substrate far field (agents/farfield/ADOPTION.md)
963
+ substrate: {commit: 37fe8236dca1a5a332a4097c5525f4f23e91b0f2, date: 2026-11-03, rollback: e0695caed5075ed8df70ffb0933d8e51d6e3b4cd,
964
+ gate: deploy/tests/results/paper_space_gate_substrate_20261103.json, live: deploy/tests/results/paper_space_live_substrate_20261103.json,
965
+ offstack: deploy/tests/results/paper_space_live_offstack_20261103.json} # calibrated substrate route (tl_squadds e60c67a): prior arms solve at the user's stack, learned-prior arms rescale + warn, solver-free refuses; rollback = the live farfield commit
966
  prior_stacks: # process-wide prior settings (geomgnn.api.set_prior_stack), installed per request
967
  corrected: &stack_corrected # since 2026-10-20: the corrected prior with substrate far field + compiled exact solver = the model's prior; also flagship_hub
968
  title: "corrected prior with substrate far field"
 
1395
  space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM
1396
  default_arm: accurate
1397
  max_conductors: 70 # signal conductors per layout (the nine-qubit lattice has 66 + ground)
1398
+ paper_models: SQuADDS/PlanarCapacitance-paper # the paper's model (model repo); the paper Space is retired (paper_hub.retired)
1399
  checkpoints: data_local/flagship_v4/checkpoints.json # sha256 of every flagship checkpoint; sync.py refuses any other file
1400
  results: agents/flagship_v4/RESULTS.md
1401
  training_layouts: 45771
 
1411
  local_copy: data_local/hf_archive/PlanarCapacitanceModel_8db73f7d}} # agents/embedspeed: F64 embedding default (TLSQ_EMBEDDING_EXACT=1 = exact recipe) + baked numba cache
1412
  farfield: {commit: 6f16a03ab7d2f7a41e66261de3c98d5051960290, date: 2026-10-20, rollback: e3e5a832e04ede8088bd91d7c0567cd68330ff51,
1413
  gate: deploy/tests/results/flagship_space_gate_farfield_20261020.json, live: deploy/tests/results/flagship_space_live_farfield_20261020.json} # corrected prior with substrate far field + Accurate / Balanced retrained (agents/farfield/ADOPTION.md)
1414
+ substrate: {commit: 4f5e6036f37b21cf9a24f6b5ad4762cbe1341809, date: 2026-11-03, rollback: 6f16a03ab7d2f7a41e66261de3c98d5051960290,
1415
+ gate: deploy/tests/results/flagship_space_gate_substrate_20261103.json, live: deploy/tests/results/flagship_space_live_substrate_20261103.json,
1416
+ offstack: deploy/tests/results/flagship_space_live_offstack_20261103.json} # calibrated substrate route (tl_squadds e60c67a; handoff/squadds_integration/reports/calibrated_substrate.md): Accurate solves the prior at the user's stack, Fast rescales + warns; rollback = the live farfield commit
1417
+ ui: {commit: null, date: 2026-11-06, rollback: 4f5e6036f37b21cf9a24f6b5ad4762cbe1341809, source: tl_squadds 8a46d6b} # UI redesign (passes 1-3, examples cache fix, ground check, physical banner); models and numbers unchanged; rollback = the live substrate commit
1418
  prior_stacks:
1419
  corrected: *stack_corrected # the corrected prior with substrate far field + compiled exact solver (the same stack as the paper Space's model)
1420
 
 
1433
  - {name: acc_v2m_sf_s1, path: data_local/flagship_v4/hpc/runs/acc_v2m_sf_s1/model.pt, sha256: 2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57} # was acc_v2m_s1 ae9c4be5 (half-space far field)
1434
  - {name: acc_v2m_sf_s2, path: data_local/flagship_v4/hpc/runs/acc_v2m_sf_s2/model.pt, sha256: d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed} # was acc_v2m_s2 0841acc6 (half-space far field)
1435
  summary: "Two thin-film method-of-moments solves (corrected prior with substrate far field, 1.5 and 3 panels per gap), Richardson-extrapolated, corrected by a 3-seed ensemble of the paper model's networks (89,858 parameters per seed, bounded residual) with a learned row-sum closure: the complete Maxwell matrix, self terms included. Networks retrained on all 45,771 on-stack Q3D layouts (2026-10-20, on the corrected prior with substrate far field)."
1436
+ own: # this release's own numbers; its networks saw every row scored here except B5 (data_local/farfield_adopt/insample.json, acc_v2m_sf ensemble)
1437
+ insample: {set: "in-sample, all 45,771 training layouts (TRAIN + VAL + the paper's test split; it was trained on them)", median_pct: 0.207, mae_ff: 0.0679, rmse_ff: 0.0770}
1438
  reference:
1439
+ recipe: "the paper's version of this model (same architecture and prior stack at inference; its networks were trained on the 35,354 TRAIN layouts only, on the uncorrected prior; retrained on the corrected prior, as here, they score validation 0.218 % (0.0774 / 0.0888 fF)). These held-out numbers belong to the paper's version, not to this release, whose networks were retrained on every labelled design, the paper's test split included"
1440
  val: {median_pct: 0.229, mae_ff: 0.0674, rmse_ff: 0.0792}
1441
  test_infamily: {median_pct: 0.177, mae_ff: 0.0203, rmse_ff: 0.0250}
1442
  test_zeroshot: {median_pct: 0.587, mae_ff: 1.092, rmse_ff: 1.152}
 
1459
  - {name: bal_v2m_sf_s1, path: data_local/flagship_v4/hpc/runs/bal_v2m_sf_s1/model.pt, sha256: 486466473eba61c090f4e3fa7988bf880fc183570c5d02bd78f4c1356691f926} # was bal_v2m_s1 5d1f0ffb (half-space far field)
1460
  - {name: bal_v2m_sf_s2, path: data_local/flagship_v4/hpc/runs/bal_v2m_sf_s2/model.pt, sha256: 1b55ded04fd624585eeeccf2ab6e4a8e9354a9b96694131e1737dde43ad3ff58} # was bal_v2m_s2 dcd14c61 (half-space far field)
1461
  summary: "The Accurate recipe on the coarser Richardson pair (0.75 and 1.5 panels per gap, about half the solve time), networks retrained on that pair on all 45,771 on-stack layouts. About 2x faster than Accurate at 1.5-1.7x its error."
1462
+ own: # data_local/farfield_adopt/insample.json, bal_v2m_sf ensemble
1463
+ insample: {set: "in-sample, all 45,771 training layouts (TRAIN + VAL + the paper's test split; it was trained on them)", median_pct: 0.300, mae_ff: 0.0872, rmse_ff: 0.0999}
1464
  reference:
1465
+ recipe: "the paper's version: the coarser pair + the model's recipe, trained on the 35,354 TRAIN layouts only (validation only, never test-scored). These numbers belong to the paper's version, not to this release"
1466
  val: {median_pct: 0.343, mae_ff: 0.123, rmse_ff: 0.138}
1467
  b5: {median_pct: 2.044, mae_ff: 0.258, rmse_ff: 0.348} # retrained 2026-10-20 (substrate far field); before 1.753 % (0.236 / 0.308 fF); B5 priors unchanged (N 3-4), within the earlier seed range 1.79-2.07 %
1468
  b5_physics: {name: "physics alone R(0.75, 1.5)", median_pct: 2.681, mae_ff: 0.396, rmse_ff: 0.583}
 
1483
  learned_prior:
1484
  name: sall_all_s0 # surrogate seed 0 by declaration (PROTOCOL.md section 3, amendment A1)
1485
  checkpoint: {name: sall_all_s0, path: data_local/flagship_v4/hpc/sur/sall_all_s0/model.pt, sha256: 132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac}
1486
+ summary: "An improved release of the paper's fast model, same architecture: a learned surrogate (1.02M parameters) predicts the two uncorrected-prior solves at 1.5 and 3 panels per gap and residual networks correct them. The surrogate is trained on more generated layouts (the prior of every on-stack layout plus 432,697 generated layouts labelled by the prior alone, against 385,593 for the paper's) and the networks are retrained on every labelled design (all 45,771 on-stack layouts, the paper's test split included). No field solve: the time is the geometric embedding."
1487
+ warning: "Use Fast only for quick screening of the component families it was trained on (interdigital, paddle, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated and synthetic campaign layouts). On new designs of a trained family (B5) it was worse than the physics alone, 3.175 % (MAE 0.583 / RMSE 0.824 fF) against 1.765 % (0.275 / 0.376 fF), and the paper's version of it was worse than the physics alone on a held-out family too, 3.11 % (0.533 / 0.633 fF) against 1.55 % (0.166 / 0.205 fF). Use Accurate for anything that matters."
1488
+ own: # data_local/flagship_v4/scores/tables.json pooled.fast_sall_all_s0_ens (agents/flagship_v4/RESULTS.md section 2)
1489
+ insample: {set: "in-sample, all 45,771 training layouts (TRAIN + VAL + the paper's test split; it was trained on them)", median_pct: 0.671, mae_ff: 0.353, rmse_ff: 0.395}
1490
  reference:
1491
+ recipe: "the paper's version of the fast model (surrogate t100_norm trained on 385,593 generated layouts + the TRAIN geometry; networks trained on the 35,354 TRAIN layouts only). These held-out numbers belong to the paper's version, not to this release, which was trained on the paper's test split too"
1492
  val: {median_pct: 0.846, mae_ff: 0.491, rmse_ff: 0.549}
1493
  test_infamily: {median_pct: 0.630, mae_ff: 0.1130, rmse_ff: 0.1414}
1494
  test_zeroshot: {median_pct: 3.576, mae_ff: 4.608, rmse_ff: 5.058}
1495
  heldout_family: {median_pct: 3.113, mae_ff: 0.533, rmse_ff: 0.633}
1496
  heldout_family_physics: {median_pct: 1.554, mae_ff: 0.166, rmse_ff: 0.205}
1497
+ val_same_surrogate: {median_pct: 0.722, mae_ff: 0.387, rmse_ff: 0.436, note: "this release's surrogate recipe trained without the validation layouts (P6 SUR-ALL) + the paper's TRAIN-only networks, held out (agents/surcov_p6/RESULTS_P6.md)"}
1498
  b5: {median_pct: 3.175, mae_ff: 0.583, rmse_ff: 0.824}
1499
  b5_physics: {name: "physics alone C^R = R(1.5, 3) (worse than the physics: Fast is behind it here)", median_pct: 1.765, mae_ff: 0.275, rmse_ff: 0.376}
1500
  time_space: "interdigital 0.036 s, xmon 0.11 s, 1-qubit lattice (N 15) 0.82 s, 16-conductor layout 0.49 s, 9-qubit lattice (N 67) 3.9 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s)"
tlsq_infer/app_ui.py CHANGED
@@ -75,6 +75,10 @@ def _roles(table) -> tuple[list, list, list]:
75
  except (TypeError, ValueError, KeyError):
76
  continue
77
  role = str(r.get("role", "ignore")).strip().lower()
 
 
 
 
78
  (g if role.startswith("g") else c if role.startswith("c") else i).append(key)
79
  return g or [(1, 0)], c or [(1, 10)], i
80
 
 
75
  except (TypeError, ValueError, KeyError):
76
  continue
77
  role = str(r.get("role", "ignore")).strip().lower()
78
+ if "+" in role or role.startswith("b"): # ground+conductor / both: one layer holds both, the ground is detected
79
+ g.append(key)
80
+ c.append(key)
81
+ continue
82
  (g if role.startswith("g") else c if role.startswith("c") else i).append(key)
83
  return g or [(1, 0)], c or [(1, 10)], i
84
 
tlsq_infer/app_v2.py CHANGED
@@ -63,17 +63,17 @@ def _crop(crop, margin_gaps, margin_um):
63
  return (float(margin_gaps) if margin_gaps not in (None, "", 0, 0.0) else "auto"), mu
64
 
65
 
66
- def _prepare(f, table, crop, margin_gaps, margin_um, select):
67
  g, c, i = _roles(table)
68
  mg, mu = _crop(crop, margin_gaps, margin_um)
69
  return prepare(_path(f), ground_layers=g, conductor_layers=c, ignore_layers=i, margin_gaps=mg, margin_um=mu,
70
- select=_parse_select(select), max_conductors=LIMITS["max_conductors"])
71
 
72
 
73
- def prepare_fn(f, table, crop, margin_gaps, margin_um, select):
74
  import matplotlib
75
  matplotlib.use("Agg")
76
- lay = _prepare(f, table, crop, margin_gaps, margin_um, select)
77
  fig = lay.render()
78
  fig.tight_layout()
79
  out = _outdir() / "prepared_1-0_ground_1-10_conductors.gds"
 
63
  return (float(margin_gaps) if margin_gaps not in (None, "", 0, 0.0) else "auto"), mu
64
 
65
 
66
+ def _prepare(f, table, crop, margin_gaps, margin_um, select, ground_pieces=None):
67
  g, c, i = _roles(table)
68
  mg, mu = _crop(crop, margin_gaps, margin_um)
69
  return prepare(_path(f), ground_layers=g, conductor_layers=c, ignore_layers=i, margin_gaps=mg, margin_um=mu,
70
+ select=_parse_select(select), max_conductors=LIMITS["max_conductors"], ground_pieces=ground_pieces)
71
 
72
 
73
+ def prepare_fn(f, table, crop, margin_gaps, margin_um, select, ground_pieces=None):
74
  import matplotlib
75
  matplotlib.use("Agg")
76
+ lay = _prepare(f, table, crop, margin_gaps, margin_um, select, ground_pieces)
77
  fig = lay.render()
78
  fig.tight_layout()
79
  out = _outdir() / "prepared_1-0_ground_1-10_conductors.gds"
tlsq_infer/layout.py CHANGED
@@ -60,10 +60,13 @@ def read_polygons(path, cell: str | None = None) -> tuple[dict, float, str]:
60
 
61
  def load_gds(path, layer_map: dict | None = None, cell: str | None = None) -> list[dict]:
62
  """Detected (layer, datatype) pairs with polygon count, area (µm²) and bounding box (µm), plus a suggested role
63
- (ground / conductor / ignore) from `layer_map` ({"ground": [(1, 0)], "conductor": [(1, 10)]} by default)."""
 
64
  layer_map = layer_map or {"ground": [GROUND], "conductor": [CONDUCTOR]}
65
  lm = {tuple(k): role for role, ks in layer_map.items() for k in ks}
66
  polys, _, top = read_polygons(path, cell)
 
 
67
  rows = []
68
  for (l, d), ps in sorted(polys.items()):
69
  b = shapely.union_all(ps).bounds if ps else (np.nan,) * 4
@@ -120,6 +123,47 @@ def _core_bounds(G, bodies: list, warnings: list) -> tuple:
120
  return (min(sb[0], pb[0]), min(sb[1], pb[1]), max(sb[2], pb[2]), max(sb[3], pb[3]))
121
 
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  @dataclass
124
  class PreparedLayout:
125
  ground: object # shapely geometry (µm), cropped
@@ -131,6 +175,7 @@ class PreparedLayout:
131
  warnings: list[str] = field(default_factory=list)
132
  extra_metal: dict = field(default_factory=dict) # label -> geometry of metal inside the window that is not modelled
133
  info: dict = field(default_factory=dict)
 
134
 
135
  @property
136
  def n_conductors(self) -> int:
@@ -169,8 +214,10 @@ class PreparedLayout:
169
  lib.write_gds(str(path))
170
  return Path(path).read_bytes()
171
 
172
- def render(self, ax=None, show_window: bool = True, title: str | None = None):
173
- """Matplotlib figure: ground (grey), conductors (coloured, labelled), unmodelled metal (hatched), window."""
 
 
174
  import matplotlib.pyplot as plt
175
  from matplotlib.patches import PathPatch, Rectangle
176
  from matplotlib.path import Path as MPath
@@ -187,16 +234,23 @@ class PreparedLayout:
187
  ax.add_patch(PathPatch(MPath(verts, codes), **kw))
188
 
189
  if ax is None:
190
- fig, ax = plt.subplots(figsize=(6.4, 6.4))
191
  else:
192
  fig = ax.figure
193
  patch(self.ground, facecolor="#b9bec7", edgecolor="#6b7280", lw=0.4)
194
  cmap = plt.get_cmap("tab10")
 
 
195
  for k, (g, nm) in enumerate(zip(self.conductors, self.names)):
196
  patch(g, facecolor=cmap(k % 10), edgecolor="black", lw=0.4, alpha=0.9)
197
  p = g.representative_point() if g.area > 0 else g.centroid
198
- ax.annotate(nm, (p.x, p.y), ha="center", va="center", fontsize=11, weight="bold", color="white",
199
  bbox=dict(boxstyle="round,pad=0.2", fc=cmap(k % 10), ec="black", lw=0.6))
 
 
 
 
 
200
  for lab, g in self.extra_metal.items():
201
  patch(g, facecolor="none", edgecolor="#dc2626", hatch="///", lw=0.6)
202
  if show_window and self.window is not None:
@@ -209,13 +263,16 @@ class PreparedLayout:
209
  ax.set_aspect("equal")
210
  ax.set_xlabel("x (µm)")
211
  ax.set_ylabel("y (µm)")
212
- ax.set_title(title or f"{len(self.conductors)} conductors + ground; min gap {self.min_gap_um:.2f} µm")
 
 
 
213
  return fig
214
 
215
 
216
  def prepare(path, ground_layers=(GROUND,), conductor_layers=(CONDUCTOR,), margin_gaps: float | str | None = None,
217
  margin_um: float | None = None, ignore_layers=(), cell: str | None = None, select=None, select_box=None,
218
- max_conductors: int = N_MAX_SIGNALS) -> PreparedLayout:
219
  """Extract the capacitance problem from a GDS file.
220
 
221
  - conductors: connected bodies of the conductor-layer polygons (touching/overlapping polygons are one net), in file
@@ -227,16 +284,76 @@ def prepare(path, ground_layers=(GROUND,), conductor_layers=(CONDUCTOR,), margin
227
  - select: optional list of conductor-body indices (0-based, file order), or select_box = (x0, y0, x1, y1) µm (bodies
228
  fully inside); the other bodies are not modelled and are flagged as extra metal when they fall inside the window.
229
  - metal on layers that are neither ground, conductor nor in `ignore_layers` is flagged when inside the window.
 
 
 
 
 
 
230
  """
231
  gl = {tuple(x) for x in ground_layers}
232
  cl = {tuple(x) for x in conductor_layers}
233
  il = {tuple(x) for x in ignore_layers}
234
- if gl & cl:
235
- raise LayoutError(f"layers {sorted(gl & cl)} are assigned both ground and conductor")
 
236
  polys, _, top = read_polygons(path, cell)
237
  warnings: list[str] = []
238
- gpolys = [p for k in polys if k in gl for p in polys[k]]
239
- cpolys = [p for k in polys if k in cl for p in polys[k]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  if not gpolys:
241
  raise LayoutError(f"no ground polygons on {sorted(gl)}; detected layers: {sorted(polys)}")
242
  if not cpolys:
@@ -335,6 +452,25 @@ def prepare(path, ground_layers=(GROUND,), conductor_layers=(CONDUCTOR,), margin
335
  warnings.append(f"smallest gap {gap:.3g} µm is below the MoM resolution floor for a {size:.0f} µm layout "
336
  f"(~{3 * size / 4096:.3g} µm): crop tighter or expect larger errors")
337
  names = [f"C{i + 1}" for i in range(len(bodies))]
 
 
 
 
 
338
  info = {"cell": top, "margin_um": m if window else None, "n_conductor_polygons": len(cvalid), "n_bodies_total": len(all_bodies), "layout_size_um": float(size),
339
  "extent_um": float(np.hypot(*np.subtract(shapely.union_all(bodies).bounds[2:], shapely.union_all(bodies).bounds[:2])))}
340
- return PreparedLayout(G, bodies, names, window, float(gap), str(path), warnings, extra, info)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  def load_gds(path, layer_map: dict | None = None, cell: str | None = None) -> list[dict]:
62
  """Detected (layer, datatype) pairs with polygon count, area (µm²) and bounding box (µm), plus a suggested role
63
+ (ground / conductor / ground+conductor / ignore) from `layer_map` ({"ground": [(1, 0)], "conductor": [(1, 10)]} by default;
64
+ a single-layer file without them gets "ground+conductor")."""
65
  layer_map = layer_map or {"ground": [GROUND], "conductor": [CONDUCTOR]}
66
  lm = {tuple(k): role for role, ks in layer_map.items() for k in ks}
67
  polys, _, top = read_polygons(path, cell)
68
+ if len(polys) == 1 and not set(lm) <= set(polys):
69
+ lm = {k: "ground+conductor" for k in polys} # one metal layer: ground detected among its pieces (prepare)
70
  rows = []
71
  for (l, d), ps in sorted(polys.items()):
72
  b = shapely.union_all(ps).bounds if ps else (np.nan,) * 4
 
123
  return (min(sb[0], pb[0]), min(sb[1], pb[1]), max(sb[2], pb[2]), max(sb[3], pb[3]))
124
 
125
 
126
+ RECT_FILL, AREA_RATIO_LOW = 0.95, 2.0 # ground detection: near-rectangular outline; top-2 piece areas within this ratio = low confidence
127
+
128
+
129
+ def _shell(g):
130
+ """The piece with its openings filled (outer boundary only)."""
131
+ return shapely.union_all([Polygon(p.exterior) for p in getattr(g, "geoms", [g]) if p.geom_type == "Polygon"])
132
+
133
+
134
+ def detect_ground(geoms: list) -> tuple[list[int], str, str]:
135
+ """(ground piece indices, reason, confidence) for metal pieces that share one layer. Ground = the piece whose openings
136
+ contain every other piece; else the largest near-rectangular piece touching the layout bounding box; else the largest."""
137
+ n = len(geoms)
138
+ areas = [float(g.area) for g in geoms]
139
+ shells = [_shell(g) for g in geoms]
140
+ enc = [i for i in range(n) if all(shells[i].contains(geoms[j]) for j in range(n) if j != i)]
141
+ if len(enc) == 1:
142
+ k, why = enc[0], "it encloses every other piece (they sit in its openings)"
143
+ else:
144
+ B = shapely.union_all(geoms).bounds
145
+ tol = 1e-6 * max(B[2] - B[0], B[3] - B[1])
146
+
147
+ def rect_edge(i):
148
+ with np.errstate(divide="ignore", invalid="ignore"): # GEOS warns on axis-aligned rectangles; the envelope is still right
149
+ fill = shells[i].area / max(shells[i].minimum_rotated_rectangle.area, 1e-30)
150
+ return fill >= RECT_FILL and any(abs(a - b) <= tol for a, b in zip(shells[i].bounds, B))
151
+
152
+ cand = [i for i in range(n) if rect_edge(i)]
153
+ if cand:
154
+ k = max(cand, key=lambda i: areas[i])
155
+ why = "no piece encloses all the others; it is the largest near-rectangular piece on the layout boundary"
156
+ else:
157
+ k = max(range(n), key=lambda i: areas[i])
158
+ why = "no piece encloses all the others and none is a near-rectangular piece on the layout boundary; it is the largest"
159
+ top = sorted(areas, reverse=True)
160
+ close = n > 1 and top[0] < AREA_RATIO_LOW * top[1]
161
+ conf = "high" if len(enc) == 1 and not close else "low"
162
+ if close:
163
+ why += f"; the two largest pieces are within {AREA_RATIO_LOW:g}x in area"
164
+ return [k], why, conf
165
+
166
+
167
  @dataclass
168
  class PreparedLayout:
169
  ground: object # shapely geometry (µm), cropped
 
175
  warnings: list[str] = field(default_factory=list)
176
  extra_metal: dict = field(default_factory=dict) # label -> geometry of metal inside the window that is not modelled
177
  info: dict = field(default_factory=dict)
178
+ pieces: list = field(default_factory=list) # metal pieces (shapely, µm) when ground and conductors share a layer; piece #k = pieces[k - 1] (conductor Ck)
179
 
180
  @property
181
  def n_conductors(self) -> int:
 
214
  lib.write_gds(str(path))
215
  return Path(path).read_bytes()
216
 
217
+ def render(self, ax=None, show_window: bool = True, title: str | None = None, figsize=(6.4, 6.4), compact: bool = False):
218
+ """Matplotlib figure: ground (grey), conductors (coloured, labelled), unmodelled metal (hatched), window. When ground and
219
+ conductors share a layer, conductor piece #k is labelled Ck and ground pieces "G #k" (the numbers ground_pieces takes);
220
+ compact = smaller labels."""
221
  import matplotlib.pyplot as plt
222
  from matplotlib.patches import PathPatch, Rectangle
223
  from matplotlib.path import Path as MPath
 
234
  ax.add_patch(PathPatch(MPath(verts, codes), **kw))
235
 
236
  if ax is None:
237
+ fig, ax = plt.subplots(figsize=figsize)
238
  else:
239
  fig = ax.figure
240
  patch(self.ground, facecolor="#b9bec7", edgecolor="#6b7280", lw=0.4)
241
  cmap = plt.get_cmap("tab10")
242
+ gd = self.info.get("ground_detection")
243
+ fs = 8 if compact else 11
244
  for k, (g, nm) in enumerate(zip(self.conductors, self.names)):
245
  patch(g, facecolor=cmap(k % 10), edgecolor="black", lw=0.4, alpha=0.9)
246
  p = g.representative_point() if g.area > 0 else g.centroid
247
+ ax.annotate(nm, (p.x, p.y), ha="center", va="center", fontsize=fs, weight="bold", color="white",
248
  bbox=dict(boxstyle="round,pad=0.2", fc=cmap(k % 10), ec="black", lw=0.6))
249
+ for r in (gd or {}).get("pieces", []):
250
+ if r["role"] != "conductor":
251
+ x, y = r["label_xy"]
252
+ ax.annotate(f"{'G' if r['role'] == 'ground' else 'not modelled'} #{r['id']}", (x, y), ha="center", va="center",
253
+ fontsize=fs, weight="bold", color="#111827", bbox=dict(boxstyle="round,pad=0.2", fc="#e5e7eb", ec="#374151", lw=0.6))
254
  for lab, g in self.extra_metal.items():
255
  patch(g, facecolor="none", edgecolor="#dc2626", hatch="///", lw=0.6)
256
  if show_window and self.window is not None:
 
263
  ax.set_aspect("equal")
264
  ax.set_xlabel("x (µm)")
265
  ax.set_ylabel("y (µm)")
266
+ if title is None and gd:
267
+ title = (f"ground = piece {', '.join(f'#{i}' for i in gd['ground_pieces'])} ({gd['method']}, confidence {gd['confidence']}); "
268
+ f"{len(self.conductors)} conductors")
269
+ ax.set_title(title or f"{len(self.conductors)} conductors + ground; min gap {self.min_gap_um:.2f} µm", fontsize=10)
270
  return fig
271
 
272
 
273
  def prepare(path, ground_layers=(GROUND,), conductor_layers=(CONDUCTOR,), margin_gaps: float | str | None = None,
274
  margin_um: float | None = None, ignore_layers=(), cell: str | None = None, select=None, select_box=None,
275
+ max_conductors: int = N_MAX_SIGNALS, ground_pieces=None) -> PreparedLayout:
276
  """Extract the capacitance problem from a GDS file.
277
 
278
  - conductors: connected bodies of the conductor-layer polygons (touching/overlapping polygons are one net), in file
 
284
  - select: optional list of conductor-body indices (0-based, file order), or select_box = (x0, y0, x1, y1) µm (bodies
285
  fully inside); the other bodies are not modelled and are flagged as extra metal when they fall inside the window.
286
  - metal on layers that are neither ground, conductor nor in `ignore_layers` is flagged when inside the window.
287
+ - ground and conductors on one layer (ground_layers == conductor_layers, or a file with a single metal layer while the default
288
+ layers 1/0 and 1/10 are not both present): the layer's metal is split into connected pieces and the ground is detected
289
+ (detect_ground; result and confidence in info["ground_detection"], plus a warning). Pieces are numbered with the
290
+ automatically detected ground last and the others in file order, and conductor piece #k is named Ck, so the automatic
291
+ split names its conductors as the two-layer file does and names stay put when roles change. ground_pieces = piece
292
+ numbers (as in render()) overrides the pick; several pieces make one ground net.
293
  """
294
  gl = {tuple(x) for x in ground_layers}
295
  cl = {tuple(x) for x in conductor_layers}
296
  il = {tuple(x) for x in ignore_layers}
297
+ if gl & cl and gl != cl:
298
+ raise LayoutError(f"layers {sorted(gl & cl)} are assigned both ground and conductor (assign the same layers to both to detect "
299
+ "the ground automatically)")
300
  polys, _, top = read_polygons(path, cell)
301
  warnings: list[str] = []
302
+ metal = [k for k in polys if k not in il]
303
+ shared = None
304
+ if gl == cl:
305
+ shared = gl
306
+ elif gl == {GROUND} and cl == {CONDUCTOR} and len(metal) == 1 and not (GROUND in polys and CONDUCTOR in polys):
307
+ shared = set(metal)
308
+ if shared is None and ground_pieces is not None:
309
+ raise LayoutError("ground_pieces applies only when ground and conductors share one layer (the same ground and conductor "
310
+ "layers, or a single-layer file)")
311
+ pieces, gdet = [], None
312
+ if shared is not None:
313
+ gl = cl = shared
314
+ allp = [p for k in polys if k in shared for p in polys[k]]
315
+ if not allp:
316
+ raise LayoutError(f"no polygons on {sorted(shared)}; detected layers: {sorted(polys)}")
317
+ val = [_valid(p) for p in allp]
318
+ ok = [i for i, g in enumerate(val) if not g.is_empty and g.area > 0]
319
+ comps = [[ok[j] for j in c] for c in _components([val[i] for i in ok])]
320
+ pieces = [val[c[0]] if len(c) == 1 else _valid(shapely.union_all([val[i] for i in c])) for c in comps]
321
+ if len(pieces) < 2:
322
+ raise LayoutError(f"the metal on {sorted(shared)} is one connected piece: no floating conductor to compute")
323
+ auto, why, conf = detect_ground(pieces)
324
+ order = [i for i in range(len(pieces)) if i not in auto] + auto
325
+ pieces, comps = [pieces[i] for i in order], [comps[i] for i in order]
326
+ if ground_pieces is None:
327
+ gids, method = list(range(len(pieces) - len(auto), len(pieces))), "automatic"
328
+ else:
329
+ try:
330
+ gp = [x for x in ground_pieces.split(",") if x.strip()] if isinstance(ground_pieces, str) else list(ground_pieces)
331
+ gids = sorted({int(i) - 1 for i in gp})
332
+ except (TypeError, ValueError) as e:
333
+ raise LayoutError(f"ground_pieces must be piece numbers such as [1] or '1,4' (got {ground_pieces!r})") from e
334
+ bad = [i + 1 for i in gids if not 0 <= i < len(pieces)]
335
+ if bad or not gids:
336
+ raise LayoutError(f"ground_pieces {bad or list(ground_pieces)} not valid: this layout has pieces 1..{len(pieces)} "
337
+ "(numbers as in the labelled figure)")
338
+ if len(gids) == len(pieces):
339
+ raise LayoutError("ground_pieces lists every piece: at least one piece must be a conductor")
340
+ why, conf, method = f"set by ground_pieces={[i + 1 for i in gids]}", "user", "user"
341
+ gset = {i for g in gids for i in comps[g]}
342
+ gpolys = [allp[i] for i in sorted(gset)]
343
+ cpolys = [allp[i] for i in range(len(allp)) if i not in gset]
344
+ lay_s = ", ".join(f"{k[0]}/{k[1]}" for k in sorted(shared))
345
+ ids = ", ".join(f"#{g + 1}" for g in gids)
346
+ if method == "automatic":
347
+ warnings.append(f"ground and conductors share layer {lay_s}: the ground was detected automatically as piece {ids} ({why}; "
348
+ f"confidence {conf}). Check the numbered figure of the pieces and, if it is wrong, resubmit with "
349
+ "ground_pieces=[piece numbers].")
350
+ else:
351
+ warnings.append(f"ground and conductors share layer {lay_s}: ground = piece {ids} (set by ground_pieces)")
352
+ gdet = {"layers": [list(k) for k in sorted(shared)], "method": method, "ground_pieces": [g + 1 for g in gids], "reason": why,
353
+ "confidence": conf, "n_pieces": len(pieces)}
354
+ else:
355
+ gpolys = [p for k in polys if k in gl for p in polys[k]]
356
+ cpolys = [p for k in polys if k in cl for p in polys[k]]
357
  if not gpolys:
358
  raise LayoutError(f"no ground polygons on {sorted(gl)}; detected layers: {sorted(polys)}")
359
  if not cpolys:
 
452
  warnings.append(f"smallest gap {gap:.3g} µm is below the MoM resolution floor for a {size:.0f} µm layout "
453
  f"(~{3 * size / 4096:.3g} µm): crop tighter or expect larger errors")
454
  names = [f"C{i + 1}" for i in range(len(bodies))]
455
+ if gdet is not None:
456
+ gset = set(gdet["ground_pieces"])
457
+ cond = sorted((k for k in range(1, len(pieces) + 1) if k not in gset), key=lambda k: comps[k - 1][0]) # file order = body order
458
+ piece_of = dict(zip(map(id, all_bodies), cond)) if len(cond) == len(all_bodies) else {}
459
+ names = [f"C{piece_of[id(b)]}" if piece_of else nm for b, nm in zip(bodies, names)]
460
  info = {"cell": top, "margin_um": m if window else None, "n_conductor_polygons": len(cvalid), "n_bodies_total": len(all_bodies), "layout_size_um": float(size),
461
  "extent_um": float(np.hypot(*np.subtract(shapely.union_all(bodies).bounds[2:], shapely.union_all(bodies).bounds[:2])))}
462
+ if gdet is not None:
463
+ info["ground_detection"] = _detection_info(gdet, pieces, comps, {piece_of[id(b)]: nm for b, nm in zip(bodies, names)} if piece_of else {})
464
+ return PreparedLayout(G, bodies, names, window, float(gap), str(path), warnings, extra, info, pieces)
465
+
466
+
467
+ def _detection_info(gdet: dict, pieces: list, comps: list, name_of: dict) -> dict:
468
+ """JSON-ready record of the pieces and their roles (name_of: piece number -> conductor name of the modelled conductors)."""
469
+ gset = set(gdet["ground_pieces"])
470
+ rows = []
471
+ for i, g in enumerate(pieces, 1):
472
+ p = g.representative_point()
473
+ role = "ground" if i in gset else "conductor" if i in name_of else "not modelled"
474
+ rows.append({"id": i, "role": role, "name": "G" if i in gset else name_of.get(i), "area_um2": round(float(g.area), 3),
475
+ "bbox_um": [round(float(x), 3) for x in g.bounds], "n_polygons": len(comps[i - 1]), "label_xy": [float(p.x), float(p.y)]})
476
+ return {**gdet, "pieces": rows}
tlsq_infer/predict.py CHANGED
@@ -466,9 +466,10 @@ def intervals_csv(result: dict) -> str:
466
  return "\n".join(lines) + "\n"
467
 
468
 
469
- def matrix_csv(result: dict) -> str:
 
470
  names = result["names"]
471
- lines = ["," + ",".join(names)]
472
  for nm, row in zip(names, result["matrix_fF"]):
473
  lines.append(nm + "," + ",".join("" if (v is None or (isinstance(v, float) and np.isnan(v))) else f"{v:.6g}" for v in row))
474
  return "\n".join(lines) + "\n"
 
466
  return "\n".join(lines) + "\n"
467
 
468
 
469
+ def matrix_csv(result: dict, corner: str = "") -> str:
470
+ """CSV of the matrix; corner = text of the top-left header cell (e.g. the unit "fF")."""
471
  names = result["names"]
472
+ lines = [corner + "," + ",".join(names)]
473
  for nm, row in zip(names, result["matrix_fF"]):
474
  lines.append(nm + "," + ",".join("" if (v is None or (isinstance(v, float) and np.isnan(v))) else f"{v:.6g}" for v in row))
475
  return "\n".join(lines) + "\n"