shanto268 commited on
Commit
9b8764d
·
verified ·
1 Parent(s): 56068de

sync from registry v1

Browse files
LIMITS.md CHANGED
@@ -100,7 +100,10 @@ returned matrix equals the local prediction of the same bundle to <= 3e-5 relati
100
  | two pads, size 20x (stress) | 61.7 (routed) | 60.2 | |
101
  | comb, 200 fingers (stress) | 224.4 (routed) | 220.0 | |
102
 
103
- The Space CPU is 3.4-5.4x slower than the Mac at 1 thread on the flagship solves (comb 200 fingers 64.7 s, two pads 20x 13.5 s, shielded concentric 14.6 s locally). Paper-models Space: same matrices and times
 
 
 
104
  (e.g. TransmonPocket 18.0 s fine). Gradio has no request timeout; the queue runs 2 requests at once (`TLSQ_CONCURRENCY`)
105
  but at most one flagship-prior solve (`TLSQ_HEAVY_CONCURRENCY`, default 1; fine tier and coarse requests routed to it),
106
  so two large solves (up to 8.3 GB each, grid_qubit_9) cannot exceed the 16 GB of cpu-basic.
 
100
  | two pads, size 20x (stress) | 61.7 (routed) | 60.2 | |
101
  | comb, 200 fingers (stress) | 224.4 (routed) | 220.0 | |
102
 
103
+ Local, same bundle through the Space API function (`app_ui.api_predict_gds`), Mac M5 Pro, 2 threads, one persistent
104
+ process, fine tier, s: Xmon 0.5, interdigital 0.3, TransmonPocket 5.2, shielded concentric 21.2, never-seen shielded
105
+ concentric exp15/0043 (slowest held-out design) 67.4, comb 200 / 400 fingers 55.6 / 77.9, two pads 20x / 50x 14.7 / 19.8;
106
+ process peak RSS 5.7 GB (H-matrix PCG on every large case; comb_f400 4.65 panels per gap). The Space CPU is 3.4-5.4x slower than the Mac at 1 thread on the flagship solves (comb 200 fingers 64.7 s, two pads 20x 13.5 s, shielded concentric 14.6 s locally). Paper-models Space: same matrices and times
107
  (e.g. TransmonPocket 18.0 s fine). Gradio has no request timeout; the queue runs 2 requests at once (`TLSQ_CONCURRENCY`)
108
  but at most one flagship-prior solve (`TLSQ_HEAVY_CONCURRENCY`, default 1; fine tier and coarse requests routed to it),
109
  so two large solves (up to 8.3 GB each, grid_qubit_9) cannot exceed the 16 GB of cpu-basic.
README.md CHANGED
@@ -22,6 +22,7 @@ models:
22
  - SQuADDS/2026PaperModels-all-data-base
23
  - SQuADDS/2026PaperModels-all-data-v3s
24
  - SQuADDS/2026PaperModels-all-data-v3-rich
 
25
  - SQuADDS/2026PaperModels-all-data-flagship
26
  - SQuADDS/2026PaperModels-pair-local-fast
27
  - SQuADDS/2026PaperModels-message-passing-fast
@@ -36,6 +37,6 @@ models:
36
 
37
  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).
38
 
39
- Programmatic use: `examples/client.py` (gradio_client, endpoint `/predict_gds`; model = `coarse` (default, fastest) or `fine` (most accurate); `fast` / `accurate` are accepted as aliases).
40
 
41
  Hardware: free CPU tier (2 vCPU, 16 GB); see LIMITS.md for measured latency and caps.
 
22
  - SQuADDS/2026PaperModels-all-data-base
23
  - SQuADDS/2026PaperModels-all-data-v3s
24
  - SQuADDS/2026PaperModels-all-data-v3-rich
25
+ - SQuADDS/2026PaperModels-all-data-lite1500
26
  - SQuADDS/2026PaperModels-all-data-flagship
27
  - SQuADDS/2026PaperModels-pair-local-fast
28
  - SQuADDS/2026PaperModels-message-passing-fast
 
37
 
38
  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).
39
 
40
+ Programmatic use: `examples/client.py` (gradio_client, endpoint `/predict_gds`; model = `fast` (default: flagship-fast, also multi-qubit chips), `coarse` or `fine` (most accurate; alias `accurate`)).
41
 
42
  Hardware: free CPU tier (2 vCPU, 16 GB); see LIMITS.md for measured latency and caps.
app.py CHANGED
@@ -25,11 +25,12 @@ reg = load_registry()
25
  hub = reg["hub"]
26
  space = os.environ.get("SPACE_ID", hub["flagship_space"])
27
  default = reg["defaults"]["flagship_model"]
28
- models = [default] + ([reg["defaults"]["flagship_accurate_model"]] if reg["defaults"].get("flagship_accurate_model") else [])
29
- t = reg["defaults"].get("tiers", {}).get("coarse") or {}
30
  d = t if t.get("median_pct") is not None else reg.model(default)["paper"]["never_seen"]
31
  where = t.get("set", "926 never-seen designs") if t else "926 never-seen designs"
32
- header = (f"Zero-shot Maxwell capacitance of planar superconducting layouts. Default (coarse prior) model: **{reg.model(default)['title']}** "
 
33
  f"({d['median_pct']} % median error, MAE {d['mae_ff']} fF, RMSE {d['rmse_ff']} fF on {where}). "
34
  f"All paper models: [{hub['paper_models_space']}](https://huggingface.co/spaces/{hub['paper_models_space']}). "
35
  f"Weights: [{reg.model(default)['repo_id']}](https://huggingface.co/{reg.model(default)['repo_id']}). "
 
25
  hub = reg["hub"]
26
  space = os.environ.get("SPACE_ID", hub["flagship_space"])
27
  default = reg["defaults"]["flagship_model"]
28
+ models = [default] + [reg["defaults"][k] for k in ("coarse_model", "flagship_accurate_model") if reg["defaults"].get(k)]
29
+ t = reg["defaults"].get("tiers", {}).get("fast") or {}
30
  d = t if t.get("median_pct") is not None else reg.model(default)["paper"]["never_seen"]
31
  where = t.get("set", "926 never-seen designs") if t else "926 never-seen designs"
32
+ header = (f"Zero-shot Maxwell capacitance of planar superconducting layouts, from one capacitor to a multi-qubit chip. Default "
33
+ f"(fast tier) model: **{reg.model(default)['title']}** "
34
  f"({d['median_pct']} % median error, MAE {d['mae_ff']} fF, RMSE {d['rmse_ff']} fF on {where}). "
35
  f"All paper models: [{hub['paper_models_space']}](https://huggingface.co/spaces/{hub['paper_models_space']}). "
36
  f"Weights: [{reg.model(default)['repo_id']}](https://huggingface.co/{reg.model(default)['repo_id']}). "
examples/client.py CHANGED
@@ -20,7 +20,7 @@ ap.add_argument("--margin-gaps", type=float, default=0.0, help="ground crop marg
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="coarse", help="coarse (default, fastest; alias fast) / fine (most accurate; alias accurate), or a registry model name")
24
  ap.add_argument("--self-from-rows", action="store_true")
25
  a = ap.parse_args()
26
 
 
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="fast", help="fast (default: flagship-fast, also multi-qubit chips) / coarse / fine (most accurate; alias accurate), or a registry model name")
24
  ap.add_argument("--self-from-rows", action="store_true")
25
  a = ap.parse_args()
26
 
models/all-data-lite1500/config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"name": "all-data-lite1500", "files": ["seed0.pt", "seed1.pt", "seed2.pt"]}
models/all-data-lite1500/seed0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:62b0e3e4f63a57a5ed467bf97ffa17cd039c69b6e750e606d5e8fd1fe70cc946
3
+ size 848449
models/all-data-lite1500/seed1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ac5907d1999fae825bda3a46654775497474834d943d2dc7c9e6961001a6050
3
+ size 848449
models/all-data-lite1500/seed2.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2a5f0fc3b5accbae0c543f1b8d8bda9a4859fc636d4ac1c9e915febce10fbf4
3
+ size 848449
registry.yaml CHANGED
@@ -83,7 +83,8 @@ artifacts:
83
  error_model: {}
84
 
85
  defaults:
86
- flagship_model: all-data-v3s # coarse tier, default (was "fast"; deploy/MODEL_SELECTION.md, amendment 1 rule)
 
87
  flagship_accurate_model: all-data-flagship # fine tier (key name kept). 2026-10-10, user-approved: all-data-v3-rich -> all-data-flagship
88
  # (same weights, flagship prior; PRIOR_SCHEME.md section 8.1, deploy/MODEL_SELECTION.md Results 3)
89
  large_layout_model: all-data-flagship # (PRIOR_SCHEME.md Part II): layouts on which the capped coarse prior would
@@ -91,7 +92,9 @@ defaults:
91
  # GRID_SCALING.md returned zero entries) are predicted with this flagship-prior model instead
92
  # (predict(large_layouts="route"), reported in model_used / warnings). In-regime layouts unchanged.
93
  paper_space_model: pair-local-fast # this work's headline (paper abstract)
94
- tiers: # shown in the flagship UI; keys = tier names (aliases fast -> coarse, accurate -> fine still accepted by predict);
 
 
95
  # held-out = OOD-60 + pocket3 random-36 + Qiskit Metal new 116, pooled mutual entries
96
  coarse: {latency_s: 4, median_pct: 1.75, mae_ff: 0.534, rmse_ff: 1.173, set: "212 held-out designs (OOD-60, random TransmonPocket-3, 6 new Qiskit Metal classes)",
97
  note: "On this free CPU Space: 1-5 s for single components (measured on the examples, 2026-10-10). Layouts whose coarse mesh would fall below the training resolution (e.g. the TransmonPocket example, long combs) are predicted with the fine tier instead (reported under model used)."}
@@ -322,13 +325,20 @@ models:
322
  summary: "flagship-fast candidate (PRIOR_SCHEME.md Part III): micro-MoM at <= 500 merged panels (one window up to 8 conductors; core-graded windows + screened-dipole far pairs beyond); network retrained on every labelled design on this prior (HPC 10-10). Not deployable until the user decides."
323
 
324
  all-data-lite1500:
325
- title: "All-data pair-local network retrained on the flagship-fast lite1500 prior (R=0)"
 
 
326
  kind: gnn
327
  prior: lite1500
328
  rounds: 0
329
- status: candidate
330
  checkpoints: [data_local/mega/alldata/lite1500_r0_s0.pt, data_local/mega/alldata/lite1500_r0_s1.pt, data_local/mega/alldata/lite1500_r0_s2.pt]
331
- summary: "flagship-fast candidate (PRIOR_SCHEME.md Part III): micro-MoM at <= 1,500 merged panels (one window up to 8 conductors; core-graded windows + screened-dipole far pairs beyond); network retrained on every labelled design on this prior (HPC 10-10). Not deployable until the user decides."
 
 
 
 
 
332
 
333
  all-data-formula:
334
  title: "All-data pair-local network retrained on the flagship-fast formula prior (R=0)"
 
83
  error_model: {}
84
 
85
  defaults:
86
+ flagship_model: all-data-lite1500 # fast tier = flagship-fast, DEFAULT since 2026-10-10 (user decision; deploy/MODEL_SELECTION.md Results 4)
87
+ coarse_model: all-data-v3s # coarse tier (default until 2026-10-10; deploy/MODEL_SELECTION.md, amendment 1 rule)
88
  flagship_accurate_model: all-data-flagship # fine tier (key name kept). 2026-10-10, user-approved: all-data-v3-rich -> all-data-flagship
89
  # (same weights, flagship prior; PRIOR_SCHEME.md section 8.1, deploy/MODEL_SELECTION.md Results 3)
90
  large_layout_model: all-data-flagship # (PRIOR_SCHEME.md Part II): layouts on which the capped coarse prior would
 
92
  # GRID_SCALING.md returned zero entries) are predicted with this flagship-prior model instead
93
  # (predict(large_layouts="route"), reported in model_used / warnings). In-regime layouts unchanged.
94
  paper_space_model: pair-local-fast # this work's headline (paper abstract)
95
+ tiers: # shown in the flagship UI; keys = tier names (alias accurate -> fine accepted by predict);
96
+ fast: {latency_s: 1, median_pct: 2.67, mae_ff: 0.768, rmse_ff: 1.874, set: "212 held-out designs (OOD-60, random TransmonPocket-3, 6 new Qiskit Metal classes)",
97
+ note: "flagship-fast (default): cheap micro-MoM prior (<= 1,500 merged panels; core-graded windows and screened-dipole far pairs beyond 8 conductors) and a network retrained on it. Less accurate than the coarse and fine tiers (large-N 40: 4.96 % vs 2.93 % / 1.64 %), 3-4x faster on components (0.23 s vs 0.77 s median end to end, 2 Mac threads) and the only tier that runs multi-qubit chips (780-conductor grid: prior 2-3 s, ~15 s end to end on 18 Mac cores). PRIOR_SCHEME.md Part III section 15.3."}
98
  # held-out = OOD-60 + pocket3 random-36 + Qiskit Metal new 116, pooled mutual entries
