shanto268 commited on
Commit
44a0d59
·
verified ·
1 Parent(s): 3897829

sync from registry v1

Browse files
.tlsq_deploy ADDED
@@ -0,0 +1 @@
 
 
1
+ managed by deploy/sync.py (registry v1)
LIMITS.md ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deployment limits (tlsq_infer 0.1.0)
2
+
3
+ Measured, not estimated. Sources: `deploy/tests/results/stress.json` (local, 2-thread budget),
4
+ `deploy/tests/results/reproduction_*.json` (accuracy vs crop), `deploy/tests/results/robustness.json`.
5
+
6
+ ## 1. Local, 2-thread budget (HF free-tier proxy)
7
+
8
+ Apple M-series host, `torch.set_num_threads(2)`, OMP/BLAS = 2 threads, one fresh process per case (peak RSS of that
9
+ process). Model pair-local unless stated. Wall = prepare + MoM prior + features + network.
10
+
11
+ | sweep | value | wall (s) | MoM prior (s) | features (s) | MoM cells | peak RSS (GB) |
12
+ |---|---|---|---|---|---|---|
13
+ | two pads, gap 5 µm, size (µm) | 1,020 | 0.8 | 0.8 | 0.03 | 6,658 | 1.04 |
14
+ | | 1,620 | 0.9 | 0.8 | 0.09 | 4,964 | 0.70 |
15
+ | | 4,820 | 3.8 | 3.3 | 0.53 | 7,244 | 1.24 |
16
+ | | 8,820 | 5.6 | 4.0 | 1.6 | 5,580 | 0.88 |
17
+ | | 20,820 | 11.8 | 4.1 | 7.7 | 4,116 | 0.65 |
18
+ | interdigital comb, 5 µm fingers/gaps, fingers | 10 | 1.4 | 1.2 | 0.19 | 5,900 | 0.87 |
19
+ | | 25 | 3.5 | 3.0 | 0.41 | 7,473 | 1.24 |
20
+ | | 50 | 6.2 | 5.5 | 0.62 | 3,680 | 0.58 |
21
+ | | 100 | 14.4 | 13.0 | 1.4 | 1,916 | 0.43 |
22
+ | | 200 | 38.9 | 35.5 | 3.4 | 6,421 | 1.23 |
23
+ | | 400 | 85.8 | 76.1 | 9.7 | 2,690 | 0.73 |
24
+ | conductor count (pads, 30 µm gaps) | 1 / 3 / 5 / 7 | 0.07 / 0.25 / 0.21 / 0.32 | | | | <= 0.38 |
25
+ | | 8 | rejected (cap: 7 conductors + ground) | | | | |
26
+ | full-chip GDS (10 mm), polygons | 1k / 10k / 100k / 300k | 0.15 / 0.46 / 4.7 / 16.4 | | | | 0.27 / 0.30 / 0.73 / 1.75 |
27
+ | model at comb 25 / 200 | pair-local | 3.4 / 39.2 | | | | 1.24 |
28
+ | | blend-pair-local | 4.3 / 39.8 (+0.08 s charge correction, +0.7 s first GBM load) | | | | 1.37 |
29
+ | | message-passing | 3.5 / 40.3 | | | | 1.25 |
30
+ | | fine-mom-prior (16k cells) | 5.7 / 52.0 | | | | 1.26 |
31
+
32
+ Findings
33
+ * **No failure point was reached** within a 300 s timeout or the 16 GB budget: the largest case (400-finger comb,
34
+ 8.8 mm) took 86 s and every case peaked below 1.8 GB RSS. The MoM matrix is capped at 8,000 cells (16,000 fine), so
35
+ memory is bounded (~1.4 GB per standard request, ~4-5 GB worst case for the fine prior).
36
+ * **Latency is driven by boundary complexity, not cell count**: the MoM mesh builder (quadtree + shapely coverage,
37
+ repeated with coarser h_min until <= 8,000 cells) dominates; long, finely gapped boundaries (combs, meanders) cost
38
+ most. Feature extraction samples every boundary at 0.25 µm and grows linearly with total perimeter (7.7 s at 21 mm).
39
+ * The network itself is < 3 ms; charge correction < 0.1 s (it reuses the prior's solve).
40
+ * GDS parsing: ~55 µs per polygon (300k polygons: 16 s, 1.75 GB).
41
+ * Paper-family designs (1 thread, all 926 never-seen designs): median 5.8 s, p90 34 s per design for blend + message
42
+ passing (two MoM solves); a single model is about half.
43
+
44
+ Recommended caps (implemented in `tlsq_infer/app_ui.py`, overridable by env):
45
+ * file <= 25 MB (`TLSQ_MAX_FILE_MB`), <= 200,000 polygons (`TLSQ_MAX_POLYGONS`), <= 7 conductors + ground;
46
+ * queue concurrency 2 per Space (`TLSQ_CONCURRENCY`; each request uses ~2 threads and <= 1.5 GB);
47
+ * expect ~1-10 s for single components, up to ~90 s for very long interdigitated or meandered boundaries.
48
+
49
+ ## 2. Ground crop and accuracy
50
+
51
+ The training chips extend 150-330 µm (15-220 conductor-ground gaps) beyond the conductors. Cropping the ground tighter
52
+ changes both the physics and the network input. 150 random never-seen designs, all mutual entries, median % / MAE fF /
53
+ RMSE fF (`reproduction_n150_crop_margins.json`, `reproduction_n150_auto.json`):
54
+
55
+ | crop | pair-local | blend-pair-local |
56
+ |---|---|---|
57
+ | none (paper setting) | 1.78 / 0.98 / 1.82 | 1.70 / 0.84 / 1.53 |
58
+ | **auto** (default: max(100 gaps, half the conductor extent, 150 µm) around the conductors and their pocket) | **1.87 / 1.00 / 1.83** | **1.82 / 0.87 / 1.54** |
59
+ | 100 gaps | 1.96 / 1.01 / 1.84 | 1.93 / 0.92 / 1.60 |
60
+ | 50 gaps | 2.61 / 1.32 / 2.27 | 2.56 / 1.31 / 2.30 |
61
+ | 20 gaps | 3.76 / 2.13 / 3.81 | 3.71 / 2.20 / 4.08 |
62
+ | 10 gaps | 4.77 / 2.76 / 4.95 | 4.90 / 2.90 / 5.36 |
63
+
64
+ (Errors against the labels of the uncropped chips, so tight crops also measure the physical change of removing ground.)
65
+ Default is therefore `auto`; tight windows are available but flagged in the docs.
66
+
67
+ ## 3. Robustness (219 files, `robustness.json`)
68
+
69
+ | source | files | result | rejected (clean error) | crashes |
70
+ |---|---|---|---|---|
71
+ | Qiskit Metal singletons (all) | 36 | 36 physical matrices | 0 | 0 |
72
+ | Qiskit Metal parametric sweeps (3 per class, 29 classes) | 87 | 87 | 0 | 0 |
73
+ | our families (exp6, exp13-15) | 15 | 15 | 0 | 0 |
74
+ | OOD-60 shapes | 60 | 60 | 0 | 0 |
75
+ | synthetic adversarial | 21 | 15 | 6 (as expected) | 0 |
76
+
77
+ Synthetic cases: non-default layers (clean error with defaults, works with explicit roles), 10 mm full-chip ground with
78
+ 48 conductors (clean error; works with `select` / `select_box`, unselected bodies flagged), conductor with holes and an
79
+ island inside, 50 nm gap (resolution-floor warning), 7 conductors (ok) / 8 (clean error), overlapping and edge-sharing
80
+ polygons (merged into one net), conductor touching ground (merged into ground, warning), references + FlexPath
81
+ (flattened), ground split by the window, no ground / empty / non-GDS (clean errors), 8 mm pocket. Invariance:
82
+ translation by 1e5 µm, 90° rotation and nm database units give identical matrices (max rel. diff 0).
83
+ Physical checks: all mutuals negative and self terms positive in every returned matrix. The network self term is
84
+ below the row sum of mutuals (C_ii < sum |C_ij|) in 87/213 matrices (mostly Qiskit Metal parts far from the training
85
+ families): use `self_from_rows=True` when a strictly consistent Maxwell matrix is needed.
86
+
87
+ ## 4. Deployed Spaces (HF free tier, cpu-basic)
88
+
89
+ Not measured yet: the push to the Hub was not performed (blocked pending the user's explicit approval). After
90
+ `python deploy/sync.py --push`, run `python deploy/tests/test_app.py --url SQuADDS/PlanarCapacitanceModel` (HF_TOKEN in
91
+ the environment for private Spaces) and the same stress cases through gradio_client, and fill this section.
README.md CHANGED
@@ -1,13 +1,27 @@
1
  ---
2
- title: PlanarCapacitanceModel
3
- emoji: 🐠
4
- colorFrom: green
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.29.1
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
 
 
 
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
1
  ---
2
+ title: Planar Capacitance Model
3
+ emoji: 🔌
4
+ colorFrom: blue
5
+ colorTo: gray
6
  sdk: gradio
7
  sdk_version: 6.29.1
8
+ python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
+ short_description: Zero-shot capacitance matrices of planar layouts
12
+ models:
13
+ - SQuADDS/2026PaperModels-pair-local
14
+ - SQuADDS/2026PaperModels-message-passing
15
+ - SQuADDS/2026PaperModels-charge-corrected-prior
16
+ - SQuADDS/2026PaperModels-blend-pair-local
17
+ - SQuADDS/2026PaperModels-blend-message-passing
18
+ - SQuADDS/2026PaperModels-geometry-only
19
  ---
20
 
21
+ # Planar Capacitance Model
22
+
23
+ Upload a GDS of a planar superconducting layout (ground 1/0, conductors 1/10, or assign your layers) and get the full Maxwell capacitance matrix in fF, zero-shot. See also [shanto268/2026PaperModels](https://huggingface.co/spaces/shanto268/2026PaperModels).
24
+
25
+ Programmatic use: `examples/client.py` (gradio_client, endpoint `/predict_gds`).
26
+
27
+ Hardware: free CPU tier (2 vCPU, 16 GB); see LIMITS.md for measured latency and caps.
app.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Flagship Space: GDS -> zero-shot Maxwell capacitance matrix. Names and links come from registry.yaml."""
2
+
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ HERE = Path(__file__).resolve().parent
8
+ if (HERE / "tlsq_infer").exists(): # built Space bundle (deploy/sync.py): vendored package, registry and weights
9
+ sys.path.insert(0, str(HERE))
10
+ os.environ.setdefault("TLSQ_REGISTRY", str(HERE / "registry.yaml"))
11
+ os.environ.setdefault("TLSQ_MODEL_DIR", str(HERE / "models"))
12
+ else: # repository checkout
13
+ sys.path.insert(0, str(HERE.parents[1] / "tlsq_infer" / "src"))
14
+
15
+ from tlsq_infer.app_ui import build_app # noqa: E402
16
+ from tlsq_infer.registry import load_registry # noqa: E402
17
+
18
+ reg = load_registry()
19
+ hub = reg["hub"]
20
+ space = os.environ.get("SPACE_ID", hub["flagship_space"])
21
+ models = [m for m in ("pair-local", "blend-pair-local", "message-passing") if m in reg.deployable()]
22
+ default = reg["defaults"]["flagship_model"]
23
+ d = reg.model(default)["paper"]["never_seen"]
24
+ header = (f"Zero-shot Maxwell capacitance of planar superconducting layouts. Default model: **{reg.model(default)['title']}** "
25
+ f"({d['median_pct']} % median error, MAE {d['mae_ff']} fF, RMSE {d['rmse_ff']} fF on 926 never-seen designs). "
26
+ f"All paper models: [{hub['paper_models_space']}](https://huggingface.co/spaces/{hub['paper_models_space']}). "
27
+ f"Weights: [{reg.model(default)['repo_id']}](https://huggingface.co/{reg.model(default)['repo_id']}). "
28
+ f"Programmatic use: `gradio_client.Client(\"{space}\")` (see the API page and examples/client.py).")
29
+ demo = build_app(hub["flagship_title"], models, default, header, examples_dir=HERE / "examples")
30
+ demo.queue(default_concurrency_limit=int(os.environ.get("TLSQ_CONCURRENCY", 2)), max_size=32)
31
+
32
+ if __name__ == "__main__":
33
+ demo.launch(server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"), server_port=int(os.environ.get("PORT", 7860)))
examples/client.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Call the Space from Python (pip install gradio_client).
2
+
3
+ python client.py my_layout.gds [--space SQuADDS/PlanarCapacitanceModel] [--substrate sapphire...] [--thickness 430]
4
+
5
+ Private Spaces need a token: set HF_TOKEN in the environment (never hard-code it). A local app: --space http://127.0.0.1:7860/
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import os
11
+
12
+ from gradio_client import Client, handle_file
13
+
14
+ ap = argparse.ArgumentParser()
15
+ ap.add_argument("gds")
16
+ ap.add_argument("--space", default=os.environ.get("TLSQ_SPACE", "SQuADDS/PlanarCapacitanceModel"))
17
+ ap.add_argument("--ground", default="1/0", help="ground layer/datatype list, e.g. '1/0' or '1/0,5/0'")
18
+ ap.add_argument("--conductors", default="1/10")
19
+ ap.add_argument("--margin-gaps", type=float, default=0.0, help="ground crop margin in conductor-ground gaps (0: auto, < 0: no crop)")
20
+ ap.add_argument("--substrate", default="Si (cryogenic, training)", help="a substrate name of the Space, or 'custom eps_r'")
21
+ ap.add_argument("--eps", type=float, default=11.45, help="eps_r when --substrate 'custom eps_r'")
22
+ ap.add_argument("--thickness", type=float, default=350.0, help="substrate thickness (µm)")
23
+ ap.add_argument("--model", default="pair-local")
24
+ ap.add_argument("--self-from-rows", action="store_true")
25
+ a = ap.parse_args()
26
+
27
+ client = Client(a.space, token=os.environ.get("HF_TOKEN")) if not a.space.startswith("http") else Client(a.space)
28
+ res = client.predict(handle_file(a.gds), a.ground, a.conductors, a.margin_gaps, a.substrate, a.eps, a.thickness, a.model,
29
+ a.self_from_rows, api_name="/predict_gds")
30
+ names = res["names"]
31
+ print("Maxwell capacitance matrix (fF):")
32
+ print(" " + "".join(f"{n:>12s}" for n in names))
33
+ for n, row in zip(names, res["matrix_fF"]):
34
+ print(f"{n:>6s}" + "".join(f"{'--':>12s}" if v is None else f"{v:12.4f}" for v in row))
35
+ e = res["expected_error"]
36
+ print(f"\nmodel {res['model']} (package {res['package_version']}); eps factor {res['eps_correction_factor']:.4f}")
37
+ if "expected_median_pct" in e:
38
+ print(f"expected error: median {e['expected_median_pct']:.2f} %, MAE {e['expected_mae_ff']:.3f} fF, RMSE {e['expected_rmse_ff']:.3f} fF")
39
+ for w in res["warnings"]:
40
+ print("warning:", w)
41
+ with open("capacitance.json", "w") as f:
42
+ json.dump(res, f, indent=1)
examples/interdigital.gds ADDED
Binary file (4.25 kB). View file
 
examples/shielded_concentric.gds ADDED
Binary file (28.4 kB). View file
 
examples/transmon_pocket.gds ADDED
Binary file (1.19 kB). View file
 
examples/xmon.gds ADDED
Binary file (2.27 kB). View file
 
models/blend-pair-local/config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"name": "blend-pair-local", "files": []}
models/charge-corrected-prior/charge_gbm.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3dcca168d8d732c19b200eba17999774e71fc760a874f451147e9b07df8d8b47
3
+ size 677172
models/charge-corrected-prior/config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"name": "charge-corrected-prior", "files": ["charge_gbm.joblib"]}
models/message-passing/config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"name": "message-passing", "files": ["seed0.pt", "seed1.pt", "seed2.pt"]}
models/message-passing/seed0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3de2e4ea45dd70e7d9fefd563f42d5c38ac8e9dd990568383e38958d3e7d087
3
+ size 3028237
models/message-passing/seed1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a924d03e0d4ceecd2e29030c8dfb5d718240e2de97514d15eaece7ad8086b08
3
+ size 3028237
models/message-passing/seed2.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37551cbdb21ca9a896eb599f0285718f2fa50102665002c1b8340ca69c9e09b5
3
+ size 3028237
models/pair-local/config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"name": "pair-local", "files": ["seed0.pt", "seed1.pt", "seed2.pt"]}
models/pair-local/seed0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a8df1507d65f2b3decdbf70e66a59e5ddfd18861d973abe093b07507848d0eb
3
+ size 848449
models/pair-local/seed1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58be037a06e4771d40ed5312a31805290e68ad433009e183864715eb93b55a70
3
+ size 848449
models/pair-local/seed2.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58a2973c7bbbec8d3d385c63fd5f8f47c5088b4b0b7df0c110030512a57dbc3a
3
+ size 848449
registry.yaml ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Single source of truth for every released name, link and paper number of the tl-squadds capacitance models.
2
+ # Everything else (tlsq_infer model loader, Space apps, model cards, paper_ml/deploy_links.tex, the sync workflow)
3
+ # reads this file. Renaming a repo or Space = edit one line here, then run `python deploy/sync.py` (dry run) /
4
+ # `python deploy/sync.py --push`.
5
+ #
6
+ # Paths are relative to the repository root. Metrics: median |relative error| (%) / MAE (fF) / RMSE (fF) over all
7
+ # mutual entries, as in the paper (paper_ml/floats/tab_candidates.tex, paper_ml/tables/cost_rows.tex).
8
+
9
+ version: 1
10
+ package_version: "0.1.0"
11
+
12
+ hub:
13
+ org: SQuADDS
14
+ private: true # create every repo private; flip deliberately when the paper is public
15
+ space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM
16
+ flagship_space: shanto268/PlanarCapacitanceModel # org Gradio Spaces need a paid HF plan; move to SQuADDS/ by editing this line
17
+ flagship_title: Planar Capacitance Model
18
+ paper_models_space: shanto268/2026PaperModels
19
+ paper_models_title: 2026 Paper Models
20
+ collection: "Zero-shot planar capacitance models (2026)"
21
+ collection_slug: null # filled in by sync.py --push after the collection is created
22
+ code_url: null # public source repository of the training code, when released
23
+
24
+ paper:
25
+ short: "Zero-shot capacitance of planar superconducting layouts"
26
+ draft_dir: paper_ml
27
+ links_tex: paper_ml/deploy_links.tex
28
+ arxiv: null # set when posted; cards and Spaces pick it up
29
+
30
+ training_stack:
31
+ substrate: Si (cryogenic)
32
+ eps_r: 11.45
33
+ thickness_um: 350
34
+ metal: zero-thickness sheet (Q3D thin conductor)
35
+ layers: {ground: [1, 0], conductor: [1, 10]}
36
+ training_designs: 40153
37
+ training_families: [interdigital (CapNInterdigital), paddle, concentric, star, multi-pad star]
38
+
39
+ eval_sets:
40
+ never_seen:
41
+ name: never-seen components (Xmon, TransmonPocket, shielded concentric)
42
+ designs: 926
43
+ entries: all mutual entries
44
+ ood60:
45
+ name: OOD-60 (procedural near / intermediate / alien shapes)
46
+ designs: 60
47
+
48
+ blend:
49
+ weights_gnn_side: {signal-signal: 0.6, signal-ground: 0.7, pad: 0.8} # log-space; rest = charge-corrected prior
50
+ note: "pad = any entry involving the third or later signal body (file order), as in the paper"
51
+
52
+ self_capacitance:
53
+ row_sum_eps: 0.0143 # C_ii = sum_j |C_ij| / (1 - eps) (IMPROVE_IDEAS.md, training median)
54
+
55
+ substrates: # dropdown of the Spaces; the 11 materials of the stack DoE + the training substrate
56
+ Si (cryogenic, training): 11.45
57
+ sapphire (c-plane, isotropic eq.): 10.34
58
+ GaAs: 12.9
59
+ fused silica: 3.8
60
+ Si (room temperature): 11.7
61
+ SiC: 9.7
62
+ MgO: 9.8
63
+ InP: 12.4
64
+ Ge: 16.0
65
+ quartz (crystalline): 4.5
66
+ diamond: 5.7
67
+ LaAlO3: 24.0
68
+
69
+ artifacts:
70
+ charge_gbm: deploy/artifacts/charge_gbm.joblib # built once by `python -m tlsq_infer.charge fit`
71
+ charge_gbm_train_cells: data_local/charge_p1/train_cells.parquet
72
+ stack_error: deploy/artifacts/stack_error.json # built by `python deploy/stack_error.py fit`
73
+
74
+ defaults:
75
+ flagship_model: pair-local
76
+ paper_space_model: blend-pair-local
77
+
78
+ models:
79
+ # ---------------------------------------------------------------- learned, released
80
+ pair-local:
81
+ title: "Pair-local network + MoM prior (R=0)"
82
+ repo_id: SQuADDS/2026PaperModels-pair-local
83
+ kind: gnn
84
+ prior: standard
85
+ rounds: 0
86
+ status: available
87
+ checkpoints: [data_local/mega/ckpt/ALL_mom_r0_s0.pt, data_local/mega/ckpt/ALL_mom_r0_s1.pt, data_local/mega/ckpt/ALL_mom_r0_s2.pt]
88
+ parameters: 209410
89
+ summary: "Default. Cheapest learned model; best accuracy-per-second for screening many layouts."
90
+ paper:
91
+ appears_in: [tab:candidates, tab:costacc, fig:costacc, tab:splits, fig:zs-arch, fig:stack, tab:stack]
92
+ never_seen: {median_pct: 1.73, mae_ff: 0.83, rmse_ff: 1.62}
93
+ ood60: {median_pct: 1.81, mae_ff: 0.78, rmse_ff: 1.63}
94
+ in_family_id: {median_pct: 0.91, mae_ff: 0.063, rmse_ff: 0.181, note: grouped in-distribution split, signal-signal}
95
+ cost_s_per_design: {never_seen: 8.75, ood60: 0.60, note: one CPU core, all stages from the GDS}
96
+
97
+ message-passing:
98
+ title: "Message-passing network + MoM prior (R=3)"
99
+ repo_id: SQuADDS/2026PaperModels-message-passing
100
+ kind: gnn
101
+ prior: standard
102
+ rounds: 3
103
+ status: available
104
+ checkpoints: [data_local/mega/ckpt/ALL_mom_s0.pt, data_local/mega/ckpt/ALL_mom_s1.pt, data_local/mega/ckpt/ALL_mom_s2.pt]
105
+ parameters: 752386
106
+ summary: "Best in-family accuracy with the standard prior; transfers slightly worse than pair-local."
107
+ paper:
108
+ appears_in: [tab:candidates, tab:costacc, fig:costacc, tab:sota, fig:zs-arch, fig:infamily]
109
+ never_seen: {median_pct: 2.08, mae_ff: 0.97, rmse_ff: 1.88}
110
+ ood60: {median_pct: 2.45, mae_ff: 0.98, rmse_ff: 1.94}
111
+ in_family_full: {median_pct: "0.21-1.05", mae_ff: "0.017-0.40", rmse_ff: "0.022-0.84", note: C_NS, range over the 5 families}
112
+ cost_s_per_design: {never_seen: 8.77, ood60: 0.61}
113
+
114
+ charge-corrected-prior:
115
+ title: "Charge-corrected MoM prior (cell GBM)"
116
+ repo_id: SQuADDS/2026PaperModels-charge-corrected-prior
117
+ kind: charge_prior
118
+ prior: standard
119
+ status: available
120
+ checkpoints: [deploy/artifacts/charge_gbm.joblib]
121
+ summary: "MoM prior with its cell charges corrected by a gradient-boosted model of local geometry; no capacitance labels. Smallest worst-case error."
122
+ paper:
123
+ appears_in: [tab:candidates, tab:costacc, fig:zs-cell, tab:splits]
124
+ never_seen: {median_pct: 2.18, mae_ff: 0.95, rmse_ff: 1.62}
125
+ ood60: {median_pct: 4.05, mae_ff: 1.30, rmse_ff: 2.33}
126
+ cost_s_per_design: {never_seen: 17.5, ood60: 1.06, note: "paper timing re-solves the MoM; tlsq_infer reuses the prior's solve"}
127
+
128
+ blend-pair-local:
129
+ title: "Blended model: pair-local network x charge-corrected prior"
130
+ repo_id: SQuADDS/2026PaperModels-blend-pair-local
131
+ kind: blend
132
+ components: [pair-local, charge-corrected-prior]
133
+ status: available
134
+ summary: "Best zero-shot model on never-seen components (paper headline)."
135
+ paper:
136
+ appears_in: [tab:candidates, tab:costacc, fig:costacc, fig:blend, fig:stack, tab:stack, fig:invdesign, tab:invdes]
137
+ never_seen: {median_pct: 1.64, mae_ff: 0.71, rmse_ff: 1.36}
138
+ ood60: {median_pct: 2.36, mae_ff: 0.87, rmse_ff: 1.75}
139
+ cost_s_per_design: {never_seen: 17.5, ood60: 1.06}
140
+
141
+ blend-message-passing:
142
+ title: "Blended model: message-passing network x charge-corrected prior"
143
+ repo_id: SQuADDS/2026PaperModels-blend-message-passing
144
+ kind: blend
145
+ components: [message-passing, charge-corrected-prior]
146
+ status: available
147
+ summary: "Blend with the R=3 network."
148
+ paper:
149
+ appears_in: [tab:costacc, fig:costacc, fig:blend]
150
+ never_seen: {median_pct: 1.84, mae_ff: 0.82, rmse_ff: 1.56}
151
+ ood60: {median_pct: 2.37, mae_ff: 0.90, rmse_ff: 1.87}
152
+ cost_s_per_design: {never_seen: 17.5, ood60: 1.07}
153
+
154
+ geometry-only:
155
+ title: "Geometry-only network (no physics prior)"
156
+ repo_id: SQuADDS/2026PaperModels-geometry-only
157
+ kind: gnn
158
+ prior: none
159
+ rounds: 3
160
+ status: available
161
+ checkpoints: [data_local/mega/ckpt/ALL_none_s0.pt]
162
+ summary: "Ablation. Accurate in family, fails on unseen geometry: do NOT use for new layouts. Released for reproducibility (seed 0 of 3)."
163
+ warning: "Not for unseen geometry (19 % median on never-seen components, single entries off by >10x)."
164
+ paper:
165
+ appears_in: [tab:candidates, tab:splits, tab:sota]
166
+ never_seen: {median_pct: 19.4, mae_ff: 6.1, rmse_ff: 9.8}
167
+ ood60: {median_pct: "4.7-15.0", mae_ff: "1.7-3.4", rmse_ff: "2.2-4.6", note: range of per-class medians}
168
+ in_family_full: {median_pct: "0.45-1.54", mae_ff: "0.011-0.90", rmse_ff: "0.015-1.32"}
169
+
170
+ # ---------------------------------------------------------------- training-free
171
+ mom-prior:
172
+ title: "MoM prior alone (training-free)"
173
+ repo_id: null
174
+ kind: prior
175
+ prior: standard
176
+ status: available
177
+ summary: "Untrained thin-film method of moments (8,000 cells). Physics baseline."
178
+ paper:
179
+ appears_in: [tab:candidates, tab:costacc, tab:prior, fig:prior-parity]
180
+ never_seen: {median_pct: 6.55, mae_ff: 3.03, rmse_ff: 4.62}
181
+ ood60: {median_pct: 8.09, mae_ff: 2.26, rmse_ff: 3.56}
182
+
183
+ fine-mom-prior:
184
+ title: "Fine MoM prior alone (training-free)"
185
+ repo_id: null
186
+ kind: prior
187
+ prior: fine
188
+ status: available
189
+ summary: "Untrained MoM, 16,000 cells, gap/6. Physics baseline at ~3-5x the cost."
190
+ paper:
191
+ appears_in: [tab:costacc]
192
+ never_seen: {median_pct: 4.99, mae_ff: 2.38, rmse_ff: 3.60}
193
+
194
+ # ---------------------------------------------------------------- pending (trained on HPC; copy checkpoints, flip status)
195
+ pair-local-fine:
196
+ title: "Pair-local network + fine MoM prior (R=0)"
197
+ repo_id: SQuADDS/2026PaperModels-pair-local-fine
198
+ kind: gnn
199
+ prior: fine
200
+ rounds: 0
201
+ status: pending
202
+ pending_reason: "checkpoints on HPC (results/mega/fine/); copy to data_local/mega/ckpt_fine/"
203
+ checkpoints: [data_local/mega/ckpt_fine/ALL_mom_r0_s0.pt, data_local/mega/ckpt_fine/ALL_mom_r0_s1.pt, data_local/mega/ckpt_fine/ALL_mom_r0_s2.pt]
204
+ summary: "Best on arbitrary or unusual geometry."
205
+ paper:
206
+ appears_in: [tab:candidates, tab:costacc, fig:costacc, tab:wonky-shape-main]
207
+ never_seen: {median_pct: 1.74, mae_ff: 0.98, rmse_ff: 1.87}
208
+ ood60: {median_pct: 0.95, mae_ff: 0.41, rmse_ff: 0.75}
209
+ cost_s_per_design: {never_seen: 38.0, ood60: 1.84}
210
+
211
+ message-passing-fine:
212
+ title: "Message-passing network + fine MoM prior (R=3)"
213
+ repo_id: SQuADDS/2026PaperModels-message-passing-fine
214
+ kind: gnn
215
+ prior: fine
216
+ rounds: 3
217
+ status: pending
218
+ pending_reason: "checkpoints on HPC (results/mega/fine/); copy to data_local/mega/ckpt_fine/"
219
+ checkpoints: [data_local/mega/ckpt_fine/ALL_mom_s0.pt, data_local/mega/ckpt_fine/ALL_mom_s1.pt, data_local/mega/ckpt_fine/ALL_mom_s2.pt]
220
+ summary: "Lowest MAE on the never-seen components among single networks."
221
+ paper:
222
+ appears_in: [tab:candidates, tab:costacc, fig:costacc]
223
+ never_seen: {median_pct: 1.74, mae_ff: 0.74, rmse_ff: 1.39}
224
+ ood60: {median_pct: 1.11, mae_ff: 0.47, rmse_ff: 0.91}
225
+ in_family_full: {median_pct: "0.18-1.04", mae_ff: "0.015-0.30", rmse_ff: "0.020-0.46"}
226
+ cost_s_per_design: {never_seen: 38.0, ood60: 1.85}
227
+
228
+ all-data:
229
+ title: "All-data deployment model (fine prior, all families + random layouts)"
230
+ repo_id: SQuADDS/2026PaperModels-all-data
231
+ kind: gnn
232
+ prior: fine
233
+ rounds: 0
234
+ status: pending
235
+ pending_reason: "training in progress on HPC (paper: \\needs{all-data model})"
236
+ checkpoints: []
237
+ summary: "Trained on every labelled design (no held-out family). Not zero-shot on any paper test set."
238
+ paper:
239
+ appears_in: [sec:res-opt (All-data model paragraph)]
240
+
241
+ # ---------------------------------------------------------------- baselines (paper comparison; not deployable on a GDS)
242
+ parameter-mlp:
243
+ title: "Parameter MLP (published surrogate, MLQubitDesign)"
244
+ repo_id: null
245
+ kind: baseline
246
+ status: not-released
247
+ deployable: false
248
+ summary: "Per-family MLP on Qiskit Metal design parameters; input undefined on a new layout."
249
+ paper:
250
+ appears_in: [tab:candidates, tab:sota, fig:infamily, tab:fewshot]
251
+ in_family_full: {median_pct: "1.78-2.62", mae_ff: "0.041-1.32", rmse_ff: "0.055-1.87", note: C_NS}
252
+
253
+ parameter-gbt:
254
+ title: "Parameter GBT (gradient-boosted trees on design parameters)"
255
+ repo_id: null
256
+ kind: baseline
257
+ status: not-released
258
+ deployable: false
259
+ summary: "Per-family GBT on design parameters; input undefined on a new layout."
260
+ paper:
261
+ appears_in: [tab:candidates, fig:infamily]
262
+ in_family_full: {median_pct: "0.35-3.36", mae_ff: "0.010-1.93", rmse_ff: "0.015-2.92"}
263
+
264
+ neural-operator:
265
+ title: "Fourier neural operator on conductor masks (no prior)"
266
+ repo_id: null
267
+ kind: baseline
268
+ status: not-released
269
+ deployable: false
270
+ summary: "Image model; most accurate in distribution, fails on held-out families."
271
+ paper:
272
+ appears_in: [tab:candidates]
273
+ in_family_id: {median_pct: 0.24, mae_ff: 0.082, rmse_ff: 0.40}
274
+
275
+ edge-nn-mom:
276
+ title: "Edge nearest-neighbour + MoM (training-free correction)"
277
+ repo_id: null
278
+ kind: baseline
279
+ status: not-released
280
+ deployable: false
281
+ summary: "Nearest-neighbour correction of the MoM prior in embedding space; needs the training index."
282
+ paper:
283
+ appears_in: [tab:candidates, tab:lofo]
284
+ never_seen: {median_pct: 4.02, mae_ff: 1.5, rmse_ff: 2.4}
285
+ ood60: {median_pct: "3.1-6.0", mae_ff: "1.2-1.6", rmse_ff: "1.5-2.2", note: range of per-class medians}
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
+ torch
3
+ numpy
4
+ scipy
5
+ shapely>=2.0
6
+ gdstk>=0.9
7
+ scikit-learn==1.9.1
8
+ joblib
9
+ pandas
10
+ pyyaml
11
+ matplotlib
12
+ huggingface_hub
tlsq_infer/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """tlsq_infer: zero-shot Maxwell capacitance matrices of planar superconducting layouts from a GDS file.
2
+
3
+ from tlsq_infer import load_gds, prepare, predict
4
+ print(load_gds("chip.gds")) # layers / datatypes present
5
+ lay = prepare("chip.gds") # ground (1, 0), conductors (1, 10), cropped window
6
+ res = predict(lay, model="pair-local", substrate="sapphire", thickness_um=430)
7
+ res["names"], res["matrix_fF"], res["expected_error"]
8
+ """
9
+
10
+ __version__ = "0.1.0"
11
+
12
+ from .layout import LayoutError, PreparedLayout, load_gds, prepare # noqa: E402
13
+ from .predict import matrix_csv, predict # noqa: E402
14
+ from .registry import load_registry # noqa: E402
15
+
16
+ __all__ = ["LayoutError", "PreparedLayout", "load_gds", "load_registry", "matrix_csv", "predict", "prepare", "__version__"]
tlsq_infer/_vendor/__init__.py ADDED
File without changes
tlsq_infer/_vendor/blocks.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Physics-agnostic geometry blocks: node (per conductor), edge (per conductor pair) and global features, all in
2
+ physical units (log µm, ratios) so that nothing is fitted to a dataset."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import numpy as np
7
+ import shapely
8
+ from scipy.special import ellipk
9
+ from scipy.spatial import cKDTree
10
+
11
+ from .geometry import fourier_descriptors, sample_boundary, shape_metrics
12
+ from .scene import Scene
13
+
14
+ GRAN_R_UM = np.geomspace(0.25, 100.0, 16)
15
+ SEP_EDGES_UM = np.geomspace(0.5, 2000.0, 11)
16
+ MOMENTS = (0.5, 1.0, 2.0)
17
+ STEP_UM = 0.25
18
+
19
+
20
+ def _log(x):
21
+ return float(np.log(max(float(x), 1e-9)))
22
+
23
+
24
+ def region(scene: Scene, i: int):
25
+ """The shape that carries conductor i's edge: the etched pocket for the ground net, the metal otherwise."""
26
+ return scene.pocket if scene.conductors[i].role == "ground" else scene.conductors[i].geom
27
+
28
+
29
+ def granulometry(g) -> np.ndarray:
30
+ a0 = g.area
31
+ return np.array([g.buffer(-r, quad_segs=4).area / a0 if a0 > 0 else 0.0 for r in GRAN_R_UM])
32
+
33
+
34
+ def node_features(scene: Scene, i: int) -> dict:
35
+ g = region(scene, i)
36
+ m = shape_metrics(g)
37
+ f = {"role_ground": float(scene.conductors[i].role == "ground"),
38
+ "log_area": _log(m["area"]), "log_perimeter": _log(m["perimeter"]), "compactness": m["compactness"],
39
+ "solidity": m["solidity"], "log_min_halfwidth": _log(m["inscribed_radius"]),
40
+ "log_aspect": abs(_log(m["bbox_w"]) - _log(m["bbox_h"])), "log_elongation": _log(m["elongation"]),
41
+ "log_Imajor_over_A2": _log(m["I_major"] / max(m["area"], 1e-9) ** 2), "n_holes": float(m["n_holes"]),
42
+ "log_width": _log(2 * m["area"] / m["perimeter"])}
43
+ for j, v in enumerate(fourier_descriptors(g)):
44
+ f[f"fourier_{j:02d}"] = float(np.log1p(50 * v))
45
+ for j, v in enumerate(granulometry(g)):
46
+ f[f"gran_{j:02d}"] = float(v)
47
+ return f
48
+
49
+
50
+ def _kratio(m):
51
+ m = np.clip(m, 1e-12, 1 - 1e-12)
52
+ return ellipk(1 - m) / ellipk(m)
53
+
54
+
55
+ def edge_features(scene: Scene, i: int, j: int, bpts: dict, widths: dict) -> dict:
56
+ """Symmetric pair features: separation spectrum (both directions averaged), minimum gap, coupling moments and the
57
+ coplanar-strip conformal-map coupling (Gevorgian modulus; the ground net is treated as infinitely wide)."""
58
+ f = {"is_ground_pair": float("ground" in (scene.conductors[i].role, scene.conductors[j].role))}
59
+ hist = np.zeros(len(SEP_EDGES_UM) - 1)
60
+ mom = np.zeros(len(MOMENTS))
61
+ cps = 0.0
62
+ dmin = np.inf
63
+ for a, b in ((i, j), (j, i)):
64
+ d, _ = cKDTree(bpts[b]).query(bpts[a])
65
+ dmin = min(dmin, d.min())
66
+ hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0]
67
+ dd = np.maximum(d, 0.05)
68
+ mom += 0.5 * np.array([np.sum(STEP_UM * dd ** (-p)) for p in MOMENTS])
69
+ w1, w2 = widths[a], widths[b]
70
+ if np.isinf(w1) or np.isinf(w2):
71
+ wf = w2 if np.isinf(w1) else w1
72
+ mm = dd / (dd + wf)
73
+ else:
74
+ mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2))
75
+ cps += 0.5 * np.sum(STEP_UM * _kratio(mm))
76
+ f["log_dmin"] = _log(dmin)
77
+ for k, v in enumerate(hist):
78
+ f[f"sep_{k:02d}"] = float(np.log1p(v))
79
+ for p, v in zip(MOMENTS, mom):
80
+ f[f"mom_{p:g}"] = _log(v)
81
+ f["log_cps"] = _log(cps)
82
+ f["_cps"] = cps # raw, used for shielding shares
83
+ return f
84
+
85
+
86
+ def global_features(scene: Scene) -> dict:
87
+ st = scene.stack
88
+ n_sig = sum(c.role == "signal" for c in scene.conductors)
89
+ return {"n_metal_layers": float(st["n_metal_layers"]), "log_metal_t": _log(st["metal_thickness_um"]),
90
+ "log_substrate_t": _log(st["substrate_thickness_um"]), "eps_eff": (st["substrate_eps_r"] + 1) / 2,
91
+ "n_signal": float(n_sig), "log_chip_area": _log(scene.chip.area),
92
+ "log_pocket_area": _log(scene.pocket.area)}
93
+
94
+
95
+ def boundary_points(scene: Scene) -> tuple[dict, dict]:
96
+ pts, widths = {}, {}
97
+ for i, c in enumerate(scene.conductors):
98
+ g = region(scene, i)
99
+ pts[i] = sample_boundary(g, STEP_UM)
100
+ widths[i] = np.inf if c.role == "ground" else 2 * g.area / g.length
101
+ return pts, widths
tlsq_infer/_vendor/geometry.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vendored from tlsq.geometry (shape metrics and boundary sampling used by the scene-graph features). Keep verbatim:
2
+ the trained networks depend on these exact features (deploy/tests/test_reproduction.py checks equality)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import numpy as np
7
+ import shapely
8
+ from shapely.geometry import Polygon
9
+
10
+ BOUNDARY_STEP_UM = 0.25
11
+ N_FOURIER = 16
12
+
13
+
14
+ def sample_boundary(geom, step: float = BOUNDARY_STEP_UM) -> np.ndarray:
15
+ rings = []
16
+ for poly in getattr(geom, "geoms", [geom]):
17
+ rings += [poly.exterior, *poly.interiors]
18
+ pts = []
19
+ for r in rings:
20
+ n = max(int(np.ceil(r.length / step)), 4)
21
+ pts.append(shapely.get_coordinates(shapely.line_interpolate_point(r, np.linspace(0, r.length, n, endpoint=False))))
22
+ return np.concatenate(pts)
23
+
24
+
25
+ def shape_metrics(poly) -> dict:
26
+ hull = poly.convex_hull
27
+ x0, y0, x1, y1 = poly.bounds
28
+ cx, cy = poly.centroid.x, poly.centroid.y
29
+ ixx, iyy, ixy = _second_moments(poly, cx, cy)
30
+ evals = np.linalg.eigvalsh([[ixx, ixy], [ixy, iyy]])
31
+ return {
32
+ "area": poly.area,
33
+ "perimeter": poly.length,
34
+ "convex_area": hull.area,
35
+ "solidity": poly.area / hull.area,
36
+ "compactness": 4 * np.pi * poly.area / poly.length**2,
37
+ "bbox_w": x1 - x0,
38
+ "bbox_h": y1 - y0,
39
+ "cx": cx,
40
+ "cy": cy,
41
+ "I_major": evals[1],
42
+ "I_minor": evals[0],
43
+ "elongation": np.sqrt(evals[1] / max(evals[0], 1e-30)),
44
+ "inscribed_radius": shapely.maximum_inscribed_circle(poly, 0.01).length if isinstance(poly, Polygon) else np.nan,
45
+ "n_vertices": int(shapely.get_num_coordinates(poly)),
46
+ "n_holes": int(sum(len(p.interiors) for p in getattr(poly, "geoms", [poly]))),
47
+ }
48
+
49
+
50
+ def _second_moments(geom, cx, cy) -> tuple[float, float, float]:
51
+ ixx = iyy = ixy = 0.0
52
+ for poly in getattr(geom, "geoms", [geom]):
53
+ for k, ring in enumerate([poly.exterior, *poly.interiors]):
54
+ xy = np.asarray(ring.coords) - (cx, cy)
55
+ x, y = xy[:-1, 0], xy[:-1, 1]
56
+ xn, yn = xy[1:, 0], xy[1:, 1]
57
+ a = x * yn - xn * y
58
+ sgn = 1.0 if ring.is_ccw == (k == 0) else -1.0
59
+ ixx += sgn * np.sum(a * (y**2 + y * yn + yn**2)) / 12
60
+ iyy += sgn * np.sum(a * (x**2 + x * xn + xn**2)) / 12
61
+ ixy += sgn * np.sum(a * (x * yn + 2 * x * y + 2 * xn * yn + xn * y)) / 24
62
+ return abs(ixx), abs(iyy), ixy
63
+
64
+
65
+ def fourier_descriptors(poly, n_samples: int = 512) -> np.ndarray:
66
+ """|c_k|/|c_1| for k=-N..N of the outer contour (translation/rotation/scale invariant)."""
67
+ ring = max(getattr(poly, "geoms", [poly]), key=lambda p: p.area).exterior
68
+ if not ring.is_ccw:
69
+ ring = shapely.reverse(ring)
70
+ pts = shapely.get_coordinates(shapely.line_interpolate_point(ring, np.linspace(0, 1, n_samples, endpoint=False), normalized=True))
71
+ c = np.fft.fft(pts[:, 0] + 1j * pts[:, 1]) / n_samples
72
+ k = np.r_[np.arange(-N_FOURIER, 0), np.arange(0, N_FOURIER + 1)]
73
+ mags = np.abs(c[k])
74
+ mags[k == 0] = 0.0
75
+ return mags / mags[k == 1][0]
tlsq_infer/_vendor/gnn.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vendored from tlsq.uge.gnn (inference only): dense padded graph batches and the scene GNN."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from itertools import combinations
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+ N_MAX = 8
12
+
13
+
14
+ def _mlp(i, o, w):
15
+ return nn.Sequential(nn.Linear(i, w), nn.GELU(), nn.Linear(w, w), nn.GELU(), nn.Linear(w, o))
16
+
17
+
18
+ @dataclass
19
+ class GraphSet:
20
+ X: np.ndarray # (B, N_MAX, dn) node features (scaled)
21
+ E: np.ndarray # (B, N_MAX, N_MAX, de) edge features (scaled, symmetric)
22
+ U: np.ndarray # (B, du) global features (scaled)
23
+ M: np.ndarray # (B, N_MAX) node mask
24
+ P: np.ndarray # (B, N_MAX, N_MAX) proxy log|C| (off-diagonal: log -C_ij, diagonal: log C_ii)
25
+ Y: np.ndarray # (B, N_MAX, N_MAX) target log|C| (NaN where absent)
26
+ ground: np.ndarray # (B, N_MAX) 1 for the ground node
27
+
28
+ def subset(self, idx):
29
+ return GraphSet(*(a[idx] for a in (self.X, self.E, self.U, self.M, self.P, self.Y, self.ground)))
30
+
31
+ def tensors(self, dev="cpu"):
32
+ return [torch.tensor(a, dtype=torch.float32, device=dev) for a in (self.X, self.E, self.U, self.M, self.P, self.Y, self.ground)]
33
+
34
+
35
+ def build_graphset(rows: list[dict], scaling: dict | None = None, proxy_key: str = "proxy_log_C") -> tuple[GraphSet, dict]:
36
+ """rows: scene-pass records. scaling (median/IQR per feature) is computed from rows when not given and returned, so it
37
+ can be frozen and shipped. proxy_key selects the edge proxy ('proxy_log_C' = MoM, 'conf_log_C' = conformal, None = none)."""
38
+ nk = [k for k in rows[0]["nodes"][0] if not k.startswith("proxy_")]
39
+ ek = [k for k in next(iter(rows[0]["edges"].values())) if not (k.startswith("proxy_") or k.startswith("conf_"))]
40
+ gk = [k for k in rows[0]["global"] if not k.startswith("proxy_")]
41
+ B = len(rows)
42
+ X = np.zeros((B, N_MAX, len(nk)))
43
+ E = np.zeros((B, N_MAX, N_MAX, len(ek)))
44
+ U = np.zeros((B, len(gk)))
45
+ M = np.zeros((B, N_MAX))
46
+ G = np.zeros((B, N_MAX))
47
+ P = np.zeros((B, N_MAX, N_MAX))
48
+ Y = np.full((B, N_MAX, N_MAX), np.nan)
49
+ for b, r in enumerate(rows):
50
+ n = len(r["names"])
51
+ M[b, :n] = 1
52
+ for i, nd in enumerate(r["nodes"]):
53
+ X[b, i] = [nd[k] for k in nk]
54
+ G[b, i] = nd["role_ground"]
55
+ P[b, i, i] = nd.get("proxy_log_Cself", 0.0) if proxy_key == "proxy_log_C" else 0.0
56
+ for (i, j), f in r["edges"].items():
57
+ E[b, i, j] = E[b, j, i] = [f[k] for k in ek]
58
+ P[b, i, j] = P[b, j, i] = f.get(proxy_key, 0.0) if proxy_key else 0.0
59
+ if proxy_key == "conf_log_C": # solver-free self term: sum of the conformal mutuals
60
+ for i in range(n):
61
+ P[b, i, i] = np.log(sum(np.exp(P[b, i, j]) for j in range(n) if j != i) + 1e-9)
62
+ U[b] = [r["global"][k] for k in gk]
63
+ T = r["target"]
64
+ for i in range(n):
65
+ Y[b, i, i] = np.log(max(T[i, i], 1e-9))
66
+ for j in range(n):
67
+ if j != i:
68
+ Y[b, i, j] = np.log(max(-T[i, j], 1e-9))
69
+ if scaling is None:
70
+ def stats(A, mask):
71
+ v = A[mask]
72
+ med = np.median(v, 0)
73
+ iqr = np.percentile(v, 75, 0) - np.percentile(v, 25, 0)
74
+ return med, np.where(iqr > 1e-9, iqr, 1.0)
75
+ em = M[:, :, None] * M[:, None, :] * (1 - np.eye(N_MAX))[None]
76
+ scaling = {"node": stats(X, M > 0), "edge": stats(E, em > 0), "global": stats(U, np.ones(B, bool)), "keys": (nk, ek, gk)}
77
+ sc = lambda A, s: np.clip(np.nan_to_num((A - s[0]) / s[1]), -20, 20) # noqa: E731
78
+ return GraphSet(sc(X, scaling["node"]) * M[..., None], sc(E, scaling["edge"]), sc(U, scaling["global"]), M, P, Y, G), scaling
79
+
80
+
81
+ class SceneGNN(nn.Module):
82
+ """gate=True: prediction = a * prior + head, with a learned per-entry trust a = sigmoid(.) in (0, 1) (starts near 1,
83
+ i.e. the plain residual model); lets the network discount a noisy prior instead of having to undo it."""
84
+
85
+ def __init__(self, dn, de, du, w=128, rounds=3, gate=False):
86
+ super().__init__()
87
+ self.enc_n, self.enc_e, self.enc_u = _mlp(dn, w, w), _mlp(de, w, w), _mlp(du, w, w)
88
+ self.msg = nn.ModuleList([_mlp(4 * w, w, w) for _ in range(rounds)])
89
+ self.upd = nn.ModuleList([_mlp(3 * w, w, w) for _ in range(rounds)])
90
+ self.head_e, self.head_n = _mlp(2 * w, 1, w), _mlp(2 * w, 1, w)
91
+ self.gate = gate
92
+ if gate:
93
+ self.gate_e, self.gate_n = _mlp(2 * w, 1, w), _mlp(2 * w, 1, w)
94
+ for g in (self.gate_e, self.gate_n):
95
+ nn.init.zeros_(g[-1].weight)
96
+ nn.init.constant_(g[-1].bias, 3.0)
97
+
98
+ def forward(self, X, E, U, M, P):
99
+ mm = M[:, :, None] * M[:, None, :] * (1 - torch.eye(M.shape[1], device=M.device))[None]
100
+ h, e, u = self.enc_n(X), self.enc_e(E), self.enc_u(U)
101
+ for msg, upd in zip(self.msg, self.upd):
102
+ hi, hj = h[:, :, None].expand_as(e), h[:, None, :].expand_as(e)
103
+ e = e + msg(torch.cat([e, hi + hj, (hi - hj).abs(), u[:, None, None].expand_as(e)], -1)) * mm[..., None]
104
+ agg = (e * mm[..., None]).sum(2) / mm.sum(2, keepdim=True).clamp(min=1)
105
+ h = h + upd(torch.cat([h, agg, u[:, None].expand_as(h)], -1)) * M[..., None]
106
+ out_e = self.head_e(torch.cat([e, u[:, None, None].expand_as(e)], -1))[..., 0]
107
+ out_e = 0.5 * (out_e + out_e.transpose(1, 2))
108
+ out_n = self.head_n(torch.cat([h, u[:, None].expand_as(h)], -1))[..., 0]
109
+ eye = torch.eye(M.shape[1], device=M.device)[None]
110
+ if self.gate:
111
+ ze, zn = torch.cat([e, u[:, None, None].expand_as(e)], -1), torch.cat([h, u[:, None].expand_as(h)], -1)
112
+ ge = torch.sigmoid(self.gate_e(ze)[..., 0])
113
+ ge = 0.5 * (ge + ge.transpose(1, 2))
114
+ a = ge * (1 - eye) + torch.diag_embed(torch.sigmoid(self.gate_n(zn)[..., 0]))
115
+ self.last_gate = a
116
+ # P is log C; scale log C about a fixed reference (log 1 fF) so a < 1 shrinks the prior towards the head
117
+ P = a * P
118
+ return P + out_e * (1 - eye) + torch.diag_embed(out_n)
119
+
120
+
121
+ @torch.no_grad()
122
+ def predict(model, gs: GraphSet, idx, dev="cpu"):
123
+ X, E, U, M, P, Y, G = gs.subset(idx).tensors(dev)
124
+ out = []
125
+ for s in range(0, len(X), 2048):
126
+ out.append(model(X[s:s + 2048], E[s:s + 2048], U[s:s + 2048], M[s:s + 2048], P[s:s + 2048]).cpu().numpy())
127
+ return np.concatenate(out)
tlsq_infer/_vendor/graph.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vendored from tlsq.uge.graph: scene graph (nodes = conductors, edges = all conductor pairs) with a precomputed
2
+ MoM prior injected (the deployment pipeline solves the MoM once and reuses its cell charges for the charge correction)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from itertools import combinations
7
+
8
+ import numpy as np
9
+
10
+ from .blocks import boundary_points, edge_features, global_features, node_features
11
+ from .scene import Scene
12
+
13
+
14
+ def prior_dict(C: np.ndarray, n_cells: int, h_min: float, edges) -> dict:
15
+ """Same output as tlsq.uge.proxies.CapacitanceMoM.compute for a given Maxwell matrix C."""
16
+ n = C.shape[0]
17
+ out = {"node": {i: {"log_Cself": float(np.log(max(C[i, i], 1e-9)))} for i in range(n)}, "edge": {},
18
+ "global": {"cells": float(n_cells), "h_min_um": float(h_min)}, "matrix": C}
19
+ for (i, j) in edges:
20
+ out["edge"][(i, j)] = {"log_C": float(np.log(max(-C[i, j], 1e-9)))}
21
+ return out
22
+
23
+
24
+ def scene_graph(scene: Scene, prior_fn=None) -> dict:
25
+ """prior_fn(edges) -> CapacitanceMoM-style dict (see prior_dict), or None for the geometry-only network."""
26
+ bpts, widths = boundary_points(scene)
27
+ nodes = [node_features(scene, i) for i in range(scene.n)]
28
+ edges = {(i, j): edge_features(scene, i, j, bpts, widths) for i, j in combinations(range(scene.n), 2)}
29
+ # shielding: share of each endpoint's total geometric coupling carried by this edge
30
+ tot = np.zeros(scene.n)
31
+ for (i, j), f in edges.items():
32
+ tot[i] += f["_cps"]
33
+ tot[j] += f["_cps"]
34
+ for (i, j), f in edges.items():
35
+ si, sj = f["_cps"] / max(tot[i], 1e-12), f["_cps"] / max(tot[j], 1e-12)
36
+ f["share_mean"], f["share_absdiff"] = 0.5 * (si + sj), abs(si - sj)
37
+ g = {"names": scene.names(), "global": global_features(scene), "nodes": nodes, "edges": edges}
38
+ if prior_fn is not None:
39
+ px = prior_fn(edges)
40
+ for i, v in px["node"].items():
41
+ nodes[i].update({f"proxy_{k}": x for k, x in v.items()})
42
+ for e, v in px["edge"].items():
43
+ edges[e].update({f"proxy_{k}": x for k, x in v.items()})
44
+ g["global"].update({f"proxy_{k}": x for k, x in px["global"].items()})
45
+ if "matrix" in px:
46
+ g["proxy_matrix"] = px["matrix"]
47
+ for f in edges.values():
48
+ f.pop("_cps")
49
+ return g
tlsq_infer/_vendor/mom.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vendored from tlsq.embed.proxy: thin-film method-of-moments (MoM) capacitance on the exact polygons, adaptive
2
+ quadtree mesh, quasi-static half-space Green's function with eps_eff = (eps_r + 1) / 2.
3
+
4
+ `mom_solve` is numerically the same solve as tlsq.embed.proxy.mom_capacitance_gds (standard: 8,000 cells, gap/3;
5
+ fine: 16,000 cells, gap/6) but keeps the cell charges of every excitation (reused by the charge correction) and builds
6
+ the dense interaction matrix in place to roughly halve peak memory."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+ import shapely
12
+ from scipy.linalg import cho_factor, cho_solve
13
+
14
+ EPS0_FF_PER_UM = 8.8541878128e-3
15
+ SELF = 4 * np.log(1 + np.sqrt(2))
16
+
17
+
18
+ def quadtree_cells(metals: list, bbox, h0: float, h_min: float, grade: float = 2.0):
19
+ """Square cells covering the metal polygons: a cell is kept whole when it lies inside one conductor and is no larger
20
+ than `grade` x its distance to the nearest metal edge; edge cells are split down to h_min, where they go to the
21
+ conductor covering >= 50 % of them. Returns centres (n, 2), sides (n,), owner (n,)."""
22
+
23
+ for g in metals:
24
+ shapely.prepare(g)
25
+ edges = shapely.union_all([g.boundary for g in metals])
26
+ shapely.prepare(edges)
27
+ x0, y0, x1, y1 = bbox
28
+ nx, ny = int(np.ceil((x1 - x0) / h0)), int(np.ceil((y1 - y0) / h0))
29
+ gx, gy = np.meshgrid(x0 + h0 * np.arange(nx), y0 + h0 * np.arange(ny))
30
+ xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0)
31
+ out_c, out_h, out_o = [], [], []
32
+ while len(xs):
33
+ boxes = shapely.box(xs, ys, xs + h, ys + h)
34
+ cov = np.stack([shapely.area(shapely.intersection(boxes, g)) for g in metals]) / h**2
35
+ tot = cov.sum(0)
36
+ keep = tot > 1e-3
37
+ xs, ys, h, cov, boxes = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep]
38
+ cx, cy = xs + h / 2, ys + h / 2
39
+ full = cov.max(0) > 0.999
40
+ d = shapely.distance(shapely.points(cx, cy), edges)
41
+ leaf = full & (h <= grade * d + 1e-12)
42
+ last = h <= h_min * 1.0001
43
+ take_last = last & ~leaf & (cov.max(0) >= 0.5)
44
+ acc = leaf | take_last
45
+ out_c.append(np.stack([cx[acc], cy[acc]], 1))
46
+ out_h.append(h[acc])
47
+ out_o.append(cov[:, acc].argmax(0))
48
+ split = ~acc & ~last
49
+ hs = h[split] / 2
50
+ xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs])
51
+ ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs])
52
+ h = np.concatenate([hs] * 4)
53
+ return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
54
+
55
+
56
+ def mesh(metals: list, max_cells: int = 8000, cells_per_gap: float = 3.0, grade: float = 2.0):
57
+ """Quadtree mesh exactly as mom_capacitance_gds: h_min = max(min gap / cells_per_gap, size / 4096), coarsened by
58
+ 1.5x until the mesh has at most max_cells cells. Returns centres, sides, owners, h_min."""
59
+ bbox = shapely.union_all(metals).bounds
60
+ size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
61
+ gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals)))
62
+ h_min = max(gap / cells_per_gap, size / 4096)
63
+ while True:
64
+ c, h, o = quadtree_cells(metals, bbox, size / 16, h_min, grade)
65
+ if len(c) <= max_cells:
66
+ return c, h, o, h_min
67
+ h_min *= 1.5
68
+
69
+
70
+ def mom_solve(metals: list, eps_r: float = 11.45, max_cells: int = 8000, cells_per_gap: float = 3.0, grade: float = 2.0):
71
+ """Returns dict(C (n, n) Maxwell matrix in fF, cen, h, own, Q (cells, n) charges for every 1 V excitation, n_cells, h_min)."""
72
+ c, h, o, h_min = mesh(metals, max_cells, cells_per_gap, grade)
73
+ dx = c[:, 0, None] - c[None, :, 0]
74
+ P = dx * dx
75
+ np.subtract(c[:, 1, None], c[None, :, 1], out=dx)
76
+ dx *= dx
77
+ P += dx
78
+ del dx
79
+ np.sqrt(P, out=P)
80
+ np.fill_diagonal(P, 1.0)
81
+ near = P < 1.5 * np.maximum(h[:, None], h[None, :])
82
+ np.fill_diagonal(near, False)
83
+ ii, jj = np.nonzero(near)
84
+ del near
85
+ np.divide(1.0, P, out=P)
86
+ if len(ii):
87
+ # neighbours: average 1/r over a 3x3 sample of the source cell (point matching is poor for close, unequal cells)
88
+ off = (np.arange(3) - 1) / 3
89
+ ox, oy = np.meshgrid(off, off)
90
+ sx = c[jj, 0, None] + ox.ravel()[None] * h[jj, None]
91
+ sy = c[jj, 1, None] + oy.ravel()[None] * h[jj, None]
92
+ r = np.sqrt((c[ii, 0, None] - sx) ** 2 + (c[ii, 1, None] - sy) ** 2)
93
+ P[ii, jj] = (1.0 / np.maximum(r, 1e-9)).mean(1)
94
+ P += P.T.copy()
95
+ P *= 0.5
96
+ np.fill_diagonal(P, SELF / h)
97
+ P /= 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2
98
+ B = (o[:, None] == np.arange(len(metals))[None, :]).astype(float)
99
+ Q = cho_solve(cho_factor(P, lower=True, overwrite_a=True, check_finite=False), B, check_finite=False)
100
+ del P
101
+ C = np.stack([Q[o == a].sum(0) for a in range(len(metals))])
102
+ return {"C": 0.5 * (C + C.T), "cen": c, "h": h, "own": o, "Q": Q, "n_cells": len(c), "h_min": h_min}
tlsq_infer/_vendor/scene.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vendored from tlsq.uge.scene: the scene container (ground net at index 0 + signal bodies) and the training stack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ import shapely
8
+ from shapely.geometry import Polygon
9
+
10
+ DEFAULT_STACK = {"n_metal_layers": 1, "metal_thickness_um": 0.25, "substrate_thickness_um": 350.0, "substrate_eps_r": 11.45}
11
+
12
+
13
+ @dataclass
14
+ class Conductor:
15
+ name: str
16
+ role: str # "ground" | "signal"
17
+ geom: object # shapely (Multi)Polygon, µm
18
+
19
+
20
+ @dataclass
21
+ class Scene:
22
+ conductors: list[Conductor] # index 0 is the ground net
23
+ chip: Polygon
24
+ pocket: object # chip minus ground metal
25
+ stack: dict = field(default_factory=lambda: dict(DEFAULT_STACK))
26
+
27
+ @property
28
+ def n(self) -> int:
29
+ return len(self.conductors)
30
+
31
+ def names(self) -> list[str]:
32
+ return [c.name for c in self.conductors]
33
+
34
+
35
+ def _valid(g):
36
+ g = shapely.make_valid(g)
37
+ parts = [p for p in getattr(g, "geoms", [g]) if p.geom_type in ("Polygon", "MultiPolygon")]
38
+ return shapely.union_all(parts)
39
+
40
+
41
+ def make_scene(ground, signals: list, names: list[str]) -> Scene:
42
+ """Same construction as tlsq.uge.scene.scene_from_gds, from already-extracted geometry."""
43
+ chip = shapely.box(*ground.bounds)
44
+ conds = [Conductor("G", "ground", ground)] + [Conductor(n, "signal", g) for n, g in zip(names, signals)]
45
+ return Scene(conds, chip, chip.difference(ground), dict(DEFAULT_STACK))
tlsq_infer/app_ui.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio front end shared by the two Spaces (flagship single-model app and the paper-models app). Needs `gradio`.
2
+
3
+ API endpoints (gradio_client, api_name):
4
+ /inspect (gds file) -> layer table (JSON rows)
5
+ /prepare (gds, layers table, margin, ...) -> preview, warnings, summary, simplified GDS
6
+ /predict (gds, layers table, margin, ..., substrate) -> matrix table, CSV, JSON, report
7
+ /predict_gds (gds, ground "1/0", conductor "1/10", margin_gaps (0 auto, <0 no crop), substrate, eps, thickness_um, model,
8
+ self_from_rows)
9
+ -> result dict (one call, for scripts; see examples/client.py)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import tempfile
17
+ import time
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+
22
+ from . import __version__
23
+ from .layout import LayoutError, load_gds, prepare, read_polygons
24
+ from .predict import matrix_csv, predict
25
+ from .registry import load_registry
26
+
27
+ LIMITS = {"max_file_mb": float(os.environ.get("TLSQ_MAX_FILE_MB", 25)), "max_polygons": int(os.environ.get("TLSQ_MAX_POLYGONS", 200_000)),
28
+ "max_conductors": 7}
29
+ CUSTOM = "custom eps_r"
30
+ LAYER_COLS = ["layer", "datatype", "role", "n_polygons", "area_um2", "bbox_um"]
31
+
32
+
33
+ def _path(f):
34
+ if f is None:
35
+ raise LayoutError("upload a GDS file first")
36
+ p = f if isinstance(f, str) else getattr(f, "name", None) or f.get("path")
37
+ if os.path.getsize(p) > LIMITS["max_file_mb"] * 1e6:
38
+ raise LayoutError(f"file larger than {LIMITS['max_file_mb']:g} MB: crop the layout to the region of interest")
39
+ return p
40
+
41
+
42
+ def _roles(table) -> tuple[list, list, list]:
43
+ """(ground, conductor, ignore) layer lists from the editable layer table (list of rows or a DataFrame)."""
44
+ if table is None:
45
+ return [(1, 0)], [(1, 10)], []
46
+ rows = table.to_dict("records") if hasattr(table, "to_dict") else [dict(zip(LAYER_COLS, r)) if isinstance(r, (list, tuple)) else r for r in table]
47
+ g, c, i = [], [], []
48
+ for r in rows:
49
+ try:
50
+ key = (int(float(r["layer"])), int(float(r["datatype"])))
51
+ except (TypeError, ValueError, KeyError):
52
+ continue
53
+ role = str(r.get("role", "ignore")).strip().lower()
54
+ (g if role.startswith("g") else c if role.startswith("c") else i).append(key)
55
+ return g or [(1, 0)], c or [(1, 10)], i
56
+
57
+
58
+ def _parse_layers(s: str) -> list:
59
+ out = []
60
+ for tok in str(s).replace(";", ",").split(","):
61
+ tok = tok.strip()
62
+ if tok:
63
+ l, d = tok.split("/")
64
+ out.append((int(l), int(d)))
65
+ return out
66
+
67
+
68
+ def _parse_select(s):
69
+ s = (s or "").strip()
70
+ if not s:
71
+ return None
72
+ return [int(x) - 1 for x in s.replace(" ", "").split(",") if x] # UI uses 1-based C1, C2, ...
73
+
74
+
75
+ def inspect_fn(f):
76
+ p = _path(f)
77
+ polys, _, _ = read_polygons(p)
78
+ n = sum(len(v) for v in polys.values())
79
+ if n > LIMITS["max_polygons"]:
80
+ raise LayoutError(f"{n} polygons (> {LIMITS['max_polygons']}): crop the layout before uploading")
81
+ rows = load_gds(p)
82
+ table = [[r["layer"], r["datatype"], r["role"], r["n_polygons"], round(r["area_um2"], 1),
83
+ "(" + ", ".join(f"{x:.1f}" for x in r["bbox_um"]) + ")"] for r in rows]
84
+ return table, layer_preview(polys)
85
+
86
+
87
+ def layer_preview(polys: dict):
88
+ import matplotlib
89
+
90
+ matplotlib.use("Agg")
91
+ import matplotlib.pyplot as plt
92
+ from matplotlib.patches import Polygon as MPoly
93
+
94
+ fig, ax = plt.subplots(figsize=(6, 6))
95
+ cmap = plt.get_cmap("tab10")
96
+ handles = []
97
+ for k, (key, ps) in enumerate(sorted(polys.items())):
98
+ col = {(1, 0): "#b9bec7", (1, 10): "#2563eb"}.get(key, cmap((k + 2) % 10))
99
+ for p in ps[:5000]:
100
+ ax.add_patch(MPoly(np.asarray(p.exterior.coords), closed=True, fc=col, ec="k", lw=0.2, alpha=0.75 if key != (1, 0) else 0.6))
101
+ handles.append(MPoly([[0, 0]], fc=col, ec="k", label=f"{key[0]}/{key[1]} ({len(ps)})"))
102
+ ax.autoscale_view()
103
+ ax.set_aspect("equal")
104
+ ax.legend(handles=handles, loc="upper right", fontsize=8, title="layer/datatype (polygons)")
105
+ ax.set_xlabel("x (µm)")
106
+ ax.set_ylabel("y (µm)")
107
+ fig.tight_layout()
108
+ return fig
109
+
110
+
111
+ def _prepare(f, table, margin_gaps, margin_um, select):
112
+ g, c, i = _roles(table)
113
+ mu = float(margin_um) if margin_um not in (None, "", 0, 0.0) else None
114
+ return prepare(_path(f), ground_layers=g, conductor_layers=c, ignore_layers=i, margin_gaps=_margin(margin_gaps), margin_um=mu,
115
+ select=_parse_select(select))
116
+
117
+
118
+ def prepare_fn(f, table, margin_gaps, margin_um, select):
119
+ lay = _prepare(f, table, margin_gaps, margin_um, select)
120
+ import matplotlib
121
+
122
+ matplotlib.use("Agg")
123
+ fig = lay.render()
124
+ fig.tight_layout()
125
+ out = Path(tempfile.mkdtemp()) / "prepared_1-0_ground_1-10_conductors.gds"
126
+ lay.to_gds(out)
127
+ summ = {"conductors": lay.names, "min_gap_um": round(lay.min_gap_um, 4), "window_um": [round(x, 2) for x in lay.window] if lay.window else None,
128
+ "lateral_extent_um": round(lay.extent_um(), 1), **{k: v for k, v in lay.info.items() if k != "cell"}}
129
+ warn = "\n".join(f"- {w}" for w in lay.warnings) or "- none"
130
+ return fig, f"**Warnings**\n\n{warn}", summ, str(out)
131
+
132
+
133
+ def _margin(v):
134
+ """0 (or 'auto') = automatic training-like window; < 0 = no crop; > 0 = that many conductor-ground gaps."""
135
+ if v in (None, "", "auto"):
136
+ return "auto"
137
+ v = float(v)
138
+ return "auto" if v == 0 else (None if v < 0 else v)
139
+
140
+
141
+ def _eps(substrate, custom_eps):
142
+ return float(custom_eps) if substrate == CUSTOM else substrate
143
+
144
+
145
+ def report_md(res: dict, reg) -> str:
146
+ e = res["expected_error"]
147
+ v = e.get("validation", {})
148
+ lines = [f"**Model** `{res['model']}` ({res['model_title']}), package {res['package_version']}, registry v{res['registry_version']}",
149
+ f"**Substrate** {res['substrate']} (eps_r {res['eps_r']:g}), {res['thickness_um']:g} µm; eps correction factor "
150
+ f"(1+eps)/(1+11.45) = {res['eps_correction_factor']:.4f}",
151
+ "**Timing** " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in res["timing_s"].items()),
152
+ "",
153
+ f"**Expected error.** On the 926 never-seen validation designs this model has median {v.get('median_pct')} % "
154
+ f"(MAE {v.get('mae_ff')} fF, RMSE {v.get('rmse_ff')} fF) over all mutual capacitances."]
155
+ if "expected_median_pct" in e:
156
+ lines.append(f"For this layout and stack: expected median {e['expected_median_pct']:.2f} %, MAE ≈ {e['expected_mae_ff']:.2f} fF, "
157
+ f"RMSE ≈ {e['expected_rmse_ff']:.2f} fF (material residual {e['material_residual_pct']:.2f} %, finite-thickness "
158
+ f"residual {e['thickness_residual_pct']:.2f} %; breakdown below ≈ {e['breakdown_thickness_um']:.0f} µm for "
159
+ f"L = {e['lateral_extent_um']:.0f} µm). Stack residuals from a 15-design Q3D DoE: indicative.")
160
+ if res["warnings"]:
161
+ lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]]
162
+ lines += ["", "Ground self-capacitance is not predicted (depends on the chip boundary).",
163
+ "Training stack: Si (eps 11.45), 350 µm, zero-thickness metal. Planar layouts only."]
164
+ return "\n".join(lines)
165
+
166
+
167
+ def predict_fn(f, table, margin_gaps, margin_um, select, substrate, custom_eps, thickness, model, self_rows):
168
+ reg = load_registry()
169
+ lay = _prepare(f, table, margin_gaps, margin_um, select)
170
+ res = predict(lay, model=model, substrate=_eps(substrate, custom_eps), thickness_um=float(thickness), self_from_rows=bool(self_rows))
171
+ d = Path(tempfile.mkdtemp())
172
+ (d / "capacitance_fF.csv").write_text(matrix_csv(res))
173
+ (d / "capacitance.json").write_text(json.dumps(res, indent=1))
174
+ names = res["names"]
175
+ table_out = [[nm] + ["" if x is None else round(x, 4) for x in row] for nm, row in zip(names, res["matrix_fF"])]
176
+ return table_out, str(d / "capacitance_fF.csv"), str(d / "capacitance.json"), report_md(res, reg)
177
+
178
+
179
+ def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps=0.0, substrate="Si (cryogenic, training)",
180
+ custom_eps=11.45, thickness_um=350.0, model="", self_from_rows=False):
181
+ t = time.perf_counter()
182
+ lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers),
183
+ margin_gaps=_margin(margin_gaps))
184
+ res = predict(lay, model=model or None, substrate=_eps(substrate, custom_eps), thickness_um=float(thickness_um),
185
+ self_from_rows=bool(self_from_rows))
186
+ res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t
187
+ return res
188
+
189
+
190
+ def _safe(fn, n_out):
191
+ import gradio as gr
192
+
193
+ def wrapped(*a):
194
+ try:
195
+ return fn(*a)
196
+ except (LayoutError, ValueError, KeyError, FileNotFoundError) as e:
197
+ raise gr.Error(str(e)) from e
198
+ except MemoryError as e:
199
+ raise gr.Error("out of memory: crop the layout or use the standard prior") from e
200
+ except Exception as e: # noqa: BLE001
201
+ raise gr.Error(f"internal error ({type(e).__name__}): {e}") from e
202
+ wrapped.__name__ = fn.__name__
203
+ return wrapped
204
+
205
+
206
+ INTRO = """
207
+ ### What this does
208
+ Upload the GDS of a **planar** superconducting layout (metal film on a dielectric substrate) and get its full
209
+ **Maxwell capacitance matrix** in fF, zero-shot: no simulation of your design. A thin-film method-of-moments solve
210
+ provides a physics prior and a graph network trained on 40,153 Q3D simulations corrects it.
211
+
212
+ ### Layer convention
213
+ * **1/0 = ground**: the ground plane (one net, everything on this layer is connected).
214
+ * **1/10 = conductors**: the floating metal islands; every connected body is one net (C1, C2, ...).
215
+ * Anything else (port markers, junctions, labels) is ignored unless you assign it a role.
216
+
217
+ Your file may use other layers: assign the roles in step 1. Up to 7 conductors plus ground.
218
+ """
219
+
220
+
221
+ def build_app(title: str, model_choices: list[str], default_model: str, header_md: str = "", examples_dir=None,
222
+ extra_tab=None):
223
+ import gradio as gr
224
+
225
+ reg = load_registry()
226
+ subs = list(reg.substrates()) + [CUSTOM]
227
+ ex = sorted(Path(examples_dir).glob("*.gds")) if examples_dir and Path(examples_dir).exists() else []
228
+ space = os.environ.get("SPACE_ID")
229
+ with gr.Blocks(title=title) as demo:
230
+ gr.Markdown(f"# {title}\n{header_md}" + (f"\n\nSpace: `{space}`" if space else ""))
231
+ if extra_tab is not None:
232
+ extra_tab(gr, reg)
233
+ with gr.Accordion("Planar circuits and the layer convention", open=True):
234
+ with gr.Row():
235
+ gr.Markdown(INTRO)
236
+ with gr.Column():
237
+ ex_pick = gr.Dropdown([p.name for p in ex], value=ex[0].name if ex else None, label="example layout")
238
+ ex_plot = gr.Plot(label="annotated example: grey = ground (1/0), colours = conductors (1/10)")
239
+ gr.Markdown("## 1. Upload a GDS and assign layer roles")
240
+ with gr.Row():
241
+ with gr.Column(scale=1):
242
+ gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"])
243
+ if ex:
244
+ gr.Examples([[str(p)] for p in ex], inputs=[gds], label="or start from an example")
245
+ layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"],
246
+ label="detected layers: edit 'role' (ground / conductor / ignore)", interactive=True,
247
+ value=[[1, 0, "ground", 0, 0, ""], [1, 10, "conductor", 0, 0, ""]])
248
+ layer_plot = gr.Plot(label="layers")
249
+ gr.Markdown("## 2. Prepare: extract nets and crop the ground")
250
+ with gr.Row():
251
+ with gr.Column(scale=1):
252
+ margin = gr.Slider(0, 300, value=0, step=1, label="ground margin around the conductors, in conductor-ground gaps (0 = auto: training-like, recommended)")
253
+ margin_um = gr.Number(value=None, label="or absolute margin (µm); overrides the slider")
254
+ select = gr.Textbox(label="conductors to model (e.g. 1,2,3; empty = all)", value="")
255
+ prep_btn = gr.Button("Prepare", variant="secondary")
256
+ warn_md = gr.Markdown()
257
+ summary = gr.JSON(label="prepared layout")
258
+ prepared_gds = gr.File(label="simplified GDS (1/0 ground, 1/10 conductors)")
259
+ prep_plot = gr.Plot(label="prepared layout (dashed: crop window)")
260
+ gr.Markdown("## 3. Substrate and model")
261
+ with gr.Row():
262
+ substrate = gr.Dropdown(subs, value=subs[0], label="substrate")
263
+ custom_eps = gr.Number(value=11.45, label="custom eps_r (when 'custom')")
264
+ thickness = gr.Number(value=350, label="substrate thickness (µm)")
265
+ model = gr.Dropdown(model_choices, value=default_model, label="model")
266
+ self_rows = gr.Checkbox(False, label="self-capacitance from row sums")
267
+ pred_btn = gr.Button("Predict", variant="primary")
268
+ gr.Markdown("## 4. Maxwell capacitance matrix (fF)")
269
+ with gr.Row():
270
+ mat = gr.Dataframe(label="Maxwell matrix (fF): diagonal = self, off-diagonal = -mutual", interactive=False)
271
+ with gr.Column():
272
+ csv_f = gr.File(label="CSV")
273
+ json_f = gr.File(label="JSON (matrix + metadata + expected error)")
274
+ report = gr.Markdown()
275
+ with gr.Row(visible=False):
276
+ a_g = gr.Textbox("1/0")
277
+ a_c = gr.Textbox("1/10")
278
+ a_m = gr.Number(0)
279
+ a_out = gr.JSON()
280
+ a_btn = gr.Button("api")
281
+
282
+ def ex_fn(name):
283
+ if not name:
284
+ return None
285
+ from .layout import prepare as _p
286
+
287
+ lay = _p(str(Path(examples_dir) / name), margin_gaps=None)
288
+ fig = lay.render(title=f"{name}: {lay.n_conductors} conductors + ground")
289
+ fig.tight_layout()
290
+ return fig
291
+
292
+ if ex:
293
+ ex_pick.change(ex_fn, ex_pick, ex_plot, api_visibility="private")
294
+ demo.load(ex_fn, ex_pick, ex_plot, api_visibility="private")
295
+ gds.upload(_safe(inspect_fn, 2), gds, [layers, layer_plot], api_name="inspect")
296
+ prep_btn.click(_safe(prepare_fn, 4), [gds, layers, margin, margin_um, select], [prep_plot, warn_md, summary, prepared_gds], api_name="prepare")
297
+ pred_btn.click(_safe(predict_fn, 4), [gds, layers, margin, margin_um, select, substrate, custom_eps, thickness, model, self_rows],
298
+ [mat, csv_f, json_f, report], api_name="predict")
299
+ a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model, self_rows], a_out,
300
+ api_name="predict_gds")
301
+ gr.Markdown(f"<small>tlsq_infer {__version__}. Limits: {LIMITS['max_file_mb']:g} MB per file, "
302
+ f"{LIMITS['max_polygons']:,} polygons, {LIMITS['max_conductors']} conductors + ground.</small>")
303
+ return demo
tlsq_infer/charge.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Charge-corrected MoM prior: a gradient-boosted model of log(|q_Q3D| / |q_MoM|) per quadtree cell from 9 local geometry
2
+ features (scripts/charge_locality.py, scripts/zs_study.py: cell_features), applied to the cell charges of every
3
+ excitation and integrated per conductor. Trained once on the surface charge of the training families (no capacitance
4
+ labels) and shipped as a joblib file.
5
+
6
+ python -m tlsq_infer.charge fit --cells data_local/charge_p1/train_cells.parquet --out deploy/artifacts/charge_gbm.joblib
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import numpy as np
12
+ import shapely
13
+
14
+ FEATS = ["owner_driven", "owner_ground", "other_is_driven", "other_is_ground", "log_h", "log_d_own", "log_d_other",
15
+ "log_h_over_d", "log_sig_mom"]
16
+ GBM_PARAMS = dict(max_iter=400, learning_rate=0.05, random_state=0)
17
+
18
+
19
+ def fit_gbm(cells_parquet):
20
+ """Exactly the cell model of the paper (all five training families, 9 features)."""
21
+ import pandas as pd
22
+ from sklearn.ensemble import HistGradientBoostingRegressor
23
+
24
+ cells = pd.read_parquet(cells_parquet)
25
+ ok = (np.sign(cells.q_mom) == np.sign(cells.q_q3d)) & (cells.q_mom.abs() > 1e-9) & (cells.q_q3d.abs() > 1e-9)
26
+ cells = cells[ok]
27
+ r = np.log(np.abs(cells.q_q3d) / np.abs(cells.q_mom))
28
+ return HistGradientBoostingRegressor(**GBM_PARAMS).fit(cells[FEATS], r, sample_weight=cells.q_mom.abs()), int(len(cells))
29
+
30
+
31
+ def cell_feature_frames(metals: list, mom: dict) -> tuple[dict, np.ndarray]:
32
+ """Per-excitation feature tables (float32, as in the paper's cell cache) and float32 cell charges."""
33
+ import pandas as pd
34
+
35
+ cen, h, own, Q = mom["cen"], mom["h"], mom["own"], mom["Q"]
36
+ pts = shapely.points(cen)
37
+ d_own, d_other, other_id = np.zeros(len(cen)), np.full(len(cen), np.inf), np.full(len(cen), -1)
38
+ for k, g in enumerate(metals):
39
+ sel = own == k
40
+ d_own[sel] = shapely.distance(g.boundary, pts[sel])
41
+ for k2, g2 in enumerate(metals):
42
+ if k2 != k:
43
+ dk = shapely.distance(g2, pts[sel])
44
+ better = dk < d_other[sel]
45
+ ix = np.nonzero(sel)[0][better]
46
+ d_other[ix], other_id[ix] = dk[better], k2
47
+ base = {"owner_ground": (own == 0).astype(float), "other_is_ground": (other_id == 0).astype(float), "log_h": np.log(h),
48
+ "log_d_own": np.log(d_own + 0.05), "log_d_other": np.log(d_other + 0.05), "log_h_over_d": np.log(h / (d_own + 0.05))}
49
+ X = {j: pd.DataFrame({**base, "owner_driven": (own == j).astype(float), "other_is_driven": (other_id == j).astype(float),
50
+ "log_sig_mom": np.log(np.abs(Q[:, j]) / h**2 + 1e-12)}).astype(np.float32) for j in range(len(metals))}
51
+ return X, Q.astype(np.float32)
52
+
53
+
54
+ def corrected_matrix(gbm, metals: list, mom: dict) -> np.ndarray:
55
+ """Charge-corrected Maxwell matrix (fF), training stack."""
56
+ X, Q = cell_feature_frames(metals, mom)
57
+ n = len(metals)
58
+ own = mom["own"]
59
+ C = np.stack([np.bincount(own, weights=Q[:, j] * np.exp(gbm.predict(X[j][FEATS])), minlength=n) for j in range(n)], 1)
60
+ return 0.5 * (C + C.T)
61
+
62
+
63
+ def load_gbm(path):
64
+ import joblib
65
+
66
+ return joblib.load(path)
67
+
68
+
69
+ if __name__ == "__main__":
70
+ import argparse
71
+ import json
72
+ import time
73
+
74
+ import joblib
75
+ import sklearn
76
+
77
+ ap = argparse.ArgumentParser()
78
+ ap.add_argument("cmd", choices=["fit"])
79
+ ap.add_argument("--cells", required=True)
80
+ ap.add_argument("--out", required=True)
81
+ a = ap.parse_args()
82
+ t = time.time()
83
+ m, n = fit_gbm(a.cells)
84
+ joblib.dump(m, a.out, compress=3)
85
+ meta = {"features": FEATS, "params": GBM_PARAMS, "n_cells": n, "sklearn": sklearn.__version__, "fit_s": round(time.time() - t, 1),
86
+ "target": "log(|q_Q3D| / |q_MoM|) per quadtree cell, weight |q_MoM|"}
87
+ with open(str(a.out).replace(".joblib", ".json"), "w") as f:
88
+ json.dump(meta, f, indent=1)
89
+ print(meta)
tlsq_infer/layout.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GDS reading and layout preparation: layers -> ground net + conductor bodies, cropped to a window around the conductors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ import gdstk
10
+ import numpy as np
11
+ import shapely
12
+ from shapely.geometry import Polygon
13
+
14
+ from ._vendor.scene import _valid
15
+
16
+ GROUND = (1, 0)
17
+ CONDUCTOR = (1, 10)
18
+ N_MAX_SIGNALS = 7
19
+ AUTO_GAPS, AUTO_FRAC, AUTO_MIN_UM = 100.0, 0.5, 150.0 # margin="auto" (see deploy/LIMITS.md: crop study) # the networks are dense over at most 8 conductors including ground
20
+
21
+
22
+ class LayoutError(ValueError):
23
+ """The layout cannot be turned into a valid capacitance problem (message says why and what to change)."""
24
+
25
+
26
+ def _top_cell(lib, cell: str | None):
27
+ if cell is not None:
28
+ for c in lib.cells:
29
+ if c.name == cell:
30
+ return c
31
+ raise LayoutError(f"cell {cell!r} not in the file (cells: {[c.name for c in lib.cells][:20]})")
32
+ tops = lib.top_level()
33
+ if not tops:
34
+ raise LayoutError("the GDS file has no cells")
35
+ if len(tops) == 1:
36
+ return tops[0]
37
+ # several top cells: take the one with the most (flattened) polygons
38
+ return max(tops, key=lambda c: len(c.get_polygons()))
39
+
40
+
41
+ def read_polygons(path, cell: str | None = None) -> tuple[dict, float, str]:
42
+ """{(layer, datatype): [shapely Polygon in µm, ...]} in file order, with references and paths flattened."""
43
+ try:
44
+ lib = gdstk.read_gds(str(path))
45
+ except Exception as e: # noqa: BLE001
46
+ raise LayoutError(f"not a readable GDS file: {e}") from e
47
+ top = _top_cell(lib, cell)
48
+ u = lib.unit / 1e-6
49
+ # flat cells (the training files): direct polygons in file order, which fixes the conductor order of the paper;
50
+ # otherwise everything is flattened (references, repetitions, paths)
51
+ polys = list(top.polygons) if not (top.references or top.paths) else top.get_polygons(apply_repetitions=True, include_paths=True)
52
+ out: dict = {}
53
+ for p in polys:
54
+ if len(p.points) < 3:
55
+ continue
56
+ out.setdefault((p.layer, p.datatype), []).append(Polygon(p.points * u))
57
+ return out, u, top.name
58
+
59
+
60
+ def load_gds(path, layer_map: dict | None = None, cell: str | None = None) -> list[dict]:
61
+ """Detected (layer, datatype) pairs with polygon count, area (µm²) and bounding box (µm), plus a suggested role
62
+ (ground / conductor / ignore) from `layer_map` ({"ground": [(1, 0)], "conductor": [(1, 10)]} by default)."""
63
+ layer_map = layer_map or {"ground": [GROUND], "conductor": [CONDUCTOR]}
64
+ lm = {tuple(k): role for role, ks in layer_map.items() for k in ks}
65
+ polys, _, top = read_polygons(path, cell)
66
+ rows = []
67
+ for (l, d), ps in sorted(polys.items()):
68
+ b = shapely.union_all(ps).bounds if ps else (np.nan,) * 4
69
+ rows.append({"layer": l, "datatype": d, "n_polygons": len(ps), "area_um2": float(sum(p.area for p in ps)),
70
+ "bbox_um": tuple(float(x) for x in b), "role": lm.get((l, d), "ignore"), "cell": top})
71
+ return rows
72
+
73
+
74
+ def _components(polys: list) -> list[list[int]]:
75
+ """Connected components (touching or overlapping polygons) as lists of polygon indices, ordered by first index."""
76
+ n = len(polys)
77
+ parent = list(range(n))
78
+
79
+ def find(a):
80
+ while parent[a] != a:
81
+ parent[a] = parent[parent[a]]
82
+ a = parent[a]
83
+ return a
84
+
85
+ if n > 1:
86
+ tree = shapely.STRtree(polys)
87
+ ii, jj = tree.query(polys, predicate="intersects")
88
+ for a, b in zip(ii, jj):
89
+ ra, rb = find(int(a)), find(int(b))
90
+ if ra != rb:
91
+ parent[max(ra, rb)] = min(ra, rb)
92
+ groups: dict = {}
93
+ for i in range(n):
94
+ groups.setdefault(find(i), []).append(i)
95
+ return sorted(groups.values(), key=lambda g: g[0])
96
+
97
+
98
+ def _core_bounds(G, bodies: list, warnings: list) -> tuple:
99
+ """Bounds of the conductors together with the etched pocket(s) that contain them, so that cropping never cuts into the
100
+ ground edge facing the conductors. Open regions (the etch reaches the outer boundary of the metal) and very large
101
+ pockets (e.g. a CPW gap running across the chip) fall back to the conductors' own bounds."""
102
+ S = shapely.union_all(bodies)
103
+ sb = S.bounds
104
+ outer = shapely.box(*shapely.union_all([G, S]).bounds)
105
+ etched = outer.difference(G)
106
+ parts = [p for p in getattr(etched, "geoms", [etched]) if p.intersects(S)]
107
+ if not parts:
108
+ return sb
109
+ P = shapely.union_all(parts)
110
+ pb = P.bounds
111
+ ob = outer.bounds
112
+ open_ = any(abs(a - b) < 1e-6 for a, b in zip(pb, ob))
113
+ big = (pb[2] - pb[0]) * (pb[3] - pb[1]) > 25 * max((sb[2] - sb[0]) * (sb[3] - sb[1]), 1e-9)
114
+ if open_ or big:
115
+ if big and not open_:
116
+ warnings.append("the etched region around the conductors is large (> 25x their bounding box); window built "
117
+ "around the conductors only: check the crop in the preview")
118
+ return sb
119
+ return (min(sb[0], pb[0]), min(sb[1], pb[1]), max(sb[2], pb[2]), max(sb[3], pb[3]))
120
+
121
+
122
+ @dataclass
123
+ class PreparedLayout:
124
+ ground: object # shapely geometry (µm), cropped
125
+ conductors: list # shapely geometries (µm), one per net, file order
126
+ names: list[str]
127
+ window: tuple | None # (x0, y0, x1, y1) µm, or None when not cropped
128
+ min_gap_um: float
129
+ source: str = ""
130
+ warnings: list[str] = field(default_factory=list)
131
+ extra_metal: dict = field(default_factory=dict) # label -> geometry of metal inside the window that is not modelled
132
+ info: dict = field(default_factory=dict)
133
+
134
+ @property
135
+ def n_conductors(self) -> int:
136
+ return len(self.conductors)
137
+
138
+ def extent_um(self) -> float:
139
+ """Lateral size L of the conductors: diagonal of their joint bounding box (µm)."""
140
+ x0, y0, x1, y1 = shapely.union_all(self.conductors).bounds
141
+ return float(np.hypot(x1 - x0, y1 - y0))
142
+
143
+ def to_gds(self, path=None) -> bytes:
144
+ """Simplified GDS in the training convention: ground on (1, 0), one or more polygons per conductor on (1, 10).
145
+ Returns the bytes (and writes them when `path` is given)."""
146
+ lib = gdstk.Library(unit=1e-6, precision=1e-9)
147
+ cell = lib.new_cell("PREPARED")
148
+
149
+ def add(g, layer, dt):
150
+ for poly in getattr(g, "geoms", [g]):
151
+ if poly.is_empty:
152
+ continue
153
+ if len(poly.interiors) == 0:
154
+ cell.add(gdstk.Polygon(np.asarray(poly.exterior.coords)[:-1], layer=layer, datatype=dt))
155
+ else: # polygons with holes: boolean in gdstk keeps them as keyhole polygons
156
+ outer = gdstk.Polygon(np.asarray(poly.exterior.coords)[:-1])
157
+ holes = [gdstk.Polygon(np.asarray(r.coords)[:-1]) for r in poly.interiors]
158
+ for p in gdstk.boolean(outer, holes, "not", layer=layer, datatype=dt):
159
+ cell.add(p)
160
+
161
+ add(self.ground, *GROUND)
162
+ for g in self.conductors:
163
+ add(g, *CONDUCTOR)
164
+ if path is None:
165
+ with tempfile.TemporaryDirectory() as d:
166
+ lib.write_gds(Path(d) / "prepared.gds")
167
+ return (Path(d) / "prepared.gds").read_bytes()
168
+ lib.write_gds(str(path))
169
+ return Path(path).read_bytes()
170
+
171
+ def render(self, ax=None, show_window: bool = True, title: str | None = None):
172
+ """Matplotlib figure: ground (grey), conductors (coloured, labelled), unmodelled metal (hatched), window."""
173
+ import matplotlib.pyplot as plt
174
+ from matplotlib.patches import PathPatch, Rectangle
175
+ from matplotlib.path import Path as MPath
176
+
177
+ def patch(g, **kw):
178
+ for poly in getattr(g, "geoms", [g]):
179
+ if poly.is_empty or poly.geom_type != "Polygon":
180
+ continue
181
+ verts, codes = [], []
182
+ for ring in [poly.exterior, *poly.interiors]:
183
+ xy = np.asarray(ring.coords)
184
+ verts += list(xy)
185
+ codes += [MPath.MOVETO] + [MPath.LINETO] * (len(xy) - 2) + [MPath.CLOSEPOLY]
186
+ ax.add_patch(PathPatch(MPath(verts, codes), **kw))
187
+
188
+ if ax is None:
189
+ fig, ax = plt.subplots(figsize=(6.4, 6.4))
190
+ else:
191
+ fig = ax.figure
192
+ patch(self.ground, facecolor="#b9bec7", edgecolor="#6b7280", lw=0.4)
193
+ cmap = plt.get_cmap("tab10")
194
+ for k, (g, nm) in enumerate(zip(self.conductors, self.names)):
195
+ patch(g, facecolor=cmap(k % 10), edgecolor="black", lw=0.4, alpha=0.9)
196
+ p = g.representative_point() if g.area > 0 else g.centroid
197
+ ax.annotate(nm, (p.x, p.y), ha="center", va="center", fontsize=11, weight="bold", color="white",
198
+ bbox=dict(boxstyle="round,pad=0.2", fc=cmap(k % 10), ec="black", lw=0.6))
199
+ for lab, g in self.extra_metal.items():
200
+ patch(g, facecolor="none", edgecolor="#dc2626", hatch="///", lw=0.6)
201
+ if show_window and self.window is not None:
202
+ x0, y0, x1, y1 = self.window
203
+ ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, ls="--", ec="#2563eb", lw=1.0))
204
+ b = shapely.union_all([self.ground, *self.conductors]).bounds
205
+ pad = 0.03 * max(b[2] - b[0], b[3] - b[1])
206
+ ax.set_xlim(b[0] - pad, b[2] + pad)
207
+ ax.set_ylim(b[1] - pad, b[3] + pad)
208
+ ax.set_aspect("equal")
209
+ ax.set_xlabel("x (µm)")
210
+ ax.set_ylabel("y (µm)")
211
+ ax.set_title(title or f"{len(self.conductors)} conductors + ground; min gap {self.min_gap_um:.2f} µm")
212
+ return fig
213
+
214
+
215
+ def prepare(path, ground_layers=(GROUND,), conductor_layers=(CONDUCTOR,), margin_gaps: float | str | None = "auto",
216
+ margin_um: float | None = None, ignore_layers=(), cell: str | None = None, select=None, select_box=None,
217
+ max_conductors: int = N_MAX_SIGNALS) -> PreparedLayout:
218
+ """Extract the capacitance problem from a GDS file.
219
+
220
+ - conductors: connected bodies of the conductor-layer polygons (touching/overlapping polygons are one net), in file
221
+ order; bodies that touch the ground metal are shorted to it and merged into the ground net (warning).
222
+ - ground: union of the ground-layer polygons, cropped to the window = bbox(conductors + the etched pocket that
223
+ contains them) expanded by `margin_um` if given, else `margin_gaps` x (smallest conductor-to-ground gap), else
224
+ ("auto", default) by max(100 gaps, half the conductor extent, 150 µm), which keeps a training-like ground
225
+ neighbourhood (tighter crops cost accuracy: 20 gaps doubles the error, see deploy/LIMITS.md). None: no crop.
226
+ - select: optional list of conductor-body indices (0-based, file order), or select_box = (x0, y0, x1, y1) µm (bodies
227
+ fully inside); the other bodies are not modelled and are flagged as extra metal when they fall inside the window.
228
+ - metal on layers that are neither ground, conductor nor in `ignore_layers` is flagged when inside the window.
229
+ """
230
+ gl = {tuple(x) for x in ground_layers}
231
+ cl = {tuple(x) for x in conductor_layers}
232
+ il = {tuple(x) for x in ignore_layers}
233
+ if gl & cl:
234
+ raise LayoutError(f"layers {sorted(gl & cl)} are assigned both ground and conductor")
235
+ polys, _, top = read_polygons(path, cell)
236
+ warnings: list[str] = []
237
+ gpolys = [p for k in polys if k in gl for p in polys[k]]
238
+ cpolys = [p for k in polys if k in cl for p in polys[k]]
239
+ if not gpolys:
240
+ raise LayoutError(f"no ground polygons on {sorted(gl)}; detected layers: {sorted(polys)}")
241
+ if not cpolys:
242
+ raise LayoutError(f"no conductor polygons on {sorted(cl)}; detected layers: {sorted(polys)}")
243
+ cvalid = [_valid(p) for p in cpolys]
244
+ keep = [i for i, g in enumerate(cvalid) if not g.is_empty and g.area > 0]
245
+ if len(keep) < len(cvalid):
246
+ warnings.append(f"{len(cvalid) - len(keep)} degenerate conductor polygon(s) (zero area) dropped")
247
+ cvalid = [cvalid[i] for i in keep]
248
+ G = _valid(shapely.union_all([_valid(g) for g in gpolys]))
249
+ bodies = []
250
+ for comp in _components(cvalid):
251
+ bodies.append(cvalid[comp[0]] if len(comp) == 1 else _valid(shapely.union_all([cvalid[i] for i in comp])))
252
+ n_merged = len(cvalid) - len(bodies)
253
+ if n_merged:
254
+ warnings.append(f"{len(cvalid)} conductor polygons form {len(bodies)} connected bodies (touching polygons merged into one net)")
255
+ # bodies in contact with ground metal are at ground potential
256
+ shorted = [i for i, b in enumerate(bodies) if shapely.intersects(b, G)]
257
+ if shorted:
258
+ warnings.append(f"{len(shorted)} conductor body(ies) touch the ground metal and were merged into the ground net")
259
+ G = _valid(shapely.union_all([G] + [bodies[i] for i in shorted]))
260
+ bodies = [b for i, b in enumerate(bodies) if i not in set(shorted)]
261
+ if not bodies:
262
+ raise LayoutError("every conductor body touches the ground: nothing floating to compute")
263
+ all_bodies = bodies
264
+ others = []
265
+ if select is not None or select_box is not None:
266
+ if select_box is not None:
267
+ box = shapely.box(*select_box)
268
+ idx = [i for i, b in enumerate(bodies) if box.contains(b)]
269
+ else:
270
+ idx = [int(i) for i in select]
271
+ bad = [i for i in idx if i < 0 or i >= len(bodies)]
272
+ if bad:
273
+ raise LayoutError(f"select indices {bad} out of range (0..{len(bodies) - 1})")
274
+ if not idx:
275
+ raise LayoutError("the selection matched no conductor body")
276
+ bodies = [all_bodies[i] for i in idx]
277
+ others = [all_bodies[i] for i in range(len(all_bodies)) if i not in set(idx)]
278
+ if len(bodies) > max_conductors:
279
+ raise LayoutError(f"{len(bodies)} conductors found; the networks take at most {max_conductors} signal conductors "
280
+ "plus ground. Use `select` (indices or a box) to pick the conductors of interest.")
281
+ metals = [G] + bodies
282
+ gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals)))
283
+ if not np.isfinite(gap) or gap <= 0:
284
+ raise LayoutError("zero gap between two nets (overlapping metal on different nets)")
285
+ window = None
286
+ if margin_um is not None or margin_gaps is not None:
287
+ gap_cg = min(shapely.distance(G, b) for b in bodies) # conductor-to-ground gap sets the scale of the ground's field
288
+ x0, y0, x1, y1 = _core_bounds(G, bodies, warnings)
289
+ if margin_um is not None:
290
+ m = float(margin_um)
291
+ elif margin_gaps == "auto":
292
+ # a training-like neighbourhood: the training chips extend ~150-330 µm (30-170 gaps) beyond the conductors
293
+ m = max(AUTO_GAPS * gap_cg, AUTO_FRAC * max(x1 - x0, y1 - y0), AUTO_MIN_UM)
294
+ else:
295
+ m = float(margin_gaps) * gap_cg
296
+ window = (x0 - m, y0 - m, x1 + m, y1 + m)
297
+ box = shapely.box(*window)
298
+ Gc = _valid(shapely.intersection(G, box))
299
+ if Gc.is_empty:
300
+ raise LayoutError("no ground metal inside the window; increase the margin")
301
+ G = Gc
302
+ metals = [G] + bodies
303
+ gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals)))
304
+ if G.geom_type == "MultiPolygon" and len(G.geoms) > 1:
305
+ warnings.append(f"cropped ground consists of {len(G.geoms)} separate pieces (all treated as one net)")
306
+ box = shapely.box(*window) if window is not None else shapely.box(*shapely.union_all(metals).bounds)
307
+ extra = {}
308
+ for k, ps in polys.items():
309
+ if k in gl or k in cl or k in il:
310
+ continue
311
+ inside = [p for p in ps if shapely.intersects(p, box)]
312
+ if inside:
313
+ extra[f"layer {k[0]}/{k[1]}"] = shapely.union_all([_valid(p) for p in inside])
314
+ for i, b in enumerate(others):
315
+ if shapely.intersects(b, box):
316
+ extra.setdefault("unselected conductors", [])
317
+ extra["unselected conductors"].append(b)
318
+ if "unselected conductors" in extra:
319
+ n_un = len(extra["unselected conductors"])
320
+ extra["unselected conductors"] = shapely.union_all(extra["unselected conductors"])
321
+ warnings.append(f"{n_un} unselected conductor body(ies) lie inside the window and are NOT modelled (they would screen the selected ones)")
322
+ for lab in extra:
323
+ if lab.startswith("layer"):
324
+ warnings.append(f"metal on {lab} inside the window is not assigned (ground / conductor) and is ignored")
325
+ holes = sum(len(p.interiors) for b in bodies for p in getattr(b, "geoms", [b]))
326
+ if holes:
327
+ warnings.append(f"conductors contain {holes} hole(s): supported, but outside the training families")
328
+ size = max(np.subtract(shapely.union_all(metals).bounds[2:], shapely.union_all(metals).bounds[:2]))
329
+ if gap < 3 * size / 4096:
330
+ warnings.append(f"smallest gap {gap:.3g} µm is below the MoM resolution floor for a {size:.0f} µm layout "
331
+ f"(~{3 * size / 4096:.3g} µm): crop tighter or expect larger errors")
332
+ names = [f"C{i + 1}" for i in range(len(bodies))]
333
+ 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),
334
+ "extent_um": float(np.hypot(*np.subtract(shapely.union_all(bodies).bounds[2:], shapely.union_all(bodies).bounds[:2])))}
335
+ return PreparedLayout(G, bodies, names, window, float(gap), str(path), warnings, extra, info)
tlsq_infer/predict.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prediction: prepared layout -> MoM prior -> scene graph -> network ensemble (-> charge correction -> blend) -> Maxwell
2
+ matrix (fF) for the requested substrate."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import time
7
+
8
+ import numpy as np
9
+
10
+ from . import __version__
11
+ from ._vendor.graph import prior_dict, scene_graph
12
+ from ._vendor.mom import mom_solve
13
+ from ._vendor.scene import make_scene
14
+ from .charge import corrected_matrix
15
+ from .layout import PreparedLayout
16
+ from .registry import PRIORS, get_component, load_registry
17
+ from .stack_error import EPS_TRAIN, eps_factor, expected_error, lateral_extent, load_params
18
+
19
+
20
+ def _internal_names(n_signal: int) -> list[str]:
21
+ """Training-convention names fixing the blend entry kinds: first two signal bodies N, S; later bodies are pads."""
22
+ return (["N", "S"] + [f"P{k}" for k in range(1, n_signal - 1)])[:n_signal]
23
+
24
+
25
+ def _kind(a: str, b: str) -> str:
26
+ if a.startswith("P") or b.startswith("P"):
27
+ return "pad"
28
+ return "signal-ground" if "G" in (a, b) else "signal-signal"
29
+
30
+
31
+ def _logC(C: np.ndarray) -> np.ndarray:
32
+ n = C.shape[0]
33
+ out = np.zeros_like(C)
34
+ for i in range(n):
35
+ for j in range(n):
36
+ out[i, j] = np.log(max(C[i, i], 1e-9)) if i == j else np.log(max(-C[i, j], 1e-9))
37
+ return out
38
+
39
+
40
+ def run_pipeline(metals: list, names: list[str], model: str, reg=None, model_dir=None, timing=None) -> tuple[np.ndarray, dict]:
41
+ """Core: log|C| matrix (diag: log C_ii, off-diag: log -C_ij) on the training stack, in `metals` order (0 = ground)."""
42
+ reg = reg or load_registry()
43
+ m = reg.model(model)
44
+ timing = {} if timing is None else timing
45
+ kind = m["kind"]
46
+ if kind == "blend":
47
+ gnn_name, ch_name = m["components"]
48
+ prior = reg.model(gnn_name).get("prior", "standard")
49
+ else:
50
+ prior = m.get("prior", "standard")
51
+ debug = {"model": model, "kind": kind}
52
+ mom = None
53
+ if prior != "none":
54
+ t = time.perf_counter()
55
+ mom = mom_solve(metals, **PRIORS[prior])
56
+ timing["prior_s"] = time.perf_counter() - t
57
+ debug.update(mom_cells=int(mom["n_cells"]), h_min_um=float(mom["h_min"]), prior_matrix=mom["C"])
58
+ if kind == "prior":
59
+ return _logC(mom["C"]), debug
60
+ out_gnn = out_corr = None
61
+ if kind in ("gnn", "blend"):
62
+ gname = model if kind == "gnn" else gnn_name
63
+ t = time.perf_counter()
64
+ sc = make_scene(metals[0], metals[1:], names[1:])
65
+ prior_fn = (lambda edges: prior_dict(mom["C"], mom["n_cells"], mom["h_min"], edges)) if mom is not None else None
66
+ g = scene_graph(sc, prior_fn)
67
+ g["target"] = np.ones((len(metals), len(metals)))
68
+ timing["features_s"] = time.perf_counter() - t
69
+ t = time.perf_counter()
70
+ ens = get_component(reg, gname, model_dir)
71
+ timing["load_s"] = timing.get("load_s", 0.0) + time.perf_counter() - t
72
+ t = time.perf_counter()
73
+ out_gnn = ens([g], proxy_key="proxy_log_C" if mom is not None else None)[0][: len(metals), : len(metals)]
74
+ timing["network_s"] = time.perf_counter() - t
75
+ debug["graph"] = g
76
+ if kind in ("charge_prior", "blend"):
77
+ cname = model if kind == "charge_prior" else ch_name
78
+ t = time.perf_counter()
79
+ gbm = get_component(reg, cname, model_dir)
80
+ timing["load_s"] = timing.get("load_s", 0.0) + time.perf_counter() - t
81
+ t = time.perf_counter()
82
+ out_corr = _logC(corrected_matrix(gbm, metals, mom))
83
+ timing["charge_correction_s"] = time.perf_counter() - t
84
+ if kind == "gnn":
85
+ return out_gnn, debug
86
+ if kind == "charge_prior":
87
+ return out_corr, debug
88
+ w = reg["blend"]["weights_gnn_side"]
89
+ out = out_gnn.copy()
90
+ for i in range(len(names)):
91
+ for j in range(len(names)):
92
+ if i != j:
93
+ wk = w[_kind(names[i], names[j])]
94
+ out[i, j] = wk * out_gnn[i, j] + (1 - wk) * out_corr[i, j]
95
+ debug["gnn_logC"], debug["corr_logC"] = out_gnn, out_corr
96
+ return out, debug
97
+
98
+
99
+ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (cryogenic, training)", thickness_um: float = 350.0,
100
+ self_from_rows: bool = False, registry=None, model_dir=None, return_debug: bool = False) -> dict:
101
+ """Maxwell capacitance matrix (fF) of a prepared layout.
102
+
103
+ model: a deployable registry name (default: the flagship model). substrate: a registry substrate name or eps_r.
104
+ The networks always see the training stack (Si 11.45, 350 µm); other permittivities are handled by the validated
105
+ half-space factor (1 + eps) / (1 + 11.45), and thickness / material residuals are reported in `expected_error`.
106
+ The ground self-capacitance is not predicted (it depends on the chip boundary, excluded from training): NaN.
107
+ """
108
+ reg = registry or load_registry()
109
+ model = model or reg["defaults"]["flagship_model"]
110
+ m = reg.model(model)
111
+ if m.get("status") != "available" or m.get("kind") == "baseline":
112
+ raise ValueError(f"model {model!r} is not deployable ({m.get('status')}); available: {reg.deployable()}")
113
+ eps = reg.eps_of(substrate)
114
+ t_all = time.perf_counter()
115
+ timing: dict = {}
116
+ n = prepared.n_conductors
117
+ names = ["G"] + _internal_names(n)
118
+ metals = [prepared.ground] + list(prepared.conductors)
119
+ logC, debug = run_pipeline(metals, names, model, reg, model_dir, timing)
120
+ k = len(metals)
121
+ Cabs = np.exp(logC[:k, :k])
122
+ M = -Cabs.copy()
123
+ for i in range(k):
124
+ M[i, i] = Cabs[i, i]
125
+ if self_from_rows:
126
+ e = float(reg["self_capacitance"]["row_sum_eps"])
127
+ for i in range(1, k):
128
+ M[i, i] = sum(Cabs[i, j] for j in range(k) if j != i) / (1 - e)
129
+ M[0, 0] = np.nan
130
+ f = eps_factor(eps)
131
+ M = M * f
132
+ timing["total_s"] = time.perf_counter() - t_all
133
+ labels = ["G"] + list(prepared.names)
134
+ iu = [(i, j) for i in range(k) for j in range(i + 1, k)]
135
+ mut = np.array([abs(M[i, j]) for i, j in iu])
136
+ base = m.get("paper", {}).get("never_seen")
137
+ if base is None and m["kind"] == "blend":
138
+ base = reg.model(m["components"][0])["paper"]["never_seen"]
139
+ P = load_params()
140
+ L = lateral_extent(prepared.conductors, P)
141
+ exp_err = expected_error(P, eps, float(thickness_um), L, {kk: base[kk] for kk in ("median_pct", "mae_ff", "rmse_ff")},
142
+ float(np.mean(mut)), float(np.sqrt(np.mean(mut**2))))
143
+ exp_err["validation_sets"] = {s: m.get("paper", {}).get(s) for s in ("never_seen", "ood60") if m.get("paper", {}).get(s)}
144
+ out = {"names": labels, "matrix_fF": [[None if np.isnan(v) else float(v) for v in row] for row in M], "units": "fF",
145
+ "convention": "Maxwell matrix: diagonal = self-capacitance, off-diagonal = -mutual; row/column 0 = ground (its self term not predicted)",
146
+ "self_capacitance": "row sums / (1 - eps_rs)" if self_from_rows else "network self term",
147
+ "model": model, "model_title": m.get("title"), "repo_id": m.get("repo_id"), "package_version": __version__,
148
+ "registry_version": reg["version"], "substrate": substrate if not isinstance(substrate, (int, float)) else f"custom eps={eps:g}",
149
+ "eps_r": eps, "eps_correction_factor": f, "thickness_um": float(thickness_um),
150
+ "training_stack": {"eps_r": EPS_TRAIN, "thickness_um": 350.0}, "timing_s": timing, "expected_error": exp_err,
151
+ "warnings": list(prepared.warnings) + ([exp_err["warning"]] if exp_err.get("warning") else [])}
152
+ if m.get("warning"):
153
+ out["warnings"].insert(0, m["warning"])
154
+ if return_debug:
155
+ out["debug"] = debug
156
+ return out
157
+
158
+
159
+ def matrix_csv(result: dict) -> str:
160
+ names = result["names"]
161
+ lines = ["," + ",".join(names)]
162
+ for nm, row in zip(names, result["matrix_fF"]):
163
+ lines.append(nm + "," + ",".join("" if (v is None or (isinstance(v, float) and np.isnan(v))) else f"{v:.6g}" for v in row))
164
+ return "\n".join(lines) + "\n"
tlsq_infer/registry.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model registry (deploy/registry.yaml) and model loading: local repository checkpoints, an exported model directory,
2
+ or the Hugging Face Hub (model repos built by deploy/sync.py)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ from functools import lru_cache
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import yaml
13
+
14
+ GNN_KINDS = {"gnn"}
15
+ PRIORS = {"standard": dict(max_cells=8000, cells_per_gap=3.0), "fine": dict(max_cells=16000, cells_per_gap=6.0)}
16
+
17
+
18
+ def find_registry(path=None) -> Path:
19
+ cands = [path, os.environ.get("TLSQ_REGISTRY"), Path.cwd() / "registry.yaml", Path.cwd() / "deploy" / "registry.yaml",
20
+ Path(__file__).resolve().parent / "registry.yaml"]
21
+ cands += [p / "registry.yaml" for p in Path(__file__).resolve().parents if (p / "registry.yaml").exists()]
22
+ cands += [p / "deploy" / "registry.yaml" for p in Path(__file__).resolve().parents]
23
+ for c in cands:
24
+ if c and Path(c).exists():
25
+ return Path(c)
26
+ raise FileNotFoundError("registry.yaml not found (set TLSQ_REGISTRY)")
27
+
28
+
29
+ class Registry:
30
+ def __init__(self, path=None):
31
+ self.path = find_registry(path)
32
+ self.data = yaml.safe_load(self.path.read_text())
33
+ # repository root: registry lives in <root>/deploy/registry.yaml (repo checkout) or next to the app (Space)
34
+ self.root = self.path.parent.parent if self.path.parent.name == "deploy" else self.path.parent
35
+
36
+ def __getitem__(self, k):
37
+ return self.data[k]
38
+
39
+ @property
40
+ def models(self) -> dict:
41
+ return self.data["models"]
42
+
43
+ def model(self, name: str) -> dict:
44
+ if name not in self.models:
45
+ raise KeyError(f"unknown model {name!r}; available: {self.deployable()}")
46
+ return {"name": name, **self.models[name]}
47
+
48
+ def deployable(self) -> list[str]:
49
+ return [k for k, v in self.models.items() if v.get("status") == "available" and v.get("kind") != "baseline"]
50
+
51
+ def substrates(self) -> dict:
52
+ return dict(self.data["substrates"])
53
+
54
+ def eps_of(self, substrate) -> float:
55
+ if isinstance(substrate, (int, float)):
56
+ return float(substrate)
57
+ subs = self.substrates()
58
+ if substrate in subs:
59
+ return float(subs[substrate])
60
+ for k, v in subs.items(): # tolerant match: "sapphire", "Si", "GaAs" ...
61
+ if k.lower().startswith(str(substrate).lower()):
62
+ return float(v)
63
+ try:
64
+ return float(substrate)
65
+ except ValueError:
66
+ raise KeyError(f"unknown substrate {substrate!r}; use one of {list(subs)} or a number") from None
67
+
68
+
69
+ @lru_cache(maxsize=4)
70
+ def load_registry(path=None) -> Registry:
71
+ return Registry(path)
72
+
73
+
74
+ # ---------------------------------------------------------------- checkpoints
75
+
76
+ def export_checkpoint(src, dst) -> dict:
77
+ """Training checkpoint (pickled numpy scaling) -> torch file loadable with weights_only=True."""
78
+ import torch
79
+
80
+ st = torch.load(src, map_location="cpu", weights_only=False)
81
+ sc = st["scaling"]
82
+ out = {"state": {k: v.clone() for k, v in st["state"].items()},
83
+ "scaling": {p: [np.asarray(sc[p][0], float).tolist(), np.asarray(sc[p][1], float).tolist()] for p in ("node", "edge", "global")}
84
+ | {"keys": [list(x) for x in sc["keys"]]},
85
+ "dims": list(st["dims"]), "w": int(st["w"]), "rounds": int(st["rounds"]), "variant": st.get("variant", ""),
86
+ "prior": st.get("prior", ""), "n_train": int(st.get("n_train", 0))}
87
+ torch.save(out, dst)
88
+ return {k: out[k] for k in ("dims", "w", "rounds", "variant", "prior", "n_train")}
89
+
90
+
91
+ def _load_ckpt(path):
92
+ import torch
93
+
94
+ try:
95
+ st = torch.load(path, map_location="cpu", weights_only=True)
96
+ except Exception: # noqa: BLE001 local training checkpoints carry numpy arrays: trusted files from this repo only
97
+ st = torch.load(path, map_location="cpu", weights_only=False)
98
+ sc = st["scaling"]
99
+ st["scaling"] = {p: (np.asarray(sc[p][0], float), np.asarray(sc[p][1], float)) for p in ("node", "edge", "global")} | {"keys": sc["keys"]}
100
+ return st
101
+
102
+
103
+ def _hub_download(repo_id: str, filename: str) -> str:
104
+ from huggingface_hub import hf_hub_download
105
+
106
+ return hf_hub_download(repo_id=repo_id, filename=filename)
107
+
108
+
109
+ def resolve_files(reg: Registry, name: str, model_dir=None) -> list[str]:
110
+ """Weight files of a model: <model_dir>/<name>/ (exported), local checkpoints, or the model's Hub repo."""
111
+ m = reg.model(name)
112
+ model_dir = model_dir or os.environ.get("TLSQ_MODEL_DIR")
113
+ if model_dir and (Path(model_dir) / name / "config.json").exists():
114
+ cfg = json.loads((Path(model_dir) / name / "config.json").read_text())
115
+ return [str(Path(model_dir) / name / f) for f in cfg["files"]]
116
+ local = [reg.root / p for p in m.get("checkpoints", [])]
117
+ if local and all(p.exists() for p in local):
118
+ return [str(p) for p in local]
119
+ if m.get("repo_id") and os.environ.get("TLSQ_OFFLINE") != "1":
120
+ cfg = json.loads(Path(_hub_download(m["repo_id"], "config.json")).read_text())
121
+ return [_hub_download(m["repo_id"], f) for f in cfg["files"]]
122
+ if m.get("status") != "available":
123
+ raise FileNotFoundError(f"model {name!r} is {m.get('status')}: {m.get('pending_reason', '')}")
124
+ raise FileNotFoundError(f"no weights for {name!r}: looked in {model_dir}, {local}, hub repo {m.get('repo_id')}")
125
+
126
+
127
+ class Ensemble:
128
+ """Mean of log C over the seeds of one GNN model."""
129
+
130
+ def __init__(self, files):
131
+ from ._vendor.gnn import SceneGNN
132
+
133
+ self.members = []
134
+ for f in files:
135
+ st = _load_ckpt(f)
136
+ net = SceneGNN(*st["dims"], st["w"], rounds=st["rounds"])
137
+ net.load_state_dict(st["state"])
138
+ net.eval()
139
+ self.members.append((net, st["scaling"]))
140
+ self.rounds = st["rounds"]
141
+
142
+ def __call__(self, rows: list[dict], proxy_key="proxy_log_C") -> np.ndarray:
143
+ from ._vendor.gnn import build_graphset, predict
144
+
145
+ out = []
146
+ for net, sc in self.members:
147
+ gs, _ = build_graphset(rows, scaling=sc, proxy_key=proxy_key)
148
+ out.append(predict(net, gs, np.arange(len(rows))))
149
+ return np.mean(out, 0)
150
+
151
+
152
+ _CACHE: dict = {}
153
+
154
+
155
+ def get_component(reg: Registry, name: str, model_dir=None):
156
+ """Loaded, cached model object: Ensemble for GNNs, the GBM for the charge-corrected prior."""
157
+ key = (str(reg.path), name)
158
+ if key not in _CACHE:
159
+ m = reg.model(name)
160
+ files = resolve_files(reg, name, model_dir)
161
+ if m["kind"] in GNN_KINDS:
162
+ _CACHE[key] = Ensemble(files)
163
+ elif m["kind"] == "charge_prior":
164
+ from .charge import load_gbm
165
+
166
+ _CACHE[key] = load_gbm(files[0])
167
+ else:
168
+ raise ValueError(f"{name}: kind {m['kind']} has no weights")
169
+ return _CACHE[key]
tlsq_infer/stack_error.json ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": 1,
3
+ "n_designs": 15,
4
+ "groups": [
5
+ "in-family (ncap_fingers)",
6
+ "never-seen (shielded_concentric)",
7
+ "never-seen (xmon)"
8
+ ],
9
+ "eps_train": 11.45,
10
+ "t_train_um": 350.0,
11
+ "material": {
12
+ "slope_pct_per_log": 1.278628010748463,
13
+ "floor_pct": 0.0,
14
+ "q90_extra_pct": 0.18992133122197666,
15
+ "n_points": 165,
16
+ "max_observed_pct": 1.9339159521641447,
17
+ "per_material_median_pct": {
18
+ "mat_GaAs": 0.106,
19
+ "mat_Ge": 0.284,
20
+ "mat_InP": 0.069,
21
+ "mat_LaAlO3": 0.534,
22
+ "mat_MgO": 0.148,
23
+ "mat_SiC": 0.159,
24
+ "mat_Si_RT": 0.019,
25
+ "mat_diamond": 0.853,
26
+ "mat_fused_silica": 1.372,
27
+ "mat_quartz": 1.124,
28
+ "mat_sapphire": 0.096
29
+ }
30
+ },
31
+ "thickness": {
32
+ "L_definition": "sqrt_area",
33
+ "A_pct": 1.5079787674195164,
34
+ "p": 1.3100240061291493,
35
+ "logo_log_rmse": 0.728244486631929,
36
+ "n_points": 64,
37
+ "thick_side_pct": 0.21511320447635818,
38
+ "solver_noise_pct": 0.3836033380842397,
39
+ "candidates": {
40
+ "bbox_diag": {
41
+ "A_pct": 0.5699362292208275,
42
+ "p": 1.1722109336174098,
43
+ "logo_log_rmse": 1.1148061086218972,
44
+ "n_points": 64
45
+ },
46
+ "bbox_max": {
47
+ "A_pct": 0.7202421947589044,
48
+ "p": 1.2100207446152025,
49
+ "logo_log_rmse": 1.0451094342685237,
50
+ "n_points": 64
51
+ },
52
+ "sqrt_area": {
53
+ "A_pct": 1.5079787674195164,
54
+ "p": 1.3100240061291493,
55
+ "logo_log_rmse": 0.728244486631929,
56
+ "n_points": 64
57
+ },
58
+ "pocket_diag": {
59
+ "A_pct": 0.4550642645800963,
60
+ "p": 1.210018780093613,
61
+ "logo_log_rmse": 1.0525505331415834,
62
+ "n_points": 64
63
+ }
64
+ },
65
+ "per_group": {
66
+ "in-family (ncap_fingers)": {
67
+ "A_pct": 2.302259643464834,
68
+ "p": 1.6322938554491087,
69
+ "L_um_median": 37.23399629370986,
70
+ "doe_breakdown_t_um": 25.0
71
+ },
72
+ "never-seen (shielded_concentric)": {
73
+ "A_pct": 1.0479516989252748,
74
+ "p": 1.4069550681680345,
75
+ "L_um_median": 248.02303237804313,
76
+ "doe_breakdown_t_um": 100.0
77
+ },
78
+ "never-seen (xmon)": {
79
+ "A_pct": 1.0239958864956118,
80
+ "p": 1.4957064823792836,
81
+ "L_um_median": 143.0913193523632,
82
+ "doe_breakdown_t_um": 25.0
83
+ }
84
+ },
85
+ "per_thickness_median_pct": {
86
+ "in-family (ncap_fingers)": {
87
+ "10.0": 23.72,
88
+ "25.0": 4.211,
89
+ "50.0": 0.363,
90
+ "100.0": 0.555,
91
+ "200.0": 0.292,
92
+ "500.0": 0.124,
93
+ "675.0": 0.189,
94
+ "1000.0": 0.292
95
+ },
96
+ "never-seen (shielded_concentric)": {
97
+ "10.0": 132.56,
98
+ "25.0": 26.155,
99
+ "50.0": 7.642,
100
+ "100.0": 5.763,
101
+ "200.0": 1.537,
102
+ "500.0": 0.204,
103
+ "675.0": 0.175,
104
+ "1000.0": 0.455
105
+ },
106
+ "never-seen (xmon)": {
107
+ "10.0": 101.263,
108
+ "25.0": 8.002,
109
+ "50.0": 6.58,
110
+ "100.0": 1.782,
111
+ "200.0": 0.64,
112
+ "500.0": 0.155,
113
+ "675.0": 0.219,
114
+ "1000.0": 0.357
115
+ }
116
+ }
117
+ },
118
+ "L_um": {
119
+ "exp6/q3d_cap_0087": {
120
+ "bbox_diag": 49.24428900898052,
121
+ "bbox_max": 43.0,
122
+ "sqrt_area": 22.891839157219326,
123
+ "pocket_diag": 61.71709649683789,
124
+ "gap": 2.0
125
+ },
126
+ "exp6/q3d_cap_1503": {
127
+ "bbox_diag": 63.631753079732135,
128
+ "bbox_max": 55.0,
129
+ "sqrt_area": 31.43171115291052,
130
+ "pocket_diag": 78.64477096412705,
131
+ "gap": 2.0
132
+ },
133
+ "exp6/q3d_cap_1603": {
134
+ "bbox_diag": 71.7007670809734,
135
+ "bbox_max": 55.0,
136
+ "sqrt_area": 37.646954431932485,
137
+ "pocket_diag": 88.52683209061533,
138
+ "gap": 1.9999999999999998
139
+ },
140
+ "exp15/q3d_cap_0079": {
141
+ "bbox_diag": 424.0575328808581,
142
+ "bbox_max": 316.15700000000004,
143
+ "sqrt_area": 238.0635929011407,
144
+ "pocket_diag": 453.80782894084143,
145
+ "gap": 2.0
146
+ },
147
+ "exp15/q3d_cap_0161": {
148
+ "bbox_diag": 686.9943742659033,
149
+ "bbox_max": 520.692,
150
+ "sqrt_area": 307.66073536770995,
151
+ "pocket_diag": 780.5691326846072,
152
+ "gap": 2.0
153
+ },
154
+ "exp15/q3d_cap_0134": {
155
+ "bbox_diag": 596.1214684944672,
156
+ "bbox_max": 471.192,
157
+ "sqrt_area": 238.87703055756518,
158
+ "pocket_diag": 718.4225593764439,
159
+ "gap": 2.0
160
+ },
161
+ "exp6/q3d_cap_0317": {
162
+ "bbox_diag": 80.26207074328447,
163
+ "bbox_max": 69.0,
164
+ "sqrt_area": 37.23399629370986,
165
+ "pocket_diag": 96.17692030835673,
166
+ "gap": 2.0
167
+ },
168
+ "exp6/q3d_cap_1691": {
169
+ "bbox_diag": 98.47842403288143,
170
+ "bbox_max": 83.0,
171
+ "sqrt_area": 51.61824698689408,
172
+ "pocket_diag": 110.78808600206071,
173
+ "gap": 1.9999999999999998
174
+ },
175
+ "exp15/q3d_cap_0123": {
176
+ "bbox_diag": 794.2259085354746,
177
+ "bbox_max": 582.165,
178
+ "sqrt_area": 401.3324007976431,
179
+ "pocket_diag": 842.7031715028727,
180
+ "gap": 2.0
181
+ },
182
+ "exp15/q3d_cap_0096": {
183
+ "bbox_diag": 552.1546761741677,
184
+ "bbox_max": 407.655,
185
+ "sqrt_area": 248.02303237804313,
186
+ "pocket_diag": 585.5440185263615,
187
+ "gap": 2.0
188
+ },
189
+ "exp13/q3d_cap_0032": {
190
+ "bbox_diag": 500.9710123350452,
191
+ "bbox_max": 354.24,
192
+ "sqrt_area": 143.0913193523632,
193
+ "pocket_diag": 541.380750666294,
194
+ "gap": 9.966999999999985
195
+ },
196
+ "exp13/q3d_cap_0580": {
197
+ "bbox_diag": 567.2537877899098,
198
+ "bbox_max": 401.10900000000004,
199
+ "sqrt_area": 143.0080934073313,
200
+ "pocket_diag": 617.2402108174742,
201
+ "gap": 4.393999999999977
202
+ },
203
+ "exp13/q3d_cap_0380": {
204
+ "bbox_diag": 441.7698424519266,
205
+ "bbox_max": 346.886,
206
+ "sqrt_area": 119.7274361038438,
207
+ "pocket_diag": 494.16827953643485,
208
+ "gap": 5.144999999999982
209
+ },
210
+ "exp13/q3d_cap_0581": {
211
+ "bbox_diag": 768.9465302249565,
212
+ "bbox_max": 595.467,
213
+ "sqrt_area": 177.69789423062954,
214
+ "pocket_diag": 853.4626354006366,
215
+ "gap": 5.095000000000006
216
+ },
217
+ "exp13/q3d_cap_0121": {
218
+ "bbox_diag": 766.2007495304348,
219
+ "bbox_max": 579.441,
220
+ "sqrt_area": 166.33747046291168,
221
+ "pocket_diag": 810.6574023056843,
222
+ "gap": 4.310999999999979
223
+ }
224
+ },
225
+ "base_scale": {
226
+ "never_seen_mean_abs_ff": 42.840808925401255,
227
+ "never_seen_rms_ff": 63.13559865994375,
228
+ "entries": 4739
229
+ },
230
+ "empirical_0round_blend_eps_scaled_median_pct": {
231
+ "mat_GaAs": {
232
+ "in-family (ncap_fingers)": 0.853,
233
+ "never-seen (shielded_concentric)": 1.36,
234
+ "never-seen (xmon)": 2.026
235
+ },
236
+ "mat_Ge": {
237
+ "in-family (ncap_fingers)": 0.869,
238
+ "never-seen (shielded_concentric)": 1.496,
239
+ "never-seen (xmon)": 1.976
240
+ },
241
+ "mat_InP": {
242
+ "in-family (ncap_fingers)": 0.835,
243
+ "never-seen (shielded_concentric)": 1.333,
244
+ "never-seen (xmon)": 2.02
245
+ },
246
+ "mat_LaAlO3": {
247
+ "in-family (ncap_fingers)": 0.787,
248
+ "never-seen (shielded_concentric)": 1.561,
249
+ "never-seen (xmon)": 1.899
250
+ },
251
+ "mat_MgO": {
252
+ "in-family (ncap_fingers)": 0.892,
253
+ "never-seen (shielded_concentric)": 1.159,
254
+ "never-seen (xmon)": 2.106
255
+ },
256
+ "mat_SiC": {
257
+ "in-family (ncap_fingers)": 0.892,
258
+ "never-seen (shielded_concentric)": 1.151,
259
+ "never-seen (xmon)": 2.107
260
+ },
261
+ "mat_Si_RT": {
262
+ "in-family (ncap_fingers)": 0.836,
263
+ "never-seen (shielded_concentric)": 1.291,
264
+ "never-seen (xmon)": 2.041
265
+ },
266
+ "mat_diamond": {
267
+ "in-family (ncap_fingers)": 1.404,
268
+ "never-seen (shielded_concentric)": 1.183,
269
+ "never-seen (xmon)": 2.205
270
+ },
271
+ "mat_fused_silica": {
272
+ "in-family (ncap_fingers)": 1.691,
273
+ "never-seen (shielded_concentric)": 1.501,
274
+ "never-seen (xmon)": 2.468
275
+ },
276
+ "mat_quartz": {
277
+ "in-family (ncap_fingers)": 1.238,
278
+ "never-seen (shielded_concentric)": 1.43,
279
+ "never-seen (xmon)": 2.336
280
+ },
281
+ "mat_sapphire": {
282
+ "in-family (ncap_fingers)": 0.891,
283
+ "never-seen (shielded_concentric)": 1.202,
284
+ "never-seen (xmon)": 2.089
285
+ },
286
+ "ref": {
287
+ "in-family (ncap_fingers)": 0.836,
288
+ "never-seen (shielded_concentric)": 1.275,
289
+ "never-seen (xmon)": 2.05
290
+ },
291
+ "sub_t10": {
292
+ "in-family (ncap_fingers)": 20.952,
293
+ "never-seen (shielded_concentric)": 116.056,
294
+ "never-seen (xmon)": 71.084
295
+ },
296
+ "sub_t100": {
297
+ "in-family (ncap_fingers)": 0.788,
298
+ "never-seen (shielded_concentric)": 4.861,
299
+ "never-seen (xmon)": 2.289
300
+ },
301
+ "sub_t1000": {
302
+ "in-family (ncap_fingers)": 0.994,
303
+ "never-seen (shielded_concentric)": 1.193,
304
+ "never-seen (xmon)": 2.014
305
+ },
306
+ "sub_t200": {
307
+ "in-family (ncap_fingers)": 0.867,
308
+ "never-seen (shielded_concentric)": 1.857,
309
+ "never-seen (xmon)": 1.921
310
+ },
311
+ "sub_t25": {
312
+ "in-family (ncap_fingers)": 4.291,
313
+ "never-seen (shielded_concentric)": 30.851,
314
+ "never-seen (xmon)": 11.784
315
+ },
316
+ "sub_t50": {
317
+ "in-family (ncap_fingers)": 0.889,
318
+ "never-seen (shielded_concentric)": 9.393,
319
+ "never-seen (xmon)": 3.281
320
+ },
321
+ "sub_t500": {
322
+ "in-family (ncap_fingers)": 0.892,
323
+ "never-seen (shielded_concentric)": 1.363,
324
+ "never-seen (xmon)": 2.103
325
+ },
326
+ "sub_t675": {
327
+ "in-family (ncap_fingers)": 0.894,
328
+ "never-seen (shielded_concentric)": 1.368,
329
+ "never-seen (xmon)": 2.081
330
+ },
331
+ "thin_t0.25": {
332
+ "in-family (ncap_fingers)": 0.836,
333
+ "never-seen (shielded_concentric)": 1.275,
334
+ "never-seen (xmon)": 2.05
335
+ }
336
+ },
337
+ "notes": [
338
+ "residuals are Q3D label shifts vs the 350 um Si reference (model-independent)",
339
+ "L = sqrt_area of the conductors (chosen by leave-one-group-out log RMSE among ['bbox_diag', 'bbox_max', 'sqrt_area', 'pocket_diag'])",
340
+ "15 designs only; shielded concentric breaks down earlier than t/L predicts for Xmon: treat thresholds as indicative"
341
+ ]
342
+ }
tlsq_infer/stack_error.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Expected extra error when the layer stack differs from the training stack (Si, eps 11.45, 350 µm), evaluated from
2
+ the parameters fitted by deploy/stack_error.py on the 15-design stack DoE (deploy/artifacts/stack_error.json).
3
+
4
+ Two independent residuals, combined in quadrature with the model's own validation error:
5
+ material after the eps correction (1 + eps_sub) / (1 + 11.45): r_mat = a_mat * |ln((1 + eps) / (1 + 11.45))| + floor
6
+ thickness finite substrate seen by the fringe field: r_t = A * (t / L)^(-p) for t < 350 µm (L = lateral extent of the
7
+ conductors), measured relative to the 350 µm reference; thicker substrates: the measured small shift.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ EPS_TRAIN = 11.45
18
+ T_TRAIN = 350.0
19
+
20
+
21
+ def eps_factor(eps_sub: float) -> float:
22
+ """Quasi-static half-space correction of every capacitance for another substrate permittivity."""
23
+ return (1.0 + float(eps_sub)) / (1.0 + EPS_TRAIN)
24
+
25
+
26
+ def load_params(path=None) -> dict | None:
27
+ for p in [path, Path(__file__).resolve().parent / "stack_error.json"] + [q / "artifacts" / "stack_error.json" for q in Path(__file__).resolve().parents]:
28
+ if p and Path(p).exists():
29
+ return json.loads(Path(p).read_text())
30
+ return None
31
+
32
+
33
+ def lateral_extent(conductors: list, P: dict | None) -> float:
34
+ """L of the thickness fit (definition stored in the parameters; default sqrt of the total conductor area)."""
35
+ import shapely
36
+
37
+ S = shapely.union_all(conductors)
38
+ how = (P or {}).get("thickness", {}).get("L_definition", "sqrt_area")
39
+ x0, y0, x1, y1 = S.bounds
40
+ return float({"sqrt_area": np.sqrt(S.area), "bbox_diag": np.hypot(x1 - x0, y1 - y0),
41
+ "bbox_max": max(x1 - x0, y1 - y0)}.get(how, np.sqrt(S.area)))
42
+
43
+
44
+ def material_residual_pct(P: dict, eps_sub: float) -> float:
45
+ x = abs(np.log(eps_factor(eps_sub)))
46
+ m = P["material"]
47
+ return 0.0 if x < 1e-9 else float(m["slope_pct_per_log"] * x + m["floor_pct"])
48
+
49
+
50
+ def thickness_residual_pct(P: dict, t_um: float, L_um: float) -> float:
51
+ th = P["thickness"]
52
+ if t_um >= T_TRAIN:
53
+ return float(th["thick_side_pct"]) if t_um > T_TRAIN * 1.01 else 0.0
54
+ x = t_um / max(L_um, 1e-9)
55
+ x_ref = T_TRAIN / max(L_um, 1e-9)
56
+ r = th["A_pct"] * x ** (-th["p"]) - th["A_pct"] * x_ref ** (-th["p"])
57
+ return float(max(r, 0.0))
58
+
59
+
60
+ def breakdown_thickness_um(P: dict, L_um: float, base_pct: float) -> float:
61
+ """Thinnest substrate at which the thickness residual stays below sqrt(3) x base error (total error <= 2x base)."""
62
+ th = P["thickness"]
63
+ target = np.sqrt(3.0) * base_pct
64
+ xr = (T_TRAIN / L_um) ** (-th["p"])
65
+ # A x^-p - A xr = target -> x = ((target / A) + xr)^(-1/p)
66
+ x = ((target / th["A_pct"]) + xr) ** (-1.0 / th["p"])
67
+ return float(x * L_um)
68
+
69
+
70
+ def expected_error(P: dict | None, eps_sub: float, t_um: float, L_um: float, base: dict, mean_abs_ff: float, rms_ff: float) -> dict:
71
+ """base = the model's validation metrics {median_pct, mae_ff, rmse_ff} (never-seen set); mean_abs_ff / rms_ff = the
72
+ mean and rms of |mutual C| of THIS prediction (to scale the paper MAE/RMSE to this layout)."""
73
+ out = {"validation": base, "assumptions": []}
74
+ if P is None:
75
+ out["warning"] = "stack-error parameters not available"
76
+ return out
77
+ rm = material_residual_pct(P, eps_sub)
78
+ rt = thickness_residual_pct(P, t_um, L_um)
79
+ b = float(base["median_pct"])
80
+ tot = float(np.sqrt(b**2 + rm**2 + rt**2))
81
+ sc = P.get("base_scale", {})
82
+ k_mae = mean_abs_ff / sc["never_seen_mean_abs_ff"] if sc.get("never_seen_mean_abs_ff") else np.nan
83
+ k_rms = rms_ff / sc["never_seen_rms_ff"] if sc.get("never_seen_rms_ff") else np.nan
84
+ # stack residuals as relative errors on this layout's entries: MAE ~ r * mean|C|, RMSE ~ r * rms|C|
85
+ rs = np.sqrt(rm**2 + rt**2) / 100
86
+ mae = float(np.sqrt((base["mae_ff"] * k_mae) ** 2 + (rs * mean_abs_ff) ** 2))
87
+ rmse = float(np.sqrt((base["rmse_ff"] * k_rms) ** 2 + (rs * rms_ff) ** 2))
88
+ t_break = breakdown_thickness_um(P, L_um, b)
89
+ out.update({"material_residual_pct": rm, "thickness_residual_pct": rt, "expected_median_pct": tot,
90
+ "expected_mae_ff": mae, "expected_rmse_ff": rmse, "breakdown_thickness_um": t_break,
91
+ "breakdown": bool(t_um < t_break), "lateral_extent_um": float(L_um), "t_over_L": float(t_um / L_um),
92
+ "doe_designs": P.get("n_designs"),
93
+ "assumptions": ["errors add in quadrature (model, material, thickness)",
94
+ "material residual fitted on 11 substrates x 15 designs after the eps correction",
95
+ "thickness residual fitted vs t/L on 8 Si thicknesses x 15 designs (3 design groups)",
96
+ "MAE/RMSE scaled from the never-seen validation set by this layout's mean / rms |C|"]})
97
+ if out["breakdown"]:
98
+ out["warning"] = (f"substrate {t_um:g} µm is below the breakdown thickness {t_break:.0f} µm for a layout of lateral "
99
+ f"extent {L_um:.0f} µm: the zero-shot prediction (training stack 350 µm) is not reliable here")
100
+ elif rt > b:
101
+ out["warning"] = f"finite-substrate error ({rt:.1f} %) exceeds the model error ({b:.1f} %)"
102
+ if not (2.0 <= eps_sub <= 30.0):
103
+ out.setdefault("warning", "")
104
+ out["warning"] += f" eps={eps_sub:g} is outside the validated range 3.8-24."
105
+ return out