sync from registry v1
Browse files- README.md +1 -0
- models/all-data-flagship/config.json +1 -0
- models/all-data-flagship/seed0.pt +3 -0
- models/all-data-flagship/seed1.pt +3 -0
- models/all-data-flagship/seed2.pt +3 -0
- registry.yaml +73 -6
- tlsq_infer/__init__.py +2 -2
- tlsq_infer/__pycache__/__init__.cpython-312.pyc +0 -0
- tlsq_infer/__pycache__/charge.cpython-312.pyc +0 -0
- tlsq_infer/__pycache__/errmodel.cpython-312.pyc +0 -0
- tlsq_infer/__pycache__/layout.cpython-312.pyc +0 -0
- tlsq_infer/__pycache__/predict.cpython-312.pyc +0 -0
- tlsq_infer/__pycache__/registry.cpython-312.pyc +0 -0
- tlsq_infer/__pycache__/stack_error.cpython-312.pyc +0 -0
- tlsq_infer/_vendor/__pycache__/__init__.cpython-312.pyc +0 -0
- tlsq_infer/_vendor/__pycache__/blocks.cpython-312.pyc +0 -0
- tlsq_infer/_vendor/__pycache__/geometry.cpython-312.pyc +0 -0
- tlsq_infer/_vendor/__pycache__/gnn.cpython-312.pyc +0 -0
- tlsq_infer/_vendor/__pycache__/graph.cpython-312.pyc +0 -0
- tlsq_infer/_vendor/__pycache__/mom.cpython-312.pyc +0 -0
- tlsq_infer/_vendor/__pycache__/scene.cpython-312.pyc +0 -0
- tlsq_infer/_vendor/mom.py +346 -1
- tlsq_infer/app_ui.py +22 -3
- tlsq_infer/predict.py +85 -3
- tlsq_infer/registry.py +5 -1
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-pair-local-fast
|
| 26 |
- SQuADDS/2026PaperModels-message-passing-fast
|
| 27 |
- SQuADDS/2026PaperModels-pair-local-accurate
|
|
|
|
| 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
|
| 28 |
- SQuADDS/2026PaperModels-pair-local-accurate
|
models/all-data-flagship/config.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"name": "all-data-flagship", "files": ["seed0.pt", "seed1.pt", "seed2.pt"]}
|
models/all-data-flagship/seed0.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e3305b5d522abccc52c31b46f13cf424be197aa7fcfbd1d9a70bb9ea3d7c8ce9
|
| 3 |
+
size 848449
|
models/all-data-flagship/seed1.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cecfb8d90711dbd0d37446f1dcff7154443fe487d45a3bd9af99ba686e6c4f31
|
| 3 |
+
size 848449
|
models/all-data-flagship/seed2.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4bbcfc763a63eeb8dd3f781051a359cd78f2cf8ef7b54818067f9f9d75788269
|
| 3 |
+
size 848449
|
registry.yaml
CHANGED
|
@@ -14,8 +14,8 @@ hub:
|
|
| 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" here = the default Space; the
|
| 18 |
-
#
|
| 19 |
flagship_title: Planar Capacitance Model
|
| 20 |
paper_models_space: shanto268/2026PaperModels
|
| 21 |
paper_models_title: 2026 Paper Models
|
|
@@ -84,14 +84,19 @@ artifacts:
|
|
| 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-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
paper_space_model: pair-local-fast # this work's headline (paper abstract)
|
| 89 |
tiers: # shown in the flagship UI; keys = tier names (aliases fast -> coarse, accurate -> fine still accepted by predict);
|
| 90 |
# held-out = OOD-60 + pocket3 random-36 + Qiskit Metal new 116, pooled mutual entries
|
| 91 |
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)",
|
| 92 |
note: "On this free CPU Space: 2.5-6 s for single components (measured on the 4 examples, refactored code); very long interdigitated combs (hundreds of fingers) can take several minutes."}
|
| 93 |
-
fine: {latency_s:
|
| 94 |
-
|
| 95 |
|
| 96 |
models:
|
| 97 |
# ---------------------------------------------------------------- learned, released
|
|
@@ -295,7 +300,7 @@ models:
|
|
| 295 |
status: available
|
| 296 |
fallback: all-data
|
| 297 |
checkpoints: [data_local/mega/alldata/v3_r0_s0.pt, data_local/mega/alldata/v3_r0_s1.pt, data_local/mega/alldata/v3_r0_s2.pt]
|
| 298 |
-
summary: "
|
| 299 |
validation: {median_pct: 1.31, mae_ff: 0.403, rmse_ff: 0.877, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"}
|
| 300 |
paper:
|
| 301 |
appears_in: [tab:candidates, tab:wonky-shape-main]
|
|
@@ -307,6 +312,68 @@ models:
|
|
| 307 |
pocket3_biased20: {median_pct: 3.15, mae_ff: 0.536, rmse_ff: 1.017}
|
| 308 |
cost_s_per_design: {median: 12.8, p90: 33.3, max: 50.4, note: "end to end from the GDS, 2 threads, HPC node; stress layouts up to 293 s (400-finger comb)"}
|
| 309 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
# ---------------------------------------------------------------- this work: conductor-anchored v3 priors (paper_ml, 2026-10-08)
|
| 311 |
# coarse prior = v3s (one gap/3 solve; was "fast"), fine prior = v3-rich (gap/3 + gap/6, Richardson; was "accurate").
|
| 312 |
# Model ids and repo names keep the old words (*-fast, *-accurate): they are published links. Metrics: paper tab:candidates
|
|
|
|
| 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" here = the default Space; the tiers are "coarse" / "fine"; since
|
| 18 |
+
# 2026-10-10 the fine tier runs on the "flagship prior", PRIOR_SCHEME.md Part II)
|
| 19 |
flagship_title: Planar Capacitance Model
|
| 20 |
paper_models_space: shanto268/2026PaperModels
|
| 21 |
paper_models_title: 2026 Paper Models
|
|
|
|
| 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
|
| 90 |
+
# resolve < 0.75 panels across the smallest gap (outside the training regime; the grids of
|
| 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: 2.5-6 s for single components (measured on the 4 examples, refactored code); very long interdigitated combs (hundreds of fingers) can take several minutes."}
|
| 98 |
+
fine: {latency_s: 5, median_pct: 1.13, mae_ff: 0.374, rmse_ff: 0.836, set: "212 held-out designs (OOD-60, random TransmonPocket-3, 6 new Qiskit Metal classes)",
|
| 99 |
+
note: "Flagship prior: strip-merged Richardson (6 and 3 panels across the smallest gap on every layout), H-matrix solve for large systems. Mac, 2 threads: median 0.9 s, p90 11.6 s on the 212 held-out designs (p90 27.6 s over 1,158 incl. large shielded concentric components); this free CPU Space is slower. One fine-tier request runs at a time."}
|
| 100 |
|
| 101 |
models:
|
| 102 |
# ---------------------------------------------------------------- learned, released
|
|
|
|
| 300 |
status: available
|
| 301 |
fallback: all-data
|
| 302 |
checkpoints: [data_local/mega/alldata/v3_r0_s0.pt, data_local/mega/alldata/v3_r0_s1.pt, data_local/mega/alldata/v3_r0_s2.pt]
|
| 303 |
+
summary: "Fine tier until 2026-10-10 (now all-data-flagship: same weights, flagship prior). Trained on every labelled design on the Richardson-extrapolated v3 MoM prior (gap/3 + gap/6). Candidate V3R-PLall of deploy/MODEL_SELECTION.md."
|
| 304 |
validation: {median_pct: 1.31, mae_ff: 0.403, rmse_ff: 0.877, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"}
|
| 305 |
paper:
|
| 306 |
appears_in: [tab:candidates, tab:wonky-shape-main]
|
|
|
|
| 312 |
pocket3_biased20: {median_pct: 3.15, mae_ff: 0.536, rmse_ff: 1.017}
|
| 313 |
cost_s_per_design: {median: 12.8, p90: 33.3, max: 50.4, note: "end to end from the GDS, 2 threads, HPC node; stress layouts up to 293 s (400-finger comb)"}
|
| 314 |
|
| 315 |
+
all-data-lite500:
|
| 316 |
+
title: "All-data pair-local network retrained on the flagship-fast lite500 prior (R=0)"
|
| 317 |
+
kind: gnn
|
| 318 |
+
prior: lite500
|
| 319 |
+
rounds: 0
|
| 320 |
+
status: candidate
|
| 321 |
+
checkpoints: [data_local/mega/alldata/lite500_r0_s0.pt, data_local/mega/alldata/lite500_r0_s1.pt, data_local/mega/alldata/lite500_r0_s2.pt]
|
| 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)"
|
| 335 |
+
kind: gnn
|
| 336 |
+
prior: formula
|
| 337 |
+
rounds: 0
|
| 338 |
+
status: candidate
|
| 339 |
+
checkpoints: [data_local/mega/alldata/formula_r0_s0.pt, data_local/mega/alldata/formula_r0_s1.pt, data_local/mega/alldata/formula_r0_s2.pt]
|
| 340 |
+
summary: "flagship-fast candidate (PRIOR_SCHEME.md Part III): closed-form edge-coupling prior (no mesh); network retrained on every labelled design on this prior (HPC 10-10). Not deployable until the user decides."
|
| 341 |
+
|
| 342 |
+
# ---------------------------------------------------------------- flagship prior (PRIOR_SCHEME.md Part II, 2026-10-09): same
|
| 343 |
+
# network as all-data-v3-rich, fed with the strip-merged, resolution-controlled Richardson prior (H-matrix solver for large
|
| 344 |
+
# layouts). all-data-flagship = released fine tier since 2026-10-10 (user-approved; PRIOR_SCHEME.md section 8.1).
|
| 345 |
+
all-data-flagship:
|
| 346 |
+
title: "All-data pair-local network + fine prior (flagship: strip-merged Richardson gap/6 + gap/3, resolution-controlled, H-matrix solve; R=0)"
|
| 347 |
+
repo_id: SQuADDS/2026PaperModels-all-data-flagship
|
| 348 |
+
kind: gnn
|
| 349 |
+
prior: flagship
|
| 350 |
+
rounds: 0
|
| 351 |
+
status: available
|
| 352 |
+
checkpoints: [data_local/mega/alldata/v3_r0_s0.pt, data_local/mega/alldata/v3_r0_s1.pt, data_local/mega/alldata/v3_r0_s2.pt]
|
| 353 |
+
summary: "Deployed fine tier (most accurate) since 2026-10-10. The all-data-v3-rich network (unchanged weights, trained on every labelled design) with the flagship prior: 6 + 3 panels across the smallest gap on every layout, Richardson-extrapolated, dense Cholesky below 12k panels and an H-matrix / PCG solve above. Scale-invariant: the same resolution from one capacitor to a multi-qubit grid. Also the model that the coarse tier routes large layouts to."
|
| 354 |
+
validation: {median_pct: 1.13, mae_ff: 0.374, rmse_ff: 0.836, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md; PRIOR_SCHEME.md section 8.1)"}
|
| 355 |
+
paper:
|
| 356 |
+
appears_in: [tab:flagship, fig:flagship, tab:flagship-cost, sec:res-opt (released models)]
|
| 357 |
+
ood60: {median_pct: 0.60, mae_ff: 0.204, rmse_ff: 0.367, note: "OOD-60 not in training"}
|
| 358 |
+
heldout:
|
| 359 |
+
never_seen926_in_training: {median_pct: 0.50, mae_ff: 0.235, rmse_ff: 0.420, note: "the all-data network trained on these families: not zero-shot"}
|
| 360 |
+
ood60: {median_pct: 0.60, mae_ff: 0.204, rmse_ff: 0.367}
|
| 361 |
+
pocket3_random36: {median_pct: 1.29, mae_ff: 0.234, rmse_ff: 0.488}
|
| 362 |
+
qiskit_metal_new116: {median_pct: 1.28, mae_ff: 0.478, rmse_ff: 1.021}
|
| 363 |
+
pocket3_biased20: {median_pct: 2.51, mae_ff: 0.477, rmse_ff: 0.988}
|
| 364 |
+
cost_s_per_design: {median: 0.87, p90: 11.6, max: 14.0, note: "212 held-out designs, end to end from the GDS, 2 threads, Mac M5 Pro (PRIOR_SCHEME.md 8.1); 1,158 held-out designs incl. never-seen: median 1.51, p90 27.6, max 78.4 s; peak RSS <= 8.3 GB (grid_qubit_9, 220k panels)"}
|
| 365 |
+
all-data-flagship-coarse:
|
| 366 |
+
title: "All-data pair-local network + flagship-coarse prior (strip-merged Richardson gap/3 + 2 gap/3, resolution-controlled; R=0)"
|
| 367 |
+
repo_id: SQuADDS/2026PaperModels-all-data-v3-rich
|
| 368 |
+
kind: gnn
|
| 369 |
+
prior: flagship-coarse
|
| 370 |
+
rounds: 0
|
| 371 |
+
status: candidate
|
| 372 |
+
pending_reason: "not released: fails the PRIOR_SCHEME.md section 7 accuracy criterion on the in-family test split (section 8.1); evaluation candidate only"
|
| 373 |
+
checkpoints: [data_local/mega/alldata/v3_r0_s0.pt, data_local/mega/alldata/v3_r0_s1.pt, data_local/mega/alldata/v3_r0_s2.pt]
|
| 374 |
+
summary: "The fine-tier network (unchanged weights) with the cheaper flagship pair (3 + 1.5 panels across the smallest gap, Richardson-extrapolated)."
|
| 375 |
+
validation: {median_pct: 1.22, mae_ff: 0.418, rmse_ff: 0.908, set: "212 deploy held-out designs (PRIOR_SCHEME.md section 8.1)"}
|
| 376 |
+
|
| 377 |
# ---------------------------------------------------------------- this work: conductor-anchored v3 priors (paper_ml, 2026-10-08)
|
| 378 |
# coarse prior = v3s (one gap/3 solve; was "fast"), fine prior = v3-rich (gap/3 + gap/6, Richardson; was "accurate").
|
| 379 |
# Model ids and repo names keep the old words (*-fast, *-accurate): they are published links. Metrics: paper tab:candidates
|
tlsq_infer/__init__.py
CHANGED
|
@@ -16,7 +16,7 @@ __version__ = "0.1.0"
|
|
| 16 |
import os # noqa: E402
|
| 17 |
|
| 18 |
from .layout import LayoutError, PreparedLayout, load_gds, prepare # noqa: E402
|
| 19 |
-
from .predict import matrix_csv, predict # noqa: E402
|
| 20 |
from .registry import load_registry # noqa: E402
|
| 21 |
|
| 22 |
|
|
@@ -53,5 +53,5 @@ def set_num_threads(n: int | None = None) -> int:
|
|
| 53 |
if os.environ.get("TLSQ_NUM_THREADS"):
|
| 54 |
set_num_threads()
|
| 55 |
|
| 56 |
-
__all__ = ["LayoutError", "PreparedLayout", "available_cpus", "load_gds", "load_registry", "matrix_csv", "predict", "prepare",
|
| 57 |
"set_num_threads", "__version__"]
|
|
|
|
| 16 |
import os # noqa: E402
|
| 17 |
|
| 18 |
from .layout import LayoutError, PreparedLayout, load_gds, prepare # noqa: E402
|
| 19 |
+
from .predict import PriorError, matrix_csv, predict # noqa: E402
|
| 20 |
from .registry import load_registry # noqa: E402
|
| 21 |
|
| 22 |
|
|
|
|
| 53 |
if os.environ.get("TLSQ_NUM_THREADS"):
|
| 54 |
set_num_threads()
|
| 55 |
|
| 56 |
+
__all__ = ["LayoutError", "PreparedLayout", "PriorError", "available_cpus", "load_gds", "load_registry", "matrix_csv", "predict", "prepare",
|
| 57 |
"set_num_threads", "__version__"]
|
tlsq_infer/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (3.19 kB). View file
|
|
|
tlsq_infer/__pycache__/charge.cpython-312.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
tlsq_infer/__pycache__/errmodel.cpython-312.pyc
ADDED
|
Binary file (10 kB). View file
|
|
|
tlsq_infer/__pycache__/layout.cpython-312.pyc
ADDED
|
Binary file (29.5 kB). View file
|
|
|
tlsq_infer/__pycache__/predict.cpython-312.pyc
ADDED
|
Binary file (31.9 kB). View file
|
|
|
tlsq_infer/__pycache__/registry.cpython-312.pyc
ADDED
|
Binary file (13.5 kB). View file
|
|
|
tlsq_infer/__pycache__/stack_error.cpython-312.pyc
ADDED
|
Binary file (8.1 kB). View file
|
|
|
tlsq_infer/_vendor/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (199 Bytes). View file
|
|
|
tlsq_infer/_vendor/__pycache__/blocks.cpython-312.pyc
ADDED
|
Binary file (8.46 kB). View file
|
|
|
tlsq_infer/_vendor/__pycache__/geometry.cpython-312.pyc
ADDED
|
Binary file (6.49 kB). View file
|
|
|
tlsq_infer/_vendor/__pycache__/gnn.cpython-312.pyc
ADDED
|
Binary file (14.1 kB). View file
|
|
|
tlsq_infer/_vendor/__pycache__/graph.cpython-312.pyc
ADDED
|
Binary file (4.23 kB). View file
|
|
|
tlsq_infer/_vendor/__pycache__/mom.cpython-312.pyc
ADDED
|
Binary file (75.1 kB). View file
|
|
|
tlsq_infer/_vendor/__pycache__/scene.cpython-312.pyc
ADDED
|
Binary file (3.11 kB). View file
|
|
|
tlsq_infer/_vendor/mom.py
CHANGED
|
@@ -558,8 +558,353 @@ def mom_solve_v3(metals: list, eps_r: float = 11.45, max_cells: int = 8000, cell
|
|
| 558 |
"C_coarse": Cc} # gap/3 solve: prior-convergence feature of the error model (tlsq_infer.errmodel)
|
| 559 |
|
| 560 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
def solve_prior(metals: list, mesh: str = "v2", **kw):
|
| 562 |
-
"""Dispatch: mesh "v2" -> mom_solve (published priors, unchanged), "v3" / "v3-rich" -> mom_solve_v3
|
|
|
|
| 563 |
if mesh == "v2":
|
| 564 |
return mom_solve(metals, **kw)
|
|
|
|
|
|
|
| 565 |
return mom_solve_v3(metals, rich=(mesh == "v3-rich"), **kw)
|
|
|
|
| 558 |
"C_coarse": Cc} # gap/3 solve: prior-convergence feature of the error model (tlsq_infer.errmodel)
|
| 559 |
|
| 560 |
|
| 561 |
+
_mom_solve_exact_near = _solve_panels_exact # name used by the flagship block below (verbatim copy of tlsq.embed.proxy)
|
| 562 |
+
# ---------------------------------------------------------------- flagship prior: strip-merged mesh, H-matrix solve, Richardson
|
| 563 |
+
# Resolution-controlled (panels per gap, no small cap), the same conductor-anchored panels as v3 merged along straight
|
| 564 |
+
# edges, the exact rectangle potential for near pairs, and for large systems an H-matrix (ACA far field) with
|
| 565 |
+
# preconditioned CG instead of the dense Cholesky: O(n log n) time and memory.
|
| 566 |
+
|
| 567 |
+
DENSE_MAX = int(os.environ.get("TLSQ_MOM_DENSE_MAX", 12000)) # panels up to which the dense Cholesky is used (faster below this size)
|
| 568 |
+
HMAT = dict(leaf=128, eta=2.0, eps=1e-9, tol=1e-12, maxit=1000) # ACA block tolerance (relative Frobenius) and PCG residual
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def _segments(metals):
|
| 572 |
+
segs, verts = [], []
|
| 573 |
+
for g in metals:
|
| 574 |
+
for p in getattr(g, "geoms", [g]):
|
| 575 |
+
for ring in [p.exterior, *p.interiors]:
|
| 576 |
+
xy = np.asarray(ring.coords)
|
| 577 |
+
verts.append(xy[:-1])
|
| 578 |
+
segs.append(np.stack([xy[:-1], xy[1:]], 1))
|
| 579 |
+
S = np.concatenate(segs)
|
| 580 |
+
return shapely.linestrings(S), S, np.concatenate(verts)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def strip_merge(c, wh, o, metals, h_f, lmax_mult: float = 16.0, grade: float = 1.0):
|
| 584 |
+
"""Merge runs of equal-width panels along the direction of their nearest polygon edge (where the charge density is
|
| 585 |
+
translation-invariant) into panels of length <= lmax_mult * h_f and <= grade * distance to the nearest vertex;
|
| 586 |
+
the size across the edge is kept. Returns merged (centres, sizes, owners)."""
|
| 587 |
+
lines, S, verts = _segments(metals)
|
| 588 |
+
near = shapely.STRtree(lines).nearest(shapely.points(c))
|
| 589 |
+
d = S[near, 1] - S[near, 0]
|
| 590 |
+
horiz = np.abs(d[:, 0]) >= np.abs(d[:, 1])
|
| 591 |
+
dv, _ = cKDTree(verts).query(c, workers=-1)
|
| 592 |
+
allow = np.minimum(lmax_mult * h_f, grade * dv)
|
| 593 |
+
out_c, out_wh, out_o = [], [], []
|
| 594 |
+
for axis, mask in ((0, horiz), (1, ~horiz)):
|
| 595 |
+
if not mask.any():
|
| 596 |
+
continue
|
| 597 |
+
idx = np.nonzero(mask)[0]
|
| 598 |
+
other = 1 - axis
|
| 599 |
+
key = np.stack([o[idx], np.round(c[idx, other], 4), np.round(wh[idx, other], 4)], 1)
|
| 600 |
+
order = np.lexsort([c[idx, axis], key[:, 2], key[:, 1], key[:, 0]])
|
| 601 |
+
idx, key = idx[order], key[order]
|
| 602 |
+
same = np.all(key[1:] == key[:-1], 1)
|
| 603 |
+
lo, hi = c[idx, axis] - wh[idx, axis] / 2, c[idx, axis] + wh[idx, axis] / 2
|
| 604 |
+
adjacent = same & (np.abs(hi[:-1] - lo[1:]) < 1e-6)
|
| 605 |
+
start = 0
|
| 606 |
+
while start < len(idx):
|
| 607 |
+
end, length, cap = start, wh[idx[start], axis], allow[idx[start]]
|
| 608 |
+
while end + 1 < len(idx) and adjacent[end] and length + wh[idx[end + 1], axis] <= min(cap, allow[idx[end + 1]]):
|
| 609 |
+
end += 1
|
| 610 |
+
length += wh[idx[end], axis]
|
| 611 |
+
cap = min(cap, allow[idx[end]])
|
| 612 |
+
cc, ww = np.zeros(2), np.zeros(2)
|
| 613 |
+
cc[axis], cc[other] = 0.5 * (lo[start] + hi[end]), c[idx[start], other]
|
| 614 |
+
ww[axis], ww[other] = hi[end] - lo[start], wh[idx[start], other]
|
| 615 |
+
out_c.append(cc)
|
| 616 |
+
out_wh.append(ww)
|
| 617 |
+
out_o.append(o[idx[start]])
|
| 618 |
+
start = end + 1
|
| 619 |
+
return np.array(out_c), np.array(out_wh), np.array(out_o)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def mesh_flagship(metals: list, h: float, max_cells: int, grade: float = 2.0, lmax_mult: float = 16.0, merge_grade: float = 1.0,
|
| 623 |
+
majority: bool = False):
|
| 624 |
+
"""Strip-merged v3 mesh at finest panel h, doubled (same lattice) until the merged mesh has at most max_cells panels.
|
| 625 |
+
Returns (centres, sizes, owners, h, raw panel count)."""
|
| 626 |
+
while True:
|
| 627 |
+
raw = anchored_cells(metals, h, grade, majority=majority, limit=8 * max_cells)
|
| 628 |
+
if raw is not None:
|
| 629 |
+
c, wh, o = strip_merge(*raw, metals, h, lmax_mult, merge_grade)
|
| 630 |
+
if len(c) <= max_cells:
|
| 631 |
+
return c, wh, o, h, len(raw[0])
|
| 632 |
+
h *= 2.0
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
class _Kernel:
|
| 636 |
+
"""Entries of P / (4 pi eps0 eps_eff) in a permuted panel order: 1 / d for far pairs, the exact rectangle potential
|
| 637 |
+
for near pairs (d < 1.5 max side) and rect_self on the diagonal; near and diagonal corrections to 1 / d are held in
|
| 638 |
+
a CSR matrix so that any block is 1 / d + N[I, J] (the same numbers as `_assemble` with `rect_potential`)."""
|
| 639 |
+
|
| 640 |
+
def __init__(self, c, wh, eps_r, perm):
|
| 641 |
+
from scipy.sparse import csr_matrix
|
| 642 |
+
|
| 643 |
+
self.x, self.y = c[perm, 0].copy(), c[perm, 1].copy()
|
| 644 |
+
self.k = 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2
|
| 645 |
+
n = len(c)
|
| 646 |
+
ii, jj = _near_pairs(c, wh.max(1))
|
| 647 |
+
d = np.sqrt(((c[ii] - c[jj]) ** 2).sum(1))
|
| 648 |
+
near = 0.5 * (rect_potential(c[ii], c[jj], wh[jj]) + rect_potential(c[jj], c[ii], wh[ii])) - 1.0 / d
|
| 649 |
+
inv = np.empty(n, np.int64)
|
| 650 |
+
inv[perm] = np.arange(n)
|
| 651 |
+
rows = inv[np.concatenate([ii, jj, np.arange(n)])]
|
| 652 |
+
cols = inv[np.concatenate([jj, ii, np.arange(n)])]
|
| 653 |
+
vals = np.concatenate([near, near, rect_self(wh[:, 0], wh[:, 1]) - 1.0])
|
| 654 |
+
self.N = csr_matrix((vals, (rows, cols)), shape=(n, n))
|
| 655 |
+
|
| 656 |
+
def block(self, a0, a1, b0, b1):
|
| 657 |
+
d = np.sqrt((self.x[a0:a1, None] - self.x[None, b0:b1]) ** 2 + (self.y[a0:a1, None] - self.y[None, b0:b1]) ** 2)
|
| 658 |
+
if a0 == b0:
|
| 659 |
+
d[np.arange(a1 - a0), np.arange(a1 - a0)] = 1.0
|
| 660 |
+
A = 1.0 / d
|
| 661 |
+
Nb = self.N[a0:a1, b0:b1]
|
| 662 |
+
if Nb.nnz:
|
| 663 |
+
A += Nb.toarray()
|
| 664 |
+
return A / self.k
|
| 665 |
+
|
| 666 |
+
def row(self, i, b0, b1):
|
| 667 |
+
d = np.sqrt((self.x[i] - self.x[b0:b1]) ** 2 + (self.y[i] - self.y[b0:b1]) ** 2)
|
| 668 |
+
r = 1.0 / d
|
| 669 |
+
Nr = self.N[i, b0:b1]
|
| 670 |
+
if Nr.nnz:
|
| 671 |
+
r += Nr.toarray()[0]
|
| 672 |
+
return r / self.k
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def _cluster_tree(c, leaf: int):
|
| 676 |
+
"""Recursive bisection of the panel centres along the longer side of their bounding box at the median: a permutation
|
| 677 |
+
making every cluster a contiguous range, and nodes (a, b, lo, hi, left, right)."""
|
| 678 |
+
perm, nodes = np.arange(len(c)), []
|
| 679 |
+
|
| 680 |
+
def rec(a, b):
|
| 681 |
+
idx = perm[a:b]
|
| 682 |
+
lo, hi = c[idx].min(0), c[idx].max(0)
|
| 683 |
+
k = len(nodes)
|
| 684 |
+
nodes.append([a, b, lo, hi, -1, -1])
|
| 685 |
+
if b - a > leaf:
|
| 686 |
+
ax = int(np.argmax(hi - lo))
|
| 687 |
+
perm[a:b] = idx[np.argsort(c[idx, ax], kind="stable")]
|
| 688 |
+
m = a + (b - a) // 2
|
| 689 |
+
nodes[k][4], nodes[k][5] = rec(a, m), rec(m, b)
|
| 690 |
+
return k
|
| 691 |
+
|
| 692 |
+
rec(0, len(c))
|
| 693 |
+
return perm, nodes
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def _aca(K, a0, a1, b0, b1, eps, max_rank):
|
| 697 |
+
"""Partial-pivoting adaptive cross approximation of the block (a0:a1, b0:b1) to relative Frobenius accuracy eps:
|
| 698 |
+
(U, V) with block ~ U V^T, or None when the rank would exceed max_rank."""
|
| 699 |
+
m, n = a1 - a0, b1 - b0
|
| 700 |
+
U, V, used_r, used_c = [], [], np.zeros(m, bool), np.zeros(n, bool)
|
| 701 |
+
i, norm2 = 0, 0.0
|
| 702 |
+
for _ in range(min(m, n, max_rank)):
|
| 703 |
+
r = K.row(a0 + i, b0, b1)
|
| 704 |
+
for u, v in zip(U, V):
|
| 705 |
+
r -= u[i] * v
|
| 706 |
+
rm = np.where(used_c, 0.0, np.abs(r))
|
| 707 |
+
j = int(np.argmax(rm))
|
| 708 |
+
if rm[j] == 0.0:
|
| 709 |
+
break
|
| 710 |
+
v = r / r[j]
|
| 711 |
+
u = K.row(b0 + j, a0, a1) # column j of the block = row j of the symmetric kernel
|
| 712 |
+
for uu, vv in zip(U, V):
|
| 713 |
+
u -= vv[j] * uu
|
| 714 |
+
used_r[i], used_c[j] = True, True
|
| 715 |
+
nu, nv = float(u @ u), float(v @ v)
|
| 716 |
+
norm2 += nu * nv + 2 * sum(float(u @ uu) * float(v @ vv) for uu, vv in zip(U, V))
|
| 717 |
+
U.append(u)
|
| 718 |
+
V.append(v)
|
| 719 |
+
if nu * nv <= eps**2 * norm2:
|
| 720 |
+
break
|
| 721 |
+
um = np.where(used_r, 0.0, np.abs(u))
|
| 722 |
+
i = int(np.argmax(um))
|
| 723 |
+
if um[i] == 0.0:
|
| 724 |
+
break
|
| 725 |
+
else:
|
| 726 |
+
return None
|
| 727 |
+
return np.stack(U, 1), np.stack(V, 1)
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
class _HMatrix:
|
| 731 |
+
"""Hierarchical matrix of the panel system: dense blocks for leaf pairs that are not well separated, ACA low-rank
|
| 732 |
+
blocks for admissible pairs (min diameter <= eta x distance); only the upper block triangle is stored (symmetric)."""
|
| 733 |
+
|
| 734 |
+
def __init__(self, c, wh, eps_r, leaf=128, eta=2.0, eps=1e-9):
|
| 735 |
+
self.n = len(c)
|
| 736 |
+
self.perm, nodes = _cluster_tree(c, leaf)
|
| 737 |
+
self.K = _Kernel(c, wh, eps_r, self.perm)
|
| 738 |
+
self.eps = eps
|
| 739 |
+
plan = []
|
| 740 |
+
|
| 741 |
+
def leafq(k):
|
| 742 |
+
return nodes[k][4] < 0
|
| 743 |
+
|
| 744 |
+
def rec(s, t):
|
| 745 |
+
a0, a1, lo_s, hi_s, sl, sr = nodes[s]
|
| 746 |
+
b0, b1, lo_t, hi_t, tl, tr = nodes[t]
|
| 747 |
+
if s == t:
|
| 748 |
+
if leafq(s):
|
| 749 |
+
plan.append(("d", a0, a1, a0, a1))
|
| 750 |
+
else:
|
| 751 |
+
rec(sl, sl), rec(sr, sr), rec(sl, sr)
|
| 752 |
+
return
|
| 753 |
+
gap = np.maximum(0.0, np.maximum(lo_s - hi_t, lo_t - hi_s))
|
| 754 |
+
diam = min(np.sqrt(((hi_s - lo_s) ** 2).sum()), np.sqrt(((hi_t - lo_t) ** 2).sum()))
|
| 755 |
+
if diam <= eta * np.sqrt((gap**2).sum()):
|
| 756 |
+
plan.append(("l", a0, a1, b0, b1))
|
| 757 |
+
elif leafq(s) and leafq(t):
|
| 758 |
+
plan.append(("d", a0, a1, b0, b1))
|
| 759 |
+
elif leafq(s):
|
| 760 |
+
rec(s, tl), rec(s, tr)
|
| 761 |
+
elif leafq(t):
|
| 762 |
+
rec(sl, t), rec(sr, t)
|
| 763 |
+
else:
|
| 764 |
+
for u in (sl, sr):
|
| 765 |
+
for v in (tl, tr):
|
| 766 |
+
rec(u, v)
|
| 767 |
+
|
| 768 |
+
rec(0, 0)
|
| 769 |
+
self.dense, self.low = [], []
|
| 770 |
+
|
| 771 |
+
def build(chunk):
|
| 772 |
+
out = []
|
| 773 |
+
for kind, a0, a1, b0, b1 in chunk:
|
| 774 |
+
if kind == "l":
|
| 775 |
+
r = _aca(self.K, a0, a1, b0, b1, eps, max(2, min(a1 - a0, b1 - b0) // 2))
|
| 776 |
+
if r is not None:
|
| 777 |
+
out.append(("l", a0, a1, b0, b1, r))
|
| 778 |
+
continue
|
| 779 |
+
out.append(("d", a0, a1, b0, b1, self.K.block(a0, a1, b0, b1)))
|
| 780 |
+
return out
|
| 781 |
+
|
| 782 |
+
for res in _run([partial(build, plan[a:b]) for a, b in _spans(len(plan), 64)]):
|
| 783 |
+
for kind, a0, a1, b0, b1, M in res:
|
| 784 |
+
(self.low if kind == "l" else self.dense).append((a0, a1, b0, b1, M))
|
| 785 |
+
self.pre = [(a0, a1, cho_factor(D, lower=True)) for a0, a1, b0, _, D in self.dense if a0 == b0] # block Jacobi
|
| 786 |
+
self.n_threads = max(1, _nthreads())
|
| 787 |
+
|
| 788 |
+
def nbytes(self):
|
| 789 |
+
return sum(D.nbytes for *_, D in self.dense) + sum(U.nbytes + V.nbytes for *_, (U, V) in self.low)
|
| 790 |
+
|
| 791 |
+
def matvec(self, X):
|
| 792 |
+
def part(dense, low):
|
| 793 |
+
Y = np.zeros_like(X)
|
| 794 |
+
for a0, a1, b0, b1, D in dense:
|
| 795 |
+
Y[a0:a1] += D @ X[b0:b1]
|
| 796 |
+
if a0 != b0:
|
| 797 |
+
Y[b0:b1] += D.T @ X[a0:a1]
|
| 798 |
+
for a0, a1, b0, b1, (U, V) in low:
|
| 799 |
+
Y[a0:a1] += U @ (V.T @ X[b0:b1])
|
| 800 |
+
Y[b0:b1] += V @ (U.T @ X[a0:a1])
|
| 801 |
+
return Y
|
| 802 |
+
|
| 803 |
+
T = self.n_threads
|
| 804 |
+
if T < 2:
|
| 805 |
+
return part(self.dense, self.low)
|
| 806 |
+
return sum(_run([partial(part, self.dense[k::T], self.low[k::T]) for k in range(T)]))
|
| 807 |
+
|
| 808 |
+
def precondition(self, R):
|
| 809 |
+
Z = np.empty_like(R)
|
| 810 |
+
for a0, a1, cf in self.pre:
|
| 811 |
+
Z[a0:a1] = cho_solve(cf, R[a0:a1], check_finite=False)
|
| 812 |
+
return Z
|
| 813 |
+
|
| 814 |
+
def pcg(self, B, tol, maxit):
|
| 815 |
+
"""Conjugate gradients on every right-hand side column at once (independent columns), block-Jacobi preconditioned,
|
| 816 |
+
until every column's relative residual is below tol. B and the result are in the permuted order."""
|
| 817 |
+
X, R = np.zeros_like(B), B.copy()
|
| 818 |
+
Z = self.precondition(R)
|
| 819 |
+
P, rz = Z.copy(), (R * Z).sum(0)
|
| 820 |
+
bn = np.sqrt((B * B).sum(0))
|
| 821 |
+
for it in range(maxit):
|
| 822 |
+
AP = self.matvec(P)
|
| 823 |
+
alpha = rz / (P * AP).sum(0)
|
| 824 |
+
X += alpha * P
|
| 825 |
+
R -= alpha * AP
|
| 826 |
+
res = (np.sqrt((R * R).sum(0)) / bn).max()
|
| 827 |
+
if res < tol:
|
| 828 |
+
return X, it + 1, res
|
| 829 |
+
Z = self.precondition(R)
|
| 830 |
+
rz_new = (R * Z).sum(0)
|
| 831 |
+
P = Z + (rz_new / rz) * P
|
| 832 |
+
rz = rz_new
|
| 833 |
+
raise np.linalg.LinAlgError(f"H-matrix PCG did not converge in {maxit} iterations (residual {res:.1e})")
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
def mom_solve_fast(c, wh, o, n_metals: int, eps_r: float = 11.45, dense_max: int | None = None):
|
| 837 |
+
"""Panel charges Q (n, n_metals) for unit excitation of every conductor, exact near field: dense Cholesky for
|
| 838 |
+
n <= dense_max panels (`_mom_solve_exact_near`), otherwise the H-matrix / PCG solve of the same system."""
|
| 839 |
+
n = len(c)
|
| 840 |
+
if n <= (DENSE_MAX if dense_max is None else dense_max):
|
| 841 |
+
return _mom_solve_exact_near(c, wh, o, n_metals, eps_r)
|
| 842 |
+
H = _HMatrix(c, wh, eps_r, HMAT["leaf"], HMAT["eta"], HMAT["eps"])
|
| 843 |
+
B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float)[H.perm]
|
| 844 |
+
Xp, _, _ = H.pcg(B, HMAT["tol"], HMAT["maxit"])
|
| 845 |
+
Q = np.empty_like(Xp)
|
| 846 |
+
Q[H.perm] = Xp
|
| 847 |
+
return Q
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
def _cap_flagship(metals, eps_r, h, max_cells, grade, lmax_mult, merge_grade):
|
| 851 |
+
c, wh, o, h, n_raw = mesh_flagship(metals, h, max_cells, grade, lmax_mult, merge_grade)
|
| 852 |
+
try:
|
| 853 |
+
Q = mom_solve_fast(c, wh, o, len(metals), eps_r)
|
| 854 |
+
except np.linalg.LinAlgError: # cut panels of different conductors overlap (lattice coarser than the finger pitch)
|
| 855 |
+
print("flagship: system not positive definite, majority finest cells", flush=True)
|
| 856 |
+
c, wh, o, h, n_raw = mesh_flagship(metals, h, max_cells, grade, lmax_mult, merge_grade, majority=True)
|
| 857 |
+
Q = mom_solve_fast(c, wh, o, len(metals), eps_r)
|
| 858 |
+
C = np.stack([Q[o == a].sum(0) for a in range(len(metals))])
|
| 859 |
+
return 0.5 * (C + C.T), len(c), h, n_raw
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def mom_capacitance_gds_flagship(metals: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, max_cells: int = 250000,
|
| 863 |
+
grade: float = 2.0, rich: bool = True, lmax_mult: float = 16.0, merge_grade: float = 1.0):
|
| 864 |
+
"""Flagship prior: strip-merged conductor-anchored mesh at h_f = max(gap / (2 cells_per_gap), size / 8192) and, with
|
| 865 |
+
rich=True, Richardson extrapolation with the mesh at 2 h_f (same lattice), both solved with `mom_solve_fast`. The
|
| 866 |
+
resolution is set by cells_per_gap (the fine mesh has 2 cells_per_gap panels across the smallest gap; the coarse
|
| 867 |
+
one cells_per_gap); max_cells is only a safety cap on the merged panel count (h doubles until it fits). The two solves
|
| 868 |
+
run concurrently when more than one thread is allowed. Returns (C, total panels, h of the fine mesh, info dict)."""
|
| 869 |
+
bbox = shapely.union_all(metals).bounds
|
| 870 |
+
size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
|
| 871 |
+
gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals)))
|
| 872 |
+
hf = max(gap / (2 * cells_per_gap), size / 8192)
|
| 873 |
+
if not rich:
|
| 874 |
+
C, n, h, n_raw = _cap_flagship(metals, eps_r, 2 * hf, max_cells, grade, lmax_mult, merge_grade)
|
| 875 |
+
return C, n, h, {"h_target_um": 2 * hf, "min_gap_um": gap, "cap_hit": h > 2 * hf * 1.0001, "raw_cells": n_raw, "extrapolated": False}
|
| 876 |
+
rf, rc = _both(partial(_cap_flagship, metals, eps_r, hf, max_cells, grade, lmax_mult, merge_grade),
|
| 877 |
+
partial(_cap_flagship, metals, eps_r, 2 * hf, max_cells, grade, lmax_mult, merge_grade))
|
| 878 |
+
for r in (rf, rc):
|
| 879 |
+
if isinstance(r, np.linalg.LinAlgError):
|
| 880 |
+
raise r
|
| 881 |
+
(Cf, nf, h_f, raw_f), (Cc, nc, h_c, raw_c) = rf, rc
|
| 882 |
+
r = h_c / h_f
|
| 883 |
+
C = Cf if r < 1.01 else Cf + (Cf - Cc) / (r - 1)
|
| 884 |
+
info = {"h_target_um": hf, "min_gap_um": gap, "cap_hit": h_f > hf * 1.0001, "raw_cells": raw_f, "coarse_cells": nc,
|
| 885 |
+
"extrapolated": bool(r >= 1.01)}
|
| 886 |
+
return C, nf + nc, h_f, info
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def mom_solve_flagship(metals: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, max_cells: int = 250000, grade: float = 2.0,
|
| 890 |
+
rich: bool = True):
|
| 891 |
+
"""Flagship prior (tlsq.embed.proxy.mom_capacitance_gds_flagship): dict(C, n_cells, h_min, mesh)."""
|
| 892 |
+
t0 = time.perf_counter()
|
| 893 |
+
C, n, h, info = mom_capacitance_gds_flagship(metals, eps_r, cells_per_gap, max_cells, grade, rich)
|
| 894 |
+
_tick("flagship", t0)
|
| 895 |
+
rep = _mesh_report(h, max_cells, h_target=info["h_target_um"], min_gap=info["min_gap_um"], raw_cells=info["raw_cells"],
|
| 896 |
+
extrapolated=info["extrapolated"], merged=True, solver="dense" if n <= DENSE_MAX else "H-matrix PCG")
|
| 897 |
+
rep["cap_hit"] = bool(info["cap_hit"])
|
| 898 |
+
if rich:
|
| 899 |
+
rep["coarse_cells"] = int(info["coarse_cells"])
|
| 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)
|
tlsq_infer/app_ui.py
CHANGED
|
@@ -14,6 +14,7 @@ from __future__ import annotations
|
|
| 14 |
import json
|
| 15 |
import os
|
| 16 |
import tempfile
|
|
|
|
| 17 |
import time
|
| 18 |
from pathlib import Path
|
| 19 |
|
|
@@ -27,6 +28,24 @@ from .registry import load_registry
|
|
| 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": 30}
|
| 29 |
CUSTOM = "custom eps_r"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
LAYER_COLS = ["layer", "datatype", "role", "n_polygons", "area_um2", "bbox_um"]
|
| 31 |
|
| 32 |
|
|
@@ -211,7 +230,7 @@ def entries_table(res):
|
|
| 211 |
def predict_fn(f, table, margin_gaps, margin_um, select, substrate, custom_eps, thickness, model, self_rows):
|
| 212 |
reg = load_registry()
|
| 213 |
lay = _prepare(f, table, margin_gaps, margin_um, select)
|
| 214 |
-
res =
|
| 215 |
d = Path(tempfile.mkdtemp())
|
| 216 |
(d / "capacitance_fF.csv").write_text(matrix_csv(res))
|
| 217 |
(d / "capacitance.json").write_text(json.dumps(res, indent=1))
|
|
@@ -228,8 +247,8 @@ def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps
|
|
| 228 |
t = time.perf_counter()
|
| 229 |
lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers),
|
| 230 |
margin_gaps=_margin(margin_gaps))
|
| 231 |
-
res =
|
| 232 |
-
|
| 233 |
res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t
|
| 234 |
return res
|
| 235 |
|
|
|
|
| 14 |
import json
|
| 15 |
import os
|
| 16 |
import tempfile
|
| 17 |
+
import threading
|
| 18 |
import time
|
| 19 |
from pathlib import Path
|
| 20 |
|
|
|
|
| 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
|
| 33 |
+
HEAVY = threading.BoundedSemaphore(int(os.environ.get("TLSQ_HEAVY_CONCURRENCY", 1)))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _predict(lay, model, **kw):
|
| 37 |
+
from .predict import large_layout_model, resolve_model, would_hit_cap
|
| 38 |
+
|
| 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]
|
| 45 |
+
if not heavy:
|
| 46 |
+
return predict(lay, model=model or None, **kw)
|
| 47 |
+
with HEAVY:
|
| 48 |
+
return predict(lay, model=model or None, **kw)
|
| 49 |
LAYER_COLS = ["layer", "datatype", "role", "n_polygons", "area_um2", "bbox_um"]
|
| 50 |
|
| 51 |
|
|
|
|
| 230 |
def predict_fn(f, table, margin_gaps, margin_um, select, substrate, custom_eps, thickness, model, self_rows):
|
| 231 |
reg = load_registry()
|
| 232 |
lay = _prepare(f, table, margin_gaps, margin_um, select)
|
| 233 |
+
res = _predict(lay, model, substrate=_eps(substrate, custom_eps), thickness_um=float(thickness), self_from_rows=bool(self_rows))
|
| 234 |
d = Path(tempfile.mkdtemp())
|
| 235 |
(d / "capacitance_fF.csv").write_text(matrix_csv(res))
|
| 236 |
(d / "capacitance.json").write_text(json.dumps(res, indent=1))
|
|
|
|
| 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
|
| 253 |
return res
|
| 254 |
|
tlsq_infer/predict.py
CHANGED
|
@@ -58,6 +58,44 @@ def _logC(C: np.ndarray) -> np.ndarray:
|
|
| 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 |
|
| 62 |
|
| 63 |
def tier_of(model: str | None) -> str | None:
|
|
@@ -153,7 +191,7 @@ def run_pipeline(metals: list, names: list[str], model: str, reg=None, model_dir
|
|
| 153 |
|
| 154 |
def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (cryogenic, training)", thickness_um: float = 350.0,
|
| 155 |
self_from_rows: bool = False, registry=None, model_dir=None, return_debug: bool = False,
|
| 156 |
-
row_sum_eps: float | None = None, blend_kinds: str | None = None) -> dict:
|
| 157 |
"""Maxwell capacitance matrix (fF) of a prepared layout.
|
| 158 |
|
| 159 |
model: a deployable registry name, or a tier: "coarse" (default: defaults.flagship_model; alias "fast") / "fine"
|
|
@@ -165,7 +203,11 @@ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (c
|
|
| 165 |
never-seen components have a median of 0.0099, so the default overestimates C_ii by ~0.45 % there; deploy/LIMITS.md).
|
| 166 |
blend_kinds: "invariant" (conductor-conductor / conductor-ground, independent of polygon order) or "published"
|
| 167 |
(paper file-order kinds); default from registry blend.kinds. Mesh coarsening by the cell cap and a v3-rich prior
|
| 168 |
-
without extrapolation are reported in `prior_mesh`, `warnings` and `expected_error["mesh_warning"]`
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
"""
|
| 170 |
reg = registry or load_registry()
|
| 171 |
model = resolve_model(reg, model)
|
|
@@ -179,6 +221,18 @@ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (c
|
|
| 179 |
names = ["G"] + _internal_names(n)
|
| 180 |
metals = [prepared.ground] + list(prepared.conductors)
|
| 181 |
fallback_note = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
try:
|
| 183 |
logC, debug = run_pipeline(metals, names, model, reg, model_dir, timing, blend_kinds)
|
| 184 |
except np.linalg.LinAlgError as e: # v3 MoM system not positive definite at gap/3 and gap/6 (e.g. long fine combs)
|
|
@@ -191,6 +245,16 @@ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (c
|
|
| 191 |
logC, debug = run_pipeline(metals, names, fb, reg, model_dir, timing, blend_kinds)
|
| 192 |
k = len(metals)
|
| 193 |
Cabs = np.exp(logC[:k, :k])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
M = -Cabs.copy()
|
| 195 |
for i in range(k):
|
| 196 |
M[i, i] = Cabs[i, i]
|
|
@@ -201,6 +265,11 @@ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (c
|
|
| 201 |
M[0, 0] = np.nan
|
| 202 |
f = eps_factor(eps)
|
| 203 |
M = M * f
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
timing["total_s"] = time.perf_counter() - t_all
|
| 205 |
labels = ["G"] + list(prepared.names)
|
| 206 |
iu = [(i, j) for i in range(k) for j in range(i + 1, k)]
|
|
@@ -210,6 +279,9 @@ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (c
|
|
| 210 |
base = mu.get("validation") or mu.get("paper", {}).get("never_seen") # deploy held-out sets for models trained on all data
|
| 211 |
if base is None and mu["kind"] == "blend":
|
| 212 |
base = reg.model(mu["components"][0]).get("validation") or reg.model(mu["components"][0])["paper"]["never_seen"]
|
|
|
|
|
|
|
|
|
|
| 213 |
P = load_params()
|
| 214 |
L = lateral_extent(prepared.conductors, P)
|
| 215 |
exp_err = expected_error(P, eps, float(thickness_um), L, {kk: base[kk] for kk in ("median_pct", "mae_ff", "rmse_ff", "set") if kk in base},
|
|
@@ -228,7 +300,6 @@ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (c
|
|
| 228 |
_per_entry(out, reg, mu_name, debug, labels, f, exp_err)
|
| 229 |
if debug.get("prior_stage_s"):
|
| 230 |
out["prior_stage_s"] = debug["prior_stage_s"]
|
| 231 |
-
mesh = debug.get("prior_mesh") or {}
|
| 232 |
if mesh:
|
| 233 |
out["prior_mesh"] = mesh
|
| 234 |
msg = []
|
|
@@ -238,8 +309,19 @@ def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (c
|
|
| 238 |
f"{mesh['min_gap_um']:.3g} µm); expect a larger prior error than on the validation sets")
|
| 239 |
if mesh.get("extrapolated") is False:
|
| 240 |
msg.append("v3-rich prior not extrapolated (" + (mesh.get("note") or "fine solve only") + ")")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
out["warnings"] += msg
|
| 242 |
exp_err["mesh_warning"] = "; ".join(msg) if msg else None
|
|
|
|
|
|
|
|
|
|
| 243 |
if self_from_rows:
|
| 244 |
out["row_sum_eps"] = float(reg["self_capacitance"]["row_sum_eps"] if row_sum_eps is None else row_sum_eps)
|
| 245 |
if fallback_note:
|
|
|
|
| 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 |
+
|
| 64 |
+
|
| 65 |
+
class PriorError(ValueError):
|
| 66 |
+
"""The physics prior produced no usable matrix (zero or non-finite mutual entries)."""
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def large_layout_model(reg, model: str) -> str | None:
|
| 70 |
+
"""Model that `model` is re-routed to when its capped prior would fall below the training regime on this layout:
|
| 71 |
+
registry defaults.large_layout_model (a flagship-prior model), or None when not configured or already such a model."""
|
| 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
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def would_hit_cap(metals: list, prior: str) -> tuple[bool, float]:
|
| 81 |
+
"""Whether the capped v3 / v3-rich mesh of `prior` falls below the training regime on this layout, decided without a
|
| 82 |
+
solve: the lattice is coarsened by factors of two until the mesh fits the cap, so it is below the regime exactly when
|
| 83 |
+
the mesh at the coarsest lattice level that still has >= REGIME_MIN_CELLS_PER_GAP panels per gap exceeds the cap (one
|
| 84 |
+
cheap mesh attempt at that level, stopped at the cap). Returns (below, upper bound on the panels per gap reached)."""
|
| 85 |
+
if prior not in ("v3", "v3-rich"):
|
| 86 |
+
return False, float("nan")
|
| 87 |
+
kw = PRIORS[prior]
|
| 88 |
+
cap = kw["max_cells"] * (2 if prior == "v3-rich" else 1)
|
| 89 |
+
cpg = kw["cells_per_gap"] * (2 if prior == "v3-rich" else 1)
|
| 90 |
+
gap, size = _mom._gap_size(metals)
|
| 91 |
+
h = max(gap / cpg, size / 4096)
|
| 92 |
+
if gap / h < REGIME_MIN_CELLS_PER_GAP: # the resolution floor alone is below the regime
|
| 93 |
+
return True, gap / h
|
| 94 |
+
while gap / (2 * h) >= REGIME_MIN_CELLS_PER_GAP: # coarsest lattice level still in the regime
|
| 95 |
+
h *= 2.0
|
| 96 |
+
if _mom.anchored_cells(metals, h, 2.0, limit=cap) is None: # does not fit: the capped mesh coarsens below the regime
|
| 97 |
+
return True, gap / (2 * h)
|
| 98 |
+
return False, float("nan")
|
| 99 |
|
| 100 |
|
| 101 |
def tier_of(model: str | None) -> str | None:
|
|
|
|
| 191 |
|
| 192 |
def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (cryogenic, training)", thickness_um: float = 350.0,
|
| 193 |
self_from_rows: bool = False, registry=None, model_dir=None, return_debug: bool = False,
|
| 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"
|
|
|
|
| 203 |
never-seen components have a median of 0.0099, so the default overestimates C_ii by ~0.45 % there; deploy/LIMITS.md).
|
| 204 |
blend_kinds: "invariant" (conductor-conductor / conductor-ground, independent of polygon order) or "published"
|
| 205 |
(paper file-order kinds); default from registry blend.kinds. Mesh coarsening by the cell cap and a v3-rich prior
|
| 206 |
+
without extrapolation are reported in `prior_mesh`, `warnings` and `expected_error["mesh_warning"]`; a prior below
|
| 207 |
+
the training regime (< 0.75 panels across the smallest gap) sets `expected_error["out_of_regime"]` with a warning.
|
| 208 |
+
large_layouts: "route" (default) re-routes a capped-prior model to the registry's `defaults.large_layout_model`
|
| 209 |
+
(flagship prior) when its mesh would fall below the training regime on this layout (reported in `model_used` and
|
| 210 |
+
`warnings`); "keep" never re-routes. A prior with zero or non-finite mutual entries raises PriorError.
|
| 211 |
"""
|
| 212 |
reg = registry or load_registry()
|
| 213 |
model = resolve_model(reg, model)
|
|
|
|
| 221 |
names = ["G"] + _internal_names(n)
|
| 222 |
metals = [prepared.ground] + list(prepared.conductors)
|
| 223 |
fallback_note = None
|
| 224 |
+
routed_note = None
|
| 225 |
+
if large_layouts == "route":
|
| 226 |
+
fb = large_layout_model(reg, model)
|
| 227 |
+
if fb is not None:
|
| 228 |
+
t = time.perf_counter()
|
| 229 |
+
below, cpg = would_hit_cap(metals, m.get("prior", "standard"))
|
| 230 |
+
timing["regime_check_s"] = time.perf_counter() - t
|
| 231 |
+
if below:
|
| 232 |
+
routed_note = (f"large layout: the capped {m.get('prior')} prior of {model!r} would resolve fewer than {cpg:.2f} panels across "
|
| 233 |
+
f"the smallest gap (training regime >= {REGIME_MIN_CELLS_PER_GAP}); predicted with {fb!r} "
|
| 234 |
+
f"({reg.model(fb).get('title')}) instead")
|
| 235 |
+
model, m = fb, reg.model(fb)
|
| 236 |
try:
|
| 237 |
logC, debug = run_pipeline(metals, names, model, reg, model_dir, timing, blend_kinds)
|
| 238 |
except np.linalg.LinAlgError as e: # v3 MoM system not positive definite at gap/3 and gap/6 (e.g. long fine combs)
|
|
|
|
| 245 |
logC, debug = run_pipeline(metals, names, fb, reg, model_dir, timing, blend_kinds)
|
| 246 |
k = len(metals)
|
| 247 |
Cabs = np.exp(logC[:k, :k])
|
| 248 |
+
mesh = debug.get("prior_mesh") or {}
|
| 249 |
+
pm = debug.get("prior_matrix")
|
| 250 |
+
if pm is not None:
|
| 251 |
+
mut = pm[np.triu_indices(k, 1)]
|
| 252 |
+
if not np.all(np.isfinite(mut)) or np.any(mut == 0):
|
| 253 |
+
raise PriorError(f"the {m.get('prior')} MoM prior of {model!r} returned {int((~np.isfinite(mut)).sum())} non-finite and "
|
| 254 |
+
f"{int((mut == 0).sum())} zero mutual entries on this layout ({mesh.get('cells_per_min_gap', float('nan')):.2f} "
|
| 255 |
+
f"panels across the smallest gap {mesh.get('min_gap_um', float('nan')):.3g} um at the cap of {mesh.get('max_cells')} "
|
| 256 |
+
"panels): no matrix is returned. Use the flagship tier (resolution-controlled prior, `all-data-flagship`) or "
|
| 257 |
+
"predict a smaller selection of conductors (prepare(select=...)).")
|
| 258 |
M = -Cabs.copy()
|
| 259 |
for i in range(k):
|
| 260 |
M[i, i] = Cabs[i, i]
|
|
|
|
| 265 |
M[0, 0] = np.nan
|
| 266 |
f = eps_factor(eps)
|
| 267 |
M = M * f
|
| 268 |
+
out_mut = M[np.triu_indices(k, 1)]
|
| 269 |
+
if not np.all(np.isfinite(out_mut)) or np.any(out_mut == 0):
|
| 270 |
+
raise PriorError(f"model {model!r} produced {int((~np.isfinite(out_mut)).sum())} non-finite and {int((out_mut == 0).sum())} zero "
|
| 271 |
+
"mutual entries on this layout: no matrix is returned. Use the flagship tier (`all-data-flagship`) or predict a "
|
| 272 |
+
"smaller selection of conductors (prepare(select=...)).")
|
| 273 |
timing["total_s"] = time.perf_counter() - t_all
|
| 274 |
labels = ["G"] + list(prepared.names)
|
| 275 |
iu = [(i, j) for i in range(k) for j in range(i + 1, k)]
|
|
|
|
| 279 |
base = mu.get("validation") or mu.get("paper", {}).get("never_seen") # deploy held-out sets for models trained on all data
|
| 280 |
if base is None and mu["kind"] == "blend":
|
| 281 |
base = reg.model(mu["components"][0]).get("validation") or reg.model(mu["components"][0])["paper"]["never_seen"]
|
| 282 |
+
if base is None or base.get("median_pct") is None: # not yet scored (e.g. a flagship-prior entry): the fine tier's numbers, labelled as such
|
| 283 |
+
ft = reg.model(reg["defaults"]["flagship_accurate_model"])["validation"]
|
| 284 |
+
base = {**ft, "set": f"{ft.get('set')} (fine-tier network with its deployed prior; this model's own score is pending)"}
|
| 285 |
P = load_params()
|
| 286 |
L = lateral_extent(prepared.conductors, P)
|
| 287 |
exp_err = expected_error(P, eps, float(thickness_um), L, {kk: base[kk] for kk in ("median_pct", "mae_ff", "rmse_ff", "set") if kk in base},
|
|
|
|
| 300 |
_per_entry(out, reg, mu_name, debug, labels, f, exp_err)
|
| 301 |
if debug.get("prior_stage_s"):
|
| 302 |
out["prior_stage_s"] = debug["prior_stage_s"]
|
|
|
|
| 303 |
if mesh:
|
| 304 |
out["prior_mesh"] = mesh
|
| 305 |
msg = []
|
|
|
|
| 309 |
f"{mesh['min_gap_um']:.3g} µm); expect a larger prior error than on the validation sets")
|
| 310 |
if mesh.get("extrapolated") is False:
|
| 311 |
msg.append("v3-rich prior not extrapolated (" + (mesh.get("note") or "fine solve only") + ")")
|
| 312 |
+
cpg = mesh.get("cells_per_min_gap")
|
| 313 |
+
exp_err["cells_per_min_gap"] = cpg
|
| 314 |
+
exp_err["out_of_regime"] = bool(cpg is not None and cpg < REGIME_MIN_CELLS_PER_GAP)
|
| 315 |
+
if exp_err["out_of_regime"]:
|
| 316 |
+
msg.insert(0, f"OUT OF THE TRAINING REGIME: the prior resolves only {cpg:.2f} panels across the smallest gap "
|
| 317 |
+
f"({mesh.get('min_gap_um', float('nan')):.3g} µm); the networks were trained on priors with "
|
| 318 |
+
f"{REGIME_MIN_CELLS_PER_GAP}-3 panels per gap and their validation errors do not apply. Use the flagship "
|
| 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)
|
| 325 |
if self_from_rows:
|
| 326 |
out["row_sum_eps"] = float(reg["self_capacitance"]["row_sum_eps"] if row_sum_eps is None else row_sum_eps)
|
| 327 |
if fallback_note:
|
tlsq_infer/registry.py
CHANGED
|
@@ -13,7 +13,11 @@ 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 |
-
"v3": dict(mesh="v3", max_cells=8000, cells_per_gap=3.0), "v3-rich": dict(mesh="v3-rich", max_cells=8000, cells_per_gap=3.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
def find_registry(path=None) -> Path:
|
|
|
|
| 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 |
+
"v3": dict(mesh="v3", max_cells=8000, cells_per_gap=3.0), "v3-rich": dict(mesh="v3-rich", max_cells=8000, cells_per_gap=3.0),
|
| 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:
|