99
  coarse: {latency_s: 4, median_pct: 1.75, mae_ff: 0.534, rmse_ff: 1.173, set: "212 held-out designs (OOD-60, random TransmonPocket-3, 6 new Qiskit Metal classes)",
100
  note: "On this free CPU Space: 1-5 s for single components (measured on the examples, 2026-10-10). Layouts whose coarse mesh would fall below the training resolution (e.g. the TransmonPocket example, long combs) are predicted with the fine tier instead (reported under model used)."}
 
325
  summary: "flagship-fast candidate (PRIOR_SCHEME.md Part III): micro-MoM at <= 500 merged panels (one window up to 8 conductors; core-graded windows + screened-dipole far pairs beyond); network retrained on every labelled design on this prior (HPC 10-10). Not deployable until the user decides."
326
 
327
  all-data-lite1500:
328
+ title: "flagship-fast: all-data pair-local network retrained on the lite-1500 micro-MoM prior (R=0)"
329
+ display_name: flagship-fast
330
+ repo_id: SQuADDS/2026PaperModels-all-data-lite1500
331
  kind: gnn
332
  prior: lite1500
333
  rounds: 0
334
+ status: available
335
  checkpoints: [data_local/mega/alldata/lite1500_r0_s0.pt, data_local/mega/alldata/lite1500_r0_s1.pt, data_local/mega/alldata/lite1500_r0_s2.pt]
336
+ summary: "Default released tier since 2026-10-10 (flagship-fast). Cheap physics prior: the flagship mesh family at <= 1,500 merged panels in a canonical frame (one window up to 8 conductors; beyond, core-graded windows of <= 8 conductors with closed-form / screened-dipole far pairs), network retrained on every labelled design on this prior (PRIOR_SCHEME.md Part III). Faster but less accurate than the coarse and fine tiers; the only tier that handles multi-qubit chips."
337
+ validation: {median_pct: 2.67, mae_ff: 0.768, rmse_ff: 1.874, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"}
338
+ heldout:
339
+ largen40: {median_pct: 4.96, mae_ff: 0.406, rmse_ff: 1.303}
340
+ pocket3_biased20: {median_pct: 5.75, mae_ff: 0.641, rmse_ff: 1.076}
341
+ cost_s_per_design: {median: 0.23, p90: 0.68, note: "end to end from the GDS, 2 threads, Mac M5 Pro, 212 held-out designs; 780-conductor grid ~15 s on 18 Mac cores"}
342
 
343
  all-data-formula:
344
  title: "All-data pair-local network retrained on the flagship-fast formula prior (R=0)"
tlsq_infer/_vendor/blocks.py CHANGED
@@ -8,7 +8,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 .mom import _nthreads
13
  from .scene import Scene
14
 
@@ -53,16 +53,17 @@ def _kratio(m):
53
  return ellipk(1 - m) / ellipk(m)
54
 
55
 
56
- def edge_features(scene: Scene, i: int, j: int, bpts: dict, widths: dict) -> dict:
57
  """Symmetric pair features: separation spectrum (both directions averaged), minimum gap, coupling moments and the
58
- coplanar-strip conformal-map coupling (Gevorgian modulus; the ground net is treated as infinitely wide)."""
 
59
  f = {"is_ground_pair": float("ground" in (scene.conductors[i].role, scene.conductors[j].role))}
60
  hist = np.zeros(len(SEP_EDGES_UM) - 1)
61
  mom = np.zeros(len(MOMENTS))
62
  cps = 0.0
63
  dmin = np.inf
64
  for a, b in ((i, j), (j, i)):
65
- d, _ = cKDTree(bpts[b]).query(bpts[a], workers=_nthreads())
66
  dmin = min(dmin, d.min())
67
  hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0]
68
  dd = np.maximum(d, 0.05)
@@ -93,10 +94,14 @@ def global_features(scene: Scene) -> dict:
93
  "log_pocket_area": _log(scene.pocket.area)}
94
 
95
 
96
- def boundary_points(scene: Scene) -> tuple[dict, dict]:
 
 
97
  pts, widths = {}, {}
98
  for i, c in enumerate(scene.conductors):
99
  g = region(scene, i)
100
- pts[i] = sample_boundary(g, STEP_UM)
 
 
101
  widths[i] = np.inf if c.role == "ground" else 2 * g.area / g.length
102
  return pts, widths
 
8
  from scipy.special import ellipk
9
  from scipy.spatial import cKDTree
10
 
11
+ from .geometry import fourier_descriptors, sample_boundary, sample_boundary_fast, shape_metrics
12
  from .mom import _nthreads
13
  from .scene import Scene
14
 
 
53
  return ellipk(1 - m) / ellipk(m)
54
 
55
 
56
+ def edge_features(scene: Scene, i: int, j: int, bpts: dict, widths: dict, trees: dict | None = None) -> dict:
57
  """Symmetric pair features: separation spectrum (both directions averaged), minimum gap, coupling moments and the
58
+ coplanar-strip conformal-map coupling (Gevorgian modulus; the ground net is treated as infinitely wide). trees: k-d
59
+ trees of bpts built once per conductor (sparse large-layout graphs; same numbers as building them per pair)."""
60
  f = {"is_ground_pair": float("ground" in (scene.conductors[i].role, scene.conductors[j].role))}
61
  hist = np.zeros(len(SEP_EDGES_UM) - 1)
62
  mom = np.zeros(len(MOMENTS))
63
  cps = 0.0
64
  dmin = np.inf
65
  for a, b in ((i, j), (j, i)):
66
+ d, _ = (trees[b] if trees is not None else cKDTree(bpts[b])).query(bpts[a], workers=_nthreads())
67
  dmin = min(dmin, d.min())
68
  hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0]
69
  dd = np.maximum(d, 0.05)
 
94
  "log_pocket_area": _log(scene.pocket.area)}
95
 
96
 
97
+ def boundary_points(scene: Scene, max_ground: int | None = None) -> tuple[dict, dict]:
98
+ """Boundary samples (STEP_UM) and widths per conductor; max_ground (sparse large-layout graphs): vectorised sampler
99
+ (`sample_boundary_fast`, the same points) and the ground samples subsampled evenly to at most this many points."""
100
  pts, widths = {}, {}
101
  for i, c in enumerate(scene.conductors):
102
  g = region(scene, i)
103
+ pts[i] = (sample_boundary_fast if max_ground else sample_boundary)(g, STEP_UM)
104
+ if max_ground and c.role == "ground" and len(pts[i]) > max_ground:
105
+ pts[i] = pts[i][:: int(np.ceil(len(pts[i]) / max_ground))]
106
  widths[i] = np.inf if c.role == "ground" else 2 * g.area / g.length
107
  return pts, widths
tlsq_infer/_vendor/fastprior.py ADDED
@@ -0,0 +1,686 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vendored from tlsq.embed.fastprior (generated by scripts/vendor_fastprior.py; do not edit by hand): the
2
+ flagship-fast cheap priors of PRIOR_SCHEME.md Part III. `micro_mom`: the flagship mesh family at a fixed merged-panel
3
+ budget, one global window up to 8 conductors, core-graded windows beyond (pairs never co-windowed from the closed form);
4
+ `formula_prior`: closed-form edge-coupling prior (no mesh). Function sources identical to the training code."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ from concurrent.futures import ProcessPoolExecutor
10
+ from multiprocessing import get_context
11
+
12
+ import numpy as np
13
+ import shapely
14
+ from scipy.spatial import cKDTree
15
+
16
+ from . import mom as P
17
+ from .blocks import _kratio
18
+ from .geometry import sample_boundary
19
+
20
+
21
+ def _valid(g):
22
+ g = shapely.make_valid(g)
23
+ parts = [p for p in getattr(g, "geoms", [g]) if p.geom_type in ("Polygon", "MultiPolygon")]
24
+ return shapely.union_all(parts) if parts else shapely.Polygon()
25
+
26
+
27
+ def gap_of(metals: list) -> float:
28
+ tree = shapely.STRtree(metals)
29
+ d = np.inf
30
+ for i, g in enumerate(metals):
31
+ j, dist = tree.query_nearest(g, return_distance=True, exclusive=True, all_matches=False)
32
+ if len(dist):
33
+ d = min(d, float(dist[0]))
34
+ return d
35
+
36
+
37
+ def anchored_cells_graded(metals: list, h_f: float, core, levels: tuple, grade: float = 2.0, majority: bool = False):
38
+ """`proxy.anchored_cells` with the finest panel graded by the distance to the core conductors: h_f within levels[0]
39
+ of `core`, 2 h_f up to levels[1], 4 h_f up to levels[2], ... (same lattice; with levels=() identical to the plain
40
+ mesh). Returns centres (n, 2), sizes (n, 2), owner (n,)."""
41
+ edges = shapely.union_all([g.boundary for g in metals])
42
+ sig = metals[1:] if len(metals) > 1 else metals
43
+ ax, ay = shapely.union_all(sig).bounds[:2]
44
+ X0, Y0, X1, Y1 = shapely.union_all(metals).bounds
45
+ span = max(X1 - X0, Y1 - Y0)
46
+ K = max(0, int(np.ceil(np.log2(max(span / 16, h_f) / h_f))))
47
+ h0 = h_f * 2**K
48
+ ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0))
49
+ ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0))
50
+ gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1))
51
+ xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0)
52
+ gq = P._Geoms(list(metals) + [edges, core])
53
+ lv = np.asarray(levels, float)
54
+ tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool)
55
+ out_c, out_h, out_o = [], [], []
56
+ while len(xs):
57
+ boxes = shapely.box(xs, ys, xs + h, ys + h)
58
+ cov, hit, inn, pcs = P._cover(gq, boxes, h, tst, inn)
59
+ keep = cov.sum(0) > 1e-3
60
+ xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep]
61
+ pcs = [p[keep] for p in pcs]
62
+ cx, cy = xs + h / 2, ys + h / 2
63
+ full = cov.max(0) > 0.999
64
+ if len(lv):
65
+ maybe = h <= h_f * 2 ** len(lv) * 1.0001 # cells that can be at their last level
66
+ hl = np.zeros(len(xs))
67
+ if maybe.any():
68
+ dc = P._distance(gq, len(metals) + 1, boxes[maybe])
69
+ hl[maybe] = h_f * 2.0 ** np.searchsorted(lv, dc, side="right")
70
+ last = h <= hl * 1.0001
71
+ else:
72
+ last = h <= h_f * 1.0001
73
+ d = np.full(len(xs), np.inf)
74
+ far = full & ~last
75
+ d[far] = P._distance(gq, len(metals), boxes[far])
76
+ leaf = full & (last | (h <= grade * d + 1e-12))
77
+ out_c.append(np.stack([cx[leaf], cy[leaf]], 1))
78
+ out_h.append(np.stack([h[leaf], h[leaf]], 1))
79
+ out_o.append(cov[:, leaf].argmax(0))
80
+ cut = last & ~leaf
81
+ if majority and cut.any():
82
+ take = cut & (cov.max(0) >= 0.5)
83
+ out_c.append(np.stack([cx[take], cy[take]], 1))
84
+ out_h.append(np.stack([h[take], h[take]], 1))
85
+ out_o.append(cov[:, take].argmax(0))
86
+ cut = cut & False
87
+ if cut.any():
88
+ gs = gq.get()
89
+ for k, g in enumerate(gs[:len(metals)]):
90
+ shapely.prepare(g)
91
+ sel = np.nonzero(cut & (cov[k] > 1e-3))[0]
92
+ if not len(sel):
93
+ continue
94
+ pcs_k = pcs[k][sel]
95
+ bb = shapely.bounds(pcs_k)
96
+ cen = shapely.get_coordinates(shapely.centroid(pcs_k))
97
+ inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1])
98
+ if not inside.all():
99
+ cen[~inside] = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside]))
100
+ out_c.append(cen)
101
+ out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6))
102
+ out_o.append(np.full(len(sel), k))
103
+ gq.put(gs)
104
+ split = ~leaf & ~last
105
+ hs = h[split] / 2
106
+ xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs])
107
+ ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs])
108
+ h = np.concatenate([hs] * 4)
109
+ tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4)
110
+ return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
111
+
112
+
113
+ def strip_merge(c, wh, o, metals, h_f: float, lmax_mult: float = 16.0, grade: float = 1.0):
114
+ """`proxy.strip_merge` with the strip length bounded by lmax_mult x the panel's own lattice level (max(width across
115
+ the edge, h_f), so coarser regions get proportionally longer strips) and by grade x the distance to the nearest
116
+ polygon vertex (coarse square cells therefore merge into longer strips than in proxy.strip_merge)."""
117
+ lines, S, verts = P._segments(metals)
118
+ near = shapely.STRtree(lines).nearest(shapely.points(c))
119
+ d = S[near, 1] - S[near, 0]
120
+ horiz = np.abs(d[:, 0]) >= np.abs(d[:, 1])
121
+ dv, _ = P.cKDTree(verts).query(c, workers=-1)
122
+ allow = np.minimum(lmax_mult * np.maximum(wh.min(1), h_f), grade * dv)
123
+ out_c, out_wh, out_o = [], [], []
124
+ for axis, mask in ((0, horiz), (1, ~horiz)):
125
+ if not mask.any():
126
+ continue
127
+ idx = np.nonzero(mask)[0]
128
+ other = 1 - axis
129
+ key = np.stack([o[idx], np.round(c[idx, other], 4), np.round(wh[idx, other], 4)], 1)
130
+ order = np.lexsort([c[idx, axis], key[:, 2], key[:, 1], key[:, 0]])
131
+ idx, key = idx[order], key[order]
132
+ same = np.all(key[1:] == key[:-1], 1)
133
+ lo, hi = c[idx, axis] - wh[idx, axis] / 2, c[idx, axis] + wh[idx, axis] / 2
134
+ adjacent = same & (np.abs(hi[:-1] - lo[1:]) < 1e-6)
135
+ start = 0
136
+ while start < len(idx):
137
+ end, length, cap = start, wh[idx[start], axis], allow[idx[start]]
138
+ while end + 1 < len(idx) and adjacent[end] and length + wh[idx[end + 1], axis] <= min(cap, allow[idx[end + 1]]):
139
+ end += 1
140
+ length += wh[idx[end], axis]
141
+ cap = min(cap, allow[idx[end]])
142
+ cc, ww = np.zeros(2), np.zeros(2)
143
+ cc[axis], cc[other] = 0.5 * (lo[start] + hi[end]), c[idx[start], other]
144
+ ww[axis], ww[other] = hi[end] - lo[start], wh[idx[start], other]
145
+ out_c.append(cc)
146
+ out_wh.append(ww)
147
+ out_o.append(o[idx[start]])
148
+ start = end + 1
149
+ return np.array(out_c), np.array(out_wh), np.array(out_o)
150
+
151
+
152
+
153
+ # formula constants: frozen 2026-10-09, not tuned on labels
154
+ FORMULA_STEP_UM = 0.25 # boundary sample step (as the pair tokens)
155
+ FORMULA_R_GAPS = 150.0 # pairs farther apart than this (in smallest gaps) use the bounding-box form
156
+ FORMULA_SCREEN_UM = 1.0 # the screening factor is evaluated every FORMULA_SCREEN_UM of boundary and held in between
157
+ LITE_REFINE = 3 # rejected window solves: refine h by 2 up to this many times before majority-owned cells
158
+ LITE_LEVEL_GAPS = (10.0, 20.0, 40.0, 80.0) # windows of large layouts: finest panel within 10 gaps of the core, doubling beyond 10/20/40/80
159
+ LITE_WINDOW_BUDGET = 2.0 # windows of large layouts: panel budget = this x the budget of the one-window (component) prior
160
+ LITE_GROWTH = 2.0 # merged panels per halving of h (measured 1.6-2.2 on the training families)
161
+ ALPHA_GAP_SHARE = 0.52 # dipole far pairs: perimeter x gap band share of the effective area; fit 0.519 (median log-ratio 0 vs the global gap/3 MoM, 68 cross-pocket pairs > 50 gaps of grid_qubit_1; PRIOR_SCHEME.md 14.2)
162
+ DIPOLE_K = 8 # nearest boundary samples searched for the nearest other conductor (gbar)
163
+ ROW_SUM_EPS = 0.0143 # training median of 1 - sum_j |C_ij| / C_ii (self = row sum / (1 - eps))
164
+ EPS0_FF_UM = 8.8541878128e-3
165
+
166
+
167
+ def plan_cores(sites: np.ndarray, max_core: int = 8) -> list:
168
+ """Cores (index arrays) by recursive bisection of the conductor sites (n, 2) along the longer extent until each core
169
+ has <= max_core conductors; each split is snapped to the widest coordinate gap between sites in the central half
170
+ of the sorted order (ties broken by the other coordinate, so the cores do not depend on the conductor order)."""
171
+ out = []
172
+
173
+ def rec(idx):
174
+ if len(idx) <= max_core:
175
+ out.append(idx)
176
+ return
177
+ s = sites[idx]
178
+ ax = int(np.argmax(s.max(0) - s.min(0)))
179
+ order = idx[np.lexsort((s[:, 1 - ax], s[:, ax]))]
180
+ x = sites[order, ax]
181
+ lo = max(1, len(order) // 4)
182
+ hi = max(lo + 1, min(len(order), (3 * len(order)) // 4 + 1))
183
+ m = lo + int(np.argmax(x[lo:hi] - x[lo - 1:hi - 1]))
184
+ rec(order[:m]), rec(order[m:])
185
+
186
+ rec(np.arange(len(sites)))
187
+ return out
188
+
189
+
190
+ def _rot90(k: int):
191
+ """Exact rotation of coordinates by k x 90 degrees (swaps and sign flips only)."""
192
+ def f(xy):
193
+ x, y = xy[:, 0], xy[:, 1]
194
+ return np.stack([(x, y), (-y, x), (-x, -y), (y, -x)][k % 4], 1)
195
+ return f
196
+
197
+
198
+ def canonical_frames(G, conds: list) -> list:
199
+ """The layout in canonical frames, so that the lattice-anchored mesh (and hence the prior) does not depend on the
200
+ position, the 90-degree orientation or the conductor order of the input: rotations by k x 90 degrees whose
201
+ rotation-invariant key (signal bounding box, sorted conductor centroids and convex-hull vertices about the box
202
+ centre, ground bounds, rounded to 1 nm) is smallest (several when the layout is symmetric), translation of the signal
203
+ bounding box corner to the origin, coordinates rounded to 1e-6 um, collinear vertices removed (`shapely.simplify(0)`),
204
+ rings in normal form (`shapely.normalize`), conductors sorted by (centroid, area). Returns [(G, conds, order)]:
205
+ conds[k] of a frame is input conductor order[k]."""
206
+ keys = []
207
+ for k in range(4):
208
+ f = _rot90(k)
209
+ sig = [shapely.transform(c, f) for c in conds]
210
+ b = shapely.bounds(np.array(sig, dtype=object))
211
+ x0, y0, x1, y1 = b[:, 0].min(), b[:, 1].min(), b[:, 2].max(), b[:, 3].max()
212
+ cen = shapely.get_coordinates(shapely.centroid(np.array(sig, dtype=object))) - [(x0 + x1) / 2, (y0 + y1) / 2]
213
+ hull = shapely.get_coordinates(shapely.convex_hull(shapely.union_all(sig)))[:-1] - [(x0 + x1) / 2, (y0 + y1) / 2]
214
+ gb = np.round(np.array(shapely.transform(G, f).bounds) - [(x0 + x1) / 2, (y0 + y1) / 2] * 2, 3)
215
+ key = ((round(x1 - x0, 3), round(y1 - y0, 3)) + tuple(sorted(map(tuple, np.round(cen, 3).tolist())))
216
+ + tuple(sorted(map(tuple, np.round(hull, 3).tolist()))) + tuple(gb.tolist()))
217
+ keys.append((key, k, x0, y0))
218
+ best = min(kk[0] for kk in keys)
219
+ out = []
220
+ for key, k, x0, y0 in keys:
221
+ if key != best:
222
+ continue
223
+ f = _rot90(k)
224
+
225
+ def to(g, f=f, x0=x0, y0=y0):
226
+ return shapely.normalize(shapely.simplify(shapely.transform(g, lambda xy: np.round(f(xy) - [x0, y0], 6)), 0.0))
227
+
228
+ cs = [to(c) for c in conds]
229
+ cen = shapely.get_coordinates(shapely.centroid(np.array(cs, dtype=object)))
230
+ order = np.lexsort((np.round([c.area for c in cs], 6), np.round(cen[:, 1], 6), np.round(cen[:, 0], 6)))
231
+ out.append((to(G), [cs[i] for i in order], order))
232
+ return out
233
+
234
+
235
+ def _gap_size(metals: list) -> tuple:
236
+ """(smallest gap, layout size) exactly as mom_capacitance_gds_flagship computes them (all pairs; small layouts)."""
237
+ bbox = shapely.union_all(metals).bounds
238
+ size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
239
+ gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals)))
240
+ return gap, size
241
+
242
+
243
+ def _graded_mesh(metals: list, n_core: int, h: float, levels: tuple, majority: bool = False) -> tuple:
244
+ """Core-graded flagship-family mesh (`anchored_cells_graded` + `strip_merge`): finest panel h within levels[0] of the
245
+ core conductors (metals[1:1 + n_core]), doubling beyond each level. Returns (centres, sizes, owners, h, raw count)."""
246
+ raw = anchored_cells_graded(metals, h, shapely.union_all(metals[1:1 + n_core]), levels, majority=majority)
247
+ c, wh, o = strip_merge(*raw, metals, h)
248
+ return c, wh, o, h, len(raw[0])
249
+
250
+
251
+ def _lite_mesh(metals: list, h: float, budget: float, n_core: int = 0, levels: tuple = ()) -> tuple:
252
+ """Flagship-family mesh at the finest lattice level h 2^k predicted to fit the budget: a probe mesh at the level
253
+ estimated (2 merged panels per h of metal edge) to hold ~budget / 4 panels, then the level LITE_GROWTH^j finer
254
+ predicted to hold <= budget panels (each halving of h multiplies the panels by ~LITE_GROWTH), doubled while it does
255
+ not fit. levels (um from the n_core core conductors): core-graded mesh (`_graded_mesh`); () = uniform
256
+ (`proxy.mesh_flagship`). With an unbounded budget: the mesh at h. Returns (centres, sizes, owners, h, raw count)."""
257
+ def mesh(hh):
258
+ if not levels:
259
+ return P.mesh_flagship(metals, hh, budget)
260
+ while True:
261
+ r = _graded_mesh(metals, n_core, hh, levels)
262
+ if len(r[0]) <= budget:
263
+ return r
264
+ hh *= 2.0
265
+
266
+ if not np.isfinite(budget):
267
+ return mesh(h)
268
+ L = sum(g.length for g in metals)
269
+ k = max(0, int(np.ceil(np.log2(max(2.0 * L / (h * budget / 4), 1.0)))))
270
+ probe = mesh(h * 2.0**k)
271
+ j = min(int(np.floor(np.log(budget / len(probe[0])) / np.log(LITE_GROWTH))), int(round(np.log2(probe[3] / h))))
272
+ return probe if j <= 0 else mesh(probe[3] / 2.0**j)
273
+
274
+
275
+ def _sym_solve(A, B):
276
+ """Solve with the lower triangle of the Fortran-ordered A from `proxy._assemble`: Cholesky, or the symmetric
277
+ indefinite (Bunch-Kaufman) factorisation when A is not positive definite."""
278
+ try:
279
+ return P._chol_solve(A.copy(order="F"), B)
280
+ except np.linalg.LinAlgError:
281
+ from scipy.linalg import solve
282
+ return solve(A, B, lower=True, assume_a="sym", overwrite_a=True, check_finite=False)
283
+
284
+
285
+ def _window_solve(metals: list, n_core: int, h: float, budget: float, eps_r: float, all_rhs: bool, levels: tuple = ()) -> tuple:
286
+ """Flagship-family mesh of one window at the lattice level of h that fits the budget (`_lite_mesh`), exact near
287
+ field, dense Cholesky (H-matrix PCG above DENSE_MAX panels); right-hand sides: every metal (all_rhs, as
288
+ `proxy._cap_flagship`) or the n_core core conductors; levels: core-graded mesh (`_lite_mesh`). A solve is rejected
289
+ when the system is not positive definite, a metal has no panel or (all_rhs) a mutual entry is not negative (cut
290
+ panels of different conductors overlapping on a lattice coarser than the features); the mesh is then refined (h / 2, budget lifted) up to LITE_REFINE times, and finally
291
+ meshed with majority-owned finest cells (as the flagship). Returns (R (n_rhs, n_metals) charges per metal, info)."""
292
+ cols = np.arange(len(metals)) if all_rhs else np.arange(1, 1 + n_core)
293
+ t_mesh = t_asm = t_sol = 0.0
294
+ hh, cap, refined, majority = h, budget, 0, False
295
+ while True:
296
+ t = time.perf_counter()
297
+ if not refined:
298
+ c, wh, o, hh, n_raw = _lite_mesh(metals, hh, cap, n_core, levels)
299
+ elif levels:
300
+ c, wh, o, hh, n_raw = _graded_mesh(metals, n_core, hh, levels, majority)
301
+ else:
302
+ c, wh, o, hh, n_raw = P.mesh_flagship(metals, hh, cap, majority=majority)
303
+ t_mesh += time.perf_counter() - t
304
+ t = time.perf_counter()
305
+ try:
306
+ if len(c) <= P.DENSE_MAX:
307
+ A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential)
308
+ t_asm += time.perf_counter() - t
309
+ t = time.perf_counter()
310
+ Bm = (o[:, None] == cols[None, :]).astype(float)
311
+ if all_rhs:
312
+ Q = P._chol_solve(A, Bm)
313
+ else: # windows: an indefinite system (overlapping cut panels on the coarse graded levels) is solved by LDL^T
314
+ Q = _sym_solve(A, Bm)
315
+ else:
316
+ Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)[:, cols]
317
+ R = np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1)
318
+ off = np.ones(R.shape, bool)
319
+ off[np.arange(len(cols)), cols] = False
320
+ ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and (not all_rhs or np.all(R[off] < 0)))
321
+ except np.linalg.LinAlgError:
322
+ ok = False
323
+ t_sol += time.perf_counter() - t
324
+ if ok or majority:
325
+ break
326
+ if refined < LITE_REFINE:
327
+ hh, cap, refined = hh / 2, np.inf, refined + 1
328
+ else:
329
+ majority = True
330
+ return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh,
331
+ "assemble_s": t_asm, "solve_s": t_sol}
332
+
333
+
334
+ def _lite_window(G, conds: list, core, R_g: float, margin: float, fill_um: float, tree, etched) -> tuple:
335
+ """Window of a core: ([ground, core..., halo...], halo). Halo = conductors within R_g of a core conductor (separate
336
+ nets at 0 V); ground = chip ground clipped to the core + halo box widened by margin, plus every farther conductor in
337
+ the box as ground metal with its etched surroundings within fill_um filled where farther than R_g from a member."""
338
+ hit = tree.query([conds[i] for i in core], predicate="dwithin", distance=R_g)[1]
339
+ halo = np.setdiff1d(np.unique(hit), core)
340
+ members = np.concatenate([core, halo]).astype(int)
341
+ b = shapely.bounds(np.array([conds[i] for i in members], dtype=object))
342
+ box = (b[:, 0].min() - margin, b[:, 1].min() - margin, b[:, 2].max() + margin, b[:, 3].max() + margin)
343
+ far = np.setdiff1d(tree.query(shapely.box(*box), predicate="intersects"), members)
344
+ Gw = shapely.clip_by_rect(G, *box)
345
+ if len(far):
346
+ farg = shapely.clip_by_rect(shapely.union_all([conds[i] for i in far]), *box)
347
+ fill = shapely.intersection(shapely.clip_by_rect(etched, *box), farg.buffer(fill_um, quad_segs=4))
348
+ fill = fill.difference(shapely.union_all([conds[i] for i in members]).buffer(R_g, quad_segs=4))
349
+ Gw = shapely.union_all([Gw, farg, fill])
350
+ return [_valid(Gw)] + [conds[i] for i in members], halo
351
+
352
+
353
+ _LITE_BUDGET_USED: list = [0.0]
354
+ _LITE: dict = {} # layout of the running micro_mom call, inherited by forked window workers
355
+
356
+
357
+ def _lite_job(k: int) -> tuple:
358
+ L = _LITE
359
+ t = time.perf_counter()
360
+ metals, halo = _lite_window(L["G"], L["conds"], L["cores"][k], L["R_g"], L["margin"], L["fill_um"], L["tree"], L["etched"])
361
+ t_build = time.perf_counter() - t
362
+ bx = shapely.bounds(metals[0])
363
+ h = max(L["h"], max(bx[2] - bx[0], bx[3] - bx[1]) / 4096)
364
+ R, info = _window_solve(metals, len(L["cores"][k]), h, L["budget"], L["eps_r"], False, L["levels"])
365
+ info.update(build_s=t_build, n_halo=len(halo), n_core=len(L["cores"][k]))
366
+ return k, halo, R, info
367
+
368
+
369
+ def micro_mom(G, conds: list, eps_r: float = 11.45, budget: float = 1500, cells_per_gap: float = 3.0, max_core: int = 8,
370
+ halo_gaps: float = 100.0, margin_gaps: float = 100.0, margin_min_um: float = 150.0, fill_um: float = 250.0,
371
+ workers: int = 1, level_gaps: tuple = LITE_LEVEL_GAPS, window_budget: float | None = None, canonical: bool = True) -> tuple:
372
+ """Cheap micro-MoM prior (PRIOR_SCHEME.md section 12, M / hybrid H): (C (N+1, N+1) fF Maxwell, far_mask, info).
373
+ <= max_core conductors: one global window = the layout as given, h = max(gap / cells_per_gap, size / 4096) doubled
374
+ on the flagship lattice until the merged mesh has <= budget panels, every metal excited (with budget = inf this is
375
+ `proxy.mom_capacitance_gds_flagship(rich=False)` bit for bit; `_lite_mesh` picks the level). More conductors: cores of <= max_core by bisection,
376
+ one window per core (halo within halo_gaps, ground clipped at margin_gaps), entry (i, j) = mean of the two window
377
+ estimates when both exist (a non-negative window estimate is not used), ground row from the columns, C_00 = row sum /
378
+ (1 - ROW_SUM_EPS); pairs never co-windowed (far_mask, > halo_gaps apart) in different ground pockets take the screened
379
+ dipole value (`dipole_far`), in the same pocket the closed form (`formula_prior`, quadrature step one smallest gap). level_gaps: core-graded window
380
+ meshes (finest panel within level_gaps[0] smallest gaps of the core, doubling beyond each level); window systems that
381
+ are not positive definite are solved by LDL^T; window budget = window_budget or LITE_WINDOW_BUDGET x budget. Windows
382
+ run on `workers` forked processes. canonical: solved in the `canonical_frames` (mean over them when the layout is
383
+ symmetric; invariant to translation, 90-degree rotation and conductor order), returned in the input order."""
384
+ t_all = time.perf_counter()
385
+ if canonical: # mean over the canonical frames (one unless the layout is symmetric), in the input order
386
+ runs = []
387
+ for Gc, cc, order in canonical_frames(G, conds):
388
+ C, far, info = micro_mom(Gc, cc, eps_r, budget, cells_per_gap, max_core, halo_gaps, margin_gaps, margin_min_um, fill_um,
389
+ workers, level_gaps, window_budget, canonical=False)
390
+ inv = np.r_[0, np.argsort(order) + 1]
391
+ runs.append((C[np.ix_(inv, inv)], far[np.ix_(inv, inv)], info))
392
+ C = runs[0][0] if len(runs) == 1 else sum(r[0] for r in runs) / len(runs)
393
+ far = np.logical_or.reduce([r[1] for r in runs])
394
+ info = runs[0][2]
395
+ for k in ("mesh_s", "assemble_s", "solve_s", "build_s", "formula_s"):
396
+ info[k] = sum(r[2][k] for r in runs)
397
+ info["n_frames"] = len(runs)
398
+ info["total_s"] = time.perf_counter() - t_all
399
+ return C, far, info
400
+ metals = [G] + list(conds)
401
+ N = len(metals)
402
+ far = np.zeros((N, N), bool)
403
+ if len(conds) <= max_core:
404
+ gap, size = _gap_size(metals)
405
+ h = max(gap / cells_per_gap, size / 4096)
406
+ R, wi = _window_solve(metals, len(conds), h, budget, eps_r, True)
407
+ C = 0.5 * (R + R.T)
408
+ info = {"n_windows": 1, "min_gap_um": gap, "h_um": [wi["h_um"]], "panels": [wi["panels"]], "panels_per_gap": [gap / wi["h_um"]],
409
+ "majority": [wi["majority"]], "refined": [wi["refined"]], "mesh_s": wi["mesh_s"], "assemble_s": wi["assemble_s"], "solve_s": wi["solve_s"],
410
+ "build_s": 0.0, "plan_s": 0.0, "formula_s": 0.0, "n_far_pairs": 0, "budget": budget}
411
+ info["total_s"] = time.perf_counter() - t_all
412
+ return C, far, info
413
+ t = time.perf_counter()
414
+ gap = gap_of(metals)
415
+ R_g, margin = halo_gaps * gap, max(margin_gaps * gap, margin_min_um)
416
+ b = shapely.bounds(np.array(conds, dtype=object))
417
+ cores = plan_cores(np.stack([(b[:, 0] + b[:, 2]) / 2, (b[:, 1] + b[:, 3]) / 2], 1), max_core)
418
+ tree = shapely.STRtree(conds)
419
+ etched = shapely.box(*G.bounds).difference(G)
420
+ _LITE.clear()
421
+ _LITE.update(G=G, conds=conds, cores=cores, R_g=R_g, margin=margin, fill_um=fill_um, tree=tree, etched=etched,
422
+ h=gap / cells_per_gap, budget=LITE_WINDOW_BUDGET * budget if window_budget is None else window_budget, eps_r=eps_r,
423
+ levels=tuple(float(x) * gap for x in level_gaps))
424
+ _LITE_BUDGET_USED[:] = [_LITE["budget"]]
425
+ t_plan = time.perf_counter() - t
426
+ t = time.perf_counter()
427
+ if workers > 1 and len(cores) > 1:
428
+ with ProcessPoolExecutor(min(workers, len(cores)), mp_context=get_context("fork")) as ex:
429
+ res = list(ex.map(_lite_job, range(len(cores))))
430
+ else:
431
+ res = [_lite_job(k) for k in range(len(cores))]
432
+ t_win = time.perf_counter() - t
433
+ _LITE.clear()
434
+ acc, cnt = np.zeros((N, N)), np.zeros((N, N))
435
+ for k, halo, R, _ in res:
436
+ idx = np.concatenate([[0], cores[k] + 1, halo + 1]).astype(int)
437
+ for r, ci in enumerate(cores[k] + 1):
438
+ use = (R[r] < 0) | (idx == ci) # a non-negative mutual estimate of a window (tiny far entries) is not used
439
+ acc[ci, idx[use]] += R[r][use]
440
+ cnt[ci, idx[use]] += 1
441
+ have = cnt > 0
442
+ Cw = np.where(have, acc / np.where(have, cnt, 1), 0.0)
443
+ C = np.where(have & have.T, 0.5 * (Cw + Cw.T), np.where(have, Cw, Cw.T))
444
+ far = ~(have | have.T)
445
+ np.fill_diagonal(far, False)
446
+ t = time.perf_counter()
447
+ iu = np.nonzero(np.triu(far, 1))
448
+ t_dip, n_dip = 0.0, 0
449
+ if len(iu[0]):
450
+ pid = np.r_[-10**9, pocket_ids(G, conds)]
451
+ cross = pid[iu[0]] != pid[iu[1]] # different ground pockets: screened dipole; same pocket: closed form
452
+ if (~cross).any():
453
+ F, _ = formula_prior(G, conds, eps_r, step_um=max(FORMULA_STEP_UM, gap), pairs=np.stack(iu, 1)[~cross], gap=gap, workers=workers)
454
+ C[iu[0][~cross], iu[1][~cross]] = F[iu[0][~cross], iu[1][~cross]]
455
+ if cross.any():
456
+ t_dip = time.perf_counter()
457
+ C[iu[0][cross], iu[1][cross]] = dipole_far(G, conds, np.stack(iu, 1)[cross], eps_r, gap)
458
+ t_dip, n_dip = time.perf_counter() - t_dip, int(cross.sum())
459
+ C[iu[1], iu[0]] = C[iu]
460
+ t_form = time.perf_counter() - t
461
+ C[0, 0] = np.abs(C[0, 1:]).sum() / (1 - ROW_SUM_EPS)
462
+ infos = [r[3] for r in res]
463
+ info = {"n_windows": len(cores), "min_gap_um": gap, "R_g_um": R_g, "margin_um": margin, "h_um": [i["h_um"] for i in infos],
464
+ "panels": [i["panels"] for i in infos], "panels_per_gap": [gap / i["h_um"] for i in infos],
465
+ "majority": [i["majority"] for i in infos], "refined": [i["refined"] for i in infos], "cores": [i["n_core"] for i in infos], "halos": [i["n_halo"] for i in infos],
466
+ "mesh_s": sum(i["mesh_s"] for i in infos), "assemble_s": sum(i["assemble_s"] for i in infos),
467
+ "solve_s": sum(i["solve_s"] for i in infos), "build_s": sum(i["build_s"] for i in infos), "plan_s": t_plan,
468
+ "windows_wall_s": t_win, "formula_s": t_form, "n_far_pairs": int(len(iu[0])), "dipole_s": t_dip,
469
+ "n_dipole_pairs": n_dip, "budget": _LITE_BUDGET_USED[0],
470
+ "workers": workers, "level_gaps": list(level_gaps)}
471
+ info["total_s"] = time.perf_counter() - t_all
472
+ return C, far, info
473
+
474
+
475
+ def pocket_ids(G, conds: list) -> np.ndarray:
476
+ """Ground pocket of every conductor: index of the interior ring of the ground metal that contains it (STRtree of the
477
+ rings' polygons, `within`); a conductor in no ring gets its own id (-1 - k)."""
478
+ rings = [shapely.Polygon(r) for p in getattr(G, "geoms", [G]) for r in p.interiors]
479
+ out = -1 - np.arange(len(conds))
480
+ if rings:
481
+ c, r = shapely.STRtree(rings).query(list(conds), predicate="within")
482
+ out[c] = r
483
+ return out
484
+
485
+
486
+ def _edge_samples(geoms: list, step: float) -> tuple:
487
+ """Points every <= step along every polygon edge of geoms (vertices included), with the index of their geometry:
488
+ (points (n, 2), owner (n,)). Vectorised over all edges (no per-ring interpolation)."""
489
+ segs, sown = [], []
490
+ for k, g in enumerate(geoms):
491
+ for p in getattr(g, "geoms", [g]):
492
+ for ring in [p.exterior, *p.interiors]:
493
+ xy = np.asarray(ring.coords)
494
+ segs.append(np.stack([xy[:-1], xy[1:]], 1))
495
+ sown.append(np.full(len(xy) - 1, k))
496
+ S, sown = np.concatenate(segs), np.concatenate(sown)
497
+ L = np.sqrt(((S[:, 1] - S[:, 0]) ** 2).sum(1))
498
+ n = np.maximum(1, np.ceil(L / step).astype(int))
499
+ seg = np.repeat(np.arange(len(S)), n)
500
+ t = (np.arange(n.sum()) - np.repeat(np.cumsum(n) - n, n)) / np.repeat(n, n)
501
+ return S[seg, 0] + t[:, None] * (S[seg, 1] - S[seg, 0]), sown[seg]
502
+
503
+
504
+ def dipole_far(G, conds: list, pairs, eps_r: float = 11.45, gap: float | None = None) -> np.ndarray:
505
+ """Screened-dipole far couplings (PRIOR_SCHEME.md 14.2): for metal-index pairs (k, 2) (1 = first conductor),
506
+ C_ij = -(1 + eps_r) eps0 At_i At_j / (2 pi d_eff^3), d_eff^2 = d^2 + a_i^2 + a_j^2, a = sqrt(At / pi), d = centroid
507
+ distance, At = A + ALPHA_GAP_SHARE x P x gbar with gbar the mean distance from i's edge samples (step one gap) to the
508
+ nearest other metal: ground edge samples (step gap / 4) by one k-d tree, other conductors by one k-d tree of all
509
+ conductor samples with owner labels (DIPOLE_K neighbours). Returns the values (k,)."""
510
+ metals = [G] + list(conds)
511
+ gap = gap_of(metals) if gap is None else gap
512
+ pairs = np.asarray(pairs, int).reshape(-1, 2)
513
+ pts, own = _edge_samples(list(conds), gap)
514
+ own = own + 1
515
+ sel = np.isin(own, np.unique(pairs))
516
+ q = pts[sel]
517
+ dg, _ = cKDTree(_edge_samples([G], gap / 4)[0]).query(q)
518
+ d, idx = cKDTree(pts).query(q, k=min(DIPOLE_K, len(own)))
519
+ if d.ndim == 1:
520
+ d, idx = d[:, None], idx[:, None]
521
+ d = np.where(own[np.minimum(idx, len(own) - 1)] != own[sel][:, None], d, np.inf).min(1)
522
+ gbar = np.bincount(own[sel], np.minimum(dg, d), len(metals)) / np.maximum(np.bincount(own[sel], minlength=len(metals)), 1)
523
+ area = np.array([g.area for g in metals])
524
+ perim = np.array([g.length for g in metals])
525
+ At = area + ALPHA_GAP_SHARE * perim * gbar
526
+ cen = shapely.get_coordinates(shapely.centroid(np.array(metals, dtype=object)))
527
+ a, b = pairs[:, 0], pairs[:, 1]
528
+ d2 = ((cen[a] - cen[b]) ** 2).sum(1) + (At[a] + At[b]) / np.pi
529
+ return -(1 + eps_r) * EPS0_FF_UM * At[a] * At[b] / (2 * np.pi * d2 ** 1.5)
530
+
531
+
532
+ def _ground_segments(G):
533
+ """Edge segments (m, 2, 2) of the ground metal and an STRtree over them."""
534
+ _, S, _ = P._segments([G])
535
+ return S, shapely.STRtree(shapely.linestrings(S))
536
+
537
+
538
+ def _metal_length(A: np.ndarray, B: np.ndarray, S: np.ndarray, tree) -> np.ndarray:
539
+ """Length of ground metal crossed by each segment A[k] -> B[k] (endpoints off the metal): crossings with the ground
540
+ edges (STRtree) sorted along the segment, alternate inside / outside intervals summed."""
541
+ out = np.zeros(len(A))
542
+ if not len(A):
543
+ return out
544
+ li, gi = tree.query(shapely.linestrings(np.stack([A, B], 1)), predicate="intersects")
545
+ if not len(li):
546
+ return out
547
+ p, r = A[li], B[li] - A[li]
548
+ q, s = S[gi, 0], S[gi, 1] - S[gi, 0]
549
+ den = r[:, 0] * s[:, 1] - r[:, 1] * s[:, 0]
550
+ ok = np.abs(den) > 1e-12
551
+ li, t = li[ok], np.clip(((q - p)[ok, 0] * s[ok, 1] - (q - p)[ok, 1] * s[ok, 0]) / den[ok], 0.0, 1.0)
552
+ order = np.lexsort((t, li))
553
+ li, t = li[order], t[order]
554
+ start = np.r_[0, np.nonzero(np.diff(li))[0] + 1]
555
+ n = np.diff(np.r_[start, len(li)])
556
+ rank = np.arange(len(li)) - np.repeat(start, n)
557
+ keep = rank < np.repeat(n // 2 * 2, n)
558
+ sgn = np.where(rank % 2 == 1, 1.0, -1.0)
559
+ out += np.bincount(li[keep], weights=(sgn * t)[keep], minlength=len(A))
560
+ return out * np.sqrt(((B - A) ** 2).sum(1))
561
+
562
+
563
+ def _cps_m(d, w1, w2):
564
+ """Coplanar-strip modulus (as `blocks.edge_features`; w = inf for the ground)."""
565
+ if np.isinf(w1) or np.isinf(w2):
566
+ wf = w2 if np.isinf(w1) else w1
567
+ return d / (d + wf)
568
+ return d * (d + w1 + w2) / ((d + w1) * (d + w2))
569
+
570
+
571
+ _FORM: dict = {} # samples and trees of the running formula_prior call, inherited by forked row workers
572
+
573
+
574
+ def _formula_row(i: int) -> tuple:
575
+ """Row i of the directed sums I[i, j] of `formula_prior` (j = the near metals of i; ground last term included)."""
576
+ F = _FORM
577
+ pts, kd, near, width, R, k, step_um, every = F["pts"], F["kd"], F["near"], F["width"], F["R"], F["k"], F["step"], F["every"]
578
+ I = np.zeros(near.shape[0])
579
+ dmin_other, dG = np.full(len(pts[i]), np.inf), None
580
+ for j in np.nonzero(near[i])[0]:
581
+ d, idx = kd[j].query(pts[i], distance_upper_bound=R if j > 0 else np.inf)
582
+ ok = np.isfinite(d)
583
+ if j > 0:
584
+ dmin_other = np.minimum(dmin_other, d)
585
+ else:
586
+ dG = d
587
+ if not ok.any():
588
+ continue
589
+ dd = np.maximum(d[ok], 0.05)
590
+ if j == 0:
591
+ S = np.ones(ok.sum())
592
+ else:
593
+ sel = np.arange(0, ok.sum(), every)
594
+ A = pts[i][ok][sel]
595
+ lg = _metal_length(A, pts[j][idx[ok][sel]], F["SG"], F["gtree"])
596
+ S = np.exp(-lg / (dd[sel] + min(width[i], width[j])))[np.arange(ok.sum()) // every]
597
+ I[j] = k * np.sum(step_um * _kratio(_cps_m(dd, width[i], width[j])) * S)
598
+ if dG is not None:
599
+ share = float(np.mean(dG <= dmin_other))
600
+ I[0] += 8 * EPS0_FF_UM * (1 + F["eps_r"]) / 2 * np.sqrt(F["area"][i] / np.pi) * share
601
+ return i, I
602
+
603
+
604
+ def formula_prior(G, conds: list, eps_r: float = 11.45, step_um: float = FORMULA_STEP_UM, R_gaps: float = FORMULA_R_GAPS,
605
+ pairs=None, gap: float | None = None, screen_um: float = FORMULA_SCREEN_UM, workers: int = 1,
606
+ max_core: int = 8) -> tuple:
607
+ """Closed-form edge-coupling prior (PRIOR_SCHEME.md section 12, F): (C (N+1, N+1) fF Maxwell, info). No mesh, no solve.
608
+ C_ij = eps0 (1 + eps_r) / 2 x mean over the directions (i, j), (j, i) of sum_p K(k') / K(k) S(p) step over the boundary
609
+ samples p of i (modulus of the local widths 2 A / P and the distance to the nearest sample of j, within R_gaps
610
+ smallest gaps; the ground without a bound), S(p) = exp(-l_G / (d + w_min)) with l_G the ground metal crossed on p -> nearest point of j. C_iG: the
611
+ same sum against the ground edge (S = 1) + 8 eps0 eps_eff sqrt(A_i / pi) x (share of i's samples nearest to the
612
+ ground). Pairs farther than R_gaps: the same form on the bounding boxes (facing length (P_i + P_j) / 2, distance of
613
+ the boxes, l_G = ground area fraction x distance). Self terms: row sums / (1 - ROW_SUM_EPS). pairs (k, 2) of metal
614
+ indices (0 = ground): only those mutual entries (the rest 0, no self terms). More than max_core conductors: the
615
+ quadrature step is at least gap / 4 and the screening spacing at least one gap (numerically equivalent: median
616
+ 0.02 %, max 1.2 % on the grids vs 0.25 um), rows on `workers` forked processes."""
617
+ t0 = time.perf_counter()
618
+ metals = [G] + list(conds)
619
+ N = len(metals)
620
+ gap = gap_of(metals) if gap is None else gap
621
+ if len(conds) > max_core:
622
+ step_um, screen_um = max(step_um, gap / 4), max(screen_um, gap)
623
+ R = R_gaps * gap
624
+ k = EPS0_FF_UM * (1 + eps_r) / 2
625
+ want = np.zeros((N, N), bool)
626
+ if pairs is None:
627
+ want[np.triu_indices(N, 1)] = True
628
+ else:
629
+ pairs = np.sort(np.asarray(pairs, int).reshape(-1, 2), 1)
630
+ want[pairs[:, 0], pairs[:, 1]] = True
631
+ area = np.array([g.area for g in metals])
632
+ perim = np.array([g.length for g in metals])
633
+ width = np.r_[np.inf, 2 * area[1:] / perim[1:]]
634
+ tree = shapely.STRtree(list(conds))
635
+ near = np.zeros((N, N), bool)
636
+ a, b = tree.query(list(conds), predicate="dwithin", distance=R)
637
+ near[a + 1, b + 1] = True
638
+ near[0, 1:] = near[1:, 0] = True
639
+ np.fill_diagonal(near, False)
640
+ near &= want | want.T
641
+ gx0, gy0, gx1, gy1 = G.bounds
642
+ need = np.unique(np.nonzero(near)[0])
643
+ pts, kd = {}, {}
644
+ for i in np.unique(np.r_[need, np.nonzero(near.any(0))[0]]):
645
+ p = sample_boundary(metals[i], step_um)
646
+ if i == 0: # ground edge = boundary of the etched region (not the chip outline)
647
+ on = (np.abs(p[:, 0] - gx0) < 1e-6) | (np.abs(p[:, 0] - gx1) < 1e-6) | (np.abs(p[:, 1] - gy0) < 1e-6) | (np.abs(p[:, 1] - gy1) < 1e-6)
648
+ p = p[~on]
649
+ pts[i] = p
650
+ kd[i] = cKDTree(p)
651
+ SG, gtree = _ground_segments(G)
652
+ _FORM.clear()
653
+ _FORM.update(pts=pts, kd=kd, near=near, width=width, area=area, R=R, k=k, step=step_um, eps_r=eps_r,
654
+ every=max(1, int(round(screen_um / step_um))), SG=SG, gtree=gtree)
655
+ rows = [i for i in need if i > 0]
656
+ if workers > 1 and len(rows) > 1:
657
+ with ProcessPoolExecutor(min(workers, len(rows)), mp_context=get_context("fork")) as ex:
658
+ res = list(ex.map(_formula_row, rows, chunksize=max(1, len(rows) // (4 * workers))))
659
+ else:
660
+ res = [_formula_row(i) for i in rows]
661
+ _FORM.clear()
662
+ I = np.zeros((N, N))
663
+ for i, row in res:
664
+ I[i] = row
665
+ C = np.zeros((N, N))
666
+ iu = np.nonzero(np.triu(near, 1))
667
+ gnd = iu[0] == 0
668
+ C[iu] = np.where(gnd, I[iu[1], iu[0]], 0.5 * (I[iu] + I[iu[1], iu[0]]))
669
+ fa, fb = np.nonzero(np.triu(want & ~near & ~near.T, 1))
670
+ if len(fa):
671
+ bb = shapely.bounds(np.array(metals, dtype=object))
672
+ dx = np.maximum(0.0, np.maximum(bb[fa, 0] - bb[fb, 2], bb[fb, 0] - bb[fa, 2]))
673
+ dy = np.maximum(0.0, np.maximum(bb[fa, 1] - bb[fb, 3], bb[fb, 1] - bb[fa, 3]))
674
+ dd = np.maximum(np.hypot(dx, dy), 0.05)
675
+ fG = G.area / max(shapely.box(*G.bounds).area, 1e-12)
676
+ w1, w2 = width[fa], width[fb]
677
+ m = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2))
678
+ S = np.exp(-fG * dd / (dd + np.minimum(w1, w2)))
679
+ C[fa, fb] = k * 0.5 * (perim[fa] + perim[fb]) * _kratio(m) * S
680
+ C = -(C + C.T)
681
+ info = {"n_sampled_pairs": int(len(iu[0])), "n_bbox_pairs": int(len(fa)), "min_gap_um": gap, "step_um": step_um,
682
+ "samples": int(sum(len(p) for p in pts.values()))}
683
+ if pairs is None:
684
+ np.fill_diagonal(C, np.abs(C).sum(1) / (1 - ROW_SUM_EPS))
685
+ info["total_s"] = time.perf_counter() - t0
686
+ return C, info
tlsq_infer/_vendor/geometry.py CHANGED
@@ -22,6 +22,26 @@ def sample_boundary(geom, step: float = BOUNDARY_STEP_UM) -> np.ndarray:
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
 
22
  return np.concatenate(pts)
23
 
24
 
25
+ def sample_boundary_fast(geom, step: float = BOUNDARY_STEP_UM) -> np.ndarray:
26
+ """`sample_boundary` vectorised over all rings and points (numpy interpolation along the ring vertices instead of
27
+ one GEOS line_interpolate_point call per ring): the same points to float rounding (large layouts, sparse graphs)."""
28
+ rings = []
29
+ for poly in getattr(geom, "geoms", [geom]):
30
+ rings += [poly.exterior, *poly.interiors]
31
+ xy = [np.asarray(r.coords) for r in rings]
32
+ seg = [np.sqrt(((c[1:] - c[:-1]) ** 2).sum(1)) for c in xy]
33
+ out = []
34
+ for c, sl, r in zip(xy, seg, rings):
35
+ L = r.length
36
+ n = max(int(np.ceil(L / step)), 4)
37
+ s = np.linspace(0, L, n, endpoint=False)
38
+ cum = np.r_[0.0, np.cumsum(sl)]
39
+ k = np.clip(np.searchsorted(cum, s, side="right") - 1, 0, len(sl) - 1)
40
+ t = np.where(sl[k] > 0, (s - cum[k]) / np.where(sl[k] > 0, sl[k], 1.0), 0.0)
41
+ out.append(c[k] + t[:, None] * (c[k + 1] - c[k]))
42
+ return np.concatenate(out)
43
+
44
+
45
  def shape_metrics(poly) -> dict:
46
  hull = poly.convex_hull
47
  x0, y0, x1, y1 = poly.bounds
tlsq_infer/_vendor/graph.py CHANGED
@@ -21,11 +21,70 @@ def prior_dict(C: np.ndarray, n_cells: int, h_min: float, edges) -> dict:
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():
 
21
  return out
22
 
23
 
24
+ MAX_GROUND_SAMPLES = 200_000 # sparse graphs: ground boundary samples kept (evenly subsampled)
25
+ _CTX: dict = {} # scene, samples and trees of the running sparse scene_graph, inherited by forked feature workers
26
+
27
+
28
+ def _workers(n: int) -> int:
29
+ from .mom import _prior_workers
30
+ return _prior_workers(n - 1)
31
+
32
+
33
+ def _feature_job(task):
34
+ from . import mom
35
+ mom.NUM_THREADS = 1 # one process per core: single-threaded k-d queries
36
+ c = _CTX
37
+ kind, items = task
38
+ if kind == "node":
39
+ return kind, [(i, node_features(c["scene"], i)) for i in items]
40
+ return kind, [((i, j), edge_features(c["scene"], i, j, c["bpts"], c["widths"], c["trees"])) for i, j in items]
41
+
42
+
43
+ def _parallel_features(scene, pairs, bpts, widths, trees, workers: int):
44
+ """node_features / edge_features of the sparse graph in `workers` forked processes; pairs are spread by cost
45
+ (boundary samples of both ends) so that the ground pairs do not land on one worker."""
46
+ from concurrent.futures import ProcessPoolExecutor
47
+ from multiprocessing import get_context
48
+
49
+ _CTX.clear()
50
+ _CTX.update(scene=scene, bpts=bpts, widths=widths, trees=trees)
51
+ cost = np.array([len(bpts[i]) + len(bpts[j]) for i, j in pairs], float)
52
+ order = np.argsort(-cost, kind="stable")
53
+ n_chunks = 8 * workers
54
+ chunks = [[pairs[k] for k in order[c::n_chunks]] for c in range(n_chunks)]
55
+ nchunks = [list(range(scene.n))[c::workers] for c in range(workers)]
56
+ tasks = [("node", c) for c in nchunks if c] + [("edge", c) for c in chunks if c]
57
+ nodes, edges = [None] * scene.n, {}
58
+ try:
59
+ with ProcessPoolExecutor(workers, mp_context=get_context("fork")) as ex:
60
+ for kind, res in ex.map(_feature_job, tasks):
61
+ for k, v in res:
62
+ if kind == "node":
63
+ nodes[k] = v
64
+ else:
65
+ edges[k] = v
66
+ finally:
67
+ _CTX.clear()
68
+ return nodes, {p: edges[p] for p in pairs}
69
+
70
+
71
+ def scene_graph(scene: Scene, prior_fn=None, edge_filter=None) -> dict:
72
+ """prior_fn(edges) -> CapacitanceMoM-style dict (see prior_dict), or None for the geometry-only network.
73
+ edge_filter(i, j) -> bool (large layouts, PRIOR_SCHEME.md Part III): only those pairs become edges (the O(N^2) pair
74
+ tokens are the cost on chips with hundreds of conductors); ground samples subsampled to MAX_GROUND_SAMPLES and one
75
+ k-d tree per conductor. None: every pair (the training graphs)."""
76
+ from scipy.spatial import cKDTree
77
+
78
+ sparse = edge_filter is not None
79
+ bpts, widths = boundary_points(scene, MAX_GROUND_SAMPLES if sparse else None)
80
+ trees = {i: cKDTree(p) for i, p in bpts.items()} if sparse else None
81
+ pairs = [(i, j) for i, j in combinations(range(scene.n), 2) if not sparse or edge_filter(i, j)]
82
+ w = _workers(scene.n) if sparse else 1
83
+ if w > 1: # large layouts: node and pair features on forked worker processes (same functions, same numbers)
84
+ nodes, edges = _parallel_features(scene, pairs, bpts, widths, trees, w)
85
+ else:
86
+ nodes = [node_features(scene, i) for i in range(scene.n)]
87
+ edges = {(i, j): edge_features(scene, i, j, bpts, widths, trees) for i, j in pairs}
88
  # shielding: share of each endpoint's total geometric coupling carried by this edge
89
  tot = np.zeros(scene.n)
90
  for (i, j), f in edges.items():
tlsq_infer/_vendor/mom.py CHANGED
@@ -900,11 +900,57 @@ def mom_solve_flagship(metals: list, eps_r: float = 11.45, cells_per_gap: float
900
  return {"C": C, "n_cells": n, "h_min": h, "mesh": rep}
901
 
902
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
903
  def solve_prior(metals: list, mesh: str = "v2", **kw):
904
  """Dispatch: mesh "v2" -> mom_solve (published priors, unchanged), "v3" / "v3-rich" -> mom_solve_v3, "flagship" ->
905
- mom_solve_flagship (strip-merged Richardson, resolution-controlled)."""
 
906
  if mesh == "v2":
907
  return mom_solve(metals, **kw)
908
  if mesh == "flagship":
909
  return mom_solve_flagship(metals, **kw)
 
 
 
 
910
  return mom_solve_v3(metals, rich=(mesh == "v3-rich"), **kw)
 
900
  return {"C": C, "n_cells": n, "h_min": h, "mesh": rep}
901
 
902
 
903
+ def _prior_workers(n_conductors: int) -> int:
904
+ """Worker processes for the windows / rows of the cheap priors on large layouts: TLSQ_PRIOR_WORKERS, else the
905
+ configured thread count; components (one window) never start a pool."""
906
+ if n_conductors <= 8:
907
+ return 1
908
+ return max(1, int(os.environ.get("TLSQ_PRIOR_WORKERS", 0)) or _nthreads())
909
+
910
+
911
+ def mom_solve_lite(metals: list, eps_r: float = 11.45, max_cells: int = 1500, cells_per_gap: float = 3.0, workers: int | None = None):
912
+ """flagship-fast micro-MoM prior (tlsq.embed.fastprior.micro_mom; PRIOR_SCHEME.md Part III): dict(C, n_cells, h_min,
913
+ mesh, far_mask). The mesh report carries panels per gap but no `cells_per_min_gap`: the lite networks are trained on
914
+ priors at this resolution, so the 0.75-panels-per-gap regime flag of the v3 tiers does not apply."""
915
+ from .fastprior import micro_mom
916
+
917
+ t0 = time.perf_counter()
918
+ w = _prior_workers(len(metals) - 1) if workers is None else workers
919
+ C, far, info = micro_mom(metals[0], list(metals[1:]), eps_r, budget=max_cells, cells_per_gap=cells_per_gap, workers=w)
920
+ _tick("lite", t0)
921
+ for k in ("mesh_s", "assemble_s", "solve_s", "build_s", "formula_s"):
922
+ with _LOCK:
923
+ STAGE_TIMES[f"lite_{k}"] = STAGE_TIMES.get(f"lite_{k}", 0.0) + float(info[k])
924
+ rep = {"prior": "lite", "h_min_um": float(min(info["h_um"])), "min_gap_um": float(info["min_gap_um"]), "max_cells": int(max_cells),
925
+ "panels_per_gap_min": float(min(info["panels_per_gap"])), "panels_per_gap_median": float(np.median(info["panels_per_gap"])),
926
+ "n_windows": int(info["n_windows"]), "panels": [int(x) for x in info["panels"]], "n_far_pairs": int(info["n_far_pairs"]),
927
+ "workers": int(w), "cap_hit": False, "merged": True, "solver": "dense (lite)"}
928
+ return {"C": C, "n_cells": int(sum(info["panels"])), "h_min": float(min(info["h_um"])), "mesh": rep, "far_mask": far}
929
+
930
+
931
+ def mom_solve_formula(metals: list, eps_r: float = 11.45, workers: int | None = None):
932
+ """flagship-fast closed-form prior (tlsq.embed.fastprior.formula_prior): dict(C, n_cells=0, h_min=smallest gap, mesh)."""
933
+ from .fastprior import formula_prior
934
+
935
+ t0 = time.perf_counter()
936
+ w = _prior_workers(len(metals) - 1) if workers is None else workers
937
+ C, info = formula_prior(metals[0], list(metals[1:]), eps_r, workers=w)
938
+ _tick("formula", t0)
939
+ rep = {"prior": "formula", "min_gap_um": float(info["min_gap_um"]), "step_um": float(info["step_um"]), "samples": int(info["samples"]),
940
+ "n_bbox_pairs": int(info["n_bbox_pairs"]), "workers": int(w), "cap_hit": False, "solver": "closed form"}
941
+ return {"C": C, "n_cells": 0, "h_min": float(info["min_gap_um"]), "mesh": rep, "far_mask": np.zeros(C.shape, bool)}
942
+
943
+
944
  def solve_prior(metals: list, mesh: str = "v2", **kw):
945
  """Dispatch: mesh "v2" -> mom_solve (published priors, unchanged), "v3" / "v3-rich" -> mom_solve_v3, "flagship" ->
946
+ mom_solve_flagship (strip-merged Richardson, resolution-controlled), "lite" / "formula" -> the flagship-fast cheap
947
+ priors (mom_solve_lite / mom_solve_formula)."""
948
  if mesh == "v2":
949
  return mom_solve(metals, **kw)
950
  if mesh == "flagship":
951
  return mom_solve_flagship(metals, **kw)
952
+ if mesh == "lite":
953
+ return mom_solve_lite(metals, **kw)
954
+ if mesh == "formula":
955
+ return mom_solve_formula(metals, **kw)
956
  return mom_solve_v3(metals, rich=(mesh == "v3-rich"), **kw)
tlsq_infer/app_ui.py CHANGED
@@ -5,7 +5,7 @@ API endpoints (gradio_client, api_name):
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); model = "coarse" (default; alias "fast") / "fine" (alias "accurate") or an explicit registry name
9
  -> result dict (one call, for scripts; see examples/client.py)
10
  """
11
 
@@ -26,7 +26,8 @@ from .predict import intervals_csv, matrix_csv, predict
26
  from .registry import load_registry
27
 
28
  LIMITS = {"max_file_mb": float(os.environ.get("TLSQ_MAX_FILE_MB", 25)), "max_polygons": int(os.environ.get("TLSQ_MAX_POLYGONS", 200_000)),
29
- "max_conductors": 30}
 
30
  CUSTOM = "custom eps_r"
31
  # flagship-prior solves (fine tier, and coarse-tier layouts routed to it) can take tens of seconds and several GB on large
32
  # layouts: at most TLSQ_HEAVY_CONCURRENCY of them at once; other requests are not blocked
@@ -39,6 +40,10 @@ def _predict(lay, model, **kw):
39
  reg = load_registry()
40
  name = resolve_model(reg, model or None)
41
  prior = str(reg.model(name).get("prior", ""))
 
 
 
 
42
  heavy = prior.startswith("flagship")
43
  if not heavy and large_layout_model(reg, name):
44
  heavy = would_hit_cap([lay.ground] + list(lay.conductors), prior)[0]
@@ -131,7 +136,7 @@ def _prepare(f, table, margin_gaps, margin_um, select):
131
  g, c, i = _roles(table)
132
  mu = float(margin_um) if margin_um not in (None, "", 0, 0.0) else None
133
  return prepare(_path(f), ground_layers=g, conductor_layers=c, ignore_layers=i, margin_gaps=_margin(margin_gaps), margin_um=mu,
134
- select=_parse_select(select))
135
 
136
 
137
  def prepare_fn(f, table, margin_gaps, margin_um, select):
@@ -246,7 +251,7 @@ def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps
246
  custom_eps=11.45, thickness_um=350.0, model="", self_from_rows=False):
247
  t = time.perf_counter()
248
  lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers),
249
- margin_gaps=_margin(margin_gaps))
250
  res = _predict(lay, model, substrate=_eps(substrate, custom_eps), thickness_um=float(thickness_um),
251
  self_from_rows=bool(self_from_rows))
252
  res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t
@@ -297,21 +302,24 @@ def _model_md(reg, k):
297
 
298
 
299
  def tier_choices(reg) -> list[tuple[str, str]]:
300
- """Flagship model choice: [("Coarse prior (fastest, default, ~X s) ...", "coarse"), ("Fine prior (most accurate, ~Y s) ...", "fine")]
301
- with the measured latency and held-out accuracy from registry defaults.tiers; the fine entry only when one is configured."""
 
 
 
302
  d = reg["defaults"]
303
  info = d.get("tiers", {})
 
304
  out = []
305
- for tier, key in (("coarse", "flagship_model"), ("fine", "flagship_accurate_model")):
306
- name = d.get(key)
307
- if not name:
308
  continue
309
  t = info.get(tier, {})
310
- lat = f", ~{t['latency_s']:.0f} s" if t.get("latency_s") is not None else ""
 
311
  acc = (f" — held-out median {t['median_pct']:.2f} %, MAE {t['mae_ff']:.2f} fF, RMSE {t['rmse_ff']:.2f} fF"
312
  if t.get("median_pct") is not None else "")
313
- label = ("Coarse prior (fastest, default" + lat + ")" if tier == "coarse" else "Fine prior (most accurate" + lat + ")") + acc
314
- out.append((label, tier))
315
  return out
316
 
317
 
@@ -374,13 +382,13 @@ def build_app(title: str, model_choices: list[str], default_model: str, header_m
374
  substrate = gr.Dropdown(subs, value=subs[0], label="substrate")
375
  custom_eps = gr.Number(value=11.45, label="custom eps_r (when 'custom')")
376
  thickness = gr.Number(value=350, label="substrate thickness (µm)")
377
- if tiers: # flagship: coarse (default) / fine prior choice instead of a model list
378
- model = gr.Radio(tier_choices(reg), value="coarse", label="model")
379
  elif not top_pick:
380
  model = gr.Dropdown(model_choices, value=default_model, label="model")
381
  self_rows = gr.Checkbox(False, label="self-capacitance from row sums")
382
  if tiers:
383
- tier_info = gr.Markdown(_tier_md(reg, "coarse"))
384
  model.change(lambda k: _tier_md(reg, k), model, tier_info, api_visibility="private")
385
  pred_btn = gr.Button("Predict", variant="primary")
386
  gr.Markdown("## 4. Maxwell capacitance matrix (fF)")
@@ -425,5 +433,6 @@ def build_app(title: str, model_choices: list[str], default_model: str, header_m
425
  a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model, self_rows], a_out,
426
  api_name="predict_gds")
427
  gr.Markdown(f"<small>tlsq_infer {__version__}. Demo-server caps (not limits of the models): {LIMITS['max_file_mb']:g} MB per file, "
428
- f"{LIMITS['max_polygons']:,} polygons, {LIMITS['max_conductors']} conductors + ground.</small>")
 
429
  return demo
 
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); model = "fast" (default, flagship-fast) / "coarse" / "fine" (alias "accurate") or an explicit registry name
9
  -> result dict (one call, for scripts; see examples/client.py)
10
  """
11
 
 
26
  from .registry import load_registry
27
 
28
  LIMITS = {"max_file_mb": float(os.environ.get("TLSQ_MAX_FILE_MB", 25)), "max_polygons": int(os.environ.get("TLSQ_MAX_POLYGONS", 200_000)),
29
+ "max_conductors": int(os.environ.get("TLSQ_MAX_CONDUCTORS", 1000)),
30
+ "max_conductors_heavy": int(os.environ.get("TLSQ_MAX_CONDUCTORS_HEAVY", 30))} # coarse / fine tiers (MoM cost); fast tier up to max_conductors
31
  CUSTOM = "custom eps_r"
32
  # flagship-prior solves (fine tier, and coarse-tier layouts routed to it) can take tens of seconds and several GB on large
33
  # layouts: at most TLSQ_HEAVY_CONCURRENCY of them at once; other requests are not blocked
 
40
  reg = load_registry()
41
  name = resolve_model(reg, model or None)
42
  prior = str(reg.model(name).get("prior", ""))
43
+ if prior not in ("lite500", "lite1500", "formula") and lay.n_conductors > LIMITS["max_conductors_heavy"]:
44
+ raise LayoutError(f"{lay.n_conductors} conductors: the coarse and fine tiers are capped at {LIMITS['max_conductors_heavy']} on "
45
+ "this server (their physics prior grows with the chip); use the fast tier (default), which handles "
46
+ "multi-qubit chips")
47
  heavy = prior.startswith("flagship")
48
  if not heavy and large_layout_model(reg, name):
49
  heavy = would_hit_cap([lay.ground] + list(lay.conductors), prior)[0]
 
136
  g, c, i = _roles(table)
137
  mu = float(margin_um) if margin_um not in (None, "", 0, 0.0) else None
138
  return prepare(_path(f), ground_layers=g, conductor_layers=c, ignore_layers=i, margin_gaps=_margin(margin_gaps), margin_um=mu,
139
+ select=_parse_select(select), max_conductors=LIMITS["max_conductors"])
140
 
141
 
142
  def prepare_fn(f, table, margin_gaps, margin_um, select):
 
251
  custom_eps=11.45, thickness_um=350.0, model="", self_from_rows=False):
252
  t = time.perf_counter()
253
  lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers),
254
+ margin_gaps=_margin(margin_gaps), max_conductors=LIMITS["max_conductors"])
255
  res = _predict(lay, model, substrate=_eps(substrate, custom_eps), thickness_um=float(thickness_um),
256
  self_from_rows=bool(self_from_rows))
257
  res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t
 
302
 
303
 
304
  def tier_choices(reg) -> list[tuple[str, str]]:
305
+ """Flagship model choice: [("Fast: flagship-fast (default, ~X s) ...", "fast"), ("Coarse prior (~Y s) ...", "coarse"),
306
+ ("Fine prior (most accurate, ~Z s) ...", "fine")] with the measured latency and held-out accuracy from registry
307
+ defaults.tiers; a tier only when its model is configured."""
308
+ from .predict import TIER_KEYS
309
+
310
  d = reg["defaults"]
311
  info = d.get("tiers", {})
312
+ labels = {"fast": "Fast: flagship-fast (default", "coarse": "Coarse prior (", "fine": "Fine prior (most accurate"}
313
  out = []
314
+ for tier in ("fast", "coarse", "fine"):
315
+ if not d.get(TIER_KEYS[tier]):
 
316
  continue
317
  t = info.get(tier, {})
318
+ lat = f"~{t['latency_s']:.0f} s" if t.get("latency_s") is not None else ""
319
+ lab = labels[tier] + ((", " if not labels[tier].endswith("(") else "") + lat if lat else "") + ")"
320
  acc = (f" — held-out median {t['median_pct']:.2f} %, MAE {t['mae_ff']:.2f} fF, RMSE {t['rmse_ff']:.2f} fF"
321
  if t.get("median_pct") is not None else "")
322
+ out.append((lab.replace("()", "") + acc, tier))
 
323
  return out
324
 
325
 
 
382
  substrate = gr.Dropdown(subs, value=subs[0], label="substrate")
383
  custom_eps = gr.Number(value=11.45, label="custom eps_r (when 'custom')")
384
  thickness = gr.Number(value=350, label="substrate thickness (µm)")
385
+ if tiers: # flagship: fast (default) / coarse / fine tier choice instead of a model list
386
+ model = gr.Radio(tier_choices(reg), value="fast", label="model")
387
  elif not top_pick:
388
  model = gr.Dropdown(model_choices, value=default_model, label="model")
389
  self_rows = gr.Checkbox(False, label="self-capacitance from row sums")
390
  if tiers:
391
+ tier_info = gr.Markdown(_tier_md(reg, "fast"))
392
  model.change(lambda k: _tier_md(reg, k), model, tier_info, api_visibility="private")
393
  pred_btn = gr.Button("Predict", variant="primary")
394
  gr.Markdown("## 4. Maxwell capacitance matrix (fF)")
 
433
  a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model, self_rows], a_out,
434
  api_name="predict_gds")
435
  gr.Markdown(f"<small>tlsq_infer {__version__}. Demo-server caps (not limits of the models): {LIMITS['max_file_mb']:g} MB per file, "
436
+ f"{LIMITS['max_polygons']:,} polygons, {LIMITS['max_conductors']} conductors + ground on the fast tier "
437
+ f"({LIMITS['max_conductors_heavy']} on the coarse / fine tiers).</small>")
438
  return demo
tlsq_infer/predict.py CHANGED
@@ -55,9 +55,11 @@ def _logC(C: np.ndarray) -> np.ndarray:
55
  return out
56
 
57
 
58
- TIERS = ("coarse", "fine") # physics-prior tiers: coarse = one gap/3 solve (default), fine = gap/3 + gap/6 with Richardson extrapolation
59
- TIER_ALIASES = {"fast": "coarse", "accurate": "fine"} # names used before 2026-10-09, kept for existing scripts
60
- TIER_KEYS = {"coarse": "flagship_model", "fine": "flagship_accurate_model"}
 
 
61
  REGIME_MIN_CELLS_PER_GAP = 0.75 # training-family priors sit at 0.75-3 panels across the smallest gap (GRID_SCALING.md section 2)
62
  LARGE_LAYOUT_MODEL_KEY = "large_layout_model" # registry defaults: model (flagship prior) that large layouts are routed to
63
 
@@ -72,6 +74,8 @@ def large_layout_model(reg, model: str) -> str | None:
72
  fb = reg["defaults"].get(LARGE_LAYOUT_MODEL_KEY)
73
  if not fb or fb == model or fb not in reg.models:
74
  return None
 
 
75
  if str(reg.model(model).get("prior", "")).startswith("flagship"):
76
  return None
77
  return fb
@@ -99,25 +103,45 @@ def would_hit_cap(metals: list, prior: str) -> tuple[bool, float]:
99
 
100
 
101
  def tier_of(model: str | None) -> str | None:
102
- """Tier name ("coarse" / "fine") of a model argument, or None for an explicit registry name."""
 
103
  if not model:
104
- return "coarse"
105
- key = str(model).lower()
106
- key = TIER_ALIASES.get(key, key)
107
- return key if key in TIERS else None
108
 
109
 
110
  def resolve_model(reg, model: str | None) -> str:
111
- """Model name from an explicit registry name or a tier: "coarse" (default; alias "fast") / "fine" (alias "accurate")."""
 
112
  tier = tier_of(model)
113
  if tier is None:
114
  return model
115
  name = reg["defaults"].get(TIER_KEYS[tier])
116
  if not name:
117
- raise ValueError(f"no {tier}-tier model is configured (defaults.{TIER_KEYS[tier]}); use 'coarse'")
118
  return name
119
 
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  def run_pipeline(metals: list, names: list[str], model: str, reg=None, model_dir=None, timing=None,
122
  blend_kinds: str | None = None) -> tuple[np.ndarray, dict]:
123
  """Core: log|C| matrix (diag: log C_ii, off-diag: log -C_ij) on the training stack, in `metals` order (0 = ground)."""
@@ -148,7 +172,8 @@ def run_pipeline(metals: list, names: list[str], model: str, reg=None, model_dir
148
  t = time.perf_counter()
149
  sc = make_scene(metals[0], metals[1:], names[1:])
150
  prior_fn = (lambda edges: prior_dict(mom["C"], mom["n_cells"], mom["h_min"], edges)) if mom is not None else None
151
- g = scene_graph(sc, prior_fn)
 
152
  g["target"] = np.ones((len(metals), len(metals)))
153
  timing["features_s"] = time.perf_counter() - t
154
  t = time.perf_counter()
@@ -157,6 +182,9 @@ def run_pipeline(metals: list, names: list[str], model: str, reg=None, model_dir
157
  t = time.perf_counter()
158
  seeds = ens.member_outputs([g], proxy_key="proxy_log_C" if mom is not None else None)[:, 0, : len(metals), : len(metals)]
159
  out_gnn = np.mean(seeds, 0)
 
 
 
160
  timing["network_s"] = time.perf_counter() - t
161
  debug["seed_logC"] = seeds
162
  debug["graph"] = g
@@ -194,8 +222,8 @@ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (c
194
  row_sum_eps: float | None = None, blend_kinds: str | None = None, large_layouts: str = "route") -> dict:
195
  """Maxwell capacitance matrix (fF) of a prepared layout.
196
 
197
- model: a deployable registry name, or a tier: "coarse" (default: defaults.flagship_model; alias "fast") / "fine"
198
- (defaults.flagship_accurate_model; alias "accurate"). substrate: a registry substrate name or eps_r.
199
  The networks always see the training stack (Si 11.45, 350 µm); other permittivities are handled by the validated
200
  half-space factor (1 + eps) / (1 + 11.45), and thickness / material residuals are reported in `expected_error`.
201
  The ground self-capacitance is not predicted (it depends on the chip boundary, excluded from training): NaN.
@@ -319,6 +347,11 @@ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (c
319
  "tier (`all-data-flagship`: resolution-controlled prior) or a smaller selection of conductors.")
320
  out["warnings"] += msg
321
  exp_err["mesh_warning"] = "; ".join(msg) if msg else None
 
 
 
 
 
322
  if routed_note:
323
  out["model_used"] = model
324
  out["warnings"].insert(0, routed_note)
 
55
  return out
56
 
57
 
58
+ TIERS = ("fast", "coarse", "fine") # released tiers (2026-10-10): fast = flagship-fast (cheap micro-MoM prior, default), coarse = one
59
+ # gap/3 conductor-anchored solve, fine = flagship prior (Richardson gap/6 + gap/3)
60
+ TIER_ALIASES = {"fast": "fast", "coarse": "coarse", "fine": "fine", "accurate": "fine", "flagship-fast": "fast", "default": "fast"}
61
+ TIER_KEYS = {"fast": "flagship_model", "coarse": "coarse_model", "fine": "flagship_accurate_model"}
62
+ CHEAP_PRIORS = ("lite500", "lite1500", "formula") # flagship-fast priors: windowed, cost bounded per conductor, never re-routed
63
  REGIME_MIN_CELLS_PER_GAP = 0.75 # training-family priors sit at 0.75-3 panels across the smallest gap (GRID_SCALING.md section 2)
64
  LARGE_LAYOUT_MODEL_KEY = "large_layout_model" # registry defaults: model (flagship prior) that large layouts are routed to
65
 
 
74
  fb = reg["defaults"].get(LARGE_LAYOUT_MODEL_KEY)
75
  if not fb or fb == model or fb not in reg.models:
76
  return None
77
+ if str(reg.model(model).get("prior", "")) in CHEAP_PRIORS: # flagship-fast handles large layouts itself
78
+ return None
79
  if str(reg.model(model).get("prior", "")).startswith("flagship"):
80
  return None
81
  return fb
 
103
 
104
 
105
  def tier_of(model: str | None) -> str | None:
106
+ """Tier name ("fast" / "coarse" / "fine") of a model argument (None or "" -> "fast", the default), or None for an
107
+ explicit registry name."""
108
  if not model:
109
+ return "fast"
110
+ return TIER_ALIASES.get(str(model).lower())
 
 
111
 
112
 
113
  def resolve_model(reg, model: str | None) -> str:
114
+ """Model name from an explicit registry name or a tier: "fast" (default: flagship-fast), "coarse", "fine" (alias
115
+ "accurate")."""
116
  tier = tier_of(model)
117
  if tier is None:
118
  return model
119
  name = reg["defaults"].get(TIER_KEYS[tier])
120
  if not name:
121
+ raise ValueError(f"no {tier}-tier model is configured (defaults.{TIER_KEYS[tier]}); use 'fast'")
122
  return name
123
 
124
 
125
+ SPARSE_MIN_CONDUCTORS = 8 # more signal conductors than this: pair tokens only for pairs within SPARSE_R_GAPS (and ground)
126
+ SPARSE_R_GAPS = 150.0
127
+
128
+
129
+ def far_pairs(metals: list) -> np.ndarray:
130
+ """(N, N) mask of the conductor pairs farther apart than SPARSE_R_GAPS smallest gaps (never the ground): not given
131
+ pair tokens on large layouts; their entries are the prior's (PRIOR_SCHEME.md Part III section 16)."""
132
+ import shapely
133
+
134
+ from ._vendor.fastprior import gap_of
135
+
136
+ conds = list(metals[1:])
137
+ a, b = shapely.STRtree(conds).query(conds, predicate="dwithin", distance=SPARSE_R_GAPS * gap_of(list(metals)))
138
+ far = np.ones((len(metals), len(metals)), bool)
139
+ far[a + 1, b + 1] = False
140
+ far[0, :] = far[:, 0] = False
141
+ np.fill_diagonal(far, False)
142
+ return far
143
+
144
+
145
  def run_pipeline(metals: list, names: list[str], model: str, reg=None, model_dir=None, timing=None,
146
  blend_kinds: str | None = None) -> tuple[np.ndarray, dict]:
147
  """Core: log|C| matrix (diag: log C_ii, off-diag: log -C_ij) on the training stack, in `metals` order (0 = ground)."""
 
172
  t = time.perf_counter()
173
  sc = make_scene(metals[0], metals[1:], names[1:])
174
  prior_fn = (lambda edges: prior_dict(mom["C"], mom["n_cells"], mom["h_min"], edges)) if mom is not None else None
175
+ far = far_pairs(metals) if mom is not None and len(metals) - 1 > SPARSE_MIN_CONDUCTORS else None
176
+ g = scene_graph(sc, prior_fn, None if far is None else (lambda i, j: not far[i, j]))
177
  g["target"] = np.ones((len(metals), len(metals)))
178
  timing["features_s"] = time.perf_counter() - t
179
  t = time.perf_counter()
 
182
  t = time.perf_counter()
183
  seeds = ens.member_outputs([g], proxy_key="proxy_log_C" if mom is not None else None)[:, 0, : len(metals), : len(metals)]
184
  out_gnn = np.mean(seeds, 0)
185
+ if far is not None and far.any(): # pairs outside the graph: the prior's value (flagged in far_mask)
186
+ out_gnn[far] = _logC(mom["C"])[far]
187
+ debug["far_mask"] = far
188
  timing["network_s"] = time.perf_counter() - t
189
  debug["seed_logC"] = seeds
190
  debug["graph"] = g
 
222
  row_sum_eps: float | None = None, blend_kinds: str | None = None, large_layouts: str = "route") -> dict:
223
  """Maxwell capacitance matrix (fF) of a prepared layout.
224
 
225
+ model: a deployable registry name, or a tier: "fast" (default: defaults.flagship_model, flagship-fast), "coarse"
226
+ (defaults.coarse_model) or "fine" (defaults.flagship_accurate_model; alias "accurate"). substrate: a registry substrate name or eps_r.
227
  The networks always see the training stack (Si 11.45, 350 µm); other permittivities are handled by the validated
228
  half-space factor (1 + eps) / (1 + 11.45), and thickness / material residuals are reported in `expected_error`.
229
  The ground self-capacitance is not predicted (it depends on the chip boundary, excluded from training): NaN.
 
347
  "tier (`all-data-flagship`: resolution-controlled prior) or a smaller selection of conductors.")
348
  out["warnings"] += msg
349
  exp_err["mesh_warning"] = "; ".join(msg) if msg else None
350
+ fm = debug.get("far_mask")
351
+ if fm is not None:
352
+ out["far_mask"] = fm.tolist()
353
+ out["warnings"].append(f"{int(np.triu(fm, 1).sum())} conductor pairs farther apart than {SPARSE_R_GAPS:g} smallest gaps are "
354
+ "not in the network graph (large layout): their entries are the physics prior's (far_mask)")
355
  if routed_note:
356
  out["model_used"] = model
357
  out["warnings"].insert(0, routed_note)
tlsq_infer/registry.py CHANGED
@@ -17,7 +17,11 @@ PRIORS = {"standard": dict(max_cells=8000, cells_per_gap=3.0), "fine": dict(max_
17
  # flagship: strip-merged conductor-anchored mesh, Richardson between gap/(2 cpg) and gap/cpg, H-matrix solve for
18
  # large systems; max_cells is a safety cap on the merged panels (PRIOR_SCHEME.md section 6)
19
  "flagship": dict(mesh="flagship", max_cells=250000, cells_per_gap=3.0),
20
- "flagship-coarse": dict(mesh="flagship", max_cells=250000, cells_per_gap=1.5)}
 
 
 
 
21
 
22
 
23
  def find_registry(path=None) -> Path:
 
17
  # flagship: strip-merged conductor-anchored mesh, Richardson between gap/(2 cpg) and gap/cpg, H-matrix solve for
18
  # large systems; max_cells is a safety cap on the merged panels (PRIOR_SCHEME.md section 6)
19
  "flagship": dict(mesh="flagship", max_cells=250000, cells_per_gap=3.0),
20
+ "flagship-coarse": dict(mesh="flagship", max_cells=250000, cells_per_gap=1.5),
21
+ # flagship-fast cheap priors (PRIOR_SCHEME.md Part III): micro-MoM at a merged-panel budget (one window up to 8
22
+ # conductors, core-graded windows beyond) and the closed-form edge-coupling prior
23
+ "lite500": dict(mesh="lite", max_cells=500, cells_per_gap=3.0), "lite1500": dict(mesh="lite", max_cells=1500, cells_per_gap=3.0),
24
+ "formula": dict(mesh="formula")}
25
 
26
 
27
  def find_registry(path=None) -> Path